title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java Program for Extended Euclidean algorithms
05 Dec, 2018 GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors. // Java program to demonstrate working of extended// Euclidean Algorithm import java.util.*;import java.lang.*; class GFG { // extended Euclidean Algorithm public static int gcdExtended(int a, int b, int x, int y) { // Base Case if (a == 0) { x = 0; y = 1; return b; } int x1 = 1, y1 = 1; // To store results of recursive call int gcd = gcdExtended(b % a, a, x1, y1); // Update x and y using results of recursive // call x = y1 - (b / a) * x1; y = x1; return gcd; } // Driver Program public static void main(String[] args) { int x = 1, y = 1; int a = 35, b = 15; int g = gcdExtended(a, b, x, y); System.out.print("gcd(" + a + ", " + b + ") = " + g); }}// Code Contributed by Mohit Gupta_OMG <(0-o)> gcd(35, 15) = 5 Please refer complete article on Basic and Extended Euclidean algorithms for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java SHA-1 Hash Java Program to Convert File to a Byte Array Java Program to Find Sum of Array Elements
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2018" }, { "code": null, "e": 179, "s": 28, "text": "GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors." }, { "code": "// Java program to demonstrate working of extended// Euclidean Algorithm import java.util.*;import java.lang.*; class GFG { // extended Euclidean Algorithm public static int gcdExtended(int a, int b, int x, int y) { // Base Case if (a == 0) { x = 0; y = 1; return b; } int x1 = 1, y1 = 1; // To store results of recursive call int gcd = gcdExtended(b % a, a, x1, y1); // Update x and y using results of recursive // call x = y1 - (b / a) * x1; y = x1; return gcd; } // Driver Program public static void main(String[] args) { int x = 1, y = 1; int a = 35, b = 15; int g = gcdExtended(a, b, x, y); System.out.print(\"gcd(\" + a + \", \" + b + \") = \" + g); }}// Code Contributed by Mohit Gupta_OMG <(0-o)>", "e": 1043, "s": 179, "text": null }, { "code": null, "e": 1060, "s": 1043, "text": "gcd(35, 15) = 5\n" }, { "code": null, "e": 1151, "s": 1060, "text": "Please refer complete article on Basic and Extended Euclidean algorithms for more details!" }, { "code": null, "e": 1165, "s": 1151, "text": "Java Programs" }, { "code": null, "e": 1263, "s": 1165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1311, "s": 1263, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 1350, "s": 1311, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 1401, "s": 1350, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 1435, "s": 1401, "text": "Java Program to Write into a File" }, { "code": null, "e": 1482, "s": 1435, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 1520, "s": 1482, "text": "Java Program to Read a File to String" }, { "code": null, "e": 1552, "s": 1520, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 1563, "s": 1552, "text": "SHA-1 Hash" }, { "code": null, "e": 1608, "s": 1563, "text": "Java Program to Convert File to a Byte Array" } ]
Java Program for compound interest
07 Feb, 2018 Compound Interest formula: Formula to calculate compound interest annually is given by:Compound Interest = P(1 + R/100)rWhere,P is principle amountR is the rate andT is the time span Example: Input : Principle (amount): 1200 Time: 2 Rate: 5.4 Output : Compound Interest = 1333.099243 // Java program to find compound interest for// given values.import java.io.*; class GFG{ public static void main(String args[]) { double principle = 10000, rate = 10.25, time = 5; /* Calculate compound interest */ double CI = principle * (Math.pow((1 + rate / 100), time)); System.out.println("Compound Interest is "+ CI); }}// This code is contributed by Anant Agarwal. Please refer complete article on Program to find compound interest for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Feb, 2018" }, { "code": null, "e": 80, "s": 53, "text": "Compound Interest formula:" }, { "code": null, "e": 236, "s": 80, "text": "Formula to calculate compound interest annually is given by:Compound Interest = P(1 + R/100)rWhere,P is principle amountR is the rate andT is the time span" }, { "code": null, "e": 245, "s": 236, "text": "Example:" }, { "code": null, "e": 354, "s": 245, "text": "Input : Principle (amount): 1200\n Time: 2\n Rate: 5.4\nOutput : Compound Interest = 1333.099243\n" }, { "code": "// Java program to find compound interest for// given values.import java.io.*; class GFG{ public static void main(String args[]) { double principle = 10000, rate = 10.25, time = 5; /* Calculate compound interest */ double CI = principle * (Math.pow((1 + rate / 100), time)); System.out.println(\"Compound Interest is \"+ CI); }}// This code is contributed by Anant Agarwal.", "e": 795, "s": 354, "text": null }, { "code": null, "e": 880, "s": 795, "text": "Please refer complete article on Program to find compound interest for more details!" }, { "code": null, "e": 894, "s": 880, "text": "Java Programs" } ]
Command Line Arguments in Java
08 Jun, 2022 Java command-line argument is an argument i.e. passed at the time of running the Java program. In the command line, the arguments passed from the console can be received in the java program and they can be used as input. The users can pass the arguments during the execution bypassing the command-line arguments inside the main() method. We need to pass the arguments as space-separated values. We can pass both strings and primitive data types(int, double, float, char, etc) as command-line arguments. These arguments convert into a string array and are provided to the main() function as a string array argument. When command-line arguments are supplied to JVM, JVM wraps these and supplies them to args[]. It can be confirmed that they are wrapped up in an args array by checking the length of args using args.length. Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass into the main() function. We can check these arguments using args.length method. JVM stores the first command-line argument at args[0], the second at args[1], the third at args[2], and so on. Illustration: Java // Java Program to Illustrate First Argument // Classclass GFG { // Main driver method public static void main(String[] args) { // Printing the first argument System.out.println(args[0]); }} Output: Implementation: If we run a Java Program by writing the command “java Hello Geeks At GeeksForGeeks” where the name of the class is “Hello”, then it will run up to Hello. It is a command up to “Hello” and after that i.e “Geeks At GeeksForGeeks”, these are command-line arguments. Example: Java // Java Program to Check for Command Line Arguments // Classclass GFG { // Main driver method public static void main(String[] args) { // Checking if length of args array is // greater than 0 if (args.length > 0) { // Print statements System.out.println("The command line" + " arguments are:"); // Iterating the args array // using for each loop for (String val : args) // Printing command line arguments System.out.println(val); } else // Print statements System.out.println("No command line " + "arguments found."); }} No command line arguments found. Steps to Run the Above Program are: To compile and run a java program in the command prompt, follow the steps written below. Save the program as Hello.java Open the command prompt window and compile the program- javac Hello.java After a successful compilation of the program, run the following command by writing the arguments- java Hello For example – java Hello Geeks at GeeksforGeeks Press Enter and you will get the desired output. Output: This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. pujasingg43 nishkarshgandhi solankimayank leelamahanthalla aekansh53 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 390, "s": 52, "text": "Java command-line argument is an argument i.e. passed at the time of running the Java program. In the command line, the arguments passed from the console can be received in the java program and they can be used as input. The users can pass the arguments during the execution bypassing the command-line arguments inside the main() method." }, { "code": null, "e": 667, "s": 390, "text": "We need to pass the arguments as space-separated values. We can pass both strings and primitive data types(int, double, float, char, etc) as command-line arguments. These arguments convert into a string array and are provided to the main() function as a string array argument." }, { "code": null, "e": 873, "s": 667, "text": "When command-line arguments are supplied to JVM, JVM wraps these and supplies them to args[]. It can be confirmed that they are wrapped up in an args array by checking the length of args using args.length." }, { "code": null, "e": 1155, "s": 873, "text": "Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass into the main() function. We can check these arguments using args.length method. JVM stores the first command-line argument at args[0], the second at args[1], the third at args[2], and so on." }, { "code": null, "e": 1169, "s": 1155, "text": "Illustration:" }, { "code": null, "e": 1174, "s": 1169, "text": "Java" }, { "code": "// Java Program to Illustrate First Argument // Classclass GFG { // Main driver method public static void main(String[] args) { // Printing the first argument System.out.println(args[0]); }}", "e": 1392, "s": 1174, "text": null }, { "code": null, "e": 1400, "s": 1392, "text": "Output:" }, { "code": null, "e": 1418, "s": 1402, "text": "Implementation:" }, { "code": null, "e": 1681, "s": 1418, "text": "If we run a Java Program by writing the command “java Hello Geeks At GeeksForGeeks” where the name of the class is “Hello”, then it will run up to Hello. It is a command up to “Hello” and after that i.e “Geeks At GeeksForGeeks”, these are command-line arguments." }, { "code": null, "e": 1690, "s": 1681, "text": "Example:" }, { "code": null, "e": 1695, "s": 1690, "text": "Java" }, { "code": "// Java Program to Check for Command Line Arguments // Classclass GFG { // Main driver method public static void main(String[] args) { // Checking if length of args array is // greater than 0 if (args.length > 0) { // Print statements System.out.println(\"The command line\" + \" arguments are:\"); // Iterating the args array // using for each loop for (String val : args) // Printing command line arguments System.out.println(val); } else // Print statements System.out.println(\"No command line \" + \"arguments found.\"); }}", "e": 2437, "s": 1695, "text": null }, { "code": null, "e": 2470, "s": 2437, "text": "No command line arguments found." }, { "code": null, "e": 2595, "s": 2470, "text": "Steps to Run the Above Program are: To compile and run a java program in the command prompt, follow the steps written below." }, { "code": null, "e": 2626, "s": 2595, "text": "Save the program as Hello.java" }, { "code": null, "e": 2699, "s": 2626, "text": "Open the command prompt window and compile the program- javac Hello.java" }, { "code": null, "e": 2809, "s": 2699, "text": "After a successful compilation of the program, run the following command by writing the arguments- java Hello" }, { "code": null, "e": 2857, "s": 2809, "text": "For example – java Hello Geeks at GeeksforGeeks" }, { "code": null, "e": 2906, "s": 2857, "text": "Press Enter and you will get the desired output." }, { "code": null, "e": 2914, "s": 2906, "text": "Output:" }, { "code": null, "e": 3340, "s": 2914, "text": "This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 3352, "s": 3340, "text": "pujasingg43" }, { "code": null, "e": 3368, "s": 3352, "text": "nishkarshgandhi" }, { "code": null, "e": 3382, "s": 3368, "text": "solankimayank" }, { "code": null, "e": 3399, "s": 3382, "text": "leelamahanthalla" }, { "code": null, "e": 3409, "s": 3399, "text": "aekansh53" }, { "code": null, "e": 3414, "s": 3409, "text": "Java" }, { "code": null, "e": 3419, "s": 3414, "text": "Java" } ]
Top 10 Cybersecurity Challenges in 2021
15 Jun, 2021 Cybersecurity is something that can help organizations grow their businesses competitively. There is an enormous potential in cybersecurity through which the small and medium businesses i.e. SMBs can confidently maintain their reputation plus prevent themselves from viruses and other malicious cyberattacks. And they need not ignore this!! The reason is that the information security market will grow to 170.4 billion dollars in 2022 (according to Gartner’s research). Such an upward projection is sufficient to make the organizations, consisting of small and mid-sized workforces, forcefully think about the solutions and the vulnerable challenges which are lying in the realms of cybersecurity. Not only them but the customers including us which are connected with their services are also affected by those critical challenges. If we and those businesses fail to identify the real-time solutions to cyber-world challenges, then we all will be in the trap of those 95% cybersecurity breaches (as per Cybint) generally caused by the error of human beings. Undoubtedly, there are some challenges that may emerge at times those businesses are offering services to the customers through security established by cyber networks. Such challenges are still not known, and it could be possible that they may heighten the difficulties of the renowned decision-makers. Let’s take a look at the top 10 biggest cybersecurity challenges which if dealt with appropriate solutions, can possibly help those small or bigger organizations overcome the board-level data breaches in the pandemic era. 5G network is something that is making the youth more curious. This is because it will let the current generation use their beloved gadgets more efficiently. But here arises a problem – the generation will be the victim of either the emotional or physical attacks. Such attacks will be from the side of cyber assaulters who will unlawfully enter the 5G wireless networks comprising complex architectures via various endpoints and misuse the data collected or stored by the smart plus speedy gadgets. Primarily, those attackers would be the third parties who have choked the necks of telecommunications departments with their revolutionary marketing steps. Till 2027, the 5G infrastructure market may reach 47.775 Million US Dollars with the rising demand for M2M connections. Thus, this is essential to identify the identities of third-party assaulters who are in a constant journey of taking unauthorized access to the users’ data and then, violating the privacy and trust towards the reliable and customer-centric organizations they are engaged with. Mobile malware is harmful software that can intentionally target the operating systems of mobiles and then, disturb their performances. The prime reason for its occurrence – non-secure usage of URLs over Wi-Fi or other internet networks. As per the 2021 Mobile Security Report, threats related to mobile malware are faced by 97% of organizations from different vendors claiming to offer next-level security to the existing cellular networks. And we can’t ignore such vendors because they will be inheriting Trojan activities, cyber-risks, and some vulnerabilities associated with them. Moreover, such an increasing rate of malware attacks over the existing mobile phones has become the pandemic theme of the COVID-19 times. Various packages naming tousanticovid.apk, covid.apk, covidMappia_v1.0.3.apk, covidMapv8.1.7.apk, and coviddetect.apk are hidden in various applications of banking. And when those applications are dropped on malicious websites and the associated hyperlinks, they have started coating the mobile users with spam and other cybersecurity attacks. Undoubtedly, the number will increase in the coming times because the masses are moving towards the remote working era and here, cybercriminals will be running their malware attack campaigns as this is and will be their assured resorts. Nowadays, healthcare industries and supply chain departments are adopting tools that support Artificial Intelligence. Also, those tools have some glimpses of Machine Learning and NLP with which they are helpful in controlling the datasets primarily involved with patients’ info or orders in which retailers/distributors are interested. As per the McKinsey report, more than 25 percent of healthcare organizations are investing in AI tools in this COVID-age. Even the banking sector has an impact of more than 30 percent of the analytics derived via AI/ML tools. Source: https://www.mckinsey.com/featured-insights/artificial-intelligence/notes-from-the-ai-frontier-applications-and-value-of-deep-learning# The main loophole in using those Artificial Intelligent tools is that passwords and biometric logins are modified frequently by the patients, distributors, and other participants of the supply chain. With that, hackers can feasibly pick the pain points thereby controlling the monitoring of details like address, bank details, etc. Since AI tools perform at minimal human input in real-times, healthcare and supply chain industries are sensing attacks of malware, ransomware strongly destroying their incentivize growth. No doubt, cybercriminals will be involved with data violence so that they can continuously gain access to that sensitive data for targeting more patients or supply chain participants. The usage of Internet-of-Things devices is trending nowadays because of their robust reaction-time and the lesser cost they invite in processing the merits of the cloud technology. Furthermore, the solutions those devices push through their communication channels are incredible and considered by organizations comprising a varying number of workforces. However, with such growing popularity, cybercrimes are increasing continuously. This is because cybercriminals can expose the profitable assets whose data is accessed from some industrial cloud network. In 2021, the IoT market has reached the potential of 418 billion US dollars, and we may expect it to grow to around 1.567 trillion USD by 2025. Source: https://www.statista.com/statistics/976313/global-iot-market-size/ All this is known to professional attackers primarily involved with selling the stolen data or acquiring control over the expanding operations of the businesses. With no hesitations, hackers are outwardly weaponizing the growing IoT popularity by destroying the channel nodes inviting prosperity plus the legitimate sales traffic for the organizations. In this process, the protocols of cybersecurity maintaining and protecting the valuable data of customers have now become prominent to vulnerability. Ransomware attacks are directly or indirectly becoming unpredictable predictions for small or medium businesses. With no hesitations, those attacks are also impacting the larger organizations having proper knowledge of data violence and other compliance standards. As per the Check Point Research, the percentage of ransomware attacks has gone up to 102 in 2021 across the globe and our country has got impacted the most by 213 attacks weekly. You may think about what happens in those attacks! In them, cybercriminals send malware or other viruses to your phones or the cellular networks you use currently. This infects the devices like mobiles, laptops you are connected with and then, all your personal info is accessed by such assaulters. Now, no one can stop those online criminals from asking you ransom (amount asked for releasing the captive) and they will be harassing you for that! Over 1000 organizations are impacted weekly due to those ransomware attacks and the number will go up if organizations aren’t skillful enough in strengthening their cybersecurity models or preventing their business aspects from being targeted by those online criminals. Spear-phishing attacks will easily be understood once we understand what phishing attacks are basically? So, phishing is somewhere related to social media and the cybercriminals prefer those phishing attacks because this helps them gather your card details (credit/debit), current location, or other sensitive info. Such attackers use deceptive emails or websites and show them in such a manner they look legitimate. Spear-phishing, on the other hand, is a sub-part of phishing and is its more sophisticated version. Here, online fraudulent send malicious emails, and they are sent to well-researched victims (such victims are analyzed well by the cyberattackers on the grounds of mental and emotional strengths). According to the 2021 investigation report of Verizon, 29,207 real-time security incidents were analyzed and 5,285 were confirmed data breaches. Out of these, 36 percent of breaches involve phishing which is increased by 11 percent from the previous year. And if we talk about spear-phishing attacks, the number is actually not mentioned, but there is a discussion about credential stuffing. Approximately 95 percent of organizations suffered such stuffing which is a spear-phishing attack. And the percentage of related breaches is 61. Source: https://www.verizon.com/business/resources/reports/dbir/ The frequency of percentage will vary industry-by-industry but the thing which will be common is sending malicious emails and attempting to access personal data through spammed websites. Besides, there are some social media cybersecurity challenges like acquiring control over the customers’ accounts, phishing various campaigns running on social platforms like Facebook, Twitter, and misuse of data which is potentially important. All around the world, people are highly engaged with such social media channels primarily demanding internet services. This has made our privacy vulnerable to phishers or spear phishers, and they can confidently plan a series of events in hacking or destroying our personal wealth. With those events, hackers would be navigating various sections of our personal Facebook or Twitter accounts and take advantage of such demonstrated weakness. And all this has created a sound disturbance in the security of social media infrastructure. Depending upon the scope of disturbance, phishing/spear-phishing attacks offer destruction to the privacy of user’s data and the cybersecurity models of businesses too. Therefore, the issues, caused by destruction like third party social media operators supporting the tactics of cybercriminals, no close inspection of phishing emails at the users’ accounts, violation of the right to information since users aren’t aware of how their security is unknowingly compromised, are challenging the cybersecurity protocols of the organizations which need to modeled with proper control and strengthened compliance standards. Hacktivism is a combination of words Hack N Activism. In general, this is done with the purpose of breaking into someone’s computer and steal that information that supports political or social agendas in the wrong way. The target of hacktivists is primarily to gain their visibility on the websites of government organizations and deface their security protocols by promoting their politically influenced cause. According to the 2021 IBM X-Force report, there was 25 percent of data thefts and leak attacks (in 2020) in which hacktivists have demonstrated their interest in seeking data of multi-national corporations and the government bodies connected with them. No matter what the intention of the hacktivists was, but such criminal attacks are a slap to government organizations taking care of the assets of their customers. With this, a sort of motivation for challenging governments or forcing them to go against their morals is unknowingly promoted. There are many anonymous hacktivist groups working (since 2008) against disturbing the internal business processes of government or multinational organizations in the name of public welfare. They mix with the C-Level executives and continue embarrassing the government through the ideology of taking revenge with their online campaigns supporting regular flow DDoS attacks. This is a newer version of breaking into cybersecurity systems of the government so that the protests of hacktivists may spread throughout the world and launch a shuttle of defacement of the reputation immorally. Dronejacking is a way through which cybercriminals are using a toy-like drone and easily taking control over personal information. According to the report of Intel, Drones have targeted deliveries, camera crews, and some hobbyists for knocking out the enforced security law standards. Though drones are a major tool for farmers, photographers, shippers, and some law enforcement agencies, yet they seem to be a new wave of cyber threats. With dronejacking, cybercriminals with their malicious intent can potentially offer financial destruction to the companies like Amazon and UPS who are known for supplying essentials to their customers. Via dronejack, hackers can easily determine how many packages will be delivered to how many customers? All this may be done for fun sometimes, but the aftereffects are really threatening as this is a direct attack on the security compliance of the organizations focusing on consumer’s success and their overall popularity in a positive way. Apart from all this, variable risks are there like loss of expensive drones, destruction of private property (commercial airplanes) with which the hackers can easily detect the response time and capabilities of the hardware controller driving those drones. If the commercial operators and cybersecurity teams of bigger organizations won’t stay themselves tuned about the latest security software and vigilant protection solutions, they will continue to bear the losses of drone attacks and become the easy targets of such criminals anonymously. Social engineering is concerned with a type of cyberattacks where hackers focus on tricks and non-tech strategies rather than using core tech approaches or tools to trap the users. There are some preventive measures associated, and they are setting the spam filters from low to high, instant denial or deletion of help requests, researching the sources of unsolicited emails, and many more. However, hackers are sophisticated nowadays and understand the frequency with which we are adopting such measures. They can feasibly take the legitimate access to our personal info and then, exploit us really well on the grounds of personality weaknesses. As per the report of Google, most of the SEAs or Social Engineering attacks are phishing via official emails or malicious websites which almost look authentic. Source: https://link.springer.com/article/10.1007/s42979-020-00443-1 In this graph, there are a number of accounts up to 5000 flagged by Google, and they are trapped by the phishing attacks initiated by government-backed attackers. The number of attacks seems to fluctuate, yet it is clear that such SEAs are tracking our communications done through instant messaging or video conferencing. Furthermore, many of the knowledge-based workers, business owners, artisans (the number is near to 260 million) are remotely working in this pandemic era and this has made them vulnerable to such Social Engineering Attacks. Those cyber-attackers can smartly deploy multiple tactics for entering into their sensitive information like passwords, usernames, and banking details. All this will look legitimate as they will be using trademarks, logos of the well-known companies whose accuracy will be 99 percent or a little higher. As soon as their websites and emails are clicked, you will be tricked and then, the height of your awareness is primarily destroyed. Furthermore, the organizations are also prone to such steals as hackers are easily breaking their business software backed by systems adhering to cybersecurity protocols. So, the security of their infrastructure is inclined towards the likelihood of success of these cybercriminals well-versed with how they should be using the preventive measures of social engineering for deploying their malicious agendas? Internal politics is something that everyone is aware of and this happens in every organization. Whether you talk about a tech-giant or a well-reputed automation agency, employees are assigned with some privileges and this makes the finances vulnerable to huge losses. All this gives rise to insider threats. They have grown up by 47 percent in the past 2 years and successfully inviting cybercriminals to nourish their fraudulent activities well. More than 34 percent of businesses are affected every year by such threats and this is giving the way to accidental breaches for breaking the trust and reputation of customers. Those insider threats are underestimated by the businesses a lot as they think it is important for them to deal with the complex market trends rather than giving such threats a look! All this disturbs the current status of a company as their employees have signed some deals with hackers for providing them the important information about the company. Later, those cyber criminals infect the security systems of organizations well which are managing the business complexities well in this second layer. If the organizations keep on underestimating them and keep on delaying in limiting the privileges, then it would be difficult for them to put a halt to the destructive and careless behavior of their employees somewhere challenging the pre-established secure protocols of cybersecurity. GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jun, 2021" }, { "code": null, "e": 1610, "s": 28, "text": "Cybersecurity is something that can help organizations grow their businesses competitively. There is an enormous potential in cybersecurity through which the small and medium businesses i.e. SMBs can confidently maintain their reputation plus prevent themselves from viruses and other malicious cyberattacks. And they need not ignore this!! The reason is that the information security market will grow to 170.4 billion dollars in 2022 (according to Gartner’s research). Such an upward projection is sufficient to make the organizations, consisting of small and mid-sized workforces, forcefully think about the solutions and the vulnerable challenges which are lying in the realms of cybersecurity. Not only them but the customers including us which are connected with their services are also affected by those critical challenges. If we and those businesses fail to identify the real-time solutions to cyber-world challenges, then we all will be in the trap of those 95% cybersecurity breaches (as per Cybint) generally caused by the error of human beings. Undoubtedly, there are some challenges that may emerge at times those businesses are offering services to the customers through security established by cyber networks. Such challenges are still not known, and it could be possible that they may heighten the difficulties of the renowned decision-makers. Let’s take a look at the top 10 biggest cybersecurity challenges which if dealt with appropriate solutions, can possibly help those small or bigger organizations overcome the board-level data breaches in the pandemic era." }, { "code": null, "e": 2663, "s": 1610, "text": "5G network is something that is making the youth more curious. This is because it will let the current generation use their beloved gadgets more efficiently. But here arises a problem – the generation will be the victim of either the emotional or physical attacks. Such attacks will be from the side of cyber assaulters who will unlawfully enter the 5G wireless networks comprising complex architectures via various endpoints and misuse the data collected or stored by the smart plus speedy gadgets. Primarily, those attackers would be the third parties who have choked the necks of telecommunications departments with their revolutionary marketing steps. Till 2027, the 5G infrastructure market may reach 47.775 Million US Dollars with the rising demand for M2M connections. Thus, this is essential to identify the identities of third-party assaulters who are in a constant journey of taking unauthorized access to the users’ data and then, violating the privacy and trust towards the reliable and customer-centric organizations they are engaged with." }, { "code": null, "e": 3970, "s": 2663, "text": "Mobile malware is harmful software that can intentionally target the operating systems of mobiles and then, disturb their performances. The prime reason for its occurrence – non-secure usage of URLs over Wi-Fi or other internet networks. As per the 2021 Mobile Security Report, threats related to mobile malware are faced by 97% of organizations from different vendors claiming to offer next-level security to the existing cellular networks. And we can’t ignore such vendors because they will be inheriting Trojan activities, cyber-risks, and some vulnerabilities associated with them. Moreover, such an increasing rate of malware attacks over the existing mobile phones has become the pandemic theme of the COVID-19 times. Various packages naming tousanticovid.apk, covid.apk, covidMappia_v1.0.3.apk, covidMapv8.1.7.apk, and coviddetect.apk are hidden in various applications of banking. And when those applications are dropped on malicious websites and the associated hyperlinks, they have started coating the mobile users with spam and other cybersecurity attacks. Undoubtedly, the number will increase in the coming times because the masses are moving towards the remote working era and here, cybercriminals will be running their malware attack campaigns as this is and will be their assured resorts. " }, { "code": null, "e": 4534, "s": 3970, "text": "Nowadays, healthcare industries and supply chain departments are adopting tools that support Artificial Intelligence. Also, those tools have some glimpses of Machine Learning and NLP with which they are helpful in controlling the datasets primarily involved with patients’ info or orders in which retailers/distributors are interested. As per the McKinsey report, more than 25 percent of healthcare organizations are investing in AI tools in this COVID-age. Even the banking sector has an impact of more than 30 percent of the analytics derived via AI/ML tools. " }, { "code": null, "e": 4677, "s": 4534, "text": "Source: https://www.mckinsey.com/featured-insights/artificial-intelligence/notes-from-the-ai-frontier-applications-and-value-of-deep-learning#" }, { "code": null, "e": 5382, "s": 4677, "text": "The main loophole in using those Artificial Intelligent tools is that passwords and biometric logins are modified frequently by the patients, distributors, and other participants of the supply chain. With that, hackers can feasibly pick the pain points thereby controlling the monitoring of details like address, bank details, etc. Since AI tools perform at minimal human input in real-times, healthcare and supply chain industries are sensing attacks of malware, ransomware strongly destroying their incentivize growth. No doubt, cybercriminals will be involved with data violence so that they can continuously gain access to that sensitive data for targeting more patients or supply chain participants." }, { "code": null, "e": 6085, "s": 5382, "text": "The usage of Internet-of-Things devices is trending nowadays because of their robust reaction-time and the lesser cost they invite in processing the merits of the cloud technology. Furthermore, the solutions those devices push through their communication channels are incredible and considered by organizations comprising a varying number of workforces. However, with such growing popularity, cybercrimes are increasing continuously. This is because cybercriminals can expose the profitable assets whose data is accessed from some industrial cloud network. In 2021, the IoT market has reached the potential of 418 billion US dollars, and we may expect it to grow to around 1.567 trillion USD by 2025. " }, { "code": null, "e": 6160, "s": 6085, "text": "Source: https://www.statista.com/statistics/976313/global-iot-market-size/" }, { "code": null, "e": 6663, "s": 6160, "text": "All this is known to professional attackers primarily involved with selling the stolen data or acquiring control over the expanding operations of the businesses. With no hesitations, hackers are outwardly weaponizing the growing IoT popularity by destroying the channel nodes inviting prosperity plus the legitimate sales traffic for the organizations. In this process, the protocols of cybersecurity maintaining and protecting the valuable data of customers have now become prominent to vulnerability." }, { "code": null, "e": 7827, "s": 6663, "text": "Ransomware attacks are directly or indirectly becoming unpredictable predictions for small or medium businesses. With no hesitations, those attacks are also impacting the larger organizations having proper knowledge of data violence and other compliance standards. As per the Check Point Research, the percentage of ransomware attacks has gone up to 102 in 2021 across the globe and our country has got impacted the most by 213 attacks weekly. You may think about what happens in those attacks! In them, cybercriminals send malware or other viruses to your phones or the cellular networks you use currently. This infects the devices like mobiles, laptops you are connected with and then, all your personal info is accessed by such assaulters. Now, no one can stop those online criminals from asking you ransom (amount asked for releasing the captive) and they will be harassing you for that! Over 1000 organizations are impacted weekly due to those ransomware attacks and the number will go up if organizations aren’t skillful enough in strengthening their cybersecurity models or preventing their business aspects from being targeted by those online criminals. " }, { "code": null, "e": 9078, "s": 7827, "text": "Spear-phishing attacks will easily be understood once we understand what phishing attacks are basically? So, phishing is somewhere related to social media and the cybercriminals prefer those phishing attacks because this helps them gather your card details (credit/debit), current location, or other sensitive info. Such attackers use deceptive emails or websites and show them in such a manner they look legitimate. Spear-phishing, on the other hand, is a sub-part of phishing and is its more sophisticated version. Here, online fraudulent send malicious emails, and they are sent to well-researched victims (such victims are analyzed well by the cyberattackers on the grounds of mental and emotional strengths). According to the 2021 investigation report of Verizon, 29,207 real-time security incidents were analyzed and 5,285 were confirmed data breaches. Out of these, 36 percent of breaches involve phishing which is increased by 11 percent from the previous year. And if we talk about spear-phishing attacks, the number is actually not mentioned, but there is a discussion about credential stuffing. Approximately 95 percent of organizations suffered such stuffing which is a spear-phishing attack. And the percentage of related breaches is 61." }, { "code": null, "e": 9143, "s": 9078, "text": "Source: https://www.verizon.com/business/resources/reports/dbir/" }, { "code": null, "e": 10729, "s": 9143, "text": "The frequency of percentage will vary industry-by-industry but the thing which will be common is sending malicious emails and attempting to access personal data through spammed websites. Besides, there are some social media cybersecurity challenges like acquiring control over the customers’ accounts, phishing various campaigns running on social platforms like Facebook, Twitter, and misuse of data which is potentially important. All around the world, people are highly engaged with such social media channels primarily demanding internet services. This has made our privacy vulnerable to phishers or spear phishers, and they can confidently plan a series of events in hacking or destroying our personal wealth. With those events, hackers would be navigating various sections of our personal Facebook or Twitter accounts and take advantage of such demonstrated weakness. And all this has created a sound disturbance in the security of social media infrastructure. Depending upon the scope of disturbance, phishing/spear-phishing attacks offer destruction to the privacy of user’s data and the cybersecurity models of businesses too. Therefore, the issues, caused by destruction like third party social media operators supporting the tactics of cybercriminals, no close inspection of phishing emails at the users’ accounts, violation of the right to information since users aren’t aware of how their security is unknowingly compromised, are challenging the cybersecurity protocols of the organizations which need to modeled with proper control and strengthened compliance standards. " }, { "code": null, "e": 12276, "s": 10729, "text": "Hacktivism is a combination of words Hack N Activism. In general, this is done with the purpose of breaking into someone’s computer and steal that information that supports political or social agendas in the wrong way. The target of hacktivists is primarily to gain their visibility on the websites of government organizations and deface their security protocols by promoting their politically influenced cause. According to the 2021 IBM X-Force report, there was 25 percent of data thefts and leak attacks (in 2020) in which hacktivists have demonstrated their interest in seeking data of multi-national corporations and the government bodies connected with them. No matter what the intention of the hacktivists was, but such criminal attacks are a slap to government organizations taking care of the assets of their customers. With this, a sort of motivation for challenging governments or forcing them to go against their morals is unknowingly promoted. There are many anonymous hacktivist groups working (since 2008) against disturbing the internal business processes of government or multinational organizations in the name of public welfare. They mix with the C-Level executives and continue embarrassing the government through the ideology of taking revenge with their online campaigns supporting regular flow DDoS attacks. This is a newer version of breaking into cybersecurity systems of the government so that the protests of hacktivists may spread throughout the world and launch a shuttle of defacement of the reputation immorally. " }, { "code": null, "e": 13804, "s": 12276, "text": "Dronejacking is a way through which cybercriminals are using a toy-like drone and easily taking control over personal information. According to the report of Intel, Drones have targeted deliveries, camera crews, and some hobbyists for knocking out the enforced security law standards. Though drones are a major tool for farmers, photographers, shippers, and some law enforcement agencies, yet they seem to be a new wave of cyber threats. With dronejacking, cybercriminals with their malicious intent can potentially offer financial destruction to the companies like Amazon and UPS who are known for supplying essentials to their customers. Via dronejack, hackers can easily determine how many packages will be delivered to how many customers? All this may be done for fun sometimes, but the aftereffects are really threatening as this is a direct attack on the security compliance of the organizations focusing on consumer’s success and their overall popularity in a positive way. Apart from all this, variable risks are there like loss of expensive drones, destruction of private property (commercial airplanes) with which the hackers can easily detect the response time and capabilities of the hardware controller driving those drones. If the commercial operators and cybersecurity teams of bigger organizations won’t stay themselves tuned about the latest security software and vigilant protection solutions, they will continue to bear the losses of drone attacks and become the easy targets of such criminals anonymously. " }, { "code": null, "e": 14611, "s": 13804, "text": "Social engineering is concerned with a type of cyberattacks where hackers focus on tricks and non-tech strategies rather than using core tech approaches or tools to trap the users. There are some preventive measures associated, and they are setting the spam filters from low to high, instant denial or deletion of help requests, researching the sources of unsolicited emails, and many more. However, hackers are sophisticated nowadays and understand the frequency with which we are adopting such measures. They can feasibly take the legitimate access to our personal info and then, exploit us really well on the grounds of personality weaknesses. As per the report of Google, most of the SEAs or Social Engineering attacks are phishing via official emails or malicious websites which almost look authentic." }, { "code": null, "e": 14680, "s": 14611, "text": "Source: https://link.springer.com/article/10.1007/s42979-020-00443-1" }, { "code": null, "e": 16072, "s": 14680, "text": "In this graph, there are a number of accounts up to 5000 flagged by Google, and they are trapped by the phishing attacks initiated by government-backed attackers. The number of attacks seems to fluctuate, yet it is clear that such SEAs are tracking our communications done through instant messaging or video conferencing. Furthermore, many of the knowledge-based workers, business owners, artisans (the number is near to 260 million) are remotely working in this pandemic era and this has made them vulnerable to such Social Engineering Attacks. Those cyber-attackers can smartly deploy multiple tactics for entering into their sensitive information like passwords, usernames, and banking details. All this will look legitimate as they will be using trademarks, logos of the well-known companies whose accuracy will be 99 percent or a little higher. As soon as their websites and emails are clicked, you will be tricked and then, the height of your awareness is primarily destroyed. Furthermore, the organizations are also prone to such steals as hackers are easily breaking their business software backed by systems adhering to cybersecurity protocols. So, the security of their infrastructure is inclined towards the likelihood of success of these cybercriminals well-versed with how they should be using the preventive measures of social engineering for deploying their malicious agendas?" }, { "code": null, "e": 16520, "s": 16072, "text": "Internal politics is something that everyone is aware of and this happens in every organization. Whether you talk about a tech-giant or a well-reputed automation agency, employees are assigned with some privileges and this makes the finances vulnerable to huge losses. All this gives rise to insider threats. They have grown up by 47 percent in the past 2 years and successfully inviting cybercriminals to nourish their fraudulent activities well." }, { "code": null, "e": 17488, "s": 16520, "text": "More than 34 percent of businesses are affected every year by such threats and this is giving the way to accidental breaches for breaking the trust and reputation of customers. Those insider threats are underestimated by the businesses a lot as they think it is important for them to deal with the complex market trends rather than giving such threats a look! All this disturbs the current status of a company as their employees have signed some deals with hackers for providing them the important information about the company. Later, those cyber criminals infect the security systems of organizations well which are managing the business complexities well in this second layer. If the organizations keep on underestimating them and keep on delaying in limiting the privileges, then it would be difficult for them to put a halt to the destructive and careless behavior of their employees somewhere challenging the pre-established secure protocols of cybersecurity. " }, { "code": null, "e": 17494, "s": 17488, "text": "GBlog" } ]
Difference between BSS and ESS
10 Nov, 2020 1. Basic Service Set (BSS) :Basic Service Set (BSS), as name suggests, is a group or set of all stations that communicate with each together. Here, stations are considered as computers or components connected to wired network. 2. Extended Service Set (ESS) :Extended Service Set (ESS), as name suggests, is a group of BSSs or one or more interconnected BSS along with their wired network. Difference between BSS and ESS : Computer Networks Difference Between Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Nov, 2020" }, { "code": null, "e": 255, "s": 28, "text": "1. Basic Service Set (BSS) :Basic Service Set (BSS), as name suggests, is a group or set of all stations that communicate with each together. Here, stations are considered as computers or components connected to wired network." }, { "code": null, "e": 417, "s": 255, "text": "2. Extended Service Set (ESS) :Extended Service Set (ESS), as name suggests, is a group of BSSs or one or more interconnected BSS along with their wired network." }, { "code": null, "e": 450, "s": 417, "text": "Difference between BSS and ESS :" }, { "code": null, "e": 468, "s": 450, "text": "Computer Networks" }, { "code": null, "e": 487, "s": 468, "text": "Difference Between" }, { "code": null, "e": 505, "s": 487, "text": "Computer Networks" }, { "code": null, "e": 603, "s": 505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 633, "s": 603, "text": "GSM in Wireless Communication" }, { "code": null, "e": 659, "s": 633, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 689, "s": 659, "text": "Wireless Application Protocol" }, { "code": null, "e": 729, "s": 689, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 764, "s": 729, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 804, "s": 764, "text": "Class method vs Static method in Python" }, { "code": null, "e": 835, "s": 804, "text": "Difference between BFS and DFS" }, { "code": null, "e": 896, "s": 835, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 964, "s": 896, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
Python | math.tan() function
20 Mar, 2019 In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.tan() function returns the tangent of value passed as argument. The value passed in this function should be in radians. Syntax: math.tan(x) Parameter:x : value to be passed to tan() Returns: Returns the tangent of value passed as argument Code #1: # Python code to demonstrate the working of tan() # importing "math" for mathematical operations import math a = math.pi / 6 # returning the value of tangent of pi / 6 print ("The value of tangent of pi / 6 is : ", end ="") print (math.tan(a)) Code #2: # Python program showing # Graphical representation of # tan() function import mathimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(0, np.pi, 10) out_array = [] for i in range(len(in_array)): out_array.append(math.tan(in_array[i])) i += 1 print("in_array : ", in_array) print("\nout_array : ", out_array) # red for numpy.sin() plt.plot(in_array, out_array, color = 'red', marker = "o") plt.title("math.tan()") plt.xlabel("X") plt.ylabel("Y") plt.show() in_array : [0. 0.34906585 0.6981317 1.04719755 1.3962634 1.745329252.0943951 2.44346095 2.7925268 3.14159265] out_array : [0.0, 0.36397023426620234, 0.8390996311772799, 1.7320508075688767, 5.671281819617707, -5.671281819617711, -1.7320508075688783, -0.8390996311772804, -0.36397023426620256, -1.2246467991473532e-16] Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Mar, 2019" }, { "code": null, "e": 273, "s": 28, "text": "In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.tan() function returns the tangent of value passed as argument. The value passed in this function should be in radians." }, { "code": null, "e": 293, "s": 273, "text": "Syntax: math.tan(x)" }, { "code": null, "e": 335, "s": 293, "text": "Parameter:x : value to be passed to tan()" }, { "code": null, "e": 392, "s": 335, "text": "Returns: Returns the tangent of value passed as argument" }, { "code": null, "e": 401, "s": 392, "text": "Code #1:" }, { "code": "# Python code to demonstrate the working of tan() # importing \"math\" for mathematical operations import math a = math.pi / 6 # returning the value of tangent of pi / 6 print (\"The value of tangent of pi / 6 is : \", end =\"\") print (math.tan(a)) ", "e": 658, "s": 401, "text": null }, { "code": null, "e": 668, "s": 658, "text": " Code #2:" }, { "code": "# Python program showing # Graphical representation of # tan() function import mathimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(0, np.pi, 10) out_array = [] for i in range(len(in_array)): out_array.append(math.tan(in_array[i])) i += 1 print(\"in_array : \", in_array) print(\"\\nout_array : \", out_array) # red for numpy.sin() plt.plot(in_array, out_array, color = 'red', marker = \"o\") plt.title(\"math.tan()\") plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.show() ", "e": 1163, "s": 668, "text": null }, { "code": null, "e": 1273, "s": 1163, "text": "in_array : [0. 0.34906585 0.6981317 1.04719755 1.3962634 1.745329252.0943951 2.44346095 2.7925268 3.14159265]" }, { "code": null, "e": 1480, "s": 1273, "text": "out_array : [0.0, 0.36397023426620234, 0.8390996311772799, 1.7320508075688767, 5.671281819617707, -5.671281819617711, -1.7320508075688783, -0.8390996311772804, -0.36397023426620256, -1.2246467991473532e-16]" }, { "code": null, "e": 1510, "s": 1480, "text": "Python math-library-functions" }, { "code": null, "e": 1517, "s": 1510, "text": "Python" }, { "code": null, "e": 1615, "s": 1517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1633, "s": 1615, "text": "Python Dictionary" }, { "code": null, "e": 1675, "s": 1633, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1697, "s": 1675, "text": "Enumerate() in Python" }, { "code": null, "e": 1732, "s": 1697, "text": "Read a file line by line in Python" }, { "code": null, "e": 1758, "s": 1732, "text": "Python String | replace()" }, { "code": null, "e": 1790, "s": 1758, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1819, "s": 1790, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1846, "s": 1819, "text": "Python Classes and Objects" }, { "code": null, "e": 1876, "s": 1846, "text": "Iterate over a list in Python" } ]
Understanding ShellExecute function and it’s application to open a list of URLs present in a file using C++ code
07 Jul, 2017 Given a URL as a string open it using a C++ code in Microsoft Windows OS.Example: Input : https://www.geeksforgeeks.org/ Output : The site opened in your browser. // C++ program to open a URL in browser.// This program is written on for Microsoft// Windows OS#include <bits/stdc++.h>#include <windows.h>using namespace std; int main(){ char url[100] = "http:// www.geeksforgeeks.org/"; ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); return 0;} Output: GeeksforGeeks site opened in Google Chrome in a new tab. ShellExecute is the code equivalent of a user double clicking a file icon. It causes Windows to work out what application the document file is associated with, launch the program and have it load the document file. By using ShellExecute, you don’t need to know the name or location of the program that’s registered to a particular file type. Windows takes care of that for you. For example, you can ShellExecute a .PDF file and, so long as Reader, Acrobat or some other PDF-reading app is installed, Windows will launch it and load the PDF for you. Parameters of ShellExecute and their meaning: HINSTANCE ShellExecute (_In_opt_ HWND hwnd,_In_opt_ LPCTSTR lpOperation,_In_ LPCTSTR lpFile,_In_opt_ LPCTSTR lpParameters,_In_opt_ LPCTSTR lpDirectory,_In_ INT nShowCmd); Parameters: Type: HWND A handle to the parent window used for displaying a UI or error messages. This value can be NULL if the operation is not associated with a window. Type: LPCTSTR A pointer to a null-terminated string, referred to in this case as a verb, that specifies the action to be performed. The set of available verbs depends on the particular file or folder. Generally, the actions available from an object’s shortcut menu are available verbs. In our case ‘open’ is used which opens the item specified by the lpFile parameter. The item can be a file or folder. Type: LPCTSTRA pointer to a null-terminated string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the “print” verb. If a relative path is used for the lpDirectory parameter do not use a relative path for lpFile. In our case it’s an array of characters ‘url’ on which the operation is executed. Type: LPCTSTRIf lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL. Type: LPCTSTRA pointer to a null-terminated string that specifies the default (working) directory for the action. If this value is NULL, the current working directory is used. If a relative path is provided at lpFile, do not use a relative path for lpDirectory. Type: INTThe flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it. These values are defined in Winuser.h. In our case SW_SHOWNORMAL is used which activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time. Return valueType: HINSTANCEIf the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Windows applications. It is not a true HINSTANCE, however. Example: Input : A list of URLs stored in a text file. Output : All the URLs opened in different tabs. // C++ program to list URLs in a text file and// open them.// This program is written only for Microsoft// Windows OS#include <bits/stdc++.h>#include <windows.h>using namespace std; int main(){ long long int s, i, x, c = 0; char temp[1000]; // Name of the text file which contains all the // URLs separated by end line. ifstream all_lines("urls.txt"); string line; // To get each line of the file as a string. while (getline(all_lines, line, 'n')) { x = 0; // For getting each character of a string. s = line.size(); // Measuring size of each string. // Here we limit number of tabs to 10, we can // change the value of c according to your // requirement. for (i = 0; i <= s && c < 10; i++) { if (line[i] != 't' && line[i] != '\0') { temp[x] = line[i]; x++; } else { temp[x] = '\0'; ShellExecute(NULL, "open", temp, NULL, NULL, SW_SHOWNORMAL); // Keeping a count of number of tabs // getting opened. c++; } } } system("pause"); return 0;} Output: List of all urls present in the urls.txt file opened in different tabs. Note: Run the above codes in some C++ editor like Codeblocks and the text file and the code should be present in the same folder. Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Polymorphism in C++ Queue in C++ Standard Template Library (STL) List in C++ Standard Template Library (STL) Command line arguments in C/C++ Exception Handling in C++ Operators in C / C++ Sorting a vector in C++ Destructors in C++ Power Function in C/C++ Pure Virtual Functions and Abstract Classes in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2017" }, { "code": null, "e": 136, "s": 54, "text": "Given a URL as a string open it using a C++ code in Microsoft Windows OS.Example:" }, { "code": null, "e": 218, "s": 136, "text": "Input : https://www.geeksforgeeks.org/\nOutput : The site opened in your browser.\n" }, { "code": "// C++ program to open a URL in browser.// This program is written on for Microsoft// Windows OS#include <bits/stdc++.h>#include <windows.h>using namespace std; int main(){ char url[100] = \"http:// www.geeksforgeeks.org/\"; ShellExecute(NULL, \"open\", url, NULL, NULL, SW_SHOWNORMAL); return 0;}", "e": 522, "s": 218, "text": null }, { "code": null, "e": 530, "s": 522, "text": "Output:" }, { "code": null, "e": 588, "s": 530, "text": "GeeksforGeeks site opened in Google Chrome in a new tab.\n" }, { "code": null, "e": 803, "s": 588, "text": "ShellExecute is the code equivalent of a user double clicking a file icon. It causes Windows to work out what application the document file is associated with, launch the program and have it load the document file." }, { "code": null, "e": 1137, "s": 803, "text": "By using ShellExecute, you don’t need to know the name or location of the program that’s registered to a particular file type. Windows takes care of that for you. For example, you can ShellExecute a .PDF file and, so long as Reader, Acrobat or some other PDF-reading app is installed, Windows will launch it and load the PDF for you." }, { "code": null, "e": 1183, "s": 1137, "text": "Parameters of ShellExecute and their meaning:" }, { "code": null, "e": 1354, "s": 1183, "text": "HINSTANCE ShellExecute (_In_opt_ HWND hwnd,_In_opt_ LPCTSTR lpOperation,_In_ LPCTSTR lpFile,_In_opt_ LPCTSTR lpParameters,_In_opt_ LPCTSTR lpDirectory,_In_ INT nShowCmd);" }, { "code": null, "e": 1366, "s": 1354, "text": "Parameters:" }, { "code": null, "e": 1377, "s": 1366, "text": "Type: HWND" }, { "code": null, "e": 1524, "s": 1377, "text": "A handle to the parent window used for displaying a UI or error messages. This value can be NULL if the operation is not associated with a window." }, { "code": null, "e": 1538, "s": 1524, "text": "Type: LPCTSTR" }, { "code": null, "e": 1927, "s": 1538, "text": "A pointer to a null-terminated string, referred to in this case as a verb, that specifies the action to be performed. The set of available verbs depends on the particular file or folder. Generally, the actions available from an object’s shortcut menu are available verbs. In our case ‘open’ is used which opens the item specified by the lpFile parameter. The item can be a file or folder." }, { "code": null, "e": 2420, "s": 1927, "text": "Type: LPCTSTRA pointer to a null-terminated string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the “print” verb. If a relative path is used for the lpDirectory parameter do not use a relative path for lpFile. In our case it’s an array of characters ‘url’ on which the operation is executed." }, { "code": null, "e": 2733, "s": 2420, "text": "Type: LPCTSTRIf lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL." }, { "code": null, "e": 2995, "s": 2733, "text": "Type: LPCTSTRA pointer to a null-terminated string that specifies the default (working) directory for the action. If this value is NULL, the current working directory is used. If a relative path is provided at lpFile, do not use a relative path for lpDirectory." }, { "code": null, "e": 3529, "s": 2995, "text": "Type: INTThe flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it. These values are defined in Winuser.h. In our case SW_SHOWNORMAL is used which activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time." }, { "code": null, "e": 3847, "s": 3529, "text": "Return valueType: HINSTANCEIf the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Windows applications. It is not a true HINSTANCE, however." }, { "code": null, "e": 3856, "s": 3847, "text": "Example:" }, { "code": null, "e": 3951, "s": 3856, "text": "Input : A list of URLs stored in a text file.\nOutput : All the URLs opened in different tabs.\n" }, { "code": "// C++ program to list URLs in a text file and// open them.// This program is written only for Microsoft// Windows OS#include <bits/stdc++.h>#include <windows.h>using namespace std; int main(){ long long int s, i, x, c = 0; char temp[1000]; // Name of the text file which contains all the // URLs separated by end line. ifstream all_lines(\"urls.txt\"); string line; // To get each line of the file as a string. while (getline(all_lines, line, 'n')) { x = 0; // For getting each character of a string. s = line.size(); // Measuring size of each string. // Here we limit number of tabs to 10, we can // change the value of c according to your // requirement. for (i = 0; i <= s && c < 10; i++) { if (line[i] != 't' && line[i] != '\\0') { temp[x] = line[i]; x++; } else { temp[x] = '\\0'; ShellExecute(NULL, \"open\", temp, NULL, NULL, SW_SHOWNORMAL); // Keeping a count of number of tabs // getting opened. c++; } } } system(\"pause\"); return 0;}", "e": 5186, "s": 3951, "text": null }, { "code": null, "e": 5194, "s": 5186, "text": "Output:" }, { "code": null, "e": 5267, "s": 5194, "text": "List of all urls present in the urls.txt file opened in different tabs.\n" }, { "code": null, "e": 5397, "s": 5267, "text": "Note: Run the above codes in some C++ editor like Codeblocks and the text file and the code should be present in the same folder." }, { "code": null, "e": 5488, "s": 5397, "text": "Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx" }, { "code": null, "e": 5788, "s": 5488, "text": "This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5913, "s": 5788, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5925, "s": 5913, "text": "CPP-Library" }, { "code": null, "e": 5929, "s": 5925, "text": "C++" }, { "code": null, "e": 5933, "s": 5929, "text": "CPP" }, { "code": null, "e": 6031, "s": 5933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6051, "s": 6031, "text": "Polymorphism in C++" }, { "code": null, "e": 6096, "s": 6051, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6140, "s": 6096, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 6172, "s": 6140, "text": "Command line arguments in C/C++" }, { "code": null, "e": 6198, "s": 6172, "text": "Exception Handling in C++" }, { "code": null, "e": 6219, "s": 6198, "text": "Operators in C / C++" }, { "code": null, "e": 6243, "s": 6219, "text": "Sorting a vector in C++" }, { "code": null, "e": 6262, "s": 6243, "text": "Destructors in C++" }, { "code": null, "e": 6286, "s": 6262, "text": "Power Function in C/C++" } ]
T-SQL - Date Functions
Following is the list of date functions in MS SQL Server. It will return the current date along with time. Syntax for the above function − GETDATE() The following query will return the current date along with time in MS SQL Server. Select getdate() as currentdatetime It will return the part of date or time. Syntax for the above function − DATEPART(datepart, datecolumnname) Example 1 − The following query will return the part of current date in MS SQL Server. Select datepart(day, getdate()) as currentdate Example 2 − The following query will return the part of current month in MS SQL Server. Select datepart(month, getdate()) as currentmonth It will display the date and time by add or subtract date and time interval. Syntax for the above function − DATEADD(datepart, number, datecolumnname) The following query will return the after 10 days date and time from the current date and time in MS SQL Server. Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime It will display the date and time between two dates. Syntax for the above function − DATEDIFF(datepart, startdate, enddate) The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server. Select datediff(hour, 2015-11-16, 2015-11-11) as differencehoursbetween20151116and20151111 It will display the date and time in different formats. Syntax for the above function − CONVERT(datatype, expression, style) The following queries will return the date and time in different format in MS SQL Server.
[ { "code": null, "e": 2252, "s": 2194, "text": "Following is the list of date functions in MS SQL Server." }, { "code": null, "e": 2301, "s": 2252, "text": "It will return the current date along with time." }, { "code": null, "e": 2333, "s": 2301, "text": "Syntax for the above function −" }, { "code": null, "e": 2344, "s": 2333, "text": "GETDATE()\n" }, { "code": null, "e": 2427, "s": 2344, "text": "The following query will return the current date along with time in MS SQL Server." }, { "code": null, "e": 2463, "s": 2427, "text": "Select getdate() as currentdatetime" }, { "code": null, "e": 2504, "s": 2463, "text": "It will return the part of date or time." }, { "code": null, "e": 2536, "s": 2504, "text": "Syntax for the above function −" }, { "code": null, "e": 2572, "s": 2536, "text": "DATEPART(datepart, datecolumnname)\n" }, { "code": null, "e": 2659, "s": 2572, "text": "Example 1 − The following query will return the part of current date in MS SQL Server." }, { "code": null, "e": 2706, "s": 2659, "text": "Select datepart(day, getdate()) as currentdate" }, { "code": null, "e": 2794, "s": 2706, "text": "Example 2 − The following query will return the part of current month in MS SQL Server." }, { "code": null, "e": 2844, "s": 2794, "text": "Select datepart(month, getdate()) as currentmonth" }, { "code": null, "e": 2921, "s": 2844, "text": "It will display the date and time by add or subtract date and time interval." }, { "code": null, "e": 2953, "s": 2921, "text": "Syntax for the above function −" }, { "code": null, "e": 2996, "s": 2953, "text": "DATEADD(datepart, number, datecolumnname)\n" }, { "code": null, "e": 3109, "s": 2996, "text": "The following query will return the after 10 days date and time from the current date and time in MS SQL Server." }, { "code": null, "e": 3187, "s": 3109, "text": "Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime " }, { "code": null, "e": 3240, "s": 3187, "text": "It will display the date and time between two dates." }, { "code": null, "e": 3272, "s": 3240, "text": "Syntax for the above function −" }, { "code": null, "e": 3312, "s": 3272, "text": "DATEDIFF(datepart, startdate, enddate)\n" }, { "code": null, "e": 3426, "s": 3312, "text": "The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server." }, { "code": null, "e": 3519, "s": 3426, "text": "Select datediff(hour, 2015-11-16, 2015-11-11) as \ndifferencehoursbetween20151116and20151111 " }, { "code": null, "e": 3575, "s": 3519, "text": "It will display the date and time in different formats." }, { "code": null, "e": 3607, "s": 3575, "text": "Syntax for the above function −" }, { "code": null, "e": 3645, "s": 3607, "text": "CONVERT(datatype, expression, style)\n" } ]
How to convert rgb() color string into an object in JavaScript ?
06 Apr, 2021 Given a color in the form of rgb( ) or rgba() and the task is to convert it into an object where the keys are the color names and values are the color values. Input: rgb(242, 52, 110) Output: { red: 242, green: 52, blue: 110 } Input: rgba(255, 99, 71, 0.5) Output: { red: 255, green: 99, blue: 71, alpha: 0.5 } Approach: To achieve this we use the following approach. Store the color in a variable named rgb. Create an array named colors that contain the names of the colors red, green, blue, and alpha. Create a variable names colorArr in which we store the color values of the input rgb. For example: [“255”, “99”, “71”, 0.5], to achieve this we slice the rgb from where the “(“ present to from where the “)” present. Now you got the string “255, 99, 71, 0.5”. Now split the array from where the “, ” present. Now you get the array [“255′′, ’99”, “71”, “0.5”]. Now create an empty object. Apply forEach loop on the colorArr and for every iteration insert the name of color and value of the color to the object. Now print the object. Javascript <script>let rgb = "rgba(255, 99, 71, 0.5)" let colors = ["red", "green", "blue", "alpha"] // Getting the index of "(" and ")" // by using the indexOf() methodlet colorArr = rgb.slice( rgb.indexOf("(") + 1, rgb.indexOf(")")).split(", "); let obj = new Object(); // Insert the values into objcolorArr.forEach((k, i) => { obj[colors[i]] = k}) console.log(obj)</script> Output: { alpha: "0.5", blue: "71", green: "99", red: "255" } Javascript <script>function rgbToObj(rgb) { let colors = ["red", "green", "blue", "alpha"] let colorArr = rgb.slice( rgb.indexOf("(") + 1, rgb.indexOf(")") ).split(", "); let obj = new Object(); colorArr.forEach((k, i) => { obj[colors[i]] = k }) return obj;} console.log(rgbToObj("rgb(255, 99, 71)"))console.log(rgbToObj("rgb(255, 99, 71, 0.5)"))</script> Output: { blue: "71", green: "99", red: "255" } { alpha: "0.5", blue: "71", green: "99", red: "255" } JavaScript-Methods JavaScript-Properties JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Apr, 2021" }, { "code": null, "e": 187, "s": 28, "text": "Given a color in the form of rgb( ) or rgba() and the task is to convert it into an object where the keys are the color names and values are the color values." }, { "code": null, "e": 363, "s": 187, "text": "Input: rgb(242, 52, 110)\nOutput: {\n red: 242,\n green: 52,\n blue: 110\n}\n\nInput: rgba(255, 99, 71, 0.5)\nOutput: {\n red: 255,\n green: 99,\n blue: 71,\n alpha: 0.5\n}" }, { "code": null, "e": 420, "s": 363, "text": "Approach: To achieve this we use the following approach." }, { "code": null, "e": 461, "s": 420, "text": "Store the color in a variable named rgb." }, { "code": null, "e": 556, "s": 461, "text": "Create an array named colors that contain the names of the colors red, green, blue, and alpha." }, { "code": null, "e": 915, "s": 556, "text": "Create a variable names colorArr in which we store the color values of the input rgb. For example: [“255”, “99”, “71”, 0.5], to achieve this we slice the rgb from where the “(“ present to from where the “)” present. Now you got the string “255, 99, 71, 0.5”. Now split the array from where the “, ” present. Now you get the array [“255′′, ’99”, “71”, “0.5”]." }, { "code": null, "e": 943, "s": 915, "text": "Now create an empty object." }, { "code": null, "e": 1065, "s": 943, "text": "Apply forEach loop on the colorArr and for every iteration insert the name of color and value of the color to the object." }, { "code": null, "e": 1087, "s": 1065, "text": "Now print the object." }, { "code": null, "e": 1098, "s": 1087, "text": "Javascript" }, { "code": "<script>let rgb = \"rgba(255, 99, 71, 0.5)\" let colors = [\"red\", \"green\", \"blue\", \"alpha\"] // Getting the index of \"(\" and \")\" // by using the indexOf() methodlet colorArr = rgb.slice( rgb.indexOf(\"(\") + 1, rgb.indexOf(\")\")).split(\", \"); let obj = new Object(); // Insert the values into objcolorArr.forEach((k, i) => { obj[colors[i]] = k}) console.log(obj)</script>", "e": 1479, "s": 1098, "text": null }, { "code": null, "e": 1487, "s": 1479, "text": "Output:" }, { "code": null, "e": 1549, "s": 1487, "text": "{\n alpha: \"0.5\",\n blue: \"71\",\n green: \"99\",\n red: \"255\"\n}" }, { "code": null, "e": 1560, "s": 1549, "text": "Javascript" }, { "code": "<script>function rgbToObj(rgb) { let colors = [\"red\", \"green\", \"blue\", \"alpha\"] let colorArr = rgb.slice( rgb.indexOf(\"(\") + 1, rgb.indexOf(\")\") ).split(\", \"); let obj = new Object(); colorArr.forEach((k, i) => { obj[colors[i]] = k }) return obj;} console.log(rgbToObj(\"rgb(255, 99, 71)\"))console.log(rgbToObj(\"rgb(255, 99, 71, 0.5)\"))</script>", "e": 1961, "s": 1560, "text": null }, { "code": null, "e": 1969, "s": 1961, "text": "Output:" }, { "code": null, "e": 2078, "s": 1969, "text": "{\n blue: \"71\",\n green: \"99\",\n red: \"255\"\n}\n\n{\n alpha: \"0.5\",\n blue: \"71\",\n green: \"99\",\n red: \"255\"\n}" }, { "code": null, "e": 2097, "s": 2078, "text": "JavaScript-Methods" }, { "code": null, "e": 2119, "s": 2097, "text": "JavaScript-Properties" }, { "code": null, "e": 2140, "s": 2119, "text": "JavaScript-Questions" }, { "code": null, "e": 2151, "s": 2140, "text": "JavaScript" }, { "code": null, "e": 2168, "s": 2151, "text": "Web Technologies" }, { "code": null, "e": 2266, "s": 2168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2327, "s": 2266, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2367, "s": 2327, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2408, "s": 2367, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2450, "s": 2408, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2472, "s": 2450, "text": "JavaScript | Promises" }, { "code": null, "e": 2505, "s": 2472, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2567, "s": 2505, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2628, "s": 2567, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2678, "s": 2628, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Russian Peasant (Multiply two numbers using bitwise operators)
28 Oct, 2021 Given two integers, write a function to multiply them without using multiplication operator.There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn’t become 1. In the process, whenever the second number become odd, we add the first number to result (result is initialized as 0) The following is simple algorithm. Let the two given numbers be 'a' and 'b' 1) Initialize result 'res' as 0. 2) Do following while 'b' is greater than 0 a) If 'b' is odd, add 'a' to 'res' b) Double 'a' and halve 'b' 3) Return 'res'. C++ Java Python 3 C# PHP Javascript #include <iostream>using namespace std; // A method to multiply two numbers using Russian Peasant methodunsigned int russianPeasant(unsigned int a, unsigned int b){ int res = 0; // initialize result // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, add the first number to result if (b & 1) res = res + a; // Double the first number and halve the second number a = a << 1; b = b >> 1; } return res;} // Driver program to test above functionint main(){ cout << russianPeasant(18, 1) << endl; cout << russianPeasant(20, 12) << endl; return 0;} // Java program for Russian Peasant Multiplicationimport java.io.*; class GFG{ // Function to multiply two // numbers using Russian Peasant method static int russianPeasant(int a, int b) { // initialize result int res = 0; // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, // add the first number to result if ((b & 1) != 0) res = res + a; // Double the first number // and halve the second number a = a << 1; b = b >> 1; } return res; } // driver program public static void main (String[] args) { System.out.println(russianPeasant(18, 1)); System.out.println(russianPeasant(20, 12)); }} // Contributed by Pramod Kumar # A method to multiply two numbers# using Russian Peasant method # Function to multiply two numbers# using Russian Peasant methoddef russianPeasant(a, b): res = 0 # initialize result # While second number doesn't # become 1 while (b > 0): # If second number becomes # odd, add the first number # to result if (b & 1): res = res + a # Double the first number # and halve the second # number a = a << 1 b = b >> 1 return res # Driver program to test# above functionprint(russianPeasant(18, 1))print(russianPeasant(20, 12))# This code is contributed by# Smitha Dinesh Semwal // C# program for Russian Peasant Multiplicationusing System; class GFG { // Function to multiply two // numbers using Russian Peasant method static int russianPeasant(int a, int b) { // initialize result int res = 0; // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, // add the first number to result if ((b & 1) != 0) res = res + a; // Double the first number // and halve the second number a = a << 1; b = b >> 1; } return res; } // driver program public static void Main() { Console.WriteLine(russianPeasant(18, 1)); Console.WriteLine(russianPeasant(20, 12)); }} // This code is contributed by Sam007. <?php// PHP Code to multiply two numbers// using Russian Peasant method // function returns the resultfunction russianPeasant($a, $b){ // initialize result $res = 0; // While second number // doesn't become 1 while ($b > 0) { // If second number becomes odd, // add the first number to result if ($b & 1) $res = $res + $a; // Double the first number and // halve the second number $a = $a << 1; $b = $b >> 1; } return $res;} // Driver Code echo russianPeasant(18, 1), "\n"; echo russianPeasant(20, 12), "\n"; // This code is contributed by Ajit?> <script> // A method to multiply two numbers using Russian Peasant methodfunction russianPeasant(a, b){ var res = 0; // initialize result // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, add the first number to result if (b & 1) res = res + a; // Double the first number and halve the second number a = a << 1; b = b >> 1; } return res;} // Driver program to test above functiondocument.write(russianPeasant(18, 1)+"<br>");document.write(russianPeasant(20, 12)); // This code is contributed by noob2000.</script> Output: 18 240 Time Complexity: O(log2b) Auxiliary Space: O(1) How does this work? The value of a*b is same as (a*2)*(b/2) if b is even, otherwise the value is same as ((a*2)*(b/2) + a). In the while loop, we keep multiplying ‘a’ with 2 and keep dividing ‘b’ by 2. If ‘b’ becomes odd in loop, we add ‘a’ to ‘res’. When value of ‘b’ becomes 1, the value of ‘res’ + ‘a’, gives us the result. Note that when ‘b’ is a power of 2, the ‘res’ would remain 0 and ‘a’ would have the multiplication. See the reference for more information.Reference: http://mathforum.org/dr.math/faq/faq.peasant.htmlThis article is compiled by Shalki Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Smitha Dinesh Semwal jit_t noob2000 subham348 Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Oct, 2021" }, { "code": null, "e": 549, "s": 52, "text": "Given two integers, write a function to multiply them without using multiplication operator.There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn’t become 1. In the process, whenever the second number become odd, we add the first number to result (result is initialized as 0) The following is simple algorithm. " }, { "code": null, "e": 754, "s": 549, "text": "Let the two given numbers be 'a' and 'b'\n1) Initialize result 'res' as 0.\n2) Do following while 'b' is greater than 0\n a) If 'b' is odd, add 'a' to 'res'\n b) Double 'a' and halve 'b'\n3) Return 'res'. " }, { "code": null, "e": 760, "s": 756, "text": "C++" }, { "code": null, "e": 765, "s": 760, "text": "Java" }, { "code": null, "e": 774, "s": 765, "text": "Python 3" }, { "code": null, "e": 777, "s": 774, "text": "C#" }, { "code": null, "e": 781, "s": 777, "text": "PHP" }, { "code": null, "e": 792, "s": 781, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // A method to multiply two numbers using Russian Peasant methodunsigned int russianPeasant(unsigned int a, unsigned int b){ int res = 0; // initialize result // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, add the first number to result if (b & 1) res = res + a; // Double the first number and halve the second number a = a << 1; b = b >> 1; } return res;} // Driver program to test above functionint main(){ cout << russianPeasant(18, 1) << endl; cout << russianPeasant(20, 12) << endl; return 0;}", "e": 1448, "s": 792, "text": null }, { "code": "// Java program for Russian Peasant Multiplicationimport java.io.*; class GFG{ // Function to multiply two // numbers using Russian Peasant method static int russianPeasant(int a, int b) { // initialize result int res = 0; // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, // add the first number to result if ((b & 1) != 0) res = res + a; // Double the first number // and halve the second number a = a << 1; b = b >> 1; } return res; } // driver program public static void main (String[] args) { System.out.println(russianPeasant(18, 1)); System.out.println(russianPeasant(20, 12)); }} // Contributed by Pramod Kumar", "e": 2302, "s": 1448, "text": null }, { "code": "# A method to multiply two numbers# using Russian Peasant method # Function to multiply two numbers# using Russian Peasant methoddef russianPeasant(a, b): res = 0 # initialize result # While second number doesn't # become 1 while (b > 0): # If second number becomes # odd, add the first number # to result if (b & 1): res = res + a # Double the first number # and halve the second # number a = a << 1 b = b >> 1 return res # Driver program to test# above functionprint(russianPeasant(18, 1))print(russianPeasant(20, 12))# This code is contributed by# Smitha Dinesh Semwal", "e": 2976, "s": 2302, "text": null }, { "code": "// C# program for Russian Peasant Multiplicationusing System; class GFG { // Function to multiply two // numbers using Russian Peasant method static int russianPeasant(int a, int b) { // initialize result int res = 0; // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, // add the first number to result if ((b & 1) != 0) res = res + a; // Double the first number // and halve the second number a = a << 1; b = b >> 1; } return res; } // driver program public static void Main() { Console.WriteLine(russianPeasant(18, 1)); Console.WriteLine(russianPeasant(20, 12)); }} // This code is contributed by Sam007.", "e": 3817, "s": 2976, "text": null }, { "code": "<?php// PHP Code to multiply two numbers// using Russian Peasant method // function returns the resultfunction russianPeasant($a, $b){ // initialize result $res = 0; // While second number // doesn't become 1 while ($b > 0) { // If second number becomes odd, // add the first number to result if ($b & 1) $res = $res + $a; // Double the first number and // halve the second number $a = $a << 1; $b = $b >> 1; } return $res;} // Driver Code echo russianPeasant(18, 1), \"\\n\"; echo russianPeasant(20, 12), \"\\n\"; // This code is contributed by Ajit?>", "e": 4478, "s": 3817, "text": null }, { "code": "<script> // A method to multiply two numbers using Russian Peasant methodfunction russianPeasant(a, b){ var res = 0; // initialize result // While second number doesn't become 1 while (b > 0) { // If second number becomes odd, add the first number to result if (b & 1) res = res + a; // Double the first number and halve the second number a = a << 1; b = b >> 1; } return res;} // Driver program to test above functiondocument.write(russianPeasant(18, 1)+\"<br>\");document.write(russianPeasant(20, 12)); // This code is contributed by noob2000.</script>", "e": 5110, "s": 4478, "text": null }, { "code": null, "e": 5119, "s": 5110, "text": "Output: " }, { "code": null, "e": 5126, "s": 5119, "text": "18\n240" }, { "code": null, "e": 5152, "s": 5126, "text": "Time Complexity: O(log2b)" }, { "code": null, "e": 5174, "s": 5152, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5869, "s": 5174, "text": "How does this work? The value of a*b is same as (a*2)*(b/2) if b is even, otherwise the value is same as ((a*2)*(b/2) + a). In the while loop, we keep multiplying ‘a’ with 2 and keep dividing ‘b’ by 2. If ‘b’ becomes odd in loop, we add ‘a’ to ‘res’. When value of ‘b’ becomes 1, the value of ‘res’ + ‘a’, gives us the result. Note that when ‘b’ is a power of 2, the ‘res’ would remain 0 and ‘a’ would have the multiplication. See the reference for more information.Reference: http://mathforum.org/dr.math/faq/faq.peasant.htmlThis article is compiled by Shalki Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 5890, "s": 5869, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 5896, "s": 5890, "text": "jit_t" }, { "code": null, "e": 5905, "s": 5896, "text": "noob2000" }, { "code": null, "e": 5915, "s": 5905, "text": "subham348" }, { "code": null, "e": 5925, "s": 5915, "text": "Bit Magic" }, { "code": null, "e": 5938, "s": 5925, "text": "Mathematical" }, { "code": null, "e": 5951, "s": 5938, "text": "Mathematical" }, { "code": null, "e": 5961, "s": 5951, "text": "Bit Magic" } ]
Find the geometric mean of a given Pandas DataFrame
05 Sep, 2020 In this article, we will discuss how to find the geometric mean of a given DataFrame. Generally geometric mean of nth numbers is the nth root of their product. It can found using the scipy.stats.gmean() method. This function calculates the geometric mean of the array elements along the specified axis of the array (list in python). Syntax: scipy.stats.gmean(array, axis=0, dtype=None) Approach : Import module Create Pandas DataFrame Create a new column for the geometric mean Find the geometric mean with scipy.stats.gmean() Store into a new column Display DataFrame Step-by-Step Implementation : Step 1: Importing module and Making Dataframe. Python # importing moduleimport pandas as pdimport numpy as npfrom scipy import stats # Create a DataFramedf = pd.DataFrame({ 'Name': ['Monty', 'Anurag', 'Kavya', 'Hunny', 'Saurabh', 'Shubham', 'Ujjawal', 'Satyam', 'Prity', 'Tanya', 'Amir', 'donald'], 'Match1_score': [52, 87, 35, 14, 41, 71, 95, 83, 22, 82, 11, 97], 'match2_score': [45, 80, 62, 53, 49, 82, 36, 97, 84, 93, 39, 59]}) # Display DataFramedf Output : Step 2: Create an empty DataFrame column. Python3 # Creating empty column in DataFramedf['Geometric Mean'] = Nonedf Output : Step 3: Find Geometric mean with scipy.stats.gmean() and store it into a new column. Python3 # Computing geometric mean# Storing into a DataFrame columndf['Geometric Mean'] = stats.gmean(df.iloc[:, 1:3], axis=1)df Output : Python pandas-dataFrame Python Pandas-exercise Python scipy-stats-functions Python-pandas Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 188, "s": 28, "text": "In this article, we will discuss how to find the geometric mean of a given DataFrame. Generally geometric mean of nth numbers is the nth root of their product." }, { "code": null, "e": 361, "s": 188, "text": "It can found using the scipy.stats.gmean() method. This function calculates the geometric mean of the array elements along the specified axis of the array (list in python)." }, { "code": null, "e": 369, "s": 361, "text": "Syntax:" }, { "code": null, "e": 414, "s": 369, "text": "scipy.stats.gmean(array, axis=0, dtype=None)" }, { "code": null, "e": 425, "s": 414, "text": "Approach :" }, { "code": null, "e": 439, "s": 425, "text": "Import module" }, { "code": null, "e": 463, "s": 439, "text": "Create Pandas DataFrame" }, { "code": null, "e": 506, "s": 463, "text": "Create a new column for the geometric mean" }, { "code": null, "e": 555, "s": 506, "text": "Find the geometric mean with scipy.stats.gmean()" }, { "code": null, "e": 579, "s": 555, "text": "Store into a new column" }, { "code": null, "e": 597, "s": 579, "text": "Display DataFrame" }, { "code": null, "e": 627, "s": 597, "text": "Step-by-Step Implementation :" }, { "code": null, "e": 674, "s": 627, "text": "Step 1: Importing module and Making Dataframe." }, { "code": null, "e": 681, "s": 674, "text": "Python" }, { "code": "# importing moduleimport pandas as pdimport numpy as npfrom scipy import stats # Create a DataFramedf = pd.DataFrame({ 'Name': ['Monty', 'Anurag', 'Kavya', 'Hunny', 'Saurabh', 'Shubham', 'Ujjawal', 'Satyam', 'Prity', 'Tanya', 'Amir', 'donald'], 'Match1_score': [52, 87, 35, 14, 41, 71, 95, 83, 22, 82, 11, 97], 'match2_score': [45, 80, 62, 53, 49, 82, 36, 97, 84, 93, 39, 59]}) # Display DataFramedf", "e": 1117, "s": 681, "text": null }, { "code": null, "e": 1126, "s": 1117, "text": "Output :" }, { "code": null, "e": 1169, "s": 1126, "text": "Step 2: Create an empty DataFrame column." }, { "code": null, "e": 1177, "s": 1169, "text": "Python3" }, { "code": "# Creating empty column in DataFramedf['Geometric Mean'] = Nonedf", "e": 1243, "s": 1177, "text": null }, { "code": null, "e": 1252, "s": 1243, "text": "Output :" }, { "code": null, "e": 1338, "s": 1252, "text": "Step 3: Find Geometric mean with scipy.stats.gmean() and store it into a new column." }, { "code": null, "e": 1346, "s": 1338, "text": "Python3" }, { "code": "# Computing geometric mean# Storing into a DataFrame columndf['Geometric Mean'] = stats.gmean(df.iloc[:, 1:3], axis=1)df", "e": 1467, "s": 1346, "text": null }, { "code": null, "e": 1476, "s": 1467, "text": "Output :" }, { "code": null, "e": 1500, "s": 1476, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1523, "s": 1500, "text": "Python Pandas-exercise" }, { "code": null, "e": 1552, "s": 1523, "text": "Python scipy-stats-functions" }, { "code": null, "e": 1566, "s": 1552, "text": "Python-pandas" }, { "code": null, "e": 1579, "s": 1566, "text": "Python-scipy" }, { "code": null, "e": 1586, "s": 1579, "text": "Python" } ]
Flight-price checker using Python and Selenium
16 Jul, 2020 Python is a scripting language with many extended libraries and frameworks. It is used in various fields of computer science such as web development and data science. Also, Python can be used to automate some minor tasks which can be really helpful in the long run. The Python script mentioned in this article will fetch the prices from paytm.com using selenium and if it is lesser or than equal to the amount(you are ready to spend) set by you, then a notification will be sent to the desired email-ids about the reduced price. The email id which will be used to send the notifications should not use the personal password since it requires the two-factor authentication and the action will fail. Rather, a different password should be set which can be accessed by the script and many other different applications one might develop in the future. Note: The password required for sending that email can be set through this link: Google App Passwords Importing all the required libraries Selenium to perform automation of the website from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys STMPLIB for sending notifications through emails import smtplib Extracting the price of flights between two selected dates # Choose the two dates# in this format x = "2020-03-10" y = "2020-03-16" a = int(x[8:10])b = int(y[8:10]) if a > b: m = a - b t = b else: m = b - a t = aprint(t) low_price = ""url_final = 'https://paytm.com/flights'data = {} for i in range(t, t + m+1): url = 'https://paytm.com/flights/flightSearch/BBI-\ Bhubaneshwar/DEL-Delhi/1/0/0/E/2020-03-'+str(i) # Locations can be changed on # the above statement print(url) date = "2019-12-" + str(i) # enables the script to run properly without # opening the chrome browser. chrome_options = Options() chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--headless") driver = webdriver.Chrome(executable_path = '/path/to/chromedriver', options=chrome_options) driver.implicitly_wait(20) driver.get(url) g = driver.find_element_by_xpath("//div[@class='_2gMo']") price = g.text x = price[0] y = price[2:5] z = str(x)+str(y) p = int(z) print(p) prices=[] if p <= 2000: data[date] = p for i in data: low_price += str(i) + ": Rs." + str(data[i]) + "\n" print(low_price) Sending the notification if there are cheap flights available through an email using SMTP if len(data) != 0: dp = 2000 server = smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.login('your_email_id','your_password') subject = "Flight price for BBI-DEL has fallen\ below Rs. " + str(dp) body = "Hey Akash! \n The price of BBI-DEL on PayTm \ has fallen down below Rs." + str(dp) + ".\n So,\ hurry up & check: " + url_final+"\n\n\n The prices of\ flight below Rs.2000 for the following days are\ :\n\n" + low_price msg = f"Subject: {subject} \n\n {body}" server.sendmail( # email ids where you want to # send the notification 'email_id_1', 'email_id_2', msg ) print("HEY,EMAIL HAS BEEN SENT SUCCESSFULLY.") server.quit() Entire Code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys import smtplib # Choose the two dates# in this format x = "2020-03-10" y = "2020-03-16" a = int(x[8:10])b = int(y[8:10]) if a > b: m = a - b t = b else: m = b - a t = aprint(t) low_price = ""url_final = 'https://paytm.com/flights'data = {} for i in range(t, t + m+1): url = 'https://paytm.com/flights/flightSearch/BBI-\ Bhubaneshwar/DEL-Delhi/1/0/0/E/2020-03-'+str(i) # Locations can be changed on # the above statement print(url) date = "2019-12-" + str(i) # enables the script to run properly without # opening the chrome browser. chrome_options = Options() chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--headless") driver = webdriver.Chrome(executable_path = '/path/to/chromedriver', options=chrome_options) driver.implicitly_wait(20) driver.get(url) g = driver.find_element_by_xpath("//div[@class='_2gMo']") price = g.text x = price[0] y = price[2:5] z = str(x)+str(y) p = int(z) print(p) prices=[] if p <= 2000: data[date] = p for i in data: low_price += str(i) + ": Rs." + str(data[i]) + "\n" print(low_price) if len(data) != 0: dp = 2000 server = smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.login('your_email_id','your_password') subject = "Flight price for BBI-DEL has fallen\ below Rs. " + str(dp) body = "Hey Akash! \n The price of BBI-DEL on PayTm \ has fallen down below Rs." + str(dp) + ".\n So,\ hurry up & check: " + url_final+"\n\n\n The prices of\ flight below Rs.2000 for the following days are\ :\n\n" + low_price msg = f"Subject: {subject} \n\n {body}" server.sendmail( # email ids where you want to # send the notification 'email_id_1', 'email_id_2', msg ) print("HEY,EMAIL HAS BEEN SENT SUCCESSFULLY.") server.quit() Output: Python-projects Python-selenium python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 294, "s": 28, "text": "Python is a scripting language with many extended libraries and frameworks. It is used in various fields of computer science such as web development and data science. Also, Python can be used to automate some minor tasks which can be really helpful in the long run." }, { "code": null, "e": 557, "s": 294, "text": "The Python script mentioned in this article will fetch the prices from paytm.com using selenium and if it is lesser or than equal to the amount(you are ready to spend) set by you, then a notification will be sent to the desired email-ids about the reduced price." }, { "code": null, "e": 876, "s": 557, "text": "The email id which will be used to send the notifications should not use the personal password since it requires the two-factor authentication and the action will fail. Rather, a different password should be set which can be accessed by the script and many other different applications one might develop in the future." }, { "code": null, "e": 978, "s": 876, "text": "Note: The password required for sending that email can be set through this link: Google App Passwords" }, { "code": null, "e": 1015, "s": 978, "text": "Importing all the required libraries" }, { "code": null, "e": 1061, "s": 1015, "text": "Selenium to perform automation of the website" }, { "code": "from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys ", "e": 1416, "s": 1061, "text": null }, { "code": null, "e": 1465, "s": 1416, "text": "STMPLIB for sending notifications through emails" }, { "code": "import smtplib", "e": 1480, "s": 1465, "text": null }, { "code": null, "e": 1539, "s": 1480, "text": "Extracting the price of flights between two selected dates" }, { "code": "# Choose the two dates# in this format x = \"2020-03-10\" y = \"2020-03-16\" a = int(x[8:10])b = int(y[8:10]) if a > b: m = a - b t = b else: m = b - a t = aprint(t) low_price = \"\"url_final = 'https://paytm.com/flights'data = {} for i in range(t, t + m+1): url = 'https://paytm.com/flights/flightSearch/BBI-\\ Bhubaneshwar/DEL-Delhi/1/0/0/E/2020-03-'+str(i) # Locations can be changed on # the above statement print(url) date = \"2019-12-\" + str(i) # enables the script to run properly without # opening the chrome browser. chrome_options = Options() chrome_options.add_argument(\"--disable-gpu\") chrome_options.add_argument(\"--headless\") driver = webdriver.Chrome(executable_path = '/path/to/chromedriver', options=chrome_options) driver.implicitly_wait(20) driver.get(url) g = driver.find_element_by_xpath(\"//div[@class='_2gMo']\") price = g.text x = price[0] y = price[2:5] z = str(x)+str(y) p = int(z) print(p) prices=[] if p <= 2000: data[date] = p for i in data: low_price += str(i) + \": Rs.\" + str(data[i]) + \"\\n\" print(low_price) ", "e": 2769, "s": 1539, "text": null }, { "code": null, "e": 2859, "s": 2769, "text": "Sending the notification if there are cheap flights available through an email using SMTP" }, { "code": "if len(data) != 0: dp = 2000 server = smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.login('your_email_id','your_password') subject = \"Flight price for BBI-DEL has fallen\\ below Rs. \" + str(dp) body = \"Hey Akash! \\n The price of BBI-DEL on PayTm \\ has fallen down below Rs.\" + str(dp) + \".\\n So,\\ hurry up & check: \" + url_final+\"\\n\\n\\n The prices of\\ flight below Rs.2000 for the following days are\\ :\\n\\n\" + low_price msg = f\"Subject: {subject} \\n\\n {body}\" server.sendmail( # email ids where you want to # send the notification 'email_id_1', 'email_id_2', msg ) print(\"HEY,EMAIL HAS BEEN SENT SUCCESSFULLY.\") server.quit()", "e": 3662, "s": 2859, "text": null }, { "code": null, "e": 3675, "s": 3662, "text": "Entire Code:" }, { "code": "from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.keys import Keys import smtplib # Choose the two dates# in this format x = \"2020-03-10\" y = \"2020-03-16\" a = int(x[8:10])b = int(y[8:10]) if a > b: m = a - b t = b else: m = b - a t = aprint(t) low_price = \"\"url_final = 'https://paytm.com/flights'data = {} for i in range(t, t + m+1): url = 'https://paytm.com/flights/flightSearch/BBI-\\ Bhubaneshwar/DEL-Delhi/1/0/0/E/2020-03-'+str(i) # Locations can be changed on # the above statement print(url) date = \"2019-12-\" + str(i) # enables the script to run properly without # opening the chrome browser. chrome_options = Options() chrome_options.add_argument(\"--disable-gpu\") chrome_options.add_argument(\"--headless\") driver = webdriver.Chrome(executable_path = '/path/to/chromedriver', options=chrome_options) driver.implicitly_wait(20) driver.get(url) g = driver.find_element_by_xpath(\"//div[@class='_2gMo']\") price = g.text x = price[0] y = price[2:5] z = str(x)+str(y) p = int(z) print(p) prices=[] if p <= 2000: data[date] = p for i in data: low_price += str(i) + \": Rs.\" + str(data[i]) + \"\\n\" print(low_price) if len(data) != 0: dp = 2000 server = smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.login('your_email_id','your_password') subject = \"Flight price for BBI-DEL has fallen\\ below Rs. \" + str(dp) body = \"Hey Akash! \\n The price of BBI-DEL on PayTm \\ has fallen down below Rs.\" + str(dp) + \".\\n So,\\ hurry up & check: \" + url_final+\"\\n\\n\\n The prices of\\ flight below Rs.2000 for the following days are\\ :\\n\\n\" + low_price msg = f\"Subject: {subject} \\n\\n {body}\" server.sendmail( # email ids where you want to # send the notification 'email_id_1', 'email_id_2', msg ) print(\"HEY,EMAIL HAS BEEN SENT SUCCESSFULLY.\") server.quit()", "e": 6081, "s": 3675, "text": null }, { "code": null, "e": 6089, "s": 6081, "text": "Output:" }, { "code": null, "e": 6105, "s": 6089, "text": "Python-projects" }, { "code": null, "e": 6121, "s": 6105, "text": "Python-selenium" }, { "code": null, "e": 6136, "s": 6121, "text": "python-utility" }, { "code": null, "e": 6143, "s": 6136, "text": "Python" }, { "code": null, "e": 6241, "s": 6143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6259, "s": 6241, "text": "Python Dictionary" }, { "code": null, "e": 6301, "s": 6259, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6323, "s": 6301, "text": "Enumerate() in Python" }, { "code": null, "e": 6358, "s": 6323, "text": "Read a file line by line in Python" }, { "code": null, "e": 6384, "s": 6358, "text": "Python String | replace()" }, { "code": null, "e": 6416, "s": 6384, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6445, "s": 6416, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6475, "s": 6445, "text": "Iterate over a list in Python" }, { "code": null, "e": 6502, "s": 6475, "text": "Python Classes and Objects" } ]
How to create button to open SMS compose to a phone number using HTML ?
08 Jun, 2020 Sometimes, when you search for a number on the web, you might want to SMS to it directly from the web page instead of noting it down and then messaging to it. It becomes quite convenient for the user. Making an SMS link is very easy in HTML. Here, we will see how to make the SMS link on a webpage. Approach: Using <a> href attribute: Enter the phone number in place of the URL and add sms: before it to make an SMS link. Add the text between the tags that will appear as the clickable link. For Single Recipient:Syntax: <a href="sms:(countrycode)(number)"> Text </a> Example: <!DOCTYPE html><html> <head> <title> Create button to open SMS compose to a phone number </title></head> <body> <p> For any queries you can text us at the below number: </p> <a href="sms:+911234567890"> +91-123-4567-890 </a></body> </html> Output:Before clicking the link:After clicking the link: For Multiple Recipient:Syntax: <a href="sms:(countrycode)(number), (countrycode)(number), ...."> Text </a> Example: <!DOCTYPE html><html> <head> <title> Create button to open SMS compose to a phone number </title></head> <body> <p> Send text to multiple recipients: </p> <a href="sms:+911234567890, +11234567890"> Send a SMS </a></body> </html> Output:Before clicking the link:After clicking the link: HTML-Misc HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2020" }, { "code": null, "e": 352, "s": 53, "text": "Sometimes, when you search for a number on the web, you might want to SMS to it directly from the web page instead of noting it down and then messaging to it. It becomes quite convenient for the user. Making an SMS link is very easy in HTML. Here, we will see how to make the SMS link on a webpage." }, { "code": null, "e": 545, "s": 352, "text": "Approach: Using <a> href attribute: Enter the phone number in place of the URL and add sms: before it to make an SMS link. Add the text between the tags that will appear as the clickable link." }, { "code": null, "e": 574, "s": 545, "text": "For Single Recipient:Syntax:" }, { "code": null, "e": 621, "s": 574, "text": "<a href=\"sms:(countrycode)(number)\"> Text </a>" }, { "code": null, "e": 630, "s": 621, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Create button to open SMS compose to a phone number </title></head> <body> <p> For any queries you can text us at the below number: </p> <a href=\"sms:+911234567890\"> +91-123-4567-890 </a></body> </html>", "e": 934, "s": 630, "text": null }, { "code": null, "e": 991, "s": 934, "text": "Output:Before clicking the link:After clicking the link:" }, { "code": null, "e": 1022, "s": 991, "text": "For Multiple Recipient:Syntax:" }, { "code": null, "e": 1103, "s": 1022, "text": "<a href=\"sms:(countrycode)(number), \n (countrycode)(number), ....\"> Text </a>" }, { "code": null, "e": 1112, "s": 1103, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Create button to open SMS compose to a phone number </title></head> <body> <p> Send text to multiple recipients: </p> <a href=\"sms:+911234567890, +11234567890\"> Send a SMS </a></body> </html>", "e": 1413, "s": 1112, "text": null }, { "code": null, "e": 1470, "s": 1413, "text": "Output:Before clicking the link:After clicking the link:" }, { "code": null, "e": 1480, "s": 1470, "text": "HTML-Misc" }, { "code": null, "e": 1485, "s": 1480, "text": "HTML" }, { "code": null, "e": 1502, "s": 1485, "text": "Web Technologies" }, { "code": null, "e": 1529, "s": 1502, "text": "Web technologies Questions" }, { "code": null, "e": 1534, "s": 1529, "text": "HTML" }, { "code": null, "e": 1632, "s": 1534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1656, "s": 1632, "text": "REST API (Introduction)" }, { "code": null, "e": 1695, "s": 1656, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1734, "s": 1695, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1771, "s": 1734, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1791, "s": 1771, "text": "Angular File Upload" }, { "code": null, "e": 1824, "s": 1791, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1885, "s": 1824, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1928, "s": 1885, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2000, "s": 1928, "text": "Differences between Functional Components and Class Components in React" } ]
Python | Carousel Widget In Kivy using .kv file
12 Apr, 2022 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial – Learn Kivy with Examples. The Carousel widget provides the classic mobile-friendly carousel view where you can swipe between slides. You can add any content to the carousel and have it move horizontally or vertically. The carousel can display pages in a sequence or a loop. To work with this widget you must have to import: from kivy.uix.carousel import Carousel Basic Approach: 1) import kivy 2) import kivy App 3) import Gridlayout 4) import Carousel 5) set minimum version(optional) 6) Create as much as widget class as needed 7) create the App class 8) return the widget/layout etc class 9) Create Carousel.kv file: 1) Create button( or what is needed) 2) Arrange the on_release / on_press function 10) Run an instance of the class In the below example we are creating the buttons in the App. In this we used load_previous() and load_next() functions. load_next(mode=’next’) Animate to the next slide. load_previous() Animate to the previous slide. Implementation of the Approach: main.py file: Python3 # Program to explain how to add carousel in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Carousel widget provides the# classic mobile-friendly carousel# view where you can swipe between slidesfrom kivy.uix.carousel import Carousel # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # Create the Layout Classclass Carousel(GridLayout): pass # Create the App classclass CarouselApp(App): def build(self): # Set carousel widget as root root = Carousel() # for multiple pages for x in range(10): root.add_widget(Carousel()) return root # run the Appif __name__ == '__main__': CarouselApp().run() Carousel.kv file: Python3 # Carousel.kv file of the code # Carousel Creation<Corousel>: rows: 2 # It shows the id which is different for different pages Label: text: str(id(root)) # This button will take you directly to the 3rd page Button text: 'load(page 3)' on_release: carousel = root.parent.parent carousel.load_slide(carousel.slides[2]) # load_previous() is used to go back to previous page Button text: 'prev' on_release: root.parent.parent.load_previous() # load_next() is used to go to next page Button text: 'next' on_release: root.parent.parent.load_next() Output: ManasChhabra2 arorakashish0911 simranarora5sos Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2022" }, { "code": null, "e": 265, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 316, "s": 265, "text": "???????? Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 614, "s": 316, "text": "The Carousel widget provides the classic mobile-friendly carousel view where you can swipe between slides. You can add any content to the carousel and have it move horizontally or vertically. The carousel can display pages in a sequence or a loop. To work with this widget you must have to import:" }, { "code": null, "e": 653, "s": 614, "text": "from kivy.uix.carousel import Carousel" }, { "code": null, "e": 1042, "s": 653, "text": "Basic Approach:\n1) import kivy\n2) import kivy App\n3) import Gridlayout\n4) import Carousel\n5) set minimum version(optional)\n6) Create as much as widget class as needed\n7) create the App class\n8) return the widget/layout etc class\n9) Create Carousel.kv file:\n 1) Create button( or what is needed)\n 2) Arrange the on_release / on_press function\n10) Run an instance of the class" }, { "code": null, "e": 1162, "s": 1042, "text": "In the below example we are creating the buttons in the App. In this we used load_previous() and load_next() functions." }, { "code": null, "e": 1259, "s": 1162, "text": "load_next(mode=’next’) Animate to the next slide. load_previous() Animate to the previous slide." }, { "code": null, "e": 1306, "s": 1259, "text": "Implementation of the Approach: main.py file: " }, { "code": null, "e": 1314, "s": 1306, "text": "Python3" }, { "code": "# Program to explain how to add carousel in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Carousel widget provides the# classic mobile-friendly carousel# view where you can swipe between slidesfrom kivy.uix.carousel import Carousel # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # Create the Layout Classclass Carousel(GridLayout): pass # Create the App classclass CarouselApp(App): def build(self): # Set carousel widget as root root = Carousel() # for multiple pages for x in range(10): root.add_widget(Carousel()) return root # run the Appif __name__ == '__main__': CarouselApp().run()", "e": 2390, "s": 1314, "text": null }, { "code": null, "e": 2409, "s": 2390, "text": "Carousel.kv file: " }, { "code": null, "e": 2417, "s": 2409, "text": "Python3" }, { "code": "# Carousel.kv file of the code # Carousel Creation<Corousel>: rows: 2 # It shows the id which is different for different pages Label: text: str(id(root)) # This button will take you directly to the 3rd page Button text: 'load(page 3)' on_release: carousel = root.parent.parent carousel.load_slide(carousel.slides[2]) # load_previous() is used to go back to previous page Button text: 'prev' on_release: root.parent.parent.load_previous() # load_next() is used to go to next page Button text: 'next' on_release: root.parent.parent.load_next()", "e": 3087, "s": 2417, "text": null }, { "code": null, "e": 3096, "s": 3087, "text": "Output: " }, { "code": null, "e": 3110, "s": 3096, "text": "ManasChhabra2" }, { "code": null, "e": 3127, "s": 3110, "text": "arorakashish0911" }, { "code": null, "e": 3143, "s": 3127, "text": "simranarora5sos" }, { "code": null, "e": 3154, "s": 3143, "text": "Python-gui" }, { "code": null, "e": 3166, "s": 3154, "text": "Python-kivy" }, { "code": null, "e": 3173, "s": 3166, "text": "Python" }, { "code": null, "e": 3271, "s": 3173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3303, "s": 3271, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3330, "s": 3303, "text": "Python Classes and Objects" }, { "code": null, "e": 3351, "s": 3330, "text": "Python OOPs Concepts" }, { "code": null, "e": 3374, "s": 3351, "text": "Introduction To PYTHON" }, { "code": null, "e": 3430, "s": 3374, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3461, "s": 3430, "text": "Python | os.path.join() method" }, { "code": null, "e": 3503, "s": 3461, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3545, "s": 3503, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3584, "s": 3545, "text": "Python | Get unique values from a list" } ]
How to set vertical alignment in Bootstrap ?
30 Nov, 2021 Vertical Alignment changes the alignment of elements vertically with the help of vertical-alignment utilities. The vertical-align utilities only affect inline(Present in one Line), inline-block(Present as blocks in one line), inline-table, and table cell(Elements in a cell of a table) elements. Vertical Alignment of div is one of the most basic requirements of a responsive web page. This can be achieved through CSS but the Bootstrap library has some classes specifically built for this purpose. In this article, we will learn the available classes & methods used for vertical-align in Bootstrap. Please refer to Vertical alignment in Bootstrap with Examples for other vertical-align classes. Here, we will discuss 2 built-in classes: Using class align-items-center Using class d-flex with class align-items-center Let’s understand both the classes through examples. Method 1: Using class align-items-center In Bootstrap 5, if we want to vertically align an <div> element in the center, we can do this by applying the class align-items-center on the containing element of that div. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container"> <div class="row align-items-center bg-success text-light" style="min-height: 100vh"> <div class="col-md-12"> <h1>GeeksforGeeks</h1> </div> </div> </div> </body></html> Output: Method 2: Using class d-flex with class align-items-center In Bootstrap 5, if we want to vertically align an <div> element in the middle of a containing element, we can do this by applying the class align-items-center and d-flex on the containing element of that div. Here, the d-flex class has the same effect as that of the display: flex; property in CSS. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="d-flex align-items-center" style="min-height: 100vh"> <div class="box w-100 text-success"> <h1>GeeksforGeeks</h1> </div> </div> </body></html> Output: nnr223442 Bootstrap-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? How to place table text into center using Bootstrap? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Nov, 2021" }, { "code": null, "e": 750, "s": 54, "text": "Vertical Alignment changes the alignment of elements vertically with the help of vertical-alignment utilities. The vertical-align utilities only affect inline(Present in one Line), inline-block(Present as blocks in one line), inline-table, and table cell(Elements in a cell of a table) elements. Vertical Alignment of div is one of the most basic requirements of a responsive web page. This can be achieved through CSS but the Bootstrap library has some classes specifically built for this purpose. In this article, we will learn the available classes & methods used for vertical-align in Bootstrap. Please refer to Vertical alignment in Bootstrap with Examples for other vertical-align classes." }, { "code": null, "e": 792, "s": 750, "text": "Here, we will discuss 2 built-in classes:" }, { "code": null, "e": 823, "s": 792, "text": "Using class align-items-center" }, { "code": null, "e": 872, "s": 823, "text": "Using class d-flex with class align-items-center" }, { "code": null, "e": 924, "s": 872, "text": "Let’s understand both the classes through examples." }, { "code": null, "e": 965, "s": 924, "text": "Method 1: Using class align-items-center" }, { "code": null, "e": 1139, "s": 965, "text": "In Bootstrap 5, if we want to vertically align an <div> element in the center, we can do this by applying the class align-items-center on the containing element of that div." }, { "code": null, "e": 1148, "s": 1139, "text": "Example:" }, { "code": null, "e": 1153, "s": 1148, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"/> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"/> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container\"> <div class=\"row align-items-center bg-success text-light\" style=\"min-height: 100vh\"> <div class=\"col-md-12\"> <h1>GeeksforGeeks</h1> </div> </div> </div> </body></html>", "e": 1975, "s": 1153, "text": null }, { "code": null, "e": 1983, "s": 1975, "text": "Output:" }, { "code": null, "e": 2042, "s": 1983, "text": "Method 2: Using class d-flex with class align-items-center" }, { "code": null, "e": 2341, "s": 2042, "text": "In Bootstrap 5, if we want to vertically align an <div> element in the middle of a containing element, we can do this by applying the class align-items-center and d-flex on the containing element of that div. Here, the d-flex class has the same effect as that of the display: flex; property in CSS." }, { "code": null, "e": 2350, "s": 2341, "text": "Example:" }, { "code": null, "e": 2355, "s": 2350, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"/> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"/> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"d-flex align-items-center\" style=\"min-height: 100vh\"> <div class=\"box w-100 text-success\"> <h1>GeeksforGeeks</h1> </div> </div> </body></html>", "e": 3109, "s": 2355, "text": null }, { "code": null, "e": 3117, "s": 3109, "text": "Output:" }, { "code": null, "e": 3127, "s": 3117, "text": "nnr223442" }, { "code": null, "e": 3147, "s": 3127, "text": "Bootstrap-Questions" }, { "code": null, "e": 3154, "s": 3147, "text": "Picked" }, { "code": null, "e": 3164, "s": 3154, "text": "Bootstrap" }, { "code": null, "e": 3169, "s": 3164, "text": "HTML" }, { "code": null, "e": 3186, "s": 3169, "text": "Web Technologies" }, { "code": null, "e": 3191, "s": 3186, "text": "HTML" }, { "code": null, "e": 3289, "s": 3191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3330, "s": 3289, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 3363, "s": 3330, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 3389, "s": 3363, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 3456, "s": 3389, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 3509, "s": 3456, "text": "How to place table text into center using Bootstrap?" }, { "code": null, "e": 3557, "s": 3509, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3619, "s": 3557, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3669, "s": 3619, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3693, "s": 3669, "text": "REST API (Introduction)" } ]
Namespaces in Ruby
22 Oct, 2021 A namespace is a container for multiple items which includes classes, constants, other modules, and more. It is ensured in a namespace that all the objects have unique names for easy identification. Generally, they are structured in a hierarchical format so, that names can be reused. Namespace in Ruby allows multiple structures to be written using hierarchical manner. Thus, one can reuse the names within the single main namespace. The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter. You can access the sub members of double with the help of :: operator. It is also called the constant resolution operator. Ruby allows nested namespace. You can use include keyword to copy the other module’s objects into the existing namespace without qualifying their name. Syntax: module Namespace_name # modules.. and classes.. end Example 1: This is an example of the simple formation of the namespace with a class and then executing the class methods defined within the class. Here, we access the sub members within the namespace, the “::” operator is used. It is also called the constant resolution operator. Ruby # Ruby program to illustrate namespace # Defining a namespace called Geekmodule Geek class GeeksforGeeks # The variable gfg attr_reader :gfg # Class GeeksforGeeks constructor def initialize(value) @gfg = value end endend # Accessing the sub members of# module using '::' operatorobj = Geek::GeeksforGeeks.new("GeeksForGeeks")puts obj.gfg Output: GeeksForGeeks Example 2: This is an example showing the implementation of hierarchical namespacing. In this, there is a combination of class and namespace within the single namespace. Here, the use of the class name is done multiple times under the concept of hierarchical namespacing. Ruby # Ruby program to illustrate namespace # The main namespacemodule Geek class GeeksforGeeks attr_reader :gfg def initialize(value) @gfg = value end end # Hierarchical namespace module Geek_1 # Reuse of the class names class GeeksforGeeks @@var = "This is the module Geek_1 " + "and class GeeksforGeeks" def printVar() puts @@var end end end # Hierarchical namespace module Geek_2 # Reuse of the class names class GeeksforGeeks attr_reader :var def initialize(var) @var = var end end end end obj_gfg = Geek::GeeksforGeeks.new("This is the module Geek " + "and class GeeksforGeeks")obj_gfg1 = Geek::Geek_1::GeeksforGeeks.new()obj_gfg2 = Geek::Geek_2::GeeksforGeeks.new("This is the module Geek_2 " + "and class GeeksforGeeks")puts obj_gfg.gfgputs obj_gfg1.printVar()puts obj_gfg2.var Output: This is the module Geek and class GeeksforGeeks This is the module Geek_1 and class GeeksforGeeks This is the module Geek_2 and class GeeksforGeeks gabaa406 Picked Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby | Array class find_index() operation Ruby For Beginners Ruby | String concat Method Ruby | Types of Variables Ruby on Rails Introduction Ruby | Array shift() function
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2021" }, { "code": null, "e": 315, "s": 28, "text": "A namespace is a container for multiple items which includes classes, constants, other modules, and more. It is ensured in a namespace that all the objects have unique names for easy identification. Generally, they are structured in a hierarchical format so, that names can be reused. " }, { "code": null, "e": 465, "s": 315, "text": "Namespace in Ruby allows multiple structures to be written using hierarchical manner. Thus, one can reuse the names within the single main namespace." }, { "code": null, "e": 562, "s": 465, "text": "The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name." }, { "code": null, "e": 633, "s": 562, "text": "The name of namespaces and classes always start from a capital letter." }, { "code": null, "e": 756, "s": 633, "text": "You can access the sub members of double with the help of :: operator. It is also called the constant resolution operator." }, { "code": null, "e": 786, "s": 756, "text": "Ruby allows nested namespace." }, { "code": null, "e": 908, "s": 786, "text": "You can use include keyword to copy the other module’s objects into the existing namespace without qualifying their name." }, { "code": null, "e": 918, "s": 908, "text": "Syntax: " }, { "code": null, "e": 974, "s": 918, "text": "module Namespace_name\n # modules.. and classes..\nend" }, { "code": null, "e": 1256, "s": 974, "text": "Example 1: This is an example of the simple formation of the namespace with a class and then executing the class methods defined within the class. Here, we access the sub members within the namespace, the “::” operator is used. It is also called the constant resolution operator. " }, { "code": null, "e": 1261, "s": 1256, "text": "Ruby" }, { "code": "# Ruby program to illustrate namespace # Defining a namespace called Geekmodule Geek class GeeksforGeeks # The variable gfg attr_reader :gfg # Class GeeksforGeeks constructor def initialize(value) @gfg = value end endend # Accessing the sub members of# module using '::' operatorobj = Geek::GeeksforGeeks.new(\"GeeksForGeeks\")puts obj.gfg", "e": 1667, "s": 1261, "text": null }, { "code": null, "e": 1677, "s": 1667, "text": "Output: " }, { "code": null, "e": 1691, "s": 1677, "text": "GeeksForGeeks" }, { "code": null, "e": 1965, "s": 1691, "text": "Example 2: This is an example showing the implementation of hierarchical namespacing. In this, there is a combination of class and namespace within the single namespace. Here, the use of the class name is done multiple times under the concept of hierarchical namespacing. " }, { "code": null, "e": 1970, "s": 1965, "text": "Ruby" }, { "code": "# Ruby program to illustrate namespace # The main namespacemodule Geek class GeeksforGeeks attr_reader :gfg def initialize(value) @gfg = value end end # Hierarchical namespace module Geek_1 # Reuse of the class names class GeeksforGeeks @@var = \"This is the module Geek_1 \" + \"and class GeeksforGeeks\" def printVar() puts @@var end end end # Hierarchical namespace module Geek_2 # Reuse of the class names class GeeksforGeeks attr_reader :var def initialize(var) @var = var end end end end obj_gfg = Geek::GeeksforGeeks.new(\"This is the module Geek \" + \"and class GeeksforGeeks\")obj_gfg1 = Geek::Geek_1::GeeksforGeeks.new()obj_gfg2 = Geek::Geek_2::GeeksforGeeks.new(\"This is the module Geek_2 \" + \"and class GeeksforGeeks\")puts obj_gfg.gfgputs obj_gfg1.printVar()puts obj_gfg2.var", "e": 3014, "s": 1970, "text": null }, { "code": null, "e": 3024, "s": 3014, "text": "Output: " }, { "code": null, "e": 3173, "s": 3024, "text": "This is the module Geek and class GeeksforGeeks\nThis is the module Geek_1 and class GeeksforGeeks\n\nThis is the module Geek_2 and class GeeksforGeeks" }, { "code": null, "e": 3184, "s": 3175, "text": "gabaa406" }, { "code": null, "e": 3191, "s": 3184, "text": "Picked" }, { "code": null, "e": 3196, "s": 3191, "text": "Ruby" }, { "code": null, "e": 3294, "s": 3196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3340, "s": 3294, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 3383, "s": 3340, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 3427, "s": 3383, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 3469, "s": 3427, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 3488, "s": 3469, "text": "Ruby For Beginners" }, { "code": null, "e": 3516, "s": 3488, "text": "Ruby | String concat Method" }, { "code": null, "e": 3542, "s": 3516, "text": "Ruby | Types of Variables" }, { "code": null, "e": 3569, "s": 3542, "text": "Ruby on Rails Introduction" } ]
How to make elements float to center?
19 May, 2022 The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout. So, we can center the elements by using position property. Example 1: This example set the position of elements exactly at the center of the screen. html <!DOCTYPE html><html> <head> <title> Make float to center to element </title> <!-- Style to set element float to center --> <style> .Center { width:200px; height:200px; position: fixed; background-color: blue; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; } </style></head> <body> <div class="Center"></div></body> </html> Output: Example: This example set the position of text float elements exactly at the center of the screen. html <!DOCTYPE html><html> <head> <!-- Style to set text-element to center --> <style> .center { text-align-last: center; border: 2px solid black; } </style></head> <body> <h2 style = "text-align:center"> Text is centered: </h2> <div class="center"> <p> <font color="green"> GeeksForGeeks A Computer Science Portal for Geeks </font> </p> </div></body> </html> Output: CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. hardikkoriintern CSS-Misc HTML-Misc Picked Web-Programs CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 52, "s": 24, "text": "\n19 May, 2022" }, { "code": null, "e": 377, "s": 52, "text": "The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout. So, we can center the elements by using position property." }, { "code": null, "e": 468, "s": 377, "text": "Example 1: This example set the position of elements exactly at the center of the screen. " }, { "code": null, "e": 473, "s": 468, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Make float to center to element </title> <!-- Style to set element float to center --> <style> .Center { width:200px; height:200px; position: fixed; background-color: blue; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; } </style></head> <body> <div class=\"Center\"></div></body> </html> ", "e": 970, "s": 473, "text": null }, { "code": null, "e": 978, "s": 970, "text": "Output:" }, { "code": null, "e": 1081, "s": 981, "text": "Example: This example set the position of text float elements exactly at the center of the screen. " }, { "code": null, "e": 1086, "s": 1081, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <!-- Style to set text-element to center --> <style> .center { text-align-last: center; border: 2px solid black; } </style></head> <body> <h2 style = \"text-align:center\"> Text is centered: </h2> <div class=\"center\"> <p> <font color=\"green\"> GeeksForGeeks A Computer Science Portal for Geeks </font> </p> </div></body> </html> ", "e": 1607, "s": 1086, "text": null }, { "code": null, "e": 1615, "s": 1607, "text": "Output:" }, { "code": null, "e": 1804, "s": 1617, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 1821, "s": 1804, "text": "hardikkoriintern" }, { "code": null, "e": 1830, "s": 1821, "text": "CSS-Misc" }, { "code": null, "e": 1840, "s": 1830, "text": "HTML-Misc" }, { "code": null, "e": 1847, "s": 1840, "text": "Picked" }, { "code": null, "e": 1860, "s": 1847, "text": "Web-Programs" }, { "code": null, "e": 1864, "s": 1860, "text": "CSS" }, { "code": null, "e": 1869, "s": 1864, "text": "HTML" }, { "code": null, "e": 1886, "s": 1869, "text": "Web Technologies" }, { "code": null, "e": 1891, "s": 1886, "text": "HTML" }, { "code": null, "e": 1989, "s": 1891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2026, "s": 1989, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2065, "s": 2026, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2104, "s": 2065, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2168, "s": 2104, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 2229, "s": 2168, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2253, "s": 2229, "text": "REST API (Introduction)" }, { "code": null, "e": 2306, "s": 2253, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2366, "s": 2306, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2427, "s": 2366, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Short Variable Declaration Operator(:=) in Go
17 May, 2021 Short Variable Declaration Operator(:=) in Golang is used to create the variables having a proper name and initial value. The main purpose of using this operator to declare and initialize the local variables inside the functions and to narrowing the scope of the variables. The type of the variable is determined by the type of the expression. var keyword is also used to create the variables of a specific type. So you can say that there are two ways to create the variables in Golang as follows: Using the var keyword Using the short variable declaration operator(:=) In this article, we will only discuss the short variable declaration operator. To know about var keyword you can refer var keyword in Go. You can also read the difference between var keyword and short variable declaration operator to get a proper idea of using both. Syntax of using short variable declaration operator: variable_name := expression or value Here, you must initialize the variable just after declaration. But using var keyword you can avoid initialization at the time of declaration. There is no need to mention the type of the variable. Expression or value on the right-hand side is used to evaluate the type of the variable. Example: Here, we are declaring the variables using short declaration operator and we are not specifying the type of the variable. The type of the variable is determined by the type of the expression on the right-hand side of := operator. Go // Go program to illustrate the use// of := (short declaration// operator)package main import "fmt" func main() { // declaring and initializing the variable a := 30 // taking a string variable Language: = "Go Programming" fmt.Println("The Value of a is: ", a) fmt.Println("The Value of Language is: ", Language) } Output: The Value of a is: 30 The Value of Language is: Go Programming Short Declaration operator can also be used to declare multiple variables of the same type or different types in the single declaration. The type of these variables is evaluated by the expression on the right-hand side of := operator. Example: Go // Go program to illustrate how to use := short// declaration operator to declare multiple// variables into a single declaration statementpackage main import "fmt" func main() { // multiple variables of same type(int)geek1, geek2, geek3 := 117, 7834, 5685 // multiple variables of different typesgeek4, geek5, geek6 := "GFG", 859.24, 1234 // Display the value and// type of the variablesfmt.Printf("The value of geek1 is : %d\n", geek1)fmt.Printf("The type of geek1 is : %T\n", geek1) fmt.Printf("\nThe value of geek2 is : %d\n", geek2)fmt.Printf("The type of geek2 is : %T\n", geek2) fmt.Printf("\nThe value of geek3 is : %d\n", geek3)fmt.Printf("The type of geek3 is : %T\n", geek3) fmt.Printf("\nThe value of geek4 is : %s\n", geek4)fmt.Printf("The type of geek4 is : %T\n", geek4) fmt.Printf("\nThe value of geek5 is : %f\n", geek5)fmt.Printf("The type of geek5 is : %T\n", geek5) fmt.Printf("\nThe value of geek6 is : %d\n", geek6)fmt.Printf("The type of geek6 is : %T\n", geek6) } Output: The value of geek1 is : 117 The type of geek1 is : int The value of geek2 is : 7834 The type of geek2 is : int The value of geek3 is : 5685 The type of geek3 is : int The value of geek4 is : GFG The type of geek4 is : string The value of geek5 is : 859.240000 The type of geek5 is : float64 The value of geek6 is : 1234 The type of geek6 is : int Important Points: Short declaration operator can be used when at least one of the variable in the left-hand side of := operator is newly declared. A short variable declaration operator behaves like an assignment for those variables which are already declared in the same lexical block. To get a better idea about this concept, let’s take an example.Example 1: Below program will give an error as there are no new variables in the left-hand side of the := operator. Go // Go program to illustrate the concept// of short variable declarationpackage main import "fmt" func main() { // taking two variables p, q := 100, 200 fmt.Println("Value of p ", p, "Value of q ", q) // this will give an error as // there are no new variable // on the left-hand side of := p, q := 500, 600 fmt.Println("Value of p ", p, "Value of q ", q)} Error: ./prog.go:17:10: no new variables on left side of := Example 2: In the below program, you can see that the line of code geek3, geek2 := 456, 200 will work fine without any error as there is at least a new variable i.e. geek3 on the left-hand side of := operator. Go // Go program to show how to use// short variable declaration operatorpackage main import "fmt" func main() { // Here, short variable declaration acts// as an assignment for geek1 variable// because same variable present in the same block// so the value of geek2 is changed from 100 to 200geek1, geek2 := 78, 100 // here, := is used as an assignment for geek2// as it is already declared. Also, this line// will work fine as geek3 is newly created// variablegeek3, geek2 := 456, 200 // If you try to run the commented lines,// then compiler will gives error because// these variables are already defined// geek1, geek2 := 745, 956// geek3 := 150 // Display the values of the variablesfmt.Printf("The value of geek1 and geek2 is : %d %d\n", geek1, geek2) fmt.Printf("The value of geek3 and geek2 is : %d %d\n", geek3, geek2)} Output: The value of geek1 and geek2 is : 78 200 The value of geek3 and geek2 is : 456 200 Go is a strongly typed language as you cannot assign a value of another type to the declared variable. Example: Go // Go program to show how to use// short variable declaration operatorpackage main import "fmt" func main() { // taking a variable of int type z := 50 fmt.Printf("Value of z is %d", z) // reassigning the value of string type // it will give an error z := "Golang"} Error: ./prog.go:16:4: no new variables on left side of := ./prog.go:16:7: cannot use “Golang” (type string) as type int in assignment In a short variable declaration, it is allowed to initializing a set of variables by the calling function which returns multiple values. Or you can say variables can also be assigned values that are evaluated during run time. Example: // Here, math.Max function return // the maximum number in i variable i := math.Max(x, y) With the help of short variable declaration operator(:=) you can only declare the local variable which has only block-level scope. Generally, local variables are declared inside the function block. If you will try to declare the global variables using the short declaration operator then you will get an error. Example 1: Go // Go program to show the use of := operator// to declare local variablespackage main import "fmt" // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar geek1 = 900 // using short variable declaration// it will give an errorgeek2 := 200 func main() { // accessing geek1 inside the functionfmt.Println(geek1) // accessing geek2 inside the functionfmt.Println(geek2) } Error: ./prog.go:15:1: syntax error: non-declaration statement outside function body Example 2: Go // Go program to show the use of := operator// to declare local variablespackage main import "fmt" // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar geek1 = 900 func main() { // using short variable declaration// inside the main function// it has local scope i.e. can't// accessed outside the main functiongeek2 := 200 // accessing geek1 inside the functionfmt.Println(geek1) // accessing geek2 inside the functionfmt.Println(geek2) } Output: 900 200 nidhi_biet clintra Go-Operators Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to Trim a String in Golang? How to compare times in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2021" }, { "code": null, "e": 526, "s": 28, "text": "Short Variable Declaration Operator(:=) in Golang is used to create the variables having a proper name and initial value. The main purpose of using this operator to declare and initialize the local variables inside the functions and to narrowing the scope of the variables. The type of the variable is determined by the type of the expression. var keyword is also used to create the variables of a specific type. So you can say that there are two ways to create the variables in Golang as follows:" }, { "code": null, "e": 548, "s": 526, "text": "Using the var keyword" }, { "code": null, "e": 598, "s": 548, "text": "Using the short variable declaration operator(:=)" }, { "code": null, "e": 865, "s": 598, "text": "In this article, we will only discuss the short variable declaration operator. To know about var keyword you can refer var keyword in Go. You can also read the difference between var keyword and short variable declaration operator to get a proper idea of using both." }, { "code": null, "e": 919, "s": 865, "text": "Syntax of using short variable declaration operator: " }, { "code": null, "e": 956, "s": 919, "text": "variable_name := expression or value" }, { "code": null, "e": 1241, "s": 956, "text": "Here, you must initialize the variable just after declaration. But using var keyword you can avoid initialization at the time of declaration. There is no need to mention the type of the variable. Expression or value on the right-hand side is used to evaluate the type of the variable." }, { "code": null, "e": 1481, "s": 1241, "text": "Example: Here, we are declaring the variables using short declaration operator and we are not specifying the type of the variable. The type of the variable is determined by the type of the expression on the right-hand side of := operator. " }, { "code": null, "e": 1484, "s": 1481, "text": "Go" }, { "code": "// Go program to illustrate the use// of := (short declaration// operator)package main import \"fmt\" func main() { // declaring and initializing the variable a := 30 // taking a string variable Language: = \"Go Programming\" fmt.Println(\"The Value of a is: \", a) fmt.Println(\"The Value of Language is: \", Language) }", "e": 1822, "s": 1484, "text": null }, { "code": null, "e": 1830, "s": 1822, "text": "Output:" }, { "code": null, "e": 1895, "s": 1830, "text": "The Value of a is: 30\nThe Value of Language is: Go Programming" }, { "code": null, "e": 2133, "s": 1897, "text": "Short Declaration operator can also be used to declare multiple variables of the same type or different types in the single declaration. The type of these variables is evaluated by the expression on the right-hand side of := operator. " }, { "code": null, "e": 2143, "s": 2133, "text": "Example: " }, { "code": null, "e": 2146, "s": 2143, "text": "Go" }, { "code": "// Go program to illustrate how to use := short// declaration operator to declare multiple// variables into a single declaration statementpackage main import \"fmt\" func main() { // multiple variables of same type(int)geek1, geek2, geek3 := 117, 7834, 5685 // multiple variables of different typesgeek4, geek5, geek6 := \"GFG\", 859.24, 1234 // Display the value and// type of the variablesfmt.Printf(\"The value of geek1 is : %d\\n\", geek1)fmt.Printf(\"The type of geek1 is : %T\\n\", geek1) fmt.Printf(\"\\nThe value of geek2 is : %d\\n\", geek2)fmt.Printf(\"The type of geek2 is : %T\\n\", geek2) fmt.Printf(\"\\nThe value of geek3 is : %d\\n\", geek3)fmt.Printf(\"The type of geek3 is : %T\\n\", geek3) fmt.Printf(\"\\nThe value of geek4 is : %s\\n\", geek4)fmt.Printf(\"The type of geek4 is : %T\\n\", geek4) fmt.Printf(\"\\nThe value of geek5 is : %f\\n\", geek5)fmt.Printf(\"The type of geek5 is : %T\\n\", geek5) fmt.Printf(\"\\nThe value of geek6 is : %d\\n\", geek6)fmt.Printf(\"The type of geek6 is : %T\\n\", geek6) }", "e": 3136, "s": 2146, "text": null }, { "code": null, "e": 3144, "s": 3136, "text": "Output:" }, { "code": null, "e": 3496, "s": 3144, "text": "The value of geek1 is : 117\nThe type of geek1 is : int\n\nThe value of geek2 is : 7834\nThe type of geek2 is : int\n\nThe value of geek3 is : 5685\nThe type of geek3 is : int\n\nThe value of geek4 is : GFG\nThe type of geek4 is : string\n\nThe value of geek5 is : 859.240000\nThe type of geek5 is : float64\n\nThe value of geek6 is : 1234\nThe type of geek6 is : int" }, { "code": null, "e": 3515, "s": 3496, "text": "Important Points: " }, { "code": null, "e": 3962, "s": 3515, "text": "Short declaration operator can be used when at least one of the variable in the left-hand side of := operator is newly declared. A short variable declaration operator behaves like an assignment for those variables which are already declared in the same lexical block. To get a better idea about this concept, let’s take an example.Example 1: Below program will give an error as there are no new variables in the left-hand side of the := operator." }, { "code": null, "e": 3965, "s": 3962, "text": "Go" }, { "code": "// Go program to illustrate the concept// of short variable declarationpackage main import \"fmt\" func main() { // taking two variables p, q := 100, 200 fmt.Println(\"Value of p \", p, \"Value of q \", q) // this will give an error as // there are no new variable // on the left-hand side of := p, q := 500, 600 fmt.Println(\"Value of p \", p, \"Value of q \", q)}", "e": 4353, "s": 3965, "text": null }, { "code": null, "e": 4360, "s": 4353, "text": "Error:" }, { "code": null, "e": 4415, "s": 4360, "text": "./prog.go:17:10: no new variables on left side of := " }, { "code": null, "e": 4625, "s": 4415, "text": "Example 2: In the below program, you can see that the line of code geek3, geek2 := 456, 200 will work fine without any error as there is at least a new variable i.e. geek3 on the left-hand side of := operator." }, { "code": null, "e": 4628, "s": 4625, "text": "Go" }, { "code": "// Go program to show how to use// short variable declaration operatorpackage main import \"fmt\" func main() { // Here, short variable declaration acts// as an assignment for geek1 variable// because same variable present in the same block// so the value of geek2 is changed from 100 to 200geek1, geek2 := 78, 100 // here, := is used as an assignment for geek2// as it is already declared. Also, this line// will work fine as geek3 is newly created// variablegeek3, geek2 := 456, 200 // If you try to run the commented lines,// then compiler will gives error because// these variables are already defined// geek1, geek2 := 745, 956// geek3 := 150 // Display the values of the variablesfmt.Printf(\"The value of geek1 and geek2 is : %d %d\\n\", geek1, geek2) fmt.Printf(\"The value of geek3 and geek2 is : %d %d\\n\", geek3, geek2)}", "e": 5497, "s": 4628, "text": null }, { "code": null, "e": 5505, "s": 5497, "text": "Output:" }, { "code": null, "e": 5588, "s": 5505, "text": "The value of geek1 and geek2 is : 78 200\nThe value of geek3 and geek2 is : 456 200" }, { "code": null, "e": 5702, "s": 5588, "text": "Go is a strongly typed language as you cannot assign a value of another type to the declared variable. Example:" }, { "code": null, "e": 5705, "s": 5702, "text": "Go" }, { "code": "// Go program to show how to use// short variable declaration operatorpackage main import \"fmt\" func main() { // taking a variable of int type z := 50 fmt.Printf(\"Value of z is %d\", z) // reassigning the value of string type // it will give an error z := \"Golang\"}", "e": 5999, "s": 5705, "text": null }, { "code": null, "e": 6006, "s": 5999, "text": "Error:" }, { "code": null, "e": 6136, "s": 6006, "text": "./prog.go:16:4: no new variables on left side of := ./prog.go:16:7: cannot use “Golang” (type string) as type int in assignment " }, { "code": null, "e": 6371, "s": 6136, "text": "In a short variable declaration, it is allowed to initializing a set of variables by the calling function which returns multiple values. Or you can say variables can also be assigned values that are evaluated during run time. Example:" }, { "code": null, "e": 6462, "s": 6371, "text": "// Here, math.Max function return \n// the maximum number in i variable\ni := math.Max(x, y)" }, { "code": null, "e": 6773, "s": 6462, "text": "With the help of short variable declaration operator(:=) you can only declare the local variable which has only block-level scope. Generally, local variables are declared inside the function block. If you will try to declare the global variables using the short declaration operator then you will get an error." }, { "code": null, "e": 6785, "s": 6773, "text": "Example 1: " }, { "code": null, "e": 6788, "s": 6785, "text": "Go" }, { "code": "// Go program to show the use of := operator// to declare local variablespackage main import \"fmt\" // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar geek1 = 900 // using short variable declaration// it will give an errorgeek2 := 200 func main() { // accessing geek1 inside the functionfmt.Println(geek1) // accessing geek2 inside the functionfmt.Println(geek2) }", "e": 7237, "s": 6788, "text": null }, { "code": null, "e": 7244, "s": 7237, "text": "Error:" }, { "code": null, "e": 7324, "s": 7244, "text": "./prog.go:15:1: syntax error: non-declaration statement outside function body " }, { "code": null, "e": 7335, "s": 7324, "text": "Example 2:" }, { "code": null, "e": 7338, "s": 7335, "text": "Go" }, { "code": "// Go program to show the use of := operator// to declare local variablespackage main import \"fmt\" // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar geek1 = 900 func main() { // using short variable declaration// inside the main function// it has local scope i.e. can't// accessed outside the main functiongeek2 := 200 // accessing geek1 inside the functionfmt.Println(geek1) // accessing geek2 inside the functionfmt.Println(geek2) }", "e": 7858, "s": 7338, "text": null }, { "code": null, "e": 7867, "s": 7858, "text": "Output: " }, { "code": null, "e": 7875, "s": 7867, "text": "900\n200" }, { "code": null, "e": 7888, "s": 7877, "text": "nidhi_biet" }, { "code": null, "e": 7896, "s": 7888, "text": "clintra" }, { "code": null, "e": 7909, "s": 7896, "text": "Go-Operators" }, { "code": null, "e": 7916, "s": 7909, "text": "Golang" }, { "code": null, "e": 7928, "s": 7916, "text": "Go Language" }, { "code": null, "e": 8026, "s": 7928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8077, "s": 8026, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 8090, "s": 8077, "text": "Arrays in Go" }, { "code": null, "e": 8102, "s": 8090, "text": "Golang Maps" }, { "code": null, "e": 8135, "s": 8102, "text": "How to Split a String in Golang?" }, { "code": null, "e": 8156, "s": 8135, "text": "Interfaces in Golang" }, { "code": null, "e": 8173, "s": 8156, "text": "Slices in Golang" }, { "code": null, "e": 8227, "s": 8173, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 8256, "s": 8227, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 8288, "s": 8256, "text": "How to Trim a String in Golang?" } ]
Class Type Casting in Java
17 Sep, 2021 Typecasting is the assessment of the value of one primitive data type to another type. In java, there are two types of casting namely upcasting and downcasting as follows: Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree. It is an automatic procedure for which there are no efforts poured in to do so where a sub-class object is referred by a superclass reference variable. One can relate it with dynamic polymorphism.Implicit casting means class typecasting done by the compiler without cast syntax.Explicit casting means class typecasting done by the programmer with cast syntax.Downcasting refers to the procedure when subclass type refers to the object of the parent class is known as downcasting. If it is performed directly compiler gives an error as ClassCastException is thrown at runtime. It is only achievable with the use of instanceof operator The object which is already upcast, that object only can be performed downcast. Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree. It is an automatic procedure for which there are no efforts poured in to do so where a sub-class object is referred by a superclass reference variable. One can relate it with dynamic polymorphism.Implicit casting means class typecasting done by the compiler without cast syntax.Explicit casting means class typecasting done by the programmer with cast syntax. Implicit casting means class typecasting done by the compiler without cast syntax. Explicit casting means class typecasting done by the programmer with cast syntax. Downcasting refers to the procedure when subclass type refers to the object of the parent class is known as downcasting. If it is performed directly compiler gives an error as ClassCastException is thrown at runtime. It is only achievable with the use of instanceof operator The object which is already upcast, that object only can be performed downcast. In order to perform class type casting we have to follow these two rules as follows: Classes must be “IS-A-Relationship “An object must have the property of a class in which it is going to cast. Classes must be “IS-A-Relationship “ An object must have the property of a class in which it is going to cast. Implementation: (A) Upcasting Example 1 Java // Importing input output classesimport java.io.*; // Class 1// Parent classclass Parent{ // Function void show() { // Print message for this class System.out.println("Parent show method is called"); }} // Class 2// Child classclass Child extends Parent { // Overriding existing method of Parent class @Override // Same Function which will override // existing Parent class function void show() { // Print message for this class System.out.println("Child show method is called"); } } // Class3// Main classclass GFG{ // Main driver method public static void main(String[] args) { // Creating a Parent class object // but referencing it to a Child class Parent obj = new Child(); // Calling the show() method to execute obj.show(); }} Child show method is called Output explanation: Here parent class object is called but referred to the child’s class object. Hence, one can relate this with dynamic polymorphism or function overriding. (B) Downcasting Example 2 Java // Java Program to illustrate Downcasting // Importing input output classesimport java.io.*; // Class 1// Parent classclass Vehicles {} // Class 2// Child classclass Car extends Vehicles { static void method(Vehicles v) { // if (v instanceof Car) { // Downcasting Car c = (Car)v; // Display message System.out.println("Downcasting performed"); } } // Main driver method public static void main(String[] args) { // Creating an object of Vehicle class // and referring it to Car class Vehicles v = new Car(); Car.method(v); }} Downcasting performed NOTE : Without perform upcast if we try to downcast , ClassCastException will be thrown. It is a runtime exception or unchecked exception. It is class, present in java.lang package. It can be avoided by using a operator known as ‘instanceof’. Example 3 Java // Java Program showing ClassCastException // Importing input output classesimport java.io.*; // Class 1// Parent class/ Member classclass Member { // Member variable of this class String name; long phone; // Member function of this class void chat() { // Print message of Member/ Child class System.out.println( name + " : chatting in whatsapp group"); }} // Class 2// Child class/ Admin classclass Admin extends Member { // Member function of this class void addUser() { // Print message of Admin/ Parent class System.out.println( name + " : adding a new user in whatsapp group"); }} // Class3 - Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object Ad Member mem = new Admin(); // Upcasting access only general property of // superclass // Custom entry for Member class mem.name = "Sneha"; mem.phone = 9876543210l; // Calling function mem.chat(); Admin ad = (Admin)mem; // Downcast to access specific property of subclass ad.addUser(); }} Sneha : chatting in whatsapp group Sneha : adding a new user in whatsapp group simmytarika5 surindertarika1234 java-inheritance Java-Object Oriented Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Sep, 2021" }, { "code": null, "e": 226, "s": 54, "text": "Typecasting is the assessment of the value of one primitive data type to another type. In java, there are two types of casting namely upcasting and downcasting as follows:" }, { "code": null, "e": 1035, "s": 226, "text": "Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree. It is an automatic procedure for which there are no efforts poured in to do so where a sub-class object is referred by a superclass reference variable. One can relate it with dynamic polymorphism.Implicit casting means class typecasting done by the compiler without cast syntax.Explicit casting means class typecasting done by the programmer with cast syntax.Downcasting refers to the procedure when subclass type refers to the object of the parent class is known as downcasting. If it is performed directly compiler gives an error as ClassCastException is thrown at runtime. It is only achievable with the use of instanceof operator The object which is already upcast, that object only can be performed downcast." }, { "code": null, "e": 1490, "s": 1035, "text": "Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree. It is an automatic procedure for which there are no efforts poured in to do so where a sub-class object is referred by a superclass reference variable. One can relate it with dynamic polymorphism.Implicit casting means class typecasting done by the compiler without cast syntax.Explicit casting means class typecasting done by the programmer with cast syntax." }, { "code": null, "e": 1573, "s": 1490, "text": "Implicit casting means class typecasting done by the compiler without cast syntax." }, { "code": null, "e": 1655, "s": 1573, "text": "Explicit casting means class typecasting done by the programmer with cast syntax." }, { "code": null, "e": 2010, "s": 1655, "text": "Downcasting refers to the procedure when subclass type refers to the object of the parent class is known as downcasting. If it is performed directly compiler gives an error as ClassCastException is thrown at runtime. It is only achievable with the use of instanceof operator The object which is already upcast, that object only can be performed downcast." }, { "code": null, "e": 2095, "s": 2010, "text": "In order to perform class type casting we have to follow these two rules as follows:" }, { "code": null, "e": 2205, "s": 2095, "text": "Classes must be “IS-A-Relationship “An object must have the property of a class in which it is going to cast." }, { "code": null, "e": 2242, "s": 2205, "text": "Classes must be “IS-A-Relationship “" }, { "code": null, "e": 2316, "s": 2242, "text": "An object must have the property of a class in which it is going to cast." }, { "code": null, "e": 2333, "s": 2316, "text": "Implementation: " }, { "code": null, "e": 2347, "s": 2333, "text": "(A) Upcasting" }, { "code": null, "e": 2357, "s": 2347, "text": "Example 1" }, { "code": null, "e": 2362, "s": 2357, "text": "Java" }, { "code": "// Importing input output classesimport java.io.*; // Class 1// Parent classclass Parent{ // Function void show() { // Print message for this class System.out.println(\"Parent show method is called\"); }} // Class 2// Child classclass Child extends Parent { // Overriding existing method of Parent class @Override // Same Function which will override // existing Parent class function void show() { // Print message for this class System.out.println(\"Child show method is called\"); } } // Class3// Main classclass GFG{ // Main driver method public static void main(String[] args) { // Creating a Parent class object // but referencing it to a Child class Parent obj = new Child(); // Calling the show() method to execute obj.show(); }}", "e": 3189, "s": 2362, "text": null }, { "code": null, "e": 3217, "s": 3189, "text": "Child show method is called" }, { "code": null, "e": 3392, "s": 3217, "text": "Output explanation: Here parent class object is called but referred to the child’s class object. Hence, one can relate this with dynamic polymorphism or function overriding. " }, { "code": null, "e": 3408, "s": 3392, "text": "(B) Downcasting" }, { "code": null, "e": 3418, "s": 3408, "text": "Example 2" }, { "code": null, "e": 3423, "s": 3418, "text": "Java" }, { "code": "// Java Program to illustrate Downcasting // Importing input output classesimport java.io.*; // Class 1// Parent classclass Vehicles {} // Class 2// Child classclass Car extends Vehicles { static void method(Vehicles v) { // if (v instanceof Car) { // Downcasting Car c = (Car)v; // Display message System.out.println(\"Downcasting performed\"); } } // Main driver method public static void main(String[] args) { // Creating an object of Vehicle class // and referring it to Car class Vehicles v = new Car(); Car.method(v); }}", "e": 4065, "s": 3423, "text": null }, { "code": null, "e": 4090, "s": 4068, "text": "Downcasting performed" }, { "code": null, "e": 4179, "s": 4090, "text": "NOTE : Without perform upcast if we try to downcast , ClassCastException will be thrown." }, { "code": null, "e": 4229, "s": 4179, "text": "It is a runtime exception or unchecked exception." }, { "code": null, "e": 4272, "s": 4229, "text": "It is class, present in java.lang package." }, { "code": null, "e": 4333, "s": 4272, "text": "It can be avoided by using a operator known as ‘instanceof’." }, { "code": null, "e": 4345, "s": 4335, "text": "Example 3" }, { "code": null, "e": 4352, "s": 4347, "text": "Java" }, { "code": "// Java Program showing ClassCastException // Importing input output classesimport java.io.*; // Class 1// Parent class/ Member classclass Member { // Member variable of this class String name; long phone; // Member function of this class void chat() { // Print message of Member/ Child class System.out.println( name + \" : chatting in whatsapp group\"); }} // Class 2// Child class/ Admin classclass Admin extends Member { // Member function of this class void addUser() { // Print message of Admin/ Parent class System.out.println( name + \" : adding a new user in whatsapp group\"); }} // Class3 - Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object Ad Member mem = new Admin(); // Upcasting access only general property of // superclass // Custom entry for Member class mem.name = \"Sneha\"; mem.phone = 9876543210l; // Calling function mem.chat(); Admin ad = (Admin)mem; // Downcast to access specific property of subclass ad.addUser(); }}", "e": 5548, "s": 4352, "text": null }, { "code": null, "e": 5630, "s": 5551, "text": "Sneha : chatting in whatsapp group\nSneha : adding a new user in whatsapp group" }, { "code": null, "e": 5645, "s": 5632, "text": "simmytarika5" }, { "code": null, "e": 5664, "s": 5645, "text": "surindertarika1234" }, { "code": null, "e": 5681, "s": 5664, "text": "java-inheritance" }, { "code": null, "e": 5702, "s": 5681, "text": "Java-Object Oriented" }, { "code": null, "e": 5707, "s": 5702, "text": "Java" }, { "code": null, "e": 5712, "s": 5707, "text": "Java" }, { "code": null, "e": 5810, "s": 5712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5825, "s": 5810, "text": "Stream In Java" }, { "code": null, "e": 5846, "s": 5825, "text": "Introduction to Java" }, { "code": null, "e": 5867, "s": 5846, "text": "Constructors in Java" }, { "code": null, "e": 5886, "s": 5867, "text": "Exceptions in Java" }, { "code": null, "e": 5903, "s": 5886, "text": "Generics in Java" }, { "code": null, "e": 5933, "s": 5903, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5959, "s": 5933, "text": "Java Programming Examples" }, { "code": null, "e": 5975, "s": 5959, "text": "Strings in Java" }, { "code": null, "e": 6012, "s": 5975, "text": "Differences between JDK, JRE and JVM" } ]
Matplotlib.pyplot.subplot2grid() in python
19 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The Matplotlib.pyplot.subplot2grid() function give additional flexibility in creating axes object at a specified location inside a grid. It also helps in spanning the axes object across multiple rows or columns. In simpler words, this function is used to create multiple charts within the same figure. It is a sub-figure layout manager. Syntax : Plt.subplot2grid(shape, location, rowspan, colspan) Parameters : shape: As the name suggests it is used to define the shape of the grid to be plotted within the graph. It is a required argument and is generally passed in as a list or tuple of two numbers which are responsible for the layout of the grid with the first number being the number of rows and the second number as the number of columns. location (loc): This is the second mandatory argument that this function takes. Similar to the shape argument it is also a required argument and is generally passed in as a list or tuple of two numbers. It is used for specifying the row and column number to place the sub-plot. It is also important to note that the indexes start from 0. So (0, 0) would be the cell in the first row and the first column of the grid. rowspan: Once the grid layout is set and the starting index is decided using location(loc) one can expand the selection to take up more rows with this argument. This is an optional parameter and has a default value of 1. colspan: Similar to rowspan it is used to expand the selection to take up more columns. It is also an optional parameter with default value of 1. Example 1: import matplotlib.pyplot as plt fig = plt.figure() axes1 = plt.subplot2grid((4, 4), (0, 0), colspan = 4) axes2 = plt.subplot2grid((4, 4), (1, 0), colspan = 3) axes3 = plt.subplot2grid((4, 4), (1, 2), rowspan = 3) axes4 = plt.subplot2grid((4, 4), (2, 0))axes5 = plt.subplot2grid((4, 4), (2, 1)) fig.tight_layout() Output : Example 2: import randomimport matplotlib.pyplot as pltfrom matplotlib import style style.use('fivethirtyeight') fig = plt.figure() # helper function to plot the linesdef helper(): xs = [] ys = [] for i in range(10): x = i y = random.randrange(10) xs.append(x) ys.append(y) return xs, ys axes1 = plt.subplot2grid ((7, 1), (0, 0), rowspan = 2, colspan = 1) axes2 = plt.subplot2grid ((7, 1), (2, 0), rowspan = 2, colspan = 1) axes3 = plt.subplot2grid ((7, 1), (4, 0), rowspan = 2, colspan = 1) x, y = helper()axes1.plot(x, y) x, y = helper()axes2.plot(x, y) x, y = helper()axes3.plot(x, y) Output: Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 577, "s": 240, "text": "The Matplotlib.pyplot.subplot2grid() function give additional flexibility in creating axes object at a specified location inside a grid. It also helps in spanning the axes object across multiple rows or columns. In simpler words, this function is used to create multiple charts within the same figure. It is a sub-figure layout manager." }, { "code": null, "e": 638, "s": 577, "text": "Syntax : Plt.subplot2grid(shape, location, rowspan, colspan)" }, { "code": null, "e": 651, "s": 638, "text": "Parameters :" }, { "code": null, "e": 985, "s": 651, "text": "shape: As the name suggests it is used to define the shape of the grid to be plotted within the graph. It is a required argument and is generally passed in as a list or tuple of two numbers which are responsible for the layout of the grid with the first number being the number of rows and the second number as the number of columns." }, { "code": null, "e": 1402, "s": 985, "text": "location (loc): This is the second mandatory argument that this function takes. Similar to the shape argument it is also a required argument and is generally passed in as a list or tuple of two numbers. It is used for specifying the row and column number to place the sub-plot. It is also important to note that the indexes start from 0. So (0, 0) would be the cell in the first row and the first column of the grid." }, { "code": null, "e": 1623, "s": 1402, "text": "rowspan: Once the grid layout is set and the starting index is decided using location(loc) one can expand the selection to take up more rows with this argument. This is an optional parameter and has a default value of 1." }, { "code": null, "e": 1769, "s": 1623, "text": "colspan: Similar to rowspan it is used to expand the selection to take up more columns. It is also an optional parameter with default value of 1." }, { "code": null, "e": 1780, "s": 1769, "text": "Example 1:" }, { "code": "import matplotlib.pyplot as plt fig = plt.figure() axes1 = plt.subplot2grid((4, 4), (0, 0), colspan = 4) axes2 = plt.subplot2grid((4, 4), (1, 0), colspan = 3) axes3 = plt.subplot2grid((4, 4), (1, 2), rowspan = 3) axes4 = plt.subplot2grid((4, 4), (2, 0))axes5 = plt.subplot2grid((4, 4), (2, 1)) fig.tight_layout()", "e": 2174, "s": 1780, "text": null }, { "code": null, "e": 2183, "s": 2174, "text": "Output :" }, { "code": null, "e": 2194, "s": 2183, "text": "Example 2:" }, { "code": "import randomimport matplotlib.pyplot as pltfrom matplotlib import style style.use('fivethirtyeight') fig = plt.figure() # helper function to plot the linesdef helper(): xs = [] ys = [] for i in range(10): x = i y = random.randrange(10) xs.append(x) ys.append(y) return xs, ys axes1 = plt.subplot2grid ((7, 1), (0, 0), rowspan = 2, colspan = 1) axes2 = plt.subplot2grid ((7, 1), (2, 0), rowspan = 2, colspan = 1) axes3 = plt.subplot2grid ((7, 1), (4, 0), rowspan = 2, colspan = 1) x, y = helper()axes1.plot(x, y) x, y = helper()axes2.plot(x, y) x, y = helper()axes3.plot(x, y)", "e": 2987, "s": 2194, "text": null }, { "code": null, "e": 2995, "s": 2987, "text": "Output:" }, { "code": null, "e": 3013, "s": 2995, "text": "Python-matplotlib" }, { "code": null, "e": 3020, "s": 3013, "text": "Python" }, { "code": null, "e": 3036, "s": 3020, "text": "Write From Home" } ]
sklearn.cross_decomposition.PLSRegression() function in Python
03 Jun, 2021 PLS regression is a Regression method that takes into account the latent structure in both datasets. Partial least squares regression performed well in MRI-based assessments for both single-label and multi-label learning reasons. PLSRegression acquires from PLS with mode=”A” and deflation_mode=”regression”. Additionally, known PLS2 or PLS in the event of a one-dimensional response. Syntax: class sklearn.cross_decomposition.PLSRegression(n_components=2, *, scale=True, max_iter=500, tol=1e-06, copy=True) Parameters: This function accepts five parameters which are mentioned above and defined below: n_components:<int>: Its default value is 2, and it accepts the number of components that are needed to keep. scale:<bool>: Its default value is True, and it accepts whether to scale the data or not. max_iteran :<int>: Its default value is 500, and it accepts the maximum number of iteration of the NIPALS inner loop. tol: <non-negative real>: Its default value is 1e-06, and it accepts tolerance used in the iterative algorithm. copy:<bool>: Its default value is True, and it shows that deflection should be done on a copy. Don’t care about side effects when the default value is set True. Return Value: PLSRegression is an approach for predicting response. The below Example illustrates the use of the PLSRegression() Model. Example: Python3 import numpy as npimport pandas as pdfrom sklearn import datasetsimport matplotlib.pyplot as pltfrom sklearn.cross_decomposition import PLSRegressionfrom sklearn.model_selection import train_test_split # load boston data using sklearn datasetsboston = datasets.load_boston() # separate data and target valuesx = boston.datay = boston.target # tabular data structure with labeled axes# (rows and columns) using DataFramedf_x = pd.DataFrame(x, columns=boston.feature_names)df_y = pd.DataFrame(y) # create PLSRegression modelpls2 = PLSRegression(n_components=2) # split datax_train, x_test, y_train, y_test = train_test_split( df_x, df_y, test_size=0.30, random_state=1) # fit the modelpls2.fit(x_train, y_train) # predict the valuesY_pred = pls2.predict(x_test) # plot the predicted Valuesplt.plot(Y_pred)plt.xticks(rotation=90)plt.show() # print the predicted valueprint(Y_pred) Output: Plot the Predicted value using PLSRegression Print the predicted value using trained model clintra Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2021" }, { "code": null, "e": 413, "s": 28, "text": "PLS regression is a Regression method that takes into account the latent structure in both datasets. Partial least squares regression performed well in MRI-based assessments for both single-label and multi-label learning reasons. PLSRegression acquires from PLS with mode=”A” and deflation_mode=”regression”. Additionally, known PLS2 or PLS in the event of a one-dimensional response." }, { "code": null, "e": 537, "s": 413, "text": "Syntax: class sklearn.cross_decomposition.PLSRegression(n_components=2, *, scale=True, max_iter=500, tol=1e-06, copy=True) " }, { "code": null, "e": 549, "s": 537, "text": "Parameters:" }, { "code": null, "e": 632, "s": 549, "text": "This function accepts five parameters which are mentioned above and defined below:" }, { "code": null, "e": 741, "s": 632, "text": "n_components:<int>: Its default value is 2, and it accepts the number of components that are needed to keep." }, { "code": null, "e": 831, "s": 741, "text": "scale:<bool>: Its default value is True, and it accepts whether to scale the data or not." }, { "code": null, "e": 949, "s": 831, "text": "max_iteran :<int>: Its default value is 500, and it accepts the maximum number of iteration of the NIPALS inner loop." }, { "code": null, "e": 1061, "s": 949, "text": "tol: <non-negative real>: Its default value is 1e-06, and it accepts tolerance used in the iterative algorithm." }, { "code": null, "e": 1222, "s": 1061, "text": "copy:<bool>: Its default value is True, and it shows that deflection should be done on a copy. Don’t care about side effects when the default value is set True." }, { "code": null, "e": 1290, "s": 1222, "text": "Return Value: PLSRegression is an approach for predicting response." }, { "code": null, "e": 1358, "s": 1290, "text": "The below Example illustrates the use of the PLSRegression() Model." }, { "code": null, "e": 1367, "s": 1358, "text": "Example:" }, { "code": null, "e": 1375, "s": 1367, "text": "Python3" }, { "code": "import numpy as npimport pandas as pdfrom sklearn import datasetsimport matplotlib.pyplot as pltfrom sklearn.cross_decomposition import PLSRegressionfrom sklearn.model_selection import train_test_split # load boston data using sklearn datasetsboston = datasets.load_boston() # separate data and target valuesx = boston.datay = boston.target # tabular data structure with labeled axes# (rows and columns) using DataFramedf_x = pd.DataFrame(x, columns=boston.feature_names)df_y = pd.DataFrame(y) # create PLSRegression modelpls2 = PLSRegression(n_components=2) # split datax_train, x_test, y_train, y_test = train_test_split( df_x, df_y, test_size=0.30, random_state=1) # fit the modelpls2.fit(x_train, y_train) # predict the valuesY_pred = pls2.predict(x_test) # plot the predicted Valuesplt.plot(Y_pred)plt.xticks(rotation=90)plt.show() # print the predicted valueprint(Y_pred)", "e": 2257, "s": 1375, "text": null }, { "code": null, "e": 2269, "s": 2261, "text": "Output:" }, { "code": null, "e": 2316, "s": 2271, "text": "Plot the Predicted value using PLSRegression" }, { "code": null, "e": 2366, "s": 2320, "text": "Print the predicted value using trained model" }, { "code": null, "e": 2378, "s": 2370, "text": "clintra" }, { "code": null, "e": 2385, "s": 2378, "text": "Python" }, { "code": null, "e": 2483, "s": 2385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2515, "s": 2483, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2542, "s": 2515, "text": "Python Classes and Objects" }, { "code": null, "e": 2563, "s": 2542, "text": "Python OOPs Concepts" }, { "code": null, "e": 2586, "s": 2563, "text": "Introduction To PYTHON" }, { "code": null, "e": 2642, "s": 2586, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2673, "s": 2642, "text": "Python | os.path.join() method" }, { "code": null, "e": 2715, "s": 2673, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2757, "s": 2715, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2796, "s": 2757, "text": "Python | Get unique values from a list" } ]
Python PIL | UnsharpMask() method
08 Sep, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.PIL.ImageFilter.UnsharpMask() method applies the Unsahrp mask filter to the input image. Syntax: PIl.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)Parameters: radius: Blur Radius percent: Unsharp strength, in percent threshold: Threshold controls the minimum brightness change that will be sharpened See this digital unsharp masking for the explanation of the parametersImage used: Python3 # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 3, percent = 200, threshold = 5)) im2.show() Output: Python3 # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 4, percent = 500, threshold = 8)) im2.show() Output: Python3 # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 5, percent = 500, threshold = 10)) im2.show() Output: gtea Image-Processing Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2021" }, { "code": null, "e": 349, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.PIL.ImageFilter.UnsharpMask() method applies the Unsahrp mask filter to the input image." }, { "code": null, "e": 575, "s": 349, "text": "Syntax: PIl.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)Parameters: radius: Blur Radius percent: Unsharp strength, in percent threshold: Threshold controls the minimum brightness change that will be sharpened " }, { "code": null, "e": 658, "s": 575, "text": "See this digital unsharp masking for the explanation of the parametersImage used: " }, { "code": null, "e": 666, "s": 658, "text": "Python3" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 3, percent = 200, threshold = 5)) im2.show()", "e": 988, "s": 666, "text": null }, { "code": null, "e": 997, "s": 988, "text": "Output: " }, { "code": null, "e": 1005, "s": 997, "text": "Python3" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 4, percent = 500, threshold = 8)) im2.show()", "e": 1327, "s": 1005, "text": null }, { "code": null, "e": 1336, "s": 1327, "text": "Output: " }, { "code": null, "e": 1344, "s": 1336, "text": "Python3" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 5, percent = 500, threshold = 10)) im2.show()", "e": 1667, "s": 1344, "text": null }, { "code": null, "e": 1676, "s": 1667, "text": "Output: " }, { "code": null, "e": 1683, "s": 1678, "text": "gtea" }, { "code": null, "e": 1700, "s": 1683, "text": "Image-Processing" }, { "code": null, "e": 1711, "s": 1700, "text": "Python-pil" }, { "code": null, "e": 1718, "s": 1711, "text": "Python" }, { "code": null, "e": 1816, "s": 1718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1848, "s": 1816, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1875, "s": 1848, "text": "Python Classes and Objects" }, { "code": null, "e": 1906, "s": 1875, "text": "Python | os.path.join() method" }, { "code": null, "e": 1929, "s": 1906, "text": "Introduction To PYTHON" }, { "code": null, "e": 1950, "s": 1929, "text": "Python OOPs Concepts" }, { "code": null, "e": 2006, "s": 1950, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2048, "s": 2006, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2090, "s": 2048, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2129, "s": 2090, "text": "Python | Get unique values from a list" } ]
numpy.fix() in Python
04 Dec, 2020 The numpy.fix() is a mathematical function that rounds elements of the array to the nearest integer towards zero. The rounded values are returned as floats. Syntax : numpy.fix(a, b = None)Parameters : a : [array_like] Input array to be floated.b : [ndarray, optional] Output array. Return : The array of rounded numbers Code #1 : Working # Python program explaining# fix() function import numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array) fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values) in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array) fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values) in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array) fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values) Output : Input array : [0.5, 1.5, 2.5, 3.5, 4.5, 10.1] Rounded values : [ 0. 1. 2. 3. 4. 10.] Input array : [0.53, 1.54, 0.71] Rounded values : [ 0. 1. 0.] Input array : [0.5538, 1.33354, 0.71445] Rounded values : [ 0. 1. 0.] Code #2 : Working # Python program explaining# fix() function import numpy as np in_array = [1, 4, 7, 9, 12]print ("Input array : \n", in_array) fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values) in_array = [133, 344, 437, 449, 12]print ("\nInput array : \n", in_array) fixoff_values = np.fix(in_array)print ("\nRounded values upto 2: \n", fixoff_values) in_array = [133, 344, 437, 449, 12]print ("\nInput array : \n", in_array) fixoff_values = np.fix(in_array)print ("\nRounded values upto 3: \n", fixoff_values) Output : Input array : [1, 4, 7, 9, 12] Rounded values : [ 1. 4. 7. 9. 12.] Input array : [133, 344, 437, 449, 12] Rounded values upto 2: [ 133. 344. 437. 449. 12.] Input array : [133, 344, 437, 449, 12] Rounded values upto 3: [ 133. 344. 437. 449. 12.] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.fix.html#numpy.fix. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 185, "s": 28, "text": "The numpy.fix() is a mathematical function that rounds elements of the array to the nearest integer towards zero. The rounded values are returned as floats." }, { "code": null, "e": 229, "s": 185, "text": "Syntax : numpy.fix(a, b = None)Parameters :" }, { "code": null, "e": 310, "s": 229, "text": "a : [array_like] Input array to be floated.b : [ndarray, optional] Output array." }, { "code": null, "e": 348, "s": 310, "text": "Return : The array of rounded numbers" }, { "code": null, "e": 367, "s": 348, "text": " Code #1 : Working" }, { "code": "# Python program explaining# fix() function import numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print (\"Input array : \\n\", in_array) fixoff_values = np.fix(in_array)print (\"\\nRounded values : \\n\", fixoff_values) in_array = [.53, 1.54, .71]print (\"\\nInput array : \\n\", in_array) fixoff_values = np.fix(in_array)print (\"\\nRounded values : \\n\", fixoff_values) in_array = [.5538, 1.33354, .71445]print (\"\\nInput array : \\n\", in_array) fixoff_values = np.fix(in_array)print (\"\\nRounded values : \\n\", fixoff_values)", "e": 894, "s": 367, "text": null }, { "code": null, "e": 903, "s": 894, "text": "Output :" }, { "code": null, "e": 1151, "s": 903, "text": "Input array : \n [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]\n\nRounded values : \n [ 0. 1. 2. 3. 4. 10.]\n\nInput array : \n [0.53, 1.54, 0.71]\n\nRounded values : \n [ 0. 1. 0.]\n\nInput array : \n [0.5538, 1.33354, 0.71445]\n\nRounded values : \n [ 0. 1. 0.]" }, { "code": null, "e": 1171, "s": 1153, "text": "Code #2 : Working" }, { "code": "# Python program explaining# fix() function import numpy as np in_array = [1, 4, 7, 9, 12]print (\"Input array : \\n\", in_array) fixoff_values = np.fix(in_array)print (\"\\nRounded values : \\n\", fixoff_values) in_array = [133, 344, 437, 449, 12]print (\"\\nInput array : \\n\", in_array) fixoff_values = np.fix(in_array)print (\"\\nRounded values upto 2: \\n\", fixoff_values) in_array = [133, 344, 437, 449, 12]print (\"\\nInput array : \\n\", in_array) fixoff_values = np.fix(in_array)print (\"\\nRounded values upto 3: \\n\", fixoff_values)", "e": 1704, "s": 1171, "text": null }, { "code": null, "e": 1713, "s": 1704, "text": "Output :" }, { "code": null, "e": 1993, "s": 1713, "text": "Input array : \n [1, 4, 7, 9, 12]\n\nRounded values : \n [ 1. 4. 7. 9. 12.]\n\nInput array : \n [133, 344, 437, 449, 12]\n\nRounded values upto 2: \n [ 133. 344. 437. 449. 12.]\n\nInput array : \n [133, 344, 437, 449, 12]\n\nRounded values upto 3: \n [ 133. 344. 437. 449. 12.]" }, { "code": null, "e": 2090, "s": 1993, "text": " References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.fix.html#numpy.fix." }, { "code": null, "e": 2125, "s": 2090, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 2138, "s": 2125, "text": "Python-numpy" }, { "code": null, "e": 2145, "s": 2138, "text": "Python" }, { "code": null, "e": 2243, "s": 2145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2275, "s": 2243, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2302, "s": 2275, "text": "Python Classes and Objects" }, { "code": null, "e": 2323, "s": 2302, "text": "Python OOPs Concepts" }, { "code": null, "e": 2346, "s": 2323, "text": "Introduction To PYTHON" }, { "code": null, "e": 2402, "s": 2346, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2433, "s": 2402, "text": "Python | os.path.join() method" }, { "code": null, "e": 2475, "s": 2433, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2517, "s": 2475, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2556, "s": 2517, "text": "Python | datetime.timedelta() function" } ]
Timeit in Python with Examples
07 Mar, 2022 This article will introduce you to a method of measuring the execution time of your python code snippets. We will be using an in-built python library timeit.This module provides a simple way to find the execution time of small bits of Python code. Why timeit? Well, how about using a simple time module? Just save the time before and after the execution of code and subtract them! But this method is not precise as there might be a background process momentarily running which disrupts the code execution and you will get significant variations in the running time of small code snippets. timeit runs your snippet of code millions of times (default value is 1000000) so that you get the statistically most relevant measurement of code execution time! timeit is pretty simple to use and has a command-line interface as well as a callable one. So now, let’s start exploring this handy library! The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments: stmt which is the statement you want to measure; it defaults to ‘pass’. setup which is the code that you run before running the stmt; it defaults to ‘pass’. We generally use this to import the required modules for our code. timer which is a timeit.Timer object; it usually has a sensible default value so you don’t have to worry about it. number which is the number of executions you’d like to run the stmt. Where the timeit.timeit() function returns the number of seconds it took to execute the code. Example 1Let us see a basic example first. Python3 # importing the required moduleimport timeit # code snippet to be executed only oncemysetup = "from math import sqrt" # code snippet whose execution time is to be measuredmycode = '''def example(): mylist = [] for x in range(100): mylist.append(sqrt(x))''' # timeit statementprint (timeit.timeit(setup = mysetup, stmt = mycode, number = 10000)) The output of above program will be the execution time(in seconds) for 10000 iterations of the code snippet passed to timeit.timeit() function.Note: Pay attention to the fact that the output is the execution time of number times iteration of the code snippet, not the single iteration. For a single iteration exec. time, divide the output time by number. The program is pretty straight-forward. All we need to do is to pass the code as a string to the timeit.timeit() function. It is advisable to keep the import statements and other static pieces of code in setup argument. Example 2Let’s see another practical example in which we will compare two searching techniques, namely, Binary search and Linear search. Also, here I demonstrate two more features, timeit.repeat function and calling the functions already defined in our program. Python3 # importing the required modulesimport timeit # binary search functiondef binary_search(mylist, find): while len(mylist) > 0: mid = (len(mylist))//2 if mylist[mid] == find: return True else if mylist[mid] < find: mylist = mylist[:mid] else: mylist = mylist[mid + 1:] return False # linear search functiondef linear_search(mylist, find): for x in mylist: if x == find: return True return False # compute binary search timedef binary_time(): SETUP_CODE = '''from __main__ import binary_searchfrom random import randint''' TEST_CODE = '''mylist = [x for x in range(10000)]find = randint(0, len(mylist))binary_search(mylist, find)''' # timeit.repeat statement times = timeit.repeat(setup = SETUP_CODE, stmt = TEST_CODE, repeat = 3, number = 10000) # printing minimum exec. time print('Binary search time: {}'.format(min(times))) # compute linear search timedef linear_time(): SETUP_CODE = '''from __main__ import linear_searchfrom random import randint''' TEST_CODE = '''mylist = [x for x in range(10000)]find = randint(0, len(mylist))linear_search(mylist, find) ''' # timeit.repeat statement times = timeit.repeat(setup = SETUP_CODE, stmt = TEST_CODE, repeat = 3, number = 10000) # printing minimum exec. time print('Linear search time: {}'.format(min(times))) if __name__ == "__main__": linear_time() binary_time() The output of above program will be the minimum value in the list times. This is how a sample output looks like: strate below how you can utilize the command lin timeit.repeat() function accepts one extra argument, repeat. The output will be a list of the execution times of all code runs repeated a specified no. of times. In setup argument, we passed: from __main__ import binary_search from random import randint This will import the definition of function binary_search, already defined in the program and random library function randint. As expected, we notice that execution time of binary search is significantly lower than linear search! Example 3 Finally, I demonstrate below how you can utilize the command line interface of timeit module: Here I explain each term individually: So, this was a brief yet concise introduction to timeit module and its practical applications. Its a pretty handy tool for python programmers when they need a quick glance of the execution time of their code snippets. This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. arorakashish0911 surinderdawra388 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Deque in Python Stack in Python Queue in Python Read a file line by line in Python Defaultdict in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Mar, 2022" }, { "code": null, "e": 302, "s": 54, "text": "This article will introduce you to a method of measuring the execution time of your python code snippets. We will be using an in-built python library timeit.This module provides a simple way to find the execution time of small bits of Python code." }, { "code": null, "e": 316, "s": 302, "text": "Why timeit? " }, { "code": null, "e": 645, "s": 316, "text": "Well, how about using a simple time module? Just save the time before and after the execution of code and subtract them! But this method is not precise as there might be a background process momentarily running which disrupts the code execution and you will get significant variations in the running time of small code snippets." }, { "code": null, "e": 807, "s": 645, "text": "timeit runs your snippet of code millions of times (default value is 1000000) so that you get the statistically most relevant measurement of code execution time!" }, { "code": null, "e": 898, "s": 807, "text": "timeit is pretty simple to use and has a command-line interface as well as a callable one." }, { "code": null, "e": 948, "s": 898, "text": "So now, let’s start exploring this handy library!" }, { "code": null, "e": 1035, "s": 948, "text": "The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments: " }, { "code": null, "e": 1107, "s": 1035, "text": "stmt which is the statement you want to measure; it defaults to ‘pass’." }, { "code": null, "e": 1259, "s": 1107, "text": "setup which is the code that you run before running the stmt; it defaults to ‘pass’. We generally use this to import the required modules for our code." }, { "code": null, "e": 1374, "s": 1259, "text": "timer which is a timeit.Timer object; it usually has a sensible default value so you don’t have to worry about it." }, { "code": null, "e": 1443, "s": 1374, "text": "number which is the number of executions you’d like to run the stmt." }, { "code": null, "e": 1537, "s": 1443, "text": "Where the timeit.timeit() function returns the number of seconds it took to execute the code." }, { "code": null, "e": 1582, "s": 1537, "text": "Example 1Let us see a basic example first. " }, { "code": null, "e": 1590, "s": 1582, "text": "Python3" }, { "code": "# importing the required moduleimport timeit # code snippet to be executed only oncemysetup = \"from math import sqrt\" # code snippet whose execution time is to be measuredmycode = '''def example(): mylist = [] for x in range(100): mylist.append(sqrt(x))''' # timeit statementprint (timeit.timeit(setup = mysetup, stmt = mycode, number = 10000))", "e": 1988, "s": 1590, "text": null }, { "code": null, "e": 2343, "s": 1988, "text": "The output of above program will be the execution time(in seconds) for 10000 iterations of the code snippet passed to timeit.timeit() function.Note: Pay attention to the fact that the output is the execution time of number times iteration of the code snippet, not the single iteration. For a single iteration exec. time, divide the output time by number." }, { "code": null, "e": 2466, "s": 2343, "text": "The program is pretty straight-forward. All we need to do is to pass the code as a string to the timeit.timeit() function." }, { "code": null, "e": 2563, "s": 2466, "text": "It is advisable to keep the import statements and other static pieces of code in setup argument." }, { "code": null, "e": 2826, "s": 2563, "text": "Example 2Let’s see another practical example in which we will compare two searching techniques, namely, Binary search and Linear search. Also, here I demonstrate two more features, timeit.repeat function and calling the functions already defined in our program. " }, { "code": null, "e": 2834, "s": 2826, "text": "Python3" }, { "code": "# importing the required modulesimport timeit # binary search functiondef binary_search(mylist, find): while len(mylist) > 0: mid = (len(mylist))//2 if mylist[mid] == find: return True else if mylist[mid] < find: mylist = mylist[:mid] else: mylist = mylist[mid + 1:] return False # linear search functiondef linear_search(mylist, find): for x in mylist: if x == find: return True return False # compute binary search timedef binary_time(): SETUP_CODE = '''from __main__ import binary_searchfrom random import randint''' TEST_CODE = '''mylist = [x for x in range(10000)]find = randint(0, len(mylist))binary_search(mylist, find)''' # timeit.repeat statement times = timeit.repeat(setup = SETUP_CODE, stmt = TEST_CODE, repeat = 3, number = 10000) # printing minimum exec. time print('Binary search time: {}'.format(min(times))) # compute linear search timedef linear_time(): SETUP_CODE = '''from __main__ import linear_searchfrom random import randint''' TEST_CODE = '''mylist = [x for x in range(10000)]find = randint(0, len(mylist))linear_search(mylist, find) ''' # timeit.repeat statement times = timeit.repeat(setup = SETUP_CODE, stmt = TEST_CODE, repeat = 3, number = 10000) # printing minimum exec. time print('Linear search time: {}'.format(min(times))) if __name__ == \"__main__\": linear_time() binary_time()", "e": 4457, "s": 2834, "text": null }, { "code": null, "e": 4570, "s": 4457, "text": "The output of above program will be the minimum value in the list times. This is how a sample output looks like:" }, { "code": null, "e": 4619, "s": 4570, "text": "strate below how you can utilize the command lin" }, { "code": null, "e": 4781, "s": 4619, "text": "timeit.repeat() function accepts one extra argument, repeat. The output will be a list of the execution times of all code runs repeated a specified no. of times." }, { "code": null, "e": 4811, "s": 4781, "text": "In setup argument, we passed:" }, { "code": null, "e": 4873, "s": 4811, "text": "from __main__ import binary_search\nfrom random import randint" }, { "code": null, "e": 5000, "s": 4873, "text": "This will import the definition of function binary_search, already defined in the program and random library function randint." }, { "code": null, "e": 5103, "s": 5000, "text": "As expected, we notice that execution time of binary search is significantly lower than linear search!" }, { "code": null, "e": 5207, "s": 5103, "text": "Example 3 Finally, I demonstrate below how you can utilize the command line interface of timeit module:" }, { "code": null, "e": 5248, "s": 5207, "text": "Here I explain each term individually: " }, { "code": null, "e": 5466, "s": 5248, "text": "So, this was a brief yet concise introduction to timeit module and its practical applications. Its a pretty handy tool for python programmers when they need a quick glance of the execution time of their code snippets." }, { "code": null, "e": 5887, "s": 5466, "text": "This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5904, "s": 5887, "text": "arorakashish0911" }, { "code": null, "e": 5921, "s": 5904, "text": "surinderdawra388" }, { "code": null, "e": 5928, "s": 5921, "text": "Python" }, { "code": null, "e": 6026, "s": 5928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6056, "s": 6026, "text": "Iterate over a list in Python" }, { "code": null, "e": 6101, "s": 6056, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 6123, "s": 6101, "text": "Enumerate() in Python" }, { "code": null, "e": 6173, "s": 6123, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 6191, "s": 6173, "text": "Python Dictionary" }, { "code": null, "e": 6207, "s": 6191, "text": "Deque in Python" }, { "code": null, "e": 6223, "s": 6207, "text": "Stack in Python" }, { "code": null, "e": 6239, "s": 6223, "text": "Queue in Python" }, { "code": null, "e": 6274, "s": 6239, "text": "Read a file line by line in Python" } ]
Structures in Golang
19 Nov, 2019 A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class that does not support inheritance but supports composition. For Example, an address has a name, street, city, state, Pincode. It makes sense to group these three properties into a single structure address as shown below. Declaring a structure: type Address struct { name string street string city string state string Pincode int } In the above, the type keyword introduces a new type. It is followed by the name of the type (Address) and the keyword struct to illustrate that we’re defining a struct. The struct contains a list of various fields inside the curly braces. Each field has a name and a type. Note: We can also make them compact by combining the various fields of the same type as shown in the below example: type Address struct { name, street, city, state string Pincode int } To Define a structure: The syntax for declaring a structure: var a Address The above code creates a variable of a type Address which is by default set to zero. For a struct, zero means all the fields are set to their corresponding zero value. So the fields name, street, city, state are set to “”, and Pincode is set to 0. You can also initialize a variable of a struct type using a struct literal as shown below: var a = Address{"Akshay", "PremNagar", "Dehradun", "Uttarakhand", 252636} Note: Always pass the field values in the same order in which they are declared in the struct. Also, you can’t initialize only a subset of fields with the above syntax. Go also supports the name: value syntax for initializing a struct (the order of fields is irrelevant when using this syntax). And this allows you to initialize only a subset of fields. All the uninitialized fields are set to their corresponding zero value.Example:var a = Address{Name:”Akshay”, street:”PremNagar”, state:”Uttarakhand”, Pincode:252636} //city:”” Example: var a = Address{Name:”Akshay”, street:”PremNagar”, state:”Uttarakhand”, Pincode:252636} //city:”” // Golang program to show how to// declare and define the struct package main import "fmt" // Defining a struct typetype Address struct { Name string city string Pincode int} func main() { // Declaring a variable of a `struct` type // All the struct fields are initialized // with their zero value var a Address fmt.Println(a) // Declaring and initializing a // struct using a struct literal a1 := Address{"Akshay", "Dehradun", 3623572} fmt.Println("Address1: ", a1) // Naming fields while // initializing a struct a2 := Address{Name: "Anikaa", city: "Ballia", Pincode: 277001} fmt.Println("Address2: ", a2) // Uninitialized fields are set to // their corresponding zero-value a3 := Address{Name: "Delhi"} fmt.Println("Address3: ", a3)} Output: { 0} Address1: {Akshay Dehradun 3623572} Address2: {Anikaa Ballia 277001} Address3: {Delhi 0} To access individual fields of a struct you have to use dot (.) operator. Example: // Golang program to show how to// access the fields of structpackage main import "fmt" // defining the structtype Car struct { Name, Model, Color string WeightInKg float64} // Main Functionfunc main() { c := Car{Name: "Ferrari", Model: "GTC4", Color: "Red", WeightInKg: 1920} // Accessing struct fields // using the dot operator fmt.Println("Car Name: ", c.Name) fmt.Println("Car Color: ", c.Color) // Assigning a new value // to a struct field c.Color = "Black" // Displaying the result fmt.Println("Car: ", c)} Output: Car Name: Ferrari Car Color: Red Car: {Ferrari GTC4 Black 1920} Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. You can also create a pointer to a struct as shown in the below example: // Golang program to illustrate// the pointer to structpackage main import "fmt" // defining a structuretype Employee struct { firstName, lastName string age, salary int} func main() { // passing the address of struct variable // emp8 is a pointer to the Employee struct emp8 := &Employee{"Sam", "Anderson", 55, 6000} // (*emp8).firstName is the syntax to access // the firstName field of the emp8 struct fmt.Println("First Name:", (*emp8).firstName) fmt.Println("Age:", (*emp8).age)} Output: First Name: Sam Age: 55 The Golang gives us the option to use emp8.firstName instead of the explicit dereference (*emp8).firstName to access the firstName field. Example to show this is following: // Golang program to illustrate// the pointer to structpackage main import "fmt" // Defining a structuretype Employee struct { firstName, lastName string age, salary int} // Main Functionfunc main() { // taking pointer to struct emp8 := &Employee{"Sam", "Anderson", 55, 6000} // emp8.firstName is used to access // the field firstName fmt.Println("First Name: ", emp8.firstName) fmt.Println("Age: ", emp8.age)} Output: First Name: Sam Age: 55 Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps Time Formatting in Golang Interfaces in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang?
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Nov, 2019" }, { "code": null, "e": 470, "s": 54, "text": "A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class that does not support inheritance but supports composition." }, { "code": null, "e": 631, "s": 470, "text": "For Example, an address has a name, street, city, state, Pincode. It makes sense to group these three properties into a single structure address as shown below." }, { "code": null, "e": 654, "s": 631, "text": "Declaring a structure:" }, { "code": null, "e": 774, "s": 654, "text": " type Address struct {\n name string \n street string\n city string\n state string\n Pincode int\n}\n" }, { "code": null, "e": 1048, "s": 774, "text": "In the above, the type keyword introduces a new type. It is followed by the name of the type (Address) and the keyword struct to illustrate that we’re defining a struct. The struct contains a list of various fields inside the curly braces. Each field has a name and a type." }, { "code": null, "e": 1164, "s": 1048, "text": "Note: We can also make them compact by combining the various fields of the same type as shown in the below example:" }, { "code": null, "e": 1242, "s": 1164, "text": "type Address struct {\n name, street, city, state string\n Pincode int\n}\n" }, { "code": null, "e": 1303, "s": 1242, "text": "To Define a structure: The syntax for declaring a structure:" }, { "code": null, "e": 1318, "s": 1303, "text": "var a Address\n" }, { "code": null, "e": 1566, "s": 1318, "text": "The above code creates a variable of a type Address which is by default set to zero. For a struct, zero means all the fields are set to their corresponding zero value. So the fields name, street, city, state are set to “”, and Pincode is set to 0." }, { "code": null, "e": 1657, "s": 1566, "text": "You can also initialize a variable of a struct type using a struct literal as shown below:" }, { "code": null, "e": 1731, "s": 1657, "text": "var a = Address{\"Akshay\", \"PremNagar\", \"Dehradun\", \"Uttarakhand\", 252636}" }, { "code": null, "e": 1737, "s": 1731, "text": "Note:" }, { "code": null, "e": 1900, "s": 1737, "text": "Always pass the field values in the same order in which they are declared in the struct. Also, you can’t initialize only a subset of fields with the above syntax." }, { "code": null, "e": 2262, "s": 1900, "text": "Go also supports the name: value syntax for initializing a struct (the order of fields is irrelevant when using this syntax). And this allows you to initialize only a subset of fields. All the uninitialized fields are set to their corresponding zero value.Example:var a = Address{Name:”Akshay”, street:”PremNagar”, state:”Uttarakhand”, Pincode:252636} //city:””" }, { "code": null, "e": 2271, "s": 2262, "text": "Example:" }, { "code": null, "e": 2369, "s": 2271, "text": "var a = Address{Name:”Akshay”, street:”PremNagar”, state:”Uttarakhand”, Pincode:252636} //city:””" }, { "code": "// Golang program to show how to// declare and define the struct package main import \"fmt\" // Defining a struct typetype Address struct { Name string city string Pincode int} func main() { // Declaring a variable of a `struct` type // All the struct fields are initialized // with their zero value var a Address fmt.Println(a) // Declaring and initializing a // struct using a struct literal a1 := Address{\"Akshay\", \"Dehradun\", 3623572} fmt.Println(\"Address1: \", a1) // Naming fields while // initializing a struct a2 := Address{Name: \"Anikaa\", city: \"Ballia\", Pincode: 277001} fmt.Println(\"Address2: \", a2) // Uninitialized fields are set to // their corresponding zero-value a3 := Address{Name: \"Delhi\"} fmt.Println(\"Address3: \", a3)}", "e": 3223, "s": 2369, "text": null }, { "code": null, "e": 3231, "s": 3223, "text": "Output:" }, { "code": null, "e": 3331, "s": 3231, "text": "{ 0}\nAddress1: {Akshay Dehradun 3623572}\nAddress2: {Anikaa Ballia 277001}\nAddress3: {Delhi 0}\n" }, { "code": null, "e": 3405, "s": 3331, "text": "To access individual fields of a struct you have to use dot (.) operator." }, { "code": null, "e": 3414, "s": 3405, "text": "Example:" }, { "code": "// Golang program to show how to// access the fields of structpackage main import \"fmt\" // defining the structtype Car struct { Name, Model, Color string WeightInKg float64} // Main Functionfunc main() { c := Car{Name: \"Ferrari\", Model: \"GTC4\", Color: \"Red\", WeightInKg: 1920} // Accessing struct fields // using the dot operator fmt.Println(\"Car Name: \", c.Name) fmt.Println(\"Car Color: \", c.Color) // Assigning a new value // to a struct field c.Color = \"Black\" // Displaying the result fmt.Println(\"Car: \", c)}", "e": 3996, "s": 3414, "text": null }, { "code": null, "e": 4004, "s": 3996, "text": "Output:" }, { "code": null, "e": 4072, "s": 4004, "text": "Car Name: Ferrari\nCar Color: Red\nCar: {Ferrari GTC4 Black 1920}\n" }, { "code": null, "e": 4268, "s": 4072, "text": "Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. You can also create a pointer to a struct as shown in the below example:" }, { "code": "// Golang program to illustrate// the pointer to structpackage main import \"fmt\" // defining a structuretype Employee struct { firstName, lastName string age, salary int} func main() { // passing the address of struct variable // emp8 is a pointer to the Employee struct emp8 := &Employee{\"Sam\", \"Anderson\", 55, 6000} // (*emp8).firstName is the syntax to access // the firstName field of the emp8 struct fmt.Println(\"First Name:\", (*emp8).firstName) fmt.Println(\"Age:\", (*emp8).age)}", "e": 4787, "s": 4268, "text": null }, { "code": null, "e": 4795, "s": 4787, "text": "Output:" }, { "code": null, "e": 4820, "s": 4795, "text": "First Name: Sam\nAge: 55\n" }, { "code": null, "e": 4993, "s": 4820, "text": "The Golang gives us the option to use emp8.firstName instead of the explicit dereference (*emp8).firstName to access the firstName field. Example to show this is following:" }, { "code": "// Golang program to illustrate// the pointer to structpackage main import \"fmt\" // Defining a structuretype Employee struct { firstName, lastName string age, salary int} // Main Functionfunc main() { // taking pointer to struct emp8 := &Employee{\"Sam\", \"Anderson\", 55, 6000} // emp8.firstName is used to access // the field firstName fmt.Println(\"First Name: \", emp8.firstName) fmt.Println(\"Age: \", emp8.age)}", "e": 5443, "s": 4993, "text": null }, { "code": null, "e": 5451, "s": 5443, "text": "Output:" }, { "code": null, "e": 5478, "s": 5451, "text": "First Name: Sam\nAge: 55\n" }, { "code": null, "e": 5485, "s": 5478, "text": "Golang" }, { "code": null, "e": 5497, "s": 5485, "text": "Go Language" }, { "code": null, "e": 5595, "s": 5497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5647, "s": 5595, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 5693, "s": 5647, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 5743, "s": 5693, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 5794, "s": 5743, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 5841, "s": 5794, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 5853, "s": 5841, "text": "Golang Maps" }, { "code": null, "e": 5879, "s": 5853, "text": "Time Formatting in Golang" }, { "code": null, "e": 5900, "s": 5879, "text": "Interfaces in Golang" }, { "code": null, "e": 5954, "s": 5900, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Evaluation of Prefix Expressions
06 Sep, 2021 Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don’t need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long as we can guarantee that a valid prefix or postfix expression is used, it can be evaluated with correctness.We can convert infix to postfix and can convert infix to prefix.In this article, we will discuss how to evaluate an expression written in prefix notation. The method is similar to evaluating a postfix expression. Please read Evaluation of Postfix Expression to know how to evaluate postfix expressionsAlgorithm EVALUATE_PREFIX(STRING) Step 1: Put a pointer P at the end of the end Step 2: If character at P is an operand push it to Stack Step 3: If the character at P is an operator pop two elements from the Stack. Operate on these elements according to the operator, and push the result back to the Stack Step 4: Decrement P by 1 and go to Step 2 as long as there are characters left to be scanned in the expression. Step 5: The Result is stored at the top of the Stack, return it Step 6: End Example to demonstrate working of the algorithm Expression: +9*26 Character | Stack | Explanation Scanned | (Front to | | Back) | ------------------------------------------- 6 6 6 is an operand, push to Stack 2 6 2 2 is an operand, push to Stack * 12 (6*2) * is an operator, pop 6 and 2, multiply them and push result to Stack 9 12 9 9 is an operand, push to Stack + 21 (12+9) + is an operator, pop 12 and 9 add them and push result to Stack Result: 21 Examples: Input : -+8/632 Output : 8 Input : -+7*45+20 Output : 25 Complexity The algorithm has linear complexity since we scan the expression once and perform at most O(N) push and pop operations which take constant time.Implementation of the algorithm is given below. C++ Java Python3 C# Javascript // C++ program to evaluate a prefix expression.#include <bits/stdc++.h>using namespace std; bool isOperand(char c){ // If the character is a digit then it must // be an operand return isdigit(c);} double evaluatePrefix(string exprsn){ stack<double> Stack; for (int j = exprsn.size() - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.push(exprsn[j] - '0'); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.top(); Stack.pop(); double o2 = Stack.top(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack.top();} // Driver codeint main(){ string exprsn = "+9*26"; cout << evaluatePrefix(exprsn) << endl; return 0;} // Java program to evaluate// a prefix expression.import java.io.*;import java.util.*; class GFG { static Boolean isOperand(char c) { // If the character is a digit // then it must be an operand if (c >= 48 && c <= 57) return true; else return false; } static double evaluatePrefix(String exprsn) { Stack<Double> Stack = new Stack<Double>(); for (int j = exprsn.length() - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn.charAt(j))) Stack.push((double)(exprsn.charAt(j) - 48)); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.peek(); Stack.pop(); double o2 = Stack.peek(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn.charAt(j)) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack.peek(); } /* Driver program to test above function */ public static void main(String[] args) { String exprsn = "+9*26"; System.out.println(evaluatePrefix(exprsn)); }} // This code is contributed by Gitanjali """Python3 program to evaluate a prefix expression.""" def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. """ stack = [] # iterate over the string in reverse order for c in expression[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() if c == '+': stack.append(o1 + o2) elif c == '-': stack.append(o1 - o2) elif c == '*': stack.append(o1 * o2) elif c == '/': stack.append(o1 / o2) return stack.pop() # Driver codeif __name__ == "__main__": test_expression = "+9*26" print(evaluate(test_expression)) # This code is contributed by Leon Morten Richter (GitHub: M0r13n) // C# program to evaluate// a prefix expression.using System;using System.Collections.Generic; class GFG { static Boolean isOperand(char c) { // If the character is a digit // then it must be an operand if (c >= 48 && c <= 57) return true; else return false; } static double evaluatePrefix(String exprsn) { Stack<Double> Stack = new Stack<Double>(); for (int j = exprsn.Length - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.Push((double)(exprsn[j] - 48)); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.Peek(); Stack.Pop(); double o2 = Stack.Peek(); Stack.Pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.Push(o1 + o2); break; case '-': Stack.Push(o1 - o2); break; case '*': Stack.Push(o1 * o2); break; case '/': Stack.Push(o1 / o2); break; } } } return Stack.Peek(); } /* Driver code */ public static void Main(String[] args) { String exprsn = "+9*26"; Console.WriteLine(evaluatePrefix(exprsn)); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to evaluate a prefix expression. function isOperand(c) { // If the character is a digit // then it must be an operand if (c.charCodeAt() >= 48 && c.charCodeAt() <= 57) return true; else return false; } function evaluatePrefix(exprsn) { let Stack = []; for (let j = exprsn.length - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.push((exprsn[j].charCodeAt() - 48)); else { // Operator encountered // Pop two elements from Stack let o1 = Stack[Stack.length - 1]; Stack.pop(); let o2 = Stack[Stack.length - 1]; Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack[Stack.length - 1]; } let exprsn = "+9*26"; document.write(evaluatePrefix(exprsn)); // This code is contributed by suresh07.</script> 21 Note: To perform more types of operations only the switch case table needs to be modified. This implementation works only for single digit operands. Multi-digit operands can be implemented if some character-like space is used to separate the operands and operators. Below given is the extended program which allows operands to have multiple digits. C++ Java Python3 C# Javascript // C++ program to evaluate a prefix expression.#include <bits/stdc++.h>using namespace std; double evaluatePrefix(string exprsn){ stack<double> Stack; for (int j = exprsn.size() - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn[j] == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn[j])) { // there may be more than // one digits in a number double num = 0, i = j; while (j < exprsn.size() && isdigit(exprsn[j])) j--; j++; // from [j, i] exprsn contains a number for (int k = j; k <= i; k++) num = num * 10 + double(exprsn[k] - '0'); Stack.push(num); } else { // Operator encountered // Pop two elements from Stack double o1 = Stack.top(); Stack.pop(); double o2 = Stack.top(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack.top();} // Driver codeint main(){ string exprsn = "+ 9 * 12 6"; cout << evaluatePrefix(exprsn) << endl; return 0; // this code is contributed by Mohd Shaad Khan} // Java program to evaluate a prefix expression.import java.util.*;public class Main{ static boolean isdigit(char ch) { if(ch >= 48 && ch <= 57) { return true; } return false; } static double evaluatePrefix(String exprsn) { Stack<Double> stack = new Stack<Double>(); for (int j = exprsn.length() - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn.charAt(j) == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn.charAt(j))) { // there may be more than // one digits in a number double num = 0, i = j; while (j < exprsn.length() && isdigit(exprsn.charAt(j))) j--; j++; // from [j, i] exprsn contains a number for (int k = j; k <= i; k++) { num = num * 10 + (double)(exprsn.charAt(k) - '0'); } stack.push(num); } else { // Operator encountered // Pop two elements from Stack double o1 = (double)stack.peek(); stack.pop(); double o2 = (double)stack.peek(); stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn.charAt(j)) { case '+': stack.push(o1 + o2); break; case '-': stack.push(o1 - o2); break; case '*': stack.push(o1 * o2); break; case '/': stack.push(o1 / o2); break; } } } return stack.peek(); } // Driver code public static void main(String[] args) { String exprsn = "+ 9 * 12 6"; System.out.print((int)evaluatePrefix(exprsn)); }} // This code is contributed by mukesh07. # Python3 program to evaluate a prefix expression.def isdigit(ch): if(ord(ch) >= 48 and ord(ch) <= 57): return True return False def evaluatePrefix(exprsn): Stack = [] for j in range(len(exprsn) - 1, -1, -1): # if jth character is the delimiter ( which is # space in this case) then skip it if (exprsn[j] == ' '): continue # Push operand to Stack # To convert exprsn[j] to digit subtract # '0' from exprsn[j]. if (isdigit(exprsn[j])): # there may be more than # one digits in a number num, i = 0, j while (j < len(exprsn) and isdigit(exprsn[j])): j-=1 j+=1 # from [j, i] exprsn contains a number for k in range(j, i + 1, 1): num = num * 10 + (ord(exprsn[k]) - ord('0')) Stack.append(num) else: # Operator encountered # Pop two elements from Stack o1 = Stack[-1] Stack.pop() o2 = Stack[-1] Stack.pop() # Use switch case to operate on o1 # and o2 and perform o1 O o2. if exprsn[j] == '+': Stack.append(o1 + o2 + 12) elif exprsn[j] == '-': Stack.append(o1 - o2) elif exprsn[j] == '*': Stack.append(o1 * o2 * 5 ) elif exprsn[j] == '/': Stack.append(o1 / o2) return Stack[-1] exprsn = "+ 9 * 12 6"print(evaluatePrefix(exprsn)) # This code is contributed by divyesh072019. // C# program to evaluate a prefix expression.using System;using System.Collections;class GFG { static bool isdigit(char ch) { if(ch >= 48 && ch <= 57) { return true; } return false; } static double evaluatePrefix(string exprsn) { Stack stack = new Stack(); for (int j = exprsn.Length - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn[j] == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn[j])) { // there may be more than // one digits in a number double num = 0, i = j; while (j < exprsn.Length && isdigit(exprsn[j])) j--; j++; // from [j, i] exprsn contains a number for (int k = j; k <= i; k++) { num = num * 10 + (double)(exprsn[k] - '0'); } stack.Push(num); } else { // Operator encountered // Pop two elements from Stack double o1 = (double)stack.Peek(); stack.Pop(); double o2 = (double)stack.Peek(); stack.Pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': stack.Push(o1 + o2); break; case '-': stack.Push(o1 - o2); break; case '*': stack.Push(o1 * o2); break; case '/': stack.Push(o1 / o2); break; } } } return (double)stack.Peek(); } static void Main() { string exprsn = "+ 9 * 12 6"; Console.Write(evaluatePrefix(exprsn)); }} // This code is contributed by divyeshrabadiya07. <script> // Javascript program to evaluate a prefix expression. function isdigit(ch) { if(ch.charCodeAt() >= 48 && ch.charCodeAt() <= 57) { return true; } return false; } function evaluatePrefix(exprsn) { let Stack = []; for (let j = exprsn.length - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn[j] == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn[j])) { // there may be more than // one digits in a number let num = 0, i = j; while (j < exprsn.length && isdigit(exprsn[j])) j--; j++; // from [j, i] exprsn contains a number for (let k = j; k <= i; k++) num = num * 10 + (exprsn[k].charCodeAt() - '0'.charCodeAt()); Stack.push(num); } else { // Operator encountered // Pop two elements from Stack let o1 = Stack[Stack.length - 1]; Stack.pop(); let o2 = Stack[Stack.length - 1]; Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack[Stack.length - 1]; } let exprsn = "+ 9 * 12 6"; document.write(evaluatePrefix(exprsn)); // This code is contributed by rameshtravel07.</script> 81 Time Complexity: O(n) Space Complexity: O(n) marborav princiraj1992 nidhi_biet dayashankar58 ankthon leonrichter1337 shaadk7865 suresh07 rameshtravel07 divyesh072019 divyeshrabadiya07 surindertarika1234 mukesh07 expression-evaluation Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Design a stack with operations on middle element How to efficiently implement k stacks in a single array? Next Smaller Element Real-time application of Data Structures Construct Binary Tree from String with bracket representation ZigZag Tree Traversal Length of the longest valid substring Reverse individual words
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Sep, 2021" }, { "code": null, "e": 825, "s": 54, "text": "Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don’t need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long as we can guarantee that a valid prefix or postfix expression is used, it can be evaluated with correctness.We can convert infix to postfix and can convert infix to prefix.In this article, we will discuss how to evaluate an expression written in prefix notation. The method is similar to evaluating a postfix expression. Please read Evaluation of Postfix Expression to know how to evaluate postfix expressionsAlgorithm " }, { "code": null, "e": 1352, "s": 825, "text": "EVALUATE_PREFIX(STRING)\nStep 1: Put a pointer P at the end of the end\nStep 2: If character at P is an operand push it to Stack\nStep 3: If the character at P is an operator pop two \n elements from the Stack. Operate on these elements\n according to the operator, and push the result \n back to the Stack\nStep 4: Decrement P by 1 and go to Step 2 as long as there\n are characters left to be scanned in the expression.\nStep 5: The Result is stored at the top of the Stack, \n return it\nStep 6: End" }, { "code": null, "e": 1402, "s": 1352, "text": "Example to demonstrate working of the algorithm " }, { "code": null, "e": 2146, "s": 1402, "text": "Expression: +9*26\n\nCharacter | Stack | Explanation\nScanned | (Front to |\n | Back) | \n-------------------------------------------\n6 6 6 is an operand, \n push to Stack\n2 6 2 2 is an operand, \n push to Stack\n* 12 (6*2) * is an operator, \n pop 6 and 2, multiply \n them and push result \n to Stack \n9 12 9 9 is an operand, push \n to Stack\n+ 21 (12+9) + is an operator, pop\n 12 and 9 add them and\n push result to Stack\n\nResult: 21" }, { "code": null, "e": 2158, "s": 2146, "text": "Examples: " }, { "code": null, "e": 2216, "s": 2158, "text": "Input : -+8/632\nOutput : 8\n\nInput : -+7*45+20\nOutput : 25" }, { "code": null, "e": 2421, "s": 2216, "text": "Complexity The algorithm has linear complexity since we scan the expression once and perform at most O(N) push and pop operations which take constant time.Implementation of the algorithm is given below. " }, { "code": null, "e": 2425, "s": 2421, "text": "C++" }, { "code": null, "e": 2430, "s": 2425, "text": "Java" }, { "code": null, "e": 2438, "s": 2430, "text": "Python3" }, { "code": null, "e": 2441, "s": 2438, "text": "C#" }, { "code": null, "e": 2452, "s": 2441, "text": "Javascript" }, { "code": "// C++ program to evaluate a prefix expression.#include <bits/stdc++.h>using namespace std; bool isOperand(char c){ // If the character is a digit then it must // be an operand return isdigit(c);} double evaluatePrefix(string exprsn){ stack<double> Stack; for (int j = exprsn.size() - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.push(exprsn[j] - '0'); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.top(); Stack.pop(); double o2 = Stack.top(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack.top();} // Driver codeint main(){ string exprsn = \"+9*26\"; cout << evaluatePrefix(exprsn) << endl; return 0;}", "e": 3770, "s": 2452, "text": null }, { "code": "// Java program to evaluate// a prefix expression.import java.io.*;import java.util.*; class GFG { static Boolean isOperand(char c) { // If the character is a digit // then it must be an operand if (c >= 48 && c <= 57) return true; else return false; } static double evaluatePrefix(String exprsn) { Stack<Double> Stack = new Stack<Double>(); for (int j = exprsn.length() - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn.charAt(j))) Stack.push((double)(exprsn.charAt(j) - 48)); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.peek(); Stack.pop(); double o2 = Stack.peek(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn.charAt(j)) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack.peek(); } /* Driver program to test above function */ public static void main(String[] args) { String exprsn = \"+9*26\"; System.out.println(evaluatePrefix(exprsn)); }} // This code is contributed by Gitanjali", "e": 5517, "s": 3770, "text": null }, { "code": "\"\"\"Python3 program to evaluate a prefix expression.\"\"\" def is_operand(c): \"\"\" Return True if the given char c is an operand, e.g. it is a number \"\"\" return c.isdigit() def evaluate(expression): \"\"\" Evaluate a given expression in prefix notation. Asserts that the given expression is valid. \"\"\" stack = [] # iterate over the string in reverse order for c in expression[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() if c == '+': stack.append(o1 + o2) elif c == '-': stack.append(o1 - o2) elif c == '*': stack.append(o1 * o2) elif c == '/': stack.append(o1 / o2) return stack.pop() # Driver codeif __name__ == \"__main__\": test_expression = \"+9*26\" print(evaluate(test_expression)) # This code is contributed by Leon Morten Richter (GitHub: M0r13n)", "e": 6647, "s": 5517, "text": null }, { "code": "// C# program to evaluate// a prefix expression.using System;using System.Collections.Generic; class GFG { static Boolean isOperand(char c) { // If the character is a digit // then it must be an operand if (c >= 48 && c <= 57) return true; else return false; } static double evaluatePrefix(String exprsn) { Stack<Double> Stack = new Stack<Double>(); for (int j = exprsn.Length - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.Push((double)(exprsn[j] - 48)); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.Peek(); Stack.Pop(); double o2 = Stack.Peek(); Stack.Pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.Push(o1 + o2); break; case '-': Stack.Push(o1 - o2); break; case '*': Stack.Push(o1 * o2); break; case '/': Stack.Push(o1 / o2); break; } } } return Stack.Peek(); } /* Driver code */ public static void Main(String[] args) { String exprsn = \"+9*26\"; Console.WriteLine(evaluatePrefix(exprsn)); }} /* This code contributed by PrinciRaj1992 */", "e": 8356, "s": 6647, "text": null }, { "code": "<script> // Javascript program to evaluate a prefix expression. function isOperand(c) { // If the character is a digit // then it must be an operand if (c.charCodeAt() >= 48 && c.charCodeAt() <= 57) return true; else return false; } function evaluatePrefix(exprsn) { let Stack = []; for (let j = exprsn.length - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.push((exprsn[j].charCodeAt() - 48)); else { // Operator encountered // Pop two elements from Stack let o1 = Stack[Stack.length - 1]; Stack.pop(); let o2 = Stack[Stack.length - 1]; Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack[Stack.length - 1]; } let exprsn = \"+9*26\"; document.write(evaluatePrefix(exprsn)); // This code is contributed by suresh07.</script>", "e": 9975, "s": 8356, "text": null }, { "code": null, "e": 9978, "s": 9975, "text": "21" }, { "code": null, "e": 10244, "s": 9978, "text": "Note: To perform more types of operations only the switch case table needs to be modified. This implementation works only for single digit operands. Multi-digit operands can be implemented if some character-like space is used to separate the operands and operators." }, { "code": null, "e": 10327, "s": 10244, "text": "Below given is the extended program which allows operands to have multiple digits." }, { "code": null, "e": 10331, "s": 10327, "text": "C++" }, { "code": null, "e": 10336, "s": 10331, "text": "Java" }, { "code": null, "e": 10344, "s": 10336, "text": "Python3" }, { "code": null, "e": 10347, "s": 10344, "text": "C#" }, { "code": null, "e": 10358, "s": 10347, "text": "Javascript" }, { "code": "// C++ program to evaluate a prefix expression.#include <bits/stdc++.h>using namespace std; double evaluatePrefix(string exprsn){ stack<double> Stack; for (int j = exprsn.size() - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn[j] == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn[j])) { // there may be more than // one digits in a number double num = 0, i = j; while (j < exprsn.size() && isdigit(exprsn[j])) j--; j++; // from [j, i] exprsn contains a number for (int k = j; k <= i; k++) num = num * 10 + double(exprsn[k] - '0'); Stack.push(num); } else { // Operator encountered // Pop two elements from Stack double o1 = Stack.top(); Stack.pop(); double o2 = Stack.top(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack.top();} // Driver codeint main(){ string exprsn = \"+ 9 * 12 6\"; cout << evaluatePrefix(exprsn) << endl; return 0; // this code is contributed by Mohd Shaad Khan}", "e": 12133, "s": 10358, "text": null }, { "code": "// Java program to evaluate a prefix expression.import java.util.*;public class Main{ static boolean isdigit(char ch) { if(ch >= 48 && ch <= 57) { return true; } return false; } static double evaluatePrefix(String exprsn) { Stack<Double> stack = new Stack<Double>(); for (int j = exprsn.length() - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn.charAt(j) == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn.charAt(j))) { // there may be more than // one digits in a number double num = 0, i = j; while (j < exprsn.length() && isdigit(exprsn.charAt(j))) j--; j++; // from [j, i] exprsn contains a number for (int k = j; k <= i; k++) { num = num * 10 + (double)(exprsn.charAt(k) - '0'); } stack.push(num); } else { // Operator encountered // Pop two elements from Stack double o1 = (double)stack.peek(); stack.pop(); double o2 = (double)stack.peek(); stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn.charAt(j)) { case '+': stack.push(o1 + o2); break; case '-': stack.push(o1 - o2); break; case '*': stack.push(o1 * o2); break; case '/': stack.push(o1 / o2); break; } } } return stack.peek(); } // Driver code public static void main(String[] args) { String exprsn = \"+ 9 * 12 6\"; System.out.print((int)evaluatePrefix(exprsn)); }} // This code is contributed by mukesh07.", "e": 14460, "s": 12133, "text": null }, { "code": "# Python3 program to evaluate a prefix expression.def isdigit(ch): if(ord(ch) >= 48 and ord(ch) <= 57): return True return False def evaluatePrefix(exprsn): Stack = [] for j in range(len(exprsn) - 1, -1, -1): # if jth character is the delimiter ( which is # space in this case) then skip it if (exprsn[j] == ' '): continue # Push operand to Stack # To convert exprsn[j] to digit subtract # '0' from exprsn[j]. if (isdigit(exprsn[j])): # there may be more than # one digits in a number num, i = 0, j while (j < len(exprsn) and isdigit(exprsn[j])): j-=1 j+=1 # from [j, i] exprsn contains a number for k in range(j, i + 1, 1): num = num * 10 + (ord(exprsn[k]) - ord('0')) Stack.append(num) else: # Operator encountered # Pop two elements from Stack o1 = Stack[-1] Stack.pop() o2 = Stack[-1] Stack.pop() # Use switch case to operate on o1 # and o2 and perform o1 O o2. if exprsn[j] == '+': Stack.append(o1 + o2 + 12) elif exprsn[j] == '-': Stack.append(o1 - o2) elif exprsn[j] == '*': Stack.append(o1 * o2 * 5 ) elif exprsn[j] == '/': Stack.append(o1 / o2) return Stack[-1] exprsn = \"+ 9 * 12 6\"print(evaluatePrefix(exprsn)) # This code is contributed by divyesh072019.", "e": 16079, "s": 14460, "text": null }, { "code": "// C# program to evaluate a prefix expression.using System;using System.Collections;class GFG { static bool isdigit(char ch) { if(ch >= 48 && ch <= 57) { return true; } return false; } static double evaluatePrefix(string exprsn) { Stack stack = new Stack(); for (int j = exprsn.Length - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn[j] == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn[j])) { // there may be more than // one digits in a number double num = 0, i = j; while (j < exprsn.Length && isdigit(exprsn[j])) j--; j++; // from [j, i] exprsn contains a number for (int k = j; k <= i; k++) { num = num * 10 + (double)(exprsn[k] - '0'); } stack.Push(num); } else { // Operator encountered // Pop two elements from Stack double o1 = (double)stack.Peek(); stack.Pop(); double o2 = (double)stack.Peek(); stack.Pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': stack.Push(o1 + o2); break; case '-': stack.Push(o1 - o2); break; case '*': stack.Push(o1 * o2); break; case '/': stack.Push(o1 / o2); break; } } } return (double)stack.Peek(); } static void Main() { string exprsn = \"+ 9 * 12 6\"; Console.Write(evaluatePrefix(exprsn)); }} // This code is contributed by divyeshrabadiya07.", "e": 18314, "s": 16079, "text": null }, { "code": "<script> // Javascript program to evaluate a prefix expression. function isdigit(ch) { if(ch.charCodeAt() >= 48 && ch.charCodeAt() <= 57) { return true; } return false; } function evaluatePrefix(exprsn) { let Stack = []; for (let j = exprsn.length - 1; j >= 0; j--) { // if jth character is the delimiter ( which is // space in this case) then skip it if (exprsn[j] == ' ') continue; // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isdigit(exprsn[j])) { // there may be more than // one digits in a number let num = 0, i = j; while (j < exprsn.length && isdigit(exprsn[j])) j--; j++; // from [j, i] exprsn contains a number for (let k = j; k <= i; k++) num = num * 10 + (exprsn[k].charCodeAt() - '0'.charCodeAt()); Stack.push(num); } else { // Operator encountered // Pop two elements from Stack let o1 = Stack[Stack.length - 1]; Stack.pop(); let o2 = Stack[Stack.length - 1]; Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break; case '/': Stack.push(o1 / o2); break; } } } return Stack[Stack.length - 1]; } let exprsn = \"+ 9 * 12 6\"; document.write(evaluatePrefix(exprsn)); // This code is contributed by rameshtravel07.</script>", "e": 20416, "s": 18314, "text": null }, { "code": null, "e": 20419, "s": 20416, "text": "81" }, { "code": null, "e": 20441, "s": 20419, "text": "Time Complexity: O(n)" }, { "code": null, "e": 20464, "s": 20441, "text": "Space Complexity: O(n)" }, { "code": null, "e": 20473, "s": 20464, "text": "marborav" }, { "code": null, "e": 20487, "s": 20473, "text": "princiraj1992" }, { "code": null, "e": 20498, "s": 20487, "text": "nidhi_biet" }, { "code": null, "e": 20512, "s": 20498, "text": "dayashankar58" }, { "code": null, "e": 20520, "s": 20512, "text": "ankthon" }, { "code": null, "e": 20536, "s": 20520, "text": "leonrichter1337" }, { "code": null, "e": 20547, "s": 20536, "text": "shaadk7865" }, { "code": null, "e": 20556, "s": 20547, "text": "suresh07" }, { "code": null, "e": 20571, "s": 20556, "text": "rameshtravel07" }, { "code": null, "e": 20585, "s": 20571, "text": "divyesh072019" }, { "code": null, "e": 20603, "s": 20585, "text": "divyeshrabadiya07" }, { "code": null, "e": 20622, "s": 20603, "text": "surindertarika1234" }, { "code": null, "e": 20631, "s": 20622, "text": "mukesh07" }, { "code": null, "e": 20653, "s": 20631, "text": "expression-evaluation" }, { "code": null, "e": 20659, "s": 20653, "text": "Stack" }, { "code": null, "e": 20665, "s": 20659, "text": "Stack" }, { "code": null, "e": 20763, "s": 20665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20795, "s": 20763, "text": "Introduction to Data Structures" }, { "code": null, "e": 20859, "s": 20795, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20908, "s": 20859, "text": "Design a stack with operations on middle element" }, { "code": null, "e": 20965, "s": 20908, "text": "How to efficiently implement k stacks in a single array?" }, { "code": null, "e": 20986, "s": 20965, "text": "Next Smaller Element" }, { "code": null, "e": 21027, "s": 20986, "text": "Real-time application of Data Structures" }, { "code": null, "e": 21089, "s": 21027, "text": "Construct Binary Tree from String with bracket representation" }, { "code": null, "e": 21111, "s": 21089, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 21149, "s": 21111, "text": "Length of the longest valid substring" } ]
Ints contains() function | Guava | Java
26 Jul, 2021 Guava’s Ints.contains() returns true if target is present as an element anywhere in array.Syntax: public static boolean contains(int[] array, int target) Parameters: This method accepts following parameters: array: An array of int values, possibly empty. target: A primitive int value. Return Value: This method returns a boolean value. It returns True if array[i] == target for some value of i.Example 1: Java // Java code to show implementation of// Guava's Ints.contains() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an Integer array int[] arr = { 5, 4, 3, 2, 1 }; int target = 3; // Using Ints.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Ints.contains(arr, target)) System.out.println("Target is present" + " in the array"); else System.out.println("Target is not present" + " in the array"); }} Target is present in the array Example 2: Java // Java code to show implementation of// Guava's Ints.contains() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an Integer array int[] arr = { 2, 4, 6, 8, 10 }; int target = 7; // Using Ints.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Ints.contains(arr, target)) System.out.println("Target is present" + " in the array"); else System.out.println("Target is not present" + " in the array"); }} Target is not present in the array Reference: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#contains-int:A-int- manikarora059 java-guava Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2021" }, { "code": null, "e": 128, "s": 28, "text": "Guava’s Ints.contains() returns true if target is present as an element anywhere in array.Syntax: " }, { "code": null, "e": 187, "s": 128, "text": "public static boolean \n contains(int[] array, int target)" }, { "code": null, "e": 243, "s": 187, "text": "Parameters: This method accepts following parameters: " }, { "code": null, "e": 290, "s": 243, "text": "array: An array of int values, possibly empty." }, { "code": null, "e": 321, "s": 290, "text": "target: A primitive int value." }, { "code": null, "e": 442, "s": 321, "text": "Return Value: This method returns a boolean value. It returns True if array[i] == target for some value of i.Example 1: " }, { "code": null, "e": 447, "s": 442, "text": "Java" }, { "code": "// Java code to show implementation of// Guava's Ints.contains() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an Integer array int[] arr = { 5, 4, 3, 2, 1 }; int target = 3; // Using Ints.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Ints.contains(arr, target)) System.out.println(\"Target is present\" + \" in the array\"); else System.out.println(\"Target is not present\" + \" in the array\"); }}", "e": 1198, "s": 447, "text": null }, { "code": null, "e": 1229, "s": 1198, "text": "Target is present in the array" }, { "code": null, "e": 1243, "s": 1231, "text": "Example 2: " }, { "code": null, "e": 1248, "s": 1243, "text": "Java" }, { "code": "// Java code to show implementation of// Guava's Ints.contains() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG { // Driver's code public static void main(String[] args) { // Creating an Integer array int[] arr = { 2, 4, 6, 8, 10 }; int target = 7; // Using Ints.contains() method to search // for an element in the array. The method // returns true if element is found, else // returns false if (Ints.contains(arr, target)) System.out.println(\"Target is present\" + \" in the array\"); else System.out.println(\"Target is not present\" + \" in the array\"); }}", "e": 2000, "s": 1248, "text": null }, { "code": null, "e": 2035, "s": 2000, "text": "Target is not present in the array" }, { "code": null, "e": 2162, "s": 2037, "text": "Reference: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#contains-int:A-int- " }, { "code": null, "e": 2176, "s": 2162, "text": "manikarora059" }, { "code": null, "e": 2187, "s": 2176, "text": "java-guava" }, { "code": null, "e": 2192, "s": 2187, "text": "Java" }, { "code": null, "e": 2197, "s": 2192, "text": "Java" } ]
Horizontal or Vertical Progress Bar in Excel
27 May, 2021 The progress bar is a pictorial representation that tells about the details of any goal or task. By seeing the progress bar one can judge how much work is completed and how much is left to be covered. By default, there is no such Progress Chart in Excel but it can be made manually using the existing vertical or horizontal bars. Generally, horizontal bars are mostly preferred to make a Progress Chart as it gives a more insightful view. In this article, we are going to see the step-by-step process of making a Progress Bar in Excel using a suitable example shown below : Example: Consider your class teacher has assigned you some tasks to complete. He also asked you to send him a report of the progress you made in the tasks every Sunday. There are two options : By using a table. The pictorial representation is the Progress Bar. Consider the table shown below : Step 1: Insert the data in the cells of Excel. Now for the column “Remaining” no need to enter the data manually. It will become cumbersome if there are more records. Excel provides us with a formula to directly calculate it. You can find the “Remaining” value for the first record T-1 and then drag the cell down and automatically all the columns will be filled with the values. The command is : = 1 - Cell_Number Cell_Number : The cell number of the "Completed" column whose remaining percentage value is to be calculated The Cell_Number can be manually entered or by just left clicking on the cell. Step 2: Now select all the data and perform the following operations : Select -> Insert -> Chart Sets -> 2-D Bar (Horizontal) 2-D Bar Insertion Step 3: This is the most important step in making a Progress bar. Here, we have to perform a lot of modifications to the above-inserted chart to make it look like a Progress bar. To perform any modification in the chart, you can simply select the point in the chart to be modified and then right-click and click on “Format”. Another way is by using the “+” button in the top right corner of the chart. Formatting the axis: Select the axis and then right-click on it and click on “Format Axis”. Now under the Format axis tab change the Bound and Unit values as shown below : Format Axis Axis changed Now, it can be observed that the order of the tasks is reversed in the chart. To edit it again go to the format axis window and check the “Categories in Reverse Order” as shown below : You can now format the Y-axis containing the tasks by increasing its font size and changing to “Bold” for a better view as shown below : Remove all the outlines by going to Shape Outline and select “No Outline”. In the Progress bar, we don’t need any title, axes for the percentage, grid lines. We can simply remove them by clicking on the “+” button in the top right corner and uncheck those options. You can simply remove the “Percentage” axis by selecting it and pressing the “Delete” button. Modified Chart Now the final goal is to make the bar more insightful by changing the color and its transparency so that it looks like a Progress bar. In the above chart, the “Blue color” part is the task completed, and the “Orange color” is the task remaining. So, the remaining part has to be made transparent. To assign different color and style to the individual bar : Select the bar “Completed Portion” in blue color. Click on “Format” on the top of Excel. Now select Theme Styles. Select the one which is having some shadow behind the color. Assign different colors to all the bars of the “Completed” portion only. Thereafter, we will deal with the “Remaining” portion and will see how to change the transparency. Now, select the “Remaining” portion in the bar individually and right-click on it and then select “Format Data Points.” Now in the Format Data Point window, select Fill as “Solid Fill” and then change the color to the original color assigned to the bar as in the previous step and change the transparency to 60-70% to reduce the glow of the color. Repeat it for all the “Remaining” bar portions. Progress bar Now, you can change the value in the initial table and see the Progress Bar will also change as shown below : To make the progress bar more appealing we can add data labels to it which tells data about how much work is completed. Select the bars only the “Completed” portion and then right-click and select “Add Data Labels”. Now Data Labels will be added to it and you can change the font, size, color, and style of the Data Labels as per convenience. Data Labels Finally, after all the modifications the Progress Bar will look like this: Final Progress Bar This is one of the famous designs for a Progress Bar. You can perform various other modifications to obtain other types of Progress Bars as per your requirements. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 May, 2021" }, { "code": null, "e": 493, "s": 54, "text": "The progress bar is a pictorial representation that tells about the details of any goal or task. By seeing the progress bar one can judge how much work is completed and how much is left to be covered. By default, there is no such Progress Chart in Excel but it can be made manually using the existing vertical or horizontal bars. Generally, horizontal bars are mostly preferred to make a Progress Chart as it gives a more insightful view." }, { "code": null, "e": 628, "s": 493, "text": "In this article, we are going to see the step-by-step process of making a Progress Bar in Excel using a suitable example shown below :" }, { "code": null, "e": 822, "s": 628, "text": "Example: Consider your class teacher has assigned you some tasks to complete. He also asked you to send him a report of the progress you made in the tasks every Sunday. There are two options : " }, { "code": null, "e": 840, "s": 822, "text": "By using a table." }, { "code": null, "e": 890, "s": 840, "text": "The pictorial representation is the Progress Bar." }, { "code": null, "e": 923, "s": 890, "text": "Consider the table shown below :" }, { "code": null, "e": 1320, "s": 923, "text": "Step 1: Insert the data in the cells of Excel. Now for the column “Remaining” no need to enter the data manually. It will become cumbersome if there are more records. Excel provides us with a formula to directly calculate it. You can find the “Remaining” value for the first record T-1 and then drag the cell down and automatically all the columns will be filled with the values. The command is :" }, { "code": null, "e": 1527, "s": 1320, "text": "= 1 - Cell_Number\n\nCell_Number : The cell number of the \"Completed\" column whose remaining percentage value is to be calculated\nThe Cell_Number can be manually entered or by just left clicking on the cell. " }, { "code": null, "e": 1598, "s": 1527, "text": "Step 2: Now select all the data and perform the following operations :" }, { "code": null, "e": 1653, "s": 1598, "text": "Select -> Insert -> Chart Sets -> 2-D Bar (Horizontal)" }, { "code": null, "e": 1671, "s": 1653, "text": "2-D Bar Insertion" }, { "code": null, "e": 1851, "s": 1671, "text": "Step 3: This is the most important step in making a Progress bar. Here, we have to perform a lot of modifications to the above-inserted chart to make it look like a Progress bar. " }, { "code": null, "e": 2074, "s": 1851, "text": "To perform any modification in the chart, you can simply select the point in the chart to be modified and then right-click and click on “Format”. Another way is by using the “+” button in the top right corner of the chart." }, { "code": null, "e": 2246, "s": 2074, "text": "Formatting the axis: Select the axis and then right-click on it and click on “Format Axis”. Now under the Format axis tab change the Bound and Unit values as shown below :" }, { "code": null, "e": 2258, "s": 2246, "text": "Format Axis" }, { "code": null, "e": 2271, "s": 2258, "text": "Axis changed" }, { "code": null, "e": 2456, "s": 2271, "text": "Now, it can be observed that the order of the tasks is reversed in the chart. To edit it again go to the format axis window and check the “Categories in Reverse Order” as shown below :" }, { "code": null, "e": 2593, "s": 2456, "text": "You can now format the Y-axis containing the tasks by increasing its font size and changing to “Bold” for a better view as shown below :" }, { "code": null, "e": 2668, "s": 2593, "text": "Remove all the outlines by going to Shape Outline and select “No Outline”." }, { "code": null, "e": 2952, "s": 2668, "text": "In the Progress bar, we don’t need any title, axes for the percentage, grid lines. We can simply remove them by clicking on the “+” button in the top right corner and uncheck those options. You can simply remove the “Percentage” axis by selecting it and pressing the “Delete” button." }, { "code": null, "e": 2967, "s": 2952, "text": "Modified Chart" }, { "code": null, "e": 3264, "s": 2967, "text": "Now the final goal is to make the bar more insightful by changing the color and its transparency so that it looks like a Progress bar. In the above chart, the “Blue color” part is the task completed, and the “Orange color” is the task remaining. So, the remaining part has to be made transparent." }, { "code": null, "e": 3324, "s": 3264, "text": "To assign different color and style to the individual bar :" }, { "code": null, "e": 3374, "s": 3324, "text": "Select the bar “Completed Portion” in blue color." }, { "code": null, "e": 3413, "s": 3374, "text": "Click on “Format” on the top of Excel." }, { "code": null, "e": 3499, "s": 3413, "text": "Now select Theme Styles. Select the one which is having some shadow behind the color." }, { "code": null, "e": 3671, "s": 3499, "text": "Assign different colors to all the bars of the “Completed” portion only. Thereafter, we will deal with the “Remaining” portion and will see how to change the transparency." }, { "code": null, "e": 3791, "s": 3671, "text": "Now, select the “Remaining” portion in the bar individually and right-click on it and then select “Format Data Points.”" }, { "code": null, "e": 4067, "s": 3791, "text": "Now in the Format Data Point window, select Fill as “Solid Fill” and then change the color to the original color assigned to the bar as in the previous step and change the transparency to 60-70% to reduce the glow of the color. Repeat it for all the “Remaining” bar portions." }, { "code": null, "e": 4080, "s": 4067, "text": "Progress bar" }, { "code": null, "e": 4190, "s": 4080, "text": "Now, you can change the value in the initial table and see the Progress Bar will also change as shown below :" }, { "code": null, "e": 4310, "s": 4190, "text": "To make the progress bar more appealing we can add data labels to it which tells data about how much work is completed." }, { "code": null, "e": 4533, "s": 4310, "text": "Select the bars only the “Completed” portion and then right-click and select “Add Data Labels”. Now Data Labels will be added to it and you can change the font, size, color, and style of the Data Labels as per convenience." }, { "code": null, "e": 4545, "s": 4533, "text": "Data Labels" }, { "code": null, "e": 4620, "s": 4545, "text": "Finally, after all the modifications the Progress Bar will look like this:" }, { "code": null, "e": 4639, "s": 4620, "text": "Final Progress Bar" }, { "code": null, "e": 4802, "s": 4639, "text": "This is one of the famous designs for a Progress Bar. You can perform various other modifications to obtain other types of Progress Bars as per your requirements." }, { "code": null, "e": 4809, "s": 4802, "text": "Picked" }, { "code": null, "e": 4815, "s": 4809, "text": "Excel" } ]
PHP | implode() Function
17 Jan, 2018 The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array. Syntax : string implode(separator,array) Parameters: The implode() function accepts two parameter out of which one is optional and one is mandatory. separator: This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string).array: The array whose value is to be joined to form a string. separator: This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string). array: The array whose value is to be joined to form a string. Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility. Return Type: The return type of implode() function is string. It will return the joined string formed from the elements of array. Examples: Input : implode(array('Geeks','for','Geeks') Output : GeeksforGeeks Input : implode("-",array('Geeks','for','Geeks') Output : Geeks-for-Geeks Below program illustrates the working of implode() function in PHP: <?php // PHP Code to implement join function $InputArray = array('Geeks','for','Geeks'); // Join without separator print_r(implode($InputArray)); print_r("\n"); // Join with separator print_r(implode("-",$InputArray));?> Output: GeeksforGeeks Geeks-for-Geeks Reference: http://php.net/manual/en/function.implode.php PHP-string Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request ReactJS | Router How to float three div side by side using CSS? Roadmap to Learn JavaScript For Beginners Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2018" }, { "code": null, "e": 216, "s": 28, "text": "The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function." }, { "code": null, "e": 475, "s": 216, "text": "If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array." }, { "code": null, "e": 484, "s": 475, "text": "Syntax :" }, { "code": null, "e": 517, "s": 484, "text": "string implode(separator,array)\n" }, { "code": null, "e": 625, "s": 517, "text": "Parameters: The implode() function accepts two parameter out of which one is optional and one is mandatory." }, { "code": null, "e": 945, "s": 625, "text": "separator: This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string).array: The array whose value is to be joined to form a string." }, { "code": null, "e": 1203, "s": 945, "text": "separator: This is an optional parameter and is of string type. The values of the array will be join to form a string and will be separated by the separator parameter provided here. This is optional, if not provided the default is “” (i.e. an empty string)." }, { "code": null, "e": 1266, "s": 1203, "text": "array: The array whose value is to be joined to form a string." }, { "code": null, "e": 1407, "s": 1266, "text": "Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility." }, { "code": null, "e": 1537, "s": 1407, "text": "Return Type: The return type of implode() function is string. It will return the joined string formed from the elements of array." }, { "code": null, "e": 1547, "s": 1537, "text": "Examples:" }, { "code": null, "e": 1691, "s": 1547, "text": "Input : implode(array('Geeks','for','Geeks')\nOutput : GeeksforGeeks\n\nInput : implode(\"-\",array('Geeks','for','Geeks')\nOutput : Geeks-for-Geeks\n" }, { "code": null, "e": 1759, "s": 1691, "text": "Below program illustrates the working of implode() function in PHP:" }, { "code": "<?php // PHP Code to implement join function $InputArray = array('Geeks','for','Geeks'); // Join without separator print_r(implode($InputArray)); print_r(\"\\n\"); // Join with separator print_r(implode(\"-\",$InputArray));?>", "e": 2025, "s": 1759, "text": null }, { "code": null, "e": 2033, "s": 2025, "text": "Output:" }, { "code": null, "e": 2064, "s": 2033, "text": "GeeksforGeeks\nGeeks-for-Geeks\n" }, { "code": null, "e": 2121, "s": 2064, "text": "Reference: http://php.net/manual/en/function.implode.php" }, { "code": null, "e": 2132, "s": 2121, "text": "PHP-string" }, { "code": null, "e": 2149, "s": 2132, "text": "Web Technologies" }, { "code": null, "e": 2247, "s": 2149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2308, "s": 2247, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2351, "s": 2308, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2423, "s": 2351, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2463, "s": 2423, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2487, "s": 2463, "text": "REST API (Introduction)" }, { "code": null, "e": 2528, "s": 2487, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2545, "s": 2528, "text": "ReactJS | Router" }, { "code": null, "e": 2592, "s": 2545, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 2634, "s": 2592, "text": "Roadmap to Learn JavaScript For Beginners" } ]
R vs Python
12 Oct, 2021 R programming Language and Python are both used extensively for Data Sciences. Both are very useful and open source languages as well. R Programming Language Python Programming Language Difference between R Programming and Python Programming Ecosystem in R Programming and Python Programming Advantages in R Programming and Python Programming R and Python usages in Data Science Example in R and Python R Language is used for machine learning algorithms, linear regression, time series, statistical inference, etc. It was designed by Ross Ihaka and Robert Gentleman in 1993. R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. Below are some major differences between R and Python: Python supports a very large community to general-purpose in data science. One of the most basic use for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas and NumPy is one of those packages and makes importing and analyzing, and visualization data much easier. R Programming has a rich ecosystem to use in standard machine learning and data mining techniques. It works in statistical analysis of large datasets, and it offers a number of different options for exploring data and It makes it easier to use probability distributions, apply different statistical tests. Advantage Python and R programming language is most useful in data science and it deals with identifying, representing and extracting meaningful information from data sources to be used to perform some business logic with these languages. It has a popular package for Data collection, Data exploration, Data modeling, Data visualization, and statical analysis. Program for the addition of two numbers R Python # R program to add two numbersnumb1 <- 8numb2 <- 4 # Adding two numberssum <- numb1 + numb2 print(paste(The sum is", sum)) # Python program to add two numbers numb1 = 8numb2 = 4 # Adding two numberssum = numb1 + numb2 # Printing the resultprint("The sum is", sum) Output: The sum is 12 kumar_satyam Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Split Column Into Multiple Columns in R DataFrame? Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 164, "s": 28, "text": "R programming Language and Python are both used extensively for Data Sciences. Both are very useful and open source languages as well. " }, { "code": null, "e": 187, "s": 164, "text": "R Programming Language" }, { "code": null, "e": 215, "s": 187, "text": "Python Programming Language" }, { "code": null, "e": 271, "s": 215, "text": "Difference between R Programming and Python Programming" }, { "code": null, "e": 321, "s": 271, "text": "Ecosystem in R Programming and Python Programming" }, { "code": null, "e": 372, "s": 321, "text": "Advantages in R Programming and Python Programming" }, { "code": null, "e": 408, "s": 372, "text": "R and Python usages in Data Science" }, { "code": null, "e": 432, "s": 408, "text": "Example in R and Python" }, { "code": null, "e": 909, "s": 432, "text": "R Language is used for machine learning algorithms, linear regression, time series, statistical inference, etc. It was designed by Ross Ihaka and Robert Gentleman in 1993. R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool." }, { "code": null, "e": 1221, "s": 909, "text": "Python is a widely-used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code." }, { "code": null, "e": 1276, "s": 1221, "text": "Below are some major differences between R and Python:" }, { "code": null, "e": 1587, "s": 1276, "text": "Python supports a very large community to general-purpose in data science. One of the most basic use for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas and NumPy is one of those packages and makes importing and analyzing, and visualization data much easier." }, { "code": null, "e": 1894, "s": 1587, "text": "R Programming has a rich ecosystem to use in standard machine learning and data mining techniques. It works in statistical analysis of large datasets, and it offers a number of different options for exploring data and It makes it easier to use probability distributions, apply different statistical tests. " }, { "code": null, "e": 1904, "s": 1894, "text": "Advantage" }, { "code": null, "e": 2255, "s": 1904, "text": "Python and R programming language is most useful in data science and it deals with identifying, representing and extracting meaningful information from data sources to be used to perform some business logic with these languages. It has a popular package for Data collection, Data exploration, Data modeling, Data visualization, and statical analysis." }, { "code": null, "e": 2295, "s": 2255, "text": "Program for the addition of two numbers" }, { "code": null, "e": 2297, "s": 2295, "text": "R" }, { "code": null, "e": 2304, "s": 2297, "text": "Python" }, { "code": "# R program to add two numbersnumb1 <- 8numb2 <- 4 # Adding two numberssum <- numb1 + numb2 print(paste(The sum is\", sum))", "e": 2427, "s": 2304, "text": null }, { "code": "# Python program to add two numbers numb1 = 8numb2 = 4 # Adding two numberssum = numb1 + numb2 # Printing the resultprint(\"The sum is\", sum)", "e": 2568, "s": 2427, "text": null }, { "code": null, "e": 2577, "s": 2568, "text": "Output: " }, { "code": null, "e": 2591, "s": 2577, "text": "The sum is 12" }, { "code": null, "e": 2604, "s": 2591, "text": "kumar_satyam" }, { "code": null, "e": 2611, "s": 2604, "text": "Picked" }, { "code": null, "e": 2622, "s": 2611, "text": "R Language" }, { "code": null, "e": 2720, "s": 2622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2765, "s": 2720, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 2817, "s": 2765, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2875, "s": 2817, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2927, "s": 2875, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2959, "s": 2927, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 3017, "s": 2959, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3080, "s": 3017, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 3115, "s": 3080, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3159, "s": 3115, "text": "How to change Row Names of DataFrame in R ?" } ]
How to Change the Whole App Language in Android Programmatically?
06 Jan, 2021 Android 7.0(API level 24) provides support for multilingual users, allowing the users to select multiple locales in the setting. A Locale object represents a specific geographical, political, or cultural region. Operations that required these Locale to perform a task are called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation so, the number should be formatted according to the conventions of the user’s native region, culture, or country. In this example, we are going to create a simple application in which the user has the option to select his desired language-English or Hindi. This will change the language of the whole application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create A New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Create Resource Files Reference: Resource Raw Folder in Android Studio In this step, we are required to create a string resource file for the Hindi language. Go to app > res > values > right-click > New > Value Resource File and name it as strings. Now, we have to choose qualifiers as Locale from the available list and select the language as Hindi from the drop-down list. Below is the picture of the steps to be performed. Now, In this resource file string.xml(hi) add the code given below in the snippet. XML <resources> <string name="app_name">GFG | Change App Language</string> <string name="selected_language">हिन्दी</string> <string name="language">नमस्ते, जी यफ जी</string></resources> And in string.xml file which is the default for English add these line. XML <resources> <string name="app_name">GFG | Change App Language</string> <string name="selected_language">English</string> <string name="language">Hi, GFG</string></resources> Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML <resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> </resources> Step 3: Create The Layout File For The Application In this step, we will create a layout for our application. Go to app > res > layout > activity_main.xml and add two TextView, one for the message and one for the language selected, and an ImageView for the drop_down icon. Below is the code snippet is given for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--text view for the message to display--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="48dp" android:text="Welcome To GeeksForGeeks" android:textAlignment="center" /> <!--button view for hindi language--> <Button android:id="@+id/btnHindi" android:layout_margin="16dp" android:background="@color/colorPrimary" android:textColor="#ffffff" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hindi"/> <!--button view for english language--> <Button android:id="@+id/btnEnglish" android:layout_margin="16dp" android:background="@color/colorPrimary" android:textColor="#ffffff" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="English"/> </LinearLayout> Step 4: Create LocaleHelper Class Now, We will create a Locale Helper class. This class contains all the functions which will help in language switching at runtime. Go to app > java > package > right-click and create a new java class and name it as LocaleHelper. Below is the code snippet is given for LocaleHelper class. Java import android.annotation.TargetApi;import android.content.Context;import android.content.SharedPreferences;import android.content.res.Configuration;import android.content.res.Resources;import android.os.Build;import android.preference.PreferenceManager; import java.util.Locale; public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; // the method is used to set the language at runtime public static Context setLocale(Context context, String language) { persist(context, language); // updating the language for devices above android nougat if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } // for devices having lower version of android os return updateResourcesLegacy(context, language); } private static void persist(Context context, String language) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } // the method is used update the language of application by creating // object of inbuilt Locale class and passing language argument to it @TargetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWarnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } Step 5: Working With the MainActivity.java File In this step, we will implement the Java code to switch between the string.xml file to use various languages. First, we will initialize all the Views and set click behavior on an Alert dialog box to choose the desired language with the help of LocalHelper class. Below is the code snippet is given for the MainActivity.java class. Java import androidx.appcompat.app.AppCompatActivity; import android.content.Context;import android.content.res.Resources;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView messageView; Button btnHindi, btnEnglish; Context context; Resources resources; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // referencing the text and button views messageView = (TextView) findViewById(R.id.textView); btnHindi = findViewById(R.id.btnHindi); btnEnglish = findViewById(R.id.btnEnglish); // setting up on click listener event over the button // in order to change the language with the help of // LocaleHelper class btnEnglish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context = LocaleHelper.setLocale(MainActivity.this, "en"); resources = context.getResources(); messageView.setText(resources.getString(R.string.language)); } }); btnHindi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context = LocaleHelper.setLocale(MainActivity.this, "hi"); resources = context.getResources(); messageView.setText(resources.getString(R.string.language)); } }); }} android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2021" }, { "code": null, "e": 559, "s": 28, "text": "Android 7.0(API level 24) provides support for multilingual users, allowing the users to select multiple locales in the setting. A Locale object represents a specific geographical, political, or cultural region. Operations that required these Locale to perform a task are called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation so, the number should be formatted according to the conventions of the user’s native region, culture, or country." }, { "code": null, "e": 923, "s": 559, "text": "In this example, we are going to create a simple application in which the user has the option to select his desired language-English or Hindi. This will change the language of the whole application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 952, "s": 923, "text": "Step 1: Create A New Project" }, { "code": null, "e": 1114, "s": 952, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1144, "s": 1114, "text": "Step 2: Create Resource Files" }, { "code": null, "e": 1193, "s": 1144, "text": "Reference: Resource Raw Folder in Android Studio" }, { "code": null, "e": 1549, "s": 1193, "text": "In this step, we are required to create a string resource file for the Hindi language. Go to app > res > values > right-click > New > Value Resource File and name it as strings. Now, we have to choose qualifiers as Locale from the available list and select the language as Hindi from the drop-down list. Below is the picture of the steps to be performed." }, { "code": null, "e": 1632, "s": 1549, "text": "Now, In this resource file string.xml(hi) add the code given below in the snippet." }, { "code": null, "e": 1636, "s": 1632, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG | Change App Language</string> <string name=\"selected_language\">हिन्दी</string> <string name=\"language\">नमस्ते, जी यफ जी</string></resources>", "e": 1827, "s": 1636, "text": null }, { "code": null, "e": 1899, "s": 1827, "text": "And in string.xml file which is the default for English add these line." }, { "code": null, "e": 1903, "s": 1899, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG | Change App Language</string> <string name=\"selected_language\">English</string> <string name=\"language\">Hi, GFG</string></resources>", "e": 2086, "s": 1903, "text": null }, { "code": null, "e": 2252, "s": 2086, "text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. " }, { "code": null, "e": 2256, "s": 2252, "text": "XML" }, { "code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> </resources> ", "e": 2426, "s": 2256, "text": null }, { "code": null, "e": 2477, "s": 2426, "text": "Step 3: Create The Layout File For The Application" }, { "code": null, "e": 2766, "s": 2477, "text": "In this step, we will create a layout for our application. Go to app > res > layout > activity_main.xml and add two TextView, one for the message and one for the language selected, and an ImageView for the drop_down icon. Below is the code snippet is given for the activity_main.xml file." }, { "code": null, "e": 2770, "s": 2766, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--text view for the message to display--> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"48dp\" android:text=\"Welcome To GeeksForGeeks\" android:textAlignment=\"center\" /> <!--button view for hindi language--> <Button android:id=\"@+id/btnHindi\" android:layout_margin=\"16dp\" android:background=\"@color/colorPrimary\" android:textColor=\"#ffffff\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hindi\"/> <!--button view for english language--> <Button android:id=\"@+id/btnEnglish\" android:layout_margin=\"16dp\" android:background=\"@color/colorPrimary\" android:textColor=\"#ffffff\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"English\"/> </LinearLayout>", "e": 4119, "s": 2770, "text": null }, { "code": null, "e": 4153, "s": 4119, "text": "Step 4: Create LocaleHelper Class" }, { "code": null, "e": 4441, "s": 4153, "text": "Now, We will create a Locale Helper class. This class contains all the functions which will help in language switching at runtime. Go to app > java > package > right-click and create a new java class and name it as LocaleHelper. Below is the code snippet is given for LocaleHelper class." }, { "code": null, "e": 4446, "s": 4441, "text": "Java" }, { "code": "import android.annotation.TargetApi;import android.content.Context;import android.content.SharedPreferences;import android.content.res.Configuration;import android.content.res.Resources;import android.os.Build;import android.preference.PreferenceManager; import java.util.Locale; public class LocaleHelper { private static final String SELECTED_LANGUAGE = \"Locale.Helper.Selected.Language\"; // the method is used to set the language at runtime public static Context setLocale(Context context, String language) { persist(context, language); // updating the language for devices above android nougat if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } // for devices having lower version of android os return updateResourcesLegacy(context, language); } private static void persist(Context context, String language) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } // the method is used update the language of application by creating // object of inbuilt Locale class and passing language argument to it @TargetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWarnings(\"deprecation\") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } }", "e": 6992, "s": 4446, "text": null }, { "code": null, "e": 7040, "s": 6992, "text": "Step 5: Working With the MainActivity.java File" }, { "code": null, "e": 7371, "s": 7040, "text": "In this step, we will implement the Java code to switch between the string.xml file to use various languages. First, we will initialize all the Views and set click behavior on an Alert dialog box to choose the desired language with the help of LocalHelper class. Below is the code snippet is given for the MainActivity.java class." }, { "code": null, "e": 7376, "s": 7371, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity; import android.content.Context;import android.content.res.Resources;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView messageView; Button btnHindi, btnEnglish; Context context; Resources resources; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // referencing the text and button views messageView = (TextView) findViewById(R.id.textView); btnHindi = findViewById(R.id.btnHindi); btnEnglish = findViewById(R.id.btnEnglish); // setting up on click listener event over the button // in order to change the language with the help of // LocaleHelper class btnEnglish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context = LocaleHelper.setLocale(MainActivity.this, \"en\"); resources = context.getResources(); messageView.setText(resources.getString(R.string.language)); } }); btnHindi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context = LocaleHelper.setLocale(MainActivity.this, \"hi\"); resources = context.getResources(); messageView.setText(resources.getString(R.string.language)); } }); }}", "e": 9005, "s": 7376, "text": null }, { "code": null, "e": 9013, "s": 9005, "text": "android" }, { "code": null, "e": 9037, "s": 9013, "text": "Technical Scripter 2020" }, { "code": null, "e": 9045, "s": 9037, "text": "Android" }, { "code": null, "e": 9050, "s": 9045, "text": "Java" }, { "code": null, "e": 9069, "s": 9050, "text": "Technical Scripter" }, { "code": null, "e": 9074, "s": 9069, "text": "Java" }, { "code": null, "e": 9082, "s": 9074, "text": "Android" } ]
Python – Concatenate values with same keys in a list of dictionaries
19 Jan, 2022 Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let’s discuss the certain ways in which this task can be performed. This task can be performed using brute force way. In this we iterate for all the dictionaries and perform the concatenation of like keys by adding one list element to other on the key match. Python3 # Python3 code to demonstrate working of# Concatenate Similar Key values# Using loop # initializing listtest_list = [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] # printing original listprint("The original list is : " + str(test_list)) # Concatenate Similar Key values# Using loopres = dict()for dict in test_list: for list in dict: if list in res: res[list] += (dict[list]) else: res[list] = dict[list] # printing resultprint("The concatenated dictionary : " + str(res)) The original list is : [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] The concatenated dictionary : {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6, 5, 7, 10], 'best': [5, 7]} Python3 from collections import defaultdicttest_list = [{'gfg' : [1, 5, 6, 7], 'good' : [9, 6, 2, 10], 'CS' : [4, 5, 6]}, {'gfg' : [5, 6, 7, 8], 'CS' : [5, 7, 10]}, {'gfg' : [7, 5], 'best' : [5, 7]}] print("Original List: " + str(test_list))result = defaultdict(list) for i in range(len(test_list)): current = test_list[i] for key, value in current.items(): for j in range(len(value)): result[key].append(value[j]) print("Concatenated Dictionary: " + str(dict(result))) Original List: [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] Concatenated Dictionary: {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6, 5, 7, 10], 'best': [5, 7]} sswarna1001 Python list-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jan, 2022" }, { "code": null, "e": 414, "s": 52, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let’s discuss the certain ways in which this task can be performed." }, { "code": null, "e": 605, "s": 414, "text": "This task can be performed using brute force way. In this we iterate for all the dictionaries and perform the concatenation of like keys by adding one list element to other on the key match." }, { "code": null, "e": 613, "s": 605, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Concatenate Similar Key values# Using loop # initializing listtest_list = [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] # printing original listprint(\"The original list is : \" + str(test_list)) # Concatenate Similar Key values# Using loopres = dict()for dict in test_list: for list in dict: if list in res: res[list] += (dict[list]) else: res[list] = dict[list] # printing resultprint(\"The concatenated dictionary : \" + str(res))", "e": 1253, "s": 613, "text": null }, { "code": null, "e": 1550, "s": 1253, "text": "The original list is : [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}]\nThe concatenated dictionary : {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6, 5, 7, 10], 'best': [5, 7]}" }, { "code": null, "e": 1558, "s": 1550, "text": "Python3" }, { "code": "from collections import defaultdicttest_list = [{'gfg' : [1, 5, 6, 7], 'good' : [9, 6, 2, 10], 'CS' : [4, 5, 6]}, {'gfg' : [5, 6, 7, 8], 'CS' : [5, 7, 10]}, {'gfg' : [7, 5], 'best' : [5, 7]}] print(\"Original List: \" + str(test_list))result = defaultdict(list) for i in range(len(test_list)): current = test_list[i] for key, value in current.items(): for j in range(len(value)): result[key].append(value[j]) print(\"Concatenated Dictionary: \" + str(dict(result)))", "e": 2081, "s": 1558, "text": null }, { "code": null, "e": 2365, "s": 2081, "text": "Original List: [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}]\nConcatenated Dictionary: {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6, 5, 7, 10], 'best': [5, 7]}" }, { "code": null, "e": 2377, "s": 2365, "text": "sswarna1001" }, { "code": null, "e": 2398, "s": 2377, "text": "Python list-programs" }, { "code": null, "e": 2405, "s": 2398, "text": "Python" }, { "code": null, "e": 2503, "s": 2405, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2533, "s": 2503, "text": "Iterate over a list in Python" }, { "code": null, "e": 2583, "s": 2533, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2605, "s": 2583, "text": "Enumerate() in Python" }, { "code": null, "e": 2621, "s": 2605, "text": "Deque in Python" }, { "code": null, "e": 2637, "s": 2621, "text": "Stack in Python" }, { "code": null, "e": 2655, "s": 2637, "text": "Python Dictionary" }, { "code": null, "e": 2680, "s": 2655, "text": "sum() function in Python" }, { "code": null, "e": 2721, "s": 2680, "text": "Print lists in Python (5 Different Ways)" }, { "code": null, "e": 2763, "s": 2721, "text": "Different ways to create Pandas Dataframe" } ]
Python Random – random() Function
13 Jun, 2022 There are certain situations that involve games or simulations which work on non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cards reCAPTCHA on login forms uses a random number generator to define different numbers and images Picking a number, flipping a coin, throwing of a dice related games required random numbers Shuffling deck of playing cards In Python, random numbers are not generated implicitly; therefore, it provides a random module in order to generate random numbers explicitly. random module in Python is used to create random numbers. To generate a random number, we need to import a random module in our program using the command: import random There are various functions associated with the random module are: random()randrange()seed()randint()uniform()choice()shuffle() random() randrange() seed() randint() uniform() choice() shuffle() and many more. We are only demonstrating the use of random() function. 1. random.random() function generates random floating numbers in the range[0.1, 1.0). (See the opening and closing brackets, it means including 0 but excluding 1). It takes no parameters and returns values uniformly distributed between 0 and 1. Syntax : random.random() Parameters : This method does not accept any parameter. Returns : This method returns a random floating number between 0 and 1. Python3 # Python3 program to demonstrate# the use of random() function . # import random from random import random # Prints random itemprint(random()) Output: 0.41941790721207284 Python3 # Python3 program to demonstrate# the use of random() function . import random # Prints random itemprint(random.random()) Output: 0.059970593824388185 Note: Every time you run this program, it will give a different answer. Example 2: Creating a list of random numbers in Python using random() function Python3 # Python3 program to demonstrate# the use of random() function . # import random from random import random lst = [] for i in range(10): lst.append(random()) # Prints random itemsprint(lst) Output: [0.12144204979175777, 0.27614050014306335, 0.8217122381411321, 0.34259785168486445, 0.6119383347065234, 0.8527573184278889, 0.9741465121560601, 0.21663626227016142, 0.9381166706029976, 0.2785298315133211] 2. seed(): This function generates a random number based on the seed value. It is used to initialize the base value of the pseudorandom number generator. If the seed value is 10, it will always generate 0.5714025946899135 as the first random number. Python3 import random random.seed(10)print(random.random())#Printing the random number twicerandom.seed(10)print(random.random()) Output: 0.5714025946899135 0.5714025946899135 kumar_satyam sheetal18june Python-random Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 255, "s": 53, "text": "There are certain situations that involve games or simulations which work on non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications:" }, { "code": null, "e": 311, "s": 255, "text": "Creating pseudo-random numbers on Lottery scratch cards" }, { "code": null, "e": 406, "s": 311, "text": "reCAPTCHA on login forms uses a random number generator to define different numbers and images" }, { "code": null, "e": 498, "s": 406, "text": "Picking a number, flipping a coin, throwing of a dice related games required random numbers" }, { "code": null, "e": 530, "s": 498, "text": "Shuffling deck of playing cards" }, { "code": null, "e": 829, "s": 530, "text": "In Python, random numbers are not generated implicitly; therefore, it provides a random module in order to generate random numbers explicitly. random module in Python is used to create random numbers. To generate a random number, we need to import a random module in our program using the command:" }, { "code": null, "e": 843, "s": 829, "text": "import random" }, { "code": null, "e": 910, "s": 843, "text": "There are various functions associated with the random module are:" }, { "code": null, "e": 971, "s": 910, "text": "random()randrange()seed()randint()uniform()choice()shuffle()" }, { "code": null, "e": 980, "s": 971, "text": "random()" }, { "code": null, "e": 992, "s": 980, "text": "randrange()" }, { "code": null, "e": 999, "s": 992, "text": "seed()" }, { "code": null, "e": 1009, "s": 999, "text": "randint()" }, { "code": null, "e": 1019, "s": 1009, "text": "uniform()" }, { "code": null, "e": 1028, "s": 1019, "text": "choice()" }, { "code": null, "e": 1038, "s": 1028, "text": "shuffle()" }, { "code": null, "e": 1109, "s": 1038, "text": "and many more. We are only demonstrating the use of random() function." }, { "code": null, "e": 1354, "s": 1109, "text": "1. random.random() function generates random floating numbers in the range[0.1, 1.0). (See the opening and closing brackets, it means including 0 but excluding 1). It takes no parameters and returns values uniformly distributed between 0 and 1." }, { "code": null, "e": 1379, "s": 1354, "text": "Syntax : random.random()" }, { "code": null, "e": 1435, "s": 1379, "text": "Parameters : This method does not accept any parameter." }, { "code": null, "e": 1507, "s": 1435, "text": "Returns : This method returns a random floating number between 0 and 1." }, { "code": null, "e": 1515, "s": 1507, "text": "Python3" }, { "code": "# Python3 program to demonstrate# the use of random() function . # import random from random import random # Prints random itemprint(random())", "e": 1662, "s": 1515, "text": null }, { "code": null, "e": 1670, "s": 1662, "text": "Output:" }, { "code": null, "e": 1690, "s": 1670, "text": "0.41941790721207284" }, { "code": null, "e": 1698, "s": 1690, "text": "Python3" }, { "code": "# Python3 program to demonstrate# the use of random() function . import random # Prints random itemprint(random.random())", "e": 1825, "s": 1698, "text": null }, { "code": null, "e": 1854, "s": 1825, "text": "Output:\n0.059970593824388185" }, { "code": null, "e": 1926, "s": 1854, "text": "Note: Every time you run this program, it will give a different answer." }, { "code": null, "e": 2006, "s": 1926, "text": "Example 2: Creating a list of random numbers in Python using random() function " }, { "code": null, "e": 2014, "s": 2006, "text": "Python3" }, { "code": "# Python3 program to demonstrate# the use of random() function . # import random from random import random lst = [] for i in range(10): lst.append(random()) # Prints random itemsprint(lst)", "e": 2207, "s": 2014, "text": null }, { "code": null, "e": 2215, "s": 2207, "text": "Output:" }, { "code": null, "e": 2421, "s": 2215, "text": "[0.12144204979175777, 0.27614050014306335, 0.8217122381411321, 0.34259785168486445, 0.6119383347065234, 0.8527573184278889, 0.9741465121560601, 0.21663626227016142, 0.9381166706029976, 0.2785298315133211] " }, { "code": null, "e": 2672, "s": 2421, "text": "2. seed(): This function generates a random number based on the seed value. It is used to initialize the base value of the pseudorandom number generator. If the seed value is 10, it will always generate 0.5714025946899135 as the first random number. " }, { "code": null, "e": 2680, "s": 2672, "text": "Python3" }, { "code": "import random random.seed(10)print(random.random())#Printing the random number twicerandom.seed(10)print(random.random())", "e": 2802, "s": 2680, "text": null }, { "code": null, "e": 2810, "s": 2802, "text": "Output:" }, { "code": null, "e": 2848, "s": 2810, "text": "0.5714025946899135\n0.5714025946899135" }, { "code": null, "e": 2861, "s": 2848, "text": "kumar_satyam" }, { "code": null, "e": 2875, "s": 2861, "text": "sheetal18june" }, { "code": null, "e": 2889, "s": 2875, "text": "Python-random" }, { "code": null, "e": 2896, "s": 2889, "text": "Python" } ]
Python | Relative Layout in Kivy using .kv file
06 Jul, 2020 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy Tutorial – Learn Kivy with Examples. Relative Layout: This layout operates in the same way as FloatLayout does, but the positioning properties (x, y, center_x, right, y, center_y, and top) are relative to the Layout size and not the window size. In reality regardless of absolute and relative positioning, the widgets are moved when the position of the layout changes. The available pos_hint keys (x, center_x, right, y, center_y, and top) are useful for aligning to edges or centering.For example:pos_hint: {‘center_x’:.5, ‘center_y’:.5} would align a Widget in the middle, no matter what the size of the window is. The first thing we need to do to use a RelativeLayout is import it. from kivy.uix.relativelayout import RelativeLayout We can do relative positioning by:pos_hint: provide hint of position. We can define upto 8 keys i.e. it takes arguments in form of dictionary.pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, “center_x”:1, “center_y”:1, “top”:1, “bottom”:1(“top”:0)} Note:Floatlayout and RelativeLayout both support absolute and relative positioning depending upon whether pos_hint or pos is used.But If you want absolute positioning, use the FloatLayout. Basic Approach to create Relative Layout: 1) import kivy 2) import kivy App 3) import Relativelayout 4) Set minimum version(optional) 5) create class for layout 6) create App class: - define build() function 7) Set up.kv file(name same ass the App class) 8) return Layout Class 9) Run an instance of the class Below is the Implementation: main.py file ## Sample Python application demonstrating the ## working of RelativeLayout in Kivy using .kv file ################################################### # import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # creating the root widget used in .kv file class RelativeLayout(RelativeLayout): pass # creating the App class in which name #.kv file is to be named Relative_Layout.kv class Relative_LayoutApp(App): # defining build() def build(self): # returning the instance of root class return RelativeLayout() # run the app if __name__ == "__main__": Relative_LayoutApp().run() .kv file implementation : #.kv file implementation of RelativeLayout # creating button feature <Button>: # size of text on button font_size: 20 # creating button # a button 20 % of the width and 20 % # of the height of the layout size_hint: 0.2, 0.2 <RelativeLayout>: # The Canvas is the root object # used for drawing by a Widget. canvas: Color: rgb:0, 1, 1 Rectangle: # creating rectangle # pos = 20 % and size = 60 % of the layout pos:[0.2 * coord for coord in self.size] size:[0.6 * coord for coord in self.size] # creating the button Button: text:"B1" background_color: 0.1, 0.5, 0.6, 1 # positioned at 0 % in x axis and 0 % in y axis # from bottom left, i.e x, y = 0, 0 from bottom left: pos_hint: {"x":0, "y":0} Button: text:"B2" background_color: 1, 0, 0, 1 pos_hint: {"right":1, "y":0} Button: text:"Yash" background_color: 0.4, 0.5, 0.6, 1 pos_hint: {"center_x":.5, "center_y":.5} Button: text:"B3" background_color: 0, 0, 1, 1 pos_hint: {"x":0, "top":1} Button: text:"B4" background_color: 0.8, 0.9, 0.2, 1 pos_hint: {"right":1, "top":1} Output: Different size of window images are there which show that How it adjust itself accordingly to window i.e relatively Image 1: Image 2: Image 3: Reference: https://kivy.org/doc/stable/api-kivy.uix.relativelayout.html nidhi_biet Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2020" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 307, "s": 264, "text": " Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 324, "s": 307, "text": "Relative Layout:" }, { "code": null, "e": 516, "s": 324, "text": "This layout operates in the same way as FloatLayout does, but the positioning properties (x, y, center_x, right, y, center_y, and top) are relative to the Layout size and not the window size." }, { "code": null, "e": 639, "s": 516, "text": "In reality regardless of absolute and relative positioning, the widgets are moved when the position of the layout changes." }, { "code": null, "e": 887, "s": 639, "text": "The available pos_hint keys (x, center_x, right, y, center_y, and top) are useful for aligning to edges or centering.For example:pos_hint: {‘center_x’:.5, ‘center_y’:.5} would align a Widget in the middle, no matter what the size of the window is." }, { "code": null, "e": 955, "s": 887, "text": "The first thing we need to do to use a RelativeLayout is import it." }, { "code": null, "e": 1006, "s": 955, "text": "from kivy.uix.relativelayout import RelativeLayout" }, { "code": null, "e": 1076, "s": 1006, "text": "We can do relative positioning by:pos_hint: provide hint of position." }, { "code": null, "e": 1253, "s": 1076, "text": "We can define upto 8 keys i.e. it takes arguments in form of dictionary.pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, “center_x”:1, “center_y”:1, “top”:1, “bottom”:1(“top”:0)}" }, { "code": null, "e": 1442, "s": 1253, "text": "Note:Floatlayout and RelativeLayout both support absolute and relative positioning depending upon whether pos_hint or pos is used.But If you want absolute positioning, use the FloatLayout." }, { "code": null, "e": 1761, "s": 1442, "text": "Basic Approach to create Relative Layout:\n1) import kivy\n2) import kivy App\n3) import Relativelayout\n4) Set minimum version(optional)\n5) create class for layout \n6) create App class:\n - define build() function\n7) Set up.kv file(name same ass the App class)\n8) return Layout Class\n9) Run an instance of the class" }, { "code": null, "e": 1791, "s": 1761, "text": " Below is the Implementation:" }, { "code": null, "e": 1804, "s": 1791, "text": "main.py file" }, { "code": "## Sample Python application demonstrating the ## working of RelativeLayout in Kivy using .kv file ################################################### # import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # creating the root widget used in .kv file class RelativeLayout(RelativeLayout): pass # creating the App class in which name #.kv file is to be named Relative_Layout.kv class Relative_LayoutApp(App): # defining build() def build(self): # returning the instance of root class return RelativeLayout() # run the app if __name__ == \"__main__\": Relative_LayoutApp().run() ", "e": 2880, "s": 1804, "text": null }, { "code": null, "e": 2906, "s": 2880, "text": ".kv file implementation :" }, { "code": "#.kv file implementation of RelativeLayout # creating button feature <Button>: # size of text on button font_size: 20 # creating button # a button 20 % of the width and 20 % # of the height of the layout size_hint: 0.2, 0.2 <RelativeLayout>: # The Canvas is the root object # used for drawing by a Widget. canvas: Color: rgb:0, 1, 1 Rectangle: # creating rectangle # pos = 20 % and size = 60 % of the layout pos:[0.2 * coord for coord in self.size] size:[0.6 * coord for coord in self.size] # creating the button Button: text:\"B1\" background_color: 0.1, 0.5, 0.6, 1 # positioned at 0 % in x axis and 0 % in y axis # from bottom left, i.e x, y = 0, 0 from bottom left: pos_hint: {\"x\":0, \"y\":0} Button: text:\"B2\" background_color: 1, 0, 0, 1 pos_hint: {\"right\":1, \"y\":0} Button: text:\"Yash\" background_color: 0.4, 0.5, 0.6, 1 pos_hint: {\"center_x\":.5, \"center_y\":.5} Button: text:\"B3\" background_color: 0, 0, 1, 1 pos_hint: {\"x\":0, \"top\":1} Button: text:\"B4\" background_color: 0.8, 0.9, 0.2, 1 pos_hint: {\"right\":1, \"top\":1} ", "e": 4536, "s": 2906, "text": null }, { "code": null, "e": 4544, "s": 4536, "text": "Output:" }, { "code": null, "e": 4660, "s": 4544, "text": "Different size of window images are there which show that How it adjust itself accordingly to window i.e relatively" }, { "code": null, "e": 4669, "s": 4660, "text": "Image 1:" }, { "code": null, "e": 4678, "s": 4669, "text": "Image 2:" }, { "code": null, "e": 4687, "s": 4678, "text": "Image 3:" }, { "code": null, "e": 4759, "s": 4687, "text": "Reference: https://kivy.org/doc/stable/api-kivy.uix.relativelayout.html" }, { "code": null, "e": 4770, "s": 4759, "text": "nidhi_biet" }, { "code": null, "e": 4781, "s": 4770, "text": "Python-gui" }, { "code": null, "e": 4793, "s": 4781, "text": "Python-kivy" }, { "code": null, "e": 4800, "s": 4793, "text": "Python" }, { "code": null, "e": 4898, "s": 4800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4930, "s": 4898, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4957, "s": 4930, "text": "Python Classes and Objects" }, { "code": null, "e": 4978, "s": 4957, "text": "Python OOPs Concepts" }, { "code": null, "e": 5001, "s": 4978, "text": "Introduction To PYTHON" }, { "code": null, "e": 5057, "s": 5001, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5088, "s": 5057, "text": "Python | os.path.join() method" }, { "code": null, "e": 5130, "s": 5088, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5172, "s": 5130, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5211, "s": 5172, "text": "Python | Get unique values from a list" } ]
Python | Check if all elements in list follow a condition
02 Oct, 2019 Sometimes, while working with Python list, we can have a problem in which we need to check if all the elements in list abide to a particular condition. This can have application in filtering in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using all()We can use all(), to perform this particular task. In this, we feed the condition and the validation with all the elements is checked by all() internally. # Python3 code to demonstrate working of# Check if all elements in list follow a condition# Using all() # initializing listtest_list = [4, 5, 8, 9, 10] # printing listprint("The original list : " + str(test_list)) # Check if all elements in list follow a condition# Using all()res = all(ele > 3 for ele in test_list) # Printing resultprint("Are all elements greater than 3 ? : " + str(res)) The original list : [4, 5, 8, 9, 10] Are all elements greater than 3 ? : True Method #2 : Using itertools.takewhile()This function can also be used to code solution of this problem. In this, we just need to process the loop till a condition is met and increment the counter. If it matches list length, then all elements meet that condition. # Python3 code to demonstrate working of# Check if all elements in list follow a condition# Using itertools.takewhile()import itertools # initializing listtest_list = [4, 5, 8, 9, 10] # printing listprint("The original list : " + str(test_list)) # Check if all elements in list follow a condition# Using itertools.takewhile()count = 0for ele in itertools.takewhile(lambda x: x > 3, test_list): count = count + 1res = count == len(test_list) # Printing resultprint("Are all elements greater than 3 ? : " + str(res)) The original list : [4, 5, 8, 9, 10] Are all elements greater than 3 ? : True Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Oct, 2019" }, { "code": null, "e": 334, "s": 52, "text": "Sometimes, while working with Python list, we can have a problem in which we need to check if all the elements in list abide to a particular condition. This can have application in filtering in web development domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 512, "s": 334, "text": "Method #1 : Using all()We can use all(), to perform this particular task. In this, we feed the condition and the validation with all the elements is checked by all() internally." }, { "code": "# Python3 code to demonstrate working of# Check if all elements in list follow a condition# Using all() # initializing listtest_list = [4, 5, 8, 9, 10] # printing listprint(\"The original list : \" + str(test_list)) # Check if all elements in list follow a condition# Using all()res = all(ele > 3 for ele in test_list) # Printing resultprint(\"Are all elements greater than 3 ? : \" + str(res))", "e": 907, "s": 512, "text": null }, { "code": null, "e": 988, "s": 907, "text": " \nThe original list : [4, 5, 8, 9, 10]\nAre all elements greater than 3 ? : True\n" }, { "code": null, "e": 1253, "s": 990, "text": "Method #2 : Using itertools.takewhile()This function can also be used to code solution of this problem. In this, we just need to process the loop till a condition is met and increment the counter. If it matches list length, then all elements meet that condition." }, { "code": "# Python3 code to demonstrate working of# Check if all elements in list follow a condition# Using itertools.takewhile()import itertools # initializing listtest_list = [4, 5, 8, 9, 10] # printing listprint(\"The original list : \" + str(test_list)) # Check if all elements in list follow a condition# Using itertools.takewhile()count = 0for ele in itertools.takewhile(lambda x: x > 3, test_list): count = count + 1res = count == len(test_list) # Printing resultprint(\"Are all elements greater than 3 ? : \" + str(res))", "e": 1775, "s": 1253, "text": null }, { "code": null, "e": 1856, "s": 1775, "text": " \nThe original list : [4, 5, 8, 9, 10]\nAre all elements greater than 3 ? : True\n" }, { "code": null, "e": 1877, "s": 1856, "text": "Python list-programs" }, { "code": null, "e": 1884, "s": 1877, "text": "Python" }, { "code": null, "e": 1900, "s": 1884, "text": "Python Programs" }, { "code": null, "e": 1998, "s": 1900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2016, "s": 1998, "text": "Python Dictionary" }, { "code": null, "e": 2058, "s": 2016, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2080, "s": 2058, "text": "Enumerate() in Python" }, { "code": null, "e": 2115, "s": 2080, "text": "Read a file line by line in Python" }, { "code": null, "e": 2141, "s": 2115, "text": "Python String | replace()" }, { "code": null, "e": 2184, "s": 2141, "text": "Python program to convert a list to string" }, { "code": null, "e": 2206, "s": 2184, "text": "Defaultdict in Python" }, { "code": null, "e": 2245, "s": 2206, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2283, "s": 2245, "text": "Python | Convert a list to dictionary" } ]
Numpy ufunc | Universal functions
21 Jul, 2021 Universal functions in Numpy are simple mathematical functions. It is just a term that we gave to mathematical functions in the Numpy library. Numpy provides various universal functions that cover a wide variety of operations. These functions include standard trigonometric functions, functions for arithmetic operations, handling complex numbers, statistical functions, etc. Universal functions have various characteristics which are as follows- These functions operates on ndarray (N-dimensional array) i.e Numpy’s array class. It performs fast element-wise array operations. It supports various features like array broadcasting, type casting etc. Numpy, universal functions are objects those belongs to numpy.ufunc class. Python functions can also be created as a universal function using frompyfunc library function. Some ufuncs are called automatically when the corresponding arithmetic operator is used on arrays. For example when addition of two array is performed element-wise using ‘+’ operator then np.add() is called internally. Some of the basic universal functions in Numpy are- These functions work on radians, so angles need to be converted to radians by multiplying by pi/180. Only then we can call trigonometric functions. They take an array as input arguments. It includes functions like- Python3 # Python code to demonstrate trigonometric functionimport numpy as np # create an array of anglesangles = np.array([0, 30, 45, 60, 90, 180]) # conversion of degree into radians# using deg2rad functionradians = np.deg2rad(angles) # sine of anglesprint('Sine of angles in the array:')sine_value = np.sin(radians)print(np.sin(radians)) # inverse sine of sine valuesprint('Inverse Sine of sine values:')print(np.rad2deg(np.arcsin(sine_value))) # hyperbolic sine of anglesprint('Sine hyperbolic of angles in the array:')sineh_value = np.sinh(radians)print(np.sinh(radians)) # inverse sine hyperbolic print('Inverse Sine hyperbolic:')print(np.sin(sineh_value)) # hypot function demonstrationbase = 4height = 3print('hypotenuse of right triangle is:')print(np.hypot(base, height)) Sine of angles in the array: [ 0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01 1.00000000e+00 1.22464680e-16] Inverse Sine of sine values: [ 0.00000000e+00 3.00000000e+01 4.50000000e+01 6.00000000e+01 9.00000000e+01 7.01670930e-15] Sine hyperbolic of angles in the array: [ 0. 0.54785347 0.86867096 1.24936705 2.3012989 11.54873936] Inverse Sine hyperbolic: [ 0. 0.52085606 0.76347126 0.94878485 0.74483916 -0.85086591] hypotenuse of right triangle is: 5.0 These functions are used to calculate mean, median, variance, minimum of array elements. It includes functions like- Python3 # Python code demonstrate statistical functionimport numpy as np # construct a weight arrayweight = np.array([50.7, 52.5, 50, 58, 55.63, 73.25, 49.5, 45]) # minimum and maximum print('Minimum and maximum weight of the students: ')print(np.amin(weight), np.amax(weight)) # range of weight i.e. max weight-min weightprint('Range of the weight of the students: ')print(np.ptp(weight)) # percentileprint('Weight below which 70 % student fall: ')print(np.percentile(weight, 70)) # mean print('Mean weight of the students: ')print(np.mean(weight)) # median print('Median weight of the students: ')print(np.median(weight)) # standard deviation print('Standard deviation of weight of the students: ')print(np.std(weight)) # variance print('Variance of weight of the students: ')print(np.var(weight)) # average print('Average weight of the students: ')print(np.average(weight)) Minimum and maximum weight of the students: 45.0 73.25 Range of the weight of the students: 28.25 Weight below which 70 % student fall: 55.317 Mean weight of the students: 54.3225 Median weight of the students: 51.6 Standard deviation of weight of the students: 8.05277397857 Variance of weight of the students: 64.84716875 Average weight of the students: 54.3225 These functions accept integer values as input arguments and perform bitwise operations on binary representations of those integers. It include functions like- Python3 # Python code to demonstrate bitwise-functionimport numpy as np # construct an array of even and odd numberseven = np.array([0, 2, 4, 6, 8, 16, 32])odd = np.array([1, 3, 5, 7, 9, 17, 33]) # bitwise_andprint('bitwise_and of two arrays: ')print(np.bitwise_and(even, odd)) # bitwise_orprint('bitwise_or of two arrays: ')print(np.bitwise_or(even, odd)) # bitwise_xorprint('bitwise_xor of two arrays: ')print(np.bitwise_xor(even, odd)) # invert or notprint('inversion of even no. array: ')print(np.invert(even)) # left_shift print('left_shift of even no. array: ')print(np.left_shift(even, 1)) # right_shift print('right_shift of even no. array: ')print(np.right_shift(even, 1)) bitwise_and of two arrays: [ 0 2 4 6 8 16 32] bitwise_or of two arrays: [ 1 3 5 7 9 17 33] bitwise_xor of two arrays: [1 1 1 1 1 1 1] inversion of even no. array: [ -1 -3 -5 -7 -9 -17 -33] left_shift of even no. array: [ 0 4 8 12 16 32 64] right_shift of even no. array: [ 0 1 2 3 4 8 16] akshaysingh98088 Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 477, "s": 28, "text": "Universal functions in Numpy are simple mathematical functions. It is just a term that we gave to mathematical functions in the Numpy library. Numpy provides various universal functions that cover a wide variety of operations. These functions include standard trigonometric functions, functions for arithmetic operations, handling complex numbers, statistical functions, etc. Universal functions have various characteristics which are as follows- " }, { "code": null, "e": 560, "s": 477, "text": "These functions operates on ndarray (N-dimensional array) i.e Numpy’s array class." }, { "code": null, "e": 608, "s": 560, "text": "It performs fast element-wise array operations." }, { "code": null, "e": 680, "s": 608, "text": "It supports various features like array broadcasting, type casting etc." }, { "code": null, "e": 755, "s": 680, "text": "Numpy, universal functions are objects those belongs to numpy.ufunc class." }, { "code": null, "e": 851, "s": 755, "text": "Python functions can also be created as a universal function using frompyfunc library function." }, { "code": null, "e": 1070, "s": 851, "text": "Some ufuncs are called automatically when the corresponding arithmetic operator is used on arrays. For example when addition of two array is performed element-wise using ‘+’ operator then np.add() is called internally." }, { "code": null, "e": 1123, "s": 1070, "text": "Some of the basic universal functions in Numpy are- " }, { "code": null, "e": 1338, "s": 1123, "text": "These functions work on radians, so angles need to be converted to radians by multiplying by pi/180. Only then we can call trigonometric functions. They take an array as input arguments. It includes functions like-" }, { "code": null, "e": 1348, "s": 1340, "text": "Python3" }, { "code": "# Python code to demonstrate trigonometric functionimport numpy as np # create an array of anglesangles = np.array([0, 30, 45, 60, 90, 180]) # conversion of degree into radians# using deg2rad functionradians = np.deg2rad(angles) # sine of anglesprint('Sine of angles in the array:')sine_value = np.sin(radians)print(np.sin(radians)) # inverse sine of sine valuesprint('Inverse Sine of sine values:')print(np.rad2deg(np.arcsin(sine_value))) # hyperbolic sine of anglesprint('Sine hyperbolic of angles in the array:')sineh_value = np.sinh(radians)print(np.sinh(radians)) # inverse sine hyperbolic print('Inverse Sine hyperbolic:')print(np.sin(sineh_value)) # hypot function demonstrationbase = 4height = 3print('hypotenuse of right triangle is:')print(np.hypot(base, height))", "e": 2131, "s": 1348, "text": null }, { "code": null, "e": 2659, "s": 2131, "text": "Sine of angles in the array:\n[ 0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01\n 1.00000000e+00 1.22464680e-16]\n\nInverse Sine of sine values:\n[ 0.00000000e+00 3.00000000e+01 4.50000000e+01 6.00000000e+01\n 9.00000000e+01 7.01670930e-15]\n\nSine hyperbolic of angles in the array:\n[ 0. 0.54785347 0.86867096 1.24936705 2.3012989\n 11.54873936]\n\nInverse Sine hyperbolic:\n[ 0. 0.52085606 0.76347126 0.94878485 0.74483916 -0.85086591]\n\nhypotenuse of right triangle is:\n5.0" }, { "code": null, "e": 2779, "s": 2661, "text": "These functions are used to calculate mean, median, variance, minimum of array elements. It includes functions like- " }, { "code": null, "e": 2789, "s": 2781, "text": "Python3" }, { "code": "# Python code demonstrate statistical functionimport numpy as np # construct a weight arrayweight = np.array([50.7, 52.5, 50, 58, 55.63, 73.25, 49.5, 45]) # minimum and maximum print('Minimum and maximum weight of the students: ')print(np.amin(weight), np.amax(weight)) # range of weight i.e. max weight-min weightprint('Range of the weight of the students: ')print(np.ptp(weight)) # percentileprint('Weight below which 70 % student fall: ')print(np.percentile(weight, 70)) # mean print('Mean weight of the students: ')print(np.mean(weight)) # median print('Median weight of the students: ')print(np.median(weight)) # standard deviation print('Standard deviation of weight of the students: ')print(np.std(weight)) # variance print('Variance of weight of the students: ')print(np.var(weight)) # average print('Average weight of the students: ')print(np.average(weight))", "e": 3668, "s": 2789, "text": null }, { "code": null, "e": 4047, "s": 3668, "text": "Minimum and maximum weight of the students: \n45.0 73.25\n\nRange of the weight of the students: \n28.25\n\nWeight below which 70 % student fall: \n55.317\n\nMean weight of the students: \n54.3225\n\nMedian weight of the students: \n51.6\n\nStandard deviation of weight of the students: \n8.05277397857\n\nVariance of weight of the students: \n64.84716875\n\nAverage weight of the students: \n54.3225" }, { "code": null, "e": 4210, "s": 4049, "text": "These functions accept integer values as input arguments and perform bitwise operations on binary representations of those integers. It include functions like- " }, { "code": null, "e": 4220, "s": 4212, "text": "Python3" }, { "code": "# Python code to demonstrate bitwise-functionimport numpy as np # construct an array of even and odd numberseven = np.array([0, 2, 4, 6, 8, 16, 32])odd = np.array([1, 3, 5, 7, 9, 17, 33]) # bitwise_andprint('bitwise_and of two arrays: ')print(np.bitwise_and(even, odd)) # bitwise_orprint('bitwise_or of two arrays: ')print(np.bitwise_or(even, odd)) # bitwise_xorprint('bitwise_xor of two arrays: ')print(np.bitwise_xor(even, odd)) # invert or notprint('inversion of even no. array: ')print(np.invert(even)) # left_shift print('left_shift of even no. array: ')print(np.left_shift(even, 1)) # right_shift print('right_shift of even no. array: ')print(np.right_shift(even, 1))", "e": 4902, "s": 4220, "text": null }, { "code": null, "e": 5221, "s": 4902, "text": "bitwise_and of two arrays: \n[ 0 2 4 6 8 16 32]\n\nbitwise_or of two arrays: \n[ 1 3 5 7 9 17 33]\n\nbitwise_xor of two arrays: \n[1 1 1 1 1 1 1]\n\ninversion of even no. array: \n[ -1 -3 -5 -7 -9 -17 -33]\n\nleft_shift of even no. array: \n[ 0 4 8 12 16 32 64]\n\nright_shift of even no. array: \n[ 0 1 2 3 4 8 16]" }, { "code": null, "e": 5240, "s": 5223, "text": "akshaysingh98088" }, { "code": null, "e": 5253, "s": 5240, "text": "Python-numpy" }, { "code": null, "e": 5260, "s": 5253, "text": "Python" }, { "code": null, "e": 5358, "s": 5260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5386, "s": 5358, "text": "Read JSON file using Python" }, { "code": null, "e": 5436, "s": 5386, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5458, "s": 5436, "text": "Python map() function" }, { "code": null, "e": 5502, "s": 5458, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5544, "s": 5502, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5566, "s": 5544, "text": "Enumerate() in Python" }, { "code": null, "e": 5601, "s": 5566, "text": "Read a file line by line in Python" }, { "code": null, "e": 5627, "s": 5601, "text": "Python String | replace()" }, { "code": null, "e": 5659, "s": 5627, "text": "How to Install PIP on Windows ?" } ]
Time Series Modeling using Scikit, Pandas, and Numpy | by Dr. Varshita Sher | Towards Data Science
Welcome to Part 2 of Time Series Analysis! In this post, we will be working our way through modeling time series data. This is a continuation of my previous post on Time Series Data. In our previous blog post, we talked about what time series data is, how to format such data to maximize its utility, and how to handle missing data. We also learned how to resample time series data by the month, week, year, etc, and calculate rolling means. We dived into concepts such as trends, seasonality, first-order differencing, and autocorrelation. If you are familiar with most of the stuff, you are good to go. In case you need a refresher, you can do a quick google search for these topics or read my previous post here. There are other, undoubtedly better, packages available for time series forecastings, such as ARIMA or Facebook’s proprietory software Prophet. However, this article was inspired by a friend’s take-home assignment that required her to use only Scikit, Numpy, and Pandas (or face instant disqualification!). We will be working with the publicly available dataset Open Power System Data. You can download the data here. It contains electricity consumption, wind power production, and solar power production for 2006–2017. url='https://raw.githubusercontent.com/jenfly/opsd/master/opsd_germany_daily.csv'data = pd.read_csv(url,sep=",") After setting the Date column as the index, this is how our dataset looks like: # to explicitly convert the date column to type DATETIMEdata['Date'] = pd.to_datetime(data['Date'])data = data.set_index('Date') Our aim is to predict Consumption (ideally for future unseen dates) from this time series dataset. We will be using 10 years of data for training i.e. 2006–2016 and last year’s data for testing i.e. 2017. In order to evaluate how good our model is, we would be using R-squared and Root Mean Squared Error (but will be printing all relevant metrics for you to take the final call). In order to print all performance metrics relevant to a regression task (such as MAE and R-square), we will be defining the regression_results function. import sklearn.metrics as metricsdef regression_results(y_true, y_pred): # Regression metrics explained_variance=metrics.explained_variance_score(y_true, y_pred) mean_absolute_error=metrics.mean_absolute_error(y_true, y_pred) mse=metrics.mean_squared_error(y_true, y_pred) mean_squared_log_error=metrics.mean_squared_log_error(y_true, y_pred) median_absolute_error=metrics.median_absolute_error(y_true, y_pred) r2=metrics.r2_score(y_true, y_pred) print('explained_variance: ', round(explained_variance,4)) print('mean_squared_log_error: ', round(mean_squared_log_error,4)) print('r2: ', round(r2,4)) print('MAE: ', round(mean_absolute_error,4)) print('MSE: ', round(mse,4)) print('RMSE: ', round(np.sqrt(mse),4)) As a baseline, we choose a simplistic model, one that predicts today’s consumption value based on yesterday’s consumption value and; difference between yesterday and the day before yesterday’s consumption value. # creating new dataframe from consumption columndata_consumption = data[['Consumption']]# inserting new column with yesterday's consumption valuesdata_consumption.loc[:,'Yesterday'] = data_consumption.loc[:,'Consumption'].shift()# inserting another column with difference between yesterday and day before yesterday's consumption values.data_consumption.loc[:,'Yesterday_Diff'] = data_consumption.loc[:,'Yesterday'].diff()# dropping NAsdata_consumption = data_consumption.dropna() X_train = data_consumption[:'2016'].drop(['Consumption'], axis = 1)y_train = data_consumption.loc[:'2016', 'Consumption']X_test = data_consumption['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption.loc['2017', 'Consumption'] A question that often comes up during data science interviews is: Which cross-validation technique would you use on time-series data? You may be tempted to gravitate towards the all-time-favorite K-Fold Cross-Validation (believe me, up until recently — don’t ask how recently! — I did not know there exist CV techniques other than K-fold). Unfortunately, that would not be the correct answer. The reason being, it does not take into account that time-series data has some natural ordering to it and the randomization in standard k-fold cross-validation does not preserve that ordering. A better alternative for cross validation on time series data (than K-fold CV) is Forward Chaining strategy. In forward chaining, say with 3 folds, the train and validation sets look like: fold 1: training [1], validation [2] fold 2: training [1 2], validation [3] fold 3: training [1 2 3], validation [4] where 1, 2, 3, 4 represent the year. This way successive training sets are supersets of those that come before them. Luckily for us, sklearn has a provision for implementing such train test split using TimeSeriesSplit. from sklearn.model_selection import TimeSeriesSplit The TimeSerieSplit function takes as input the number of splits. Since our training data has 11 unique years (2006 -2016), we would be setting n_splits = 10. This way we have neat training and validation sets: fold 1: training [2006], validation [2007] fold 2: training [2006 2007], validation [2008] fold 3: training [2006 2007 2008], validation [2009] fold 4: training [2006 2007 2008 2009], validation [2010] fold 5: training [2006 2007 2008 2009 2010], validation [2011] fold 6: training [2006 2007 2008 2009 2010 2011], validation [2012] fold 7: training [2006 2007 2008 2009 2010 2011 2012], validation [2013] fold 8: training [2006 2007 2008 2009 2010 2011 2012 2013], validation [2014] fold 9: training [2006 2007 2008 2009 2010 2011 2012 2013 2014], validation [2015] fold 10: training [2006 2007 2008 2009 2010 2011 2012 2013 2014 2015], validation [2016] # Spot Check Algorithmsmodels = []models.append(('LR', LinearRegression()))models.append(('NN', MLPRegressor(solver = 'lbfgs'))) #neural networkmodels.append(('KNN', KNeighborsRegressor())) models.append(('RF', RandomForestRegressor(n_estimators = 10))) # Ensemble method - collection of many decision treesmodels.append(('SVR', SVR(gamma='auto'))) # kernel = linear# Evaluate each model in turnresults = []names = []for name, model in models: # TimeSeries Cross validation tscv = TimeSeriesSplit(n_splits=10) cv_results = cross_val_score(model, X_train, y_train, cv=tscv, scoring='r2') results.append(cv_results) names.append(name) print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std())) # Compare Algorithmsplt.boxplot(results, labels=names)plt.title('Algorithm Comparison')plt.show() Both KNN and RF perform equally well. But I personally prefer RF since this ensemble model (combine multiple ‘individual’ (diverse) models together and deliver superior prediction power.) can almost work out of the box and that is one reason why they are very popular. I discussed the need for grid searching hyperparameters in one of my previous articles. An optimal combination of hyperparameters maximizes a model’s performance without leading to a high variance problem (overfitting). The Python code for performing grid-search is as follows: from sklearn.model_selection import GridSearchCVmodel = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=10)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train, y_train)best_score = gsearch.best_score_best_model = gsearch.best_estimator_ If you notice the code above, we have defined a custom scorer by setting scoring = rmse_scoreinstead of using one of the common scoring metrics defined in sklearn. We define our custom scorer as follows: from sklearn.metrics import make_scorerdef rmse(actual, predict):predict = np.array(predict) actual = np.array(actual)distance = predict - actualsquare_distance = distance ** 2mean_square_distance = square_distance.mean()score = np.sqrt(mean_square_distance)return scorermse_score = make_scorer(rmse, greater_is_better = False) y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred) This is not bad for starters. Let’s see if we can further improve our model. Up until now, we have been using values at (t-1)th day to predict values on t date. Now, let us also use values from (t-2)days to predict consumption: # creating copy of original dataframedata_consumption_2o = data_consumption.copy()# inserting column with yesterday-1 valuesdata_consumption_2o['Yesterday-1'] = data_consumption_2o['Yesterday'].shift()# inserting column with difference in yesterday-1 and yesterday-2 values.data_consumption_2o['Yesterday-1_Diff'] = data_consumption_2o['Yesterday-1'].diff()# dropping NAsdata_consumption_2o = data_consumption_2o.dropna() X_train_2o = data_consumption_2o[:'2016'].drop(['Consumption'], axis = 1)y_train_2o = data_consumption_2o.loc[:'2016', 'Consumption']X_test = data_consumption_2o['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption_2o.loc['2017', 'Consumption'] model = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=10)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train_2o, y_train_2o)best_score = gsearch.best_score_best_model = gsearch.best_estimator_y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred) Great news!! We have significantly brought down the RMSE and MAE values, whereas the R-squared value has also gone up. Let us see if adding the value of solar production is beneficial in some way to predicting electricity consumption. data_consumption_2o_solar = data_consumption_2o.join(data[['Solar']])data_consumption_2o_solar = data_consumption_2o_solar.dropna() X_train_2o_solar = data_consumption_2o_solar[:'2016'].drop(['Consumption'], axis = 1)y_train_2o_solar = data_consumption_2o_solar.loc[:'2016', 'Consumption']X_test = data_consumption_2o_solar['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption_2o_solar.loc['2017', 'Consumption']model = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=5)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train_2o_solar, y_train_2o_solar)best_score = gsearch.best_score_best_model = gsearch.best_estimator_y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred) Voila, the model’s performance is even better now. imp = best_model.feature_importances_features = X_train_2o_solar.columnsindices = np.argsort(imp)plt.title('Feature Importances')plt.barh(range(len(indices)), imp[indices], color='b', align='center')plt.yticks(range(len(indices)), [features[i] for i in indices])plt.xlabel('Relative Importance')plt.show() As we can see, the amount of solar production is not as strong a predictor of power consumption as other time-based predictors. If you followed the narrative in Part 1 of my previous blog post, you would remember that our dataset has some seasonal element to it, weekly seasonality to be more precise. Thus, it would make more sense to feed as input to the model, consumption value in the week prior to the given date. That means, if the model is trying to predict the consumption value on Jan 8, it must be fed information about the consumption on Jan 1. data_consumption_2o_solar_weeklyShift = data_consumption_2o_solar.copy()data_consumption_2o_solar_weeklyShift['Last_Week'] = data_consumption_2o_solar['Consumption'].shift(7)data_consumption_2o_solar_weeklyShift = data_consumption_2o_solar_weeklyShift.dropna() X_train_2o_solar_weeklyShift = data_consumption_2o_solar_weeklyShift[:'2016'].drop(['Consumption'], axis = 1)y_train_2o_solar_weeklyShift = data_consumption_2o_solar_weeklyShift.loc[:'2016', 'Consumption']X_test = data_consumption_2o_solar_weeklyShift['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption_2o_solar_weeklyShift.loc['2017', 'Consumption']model = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=10)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train_2o_solar_weeklyShift, y_train_2o_solar_weeklyShift)best_score = gsearch.best_score_best_model = gsearch.best_estimator_y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred) And we did it again.. The errors have been reduced further and r-square increased. We could keep on adding more relevant features but I guess you get the idea now! As we rightly hypothesized, the value on (t-7)th day is a much stronger predictor than the value on (t-1)th day. In this article, we learned how to model time series data, conduct cross-validation on time series data, and fine-tune our model hyperparameters. We also successfully managed to reduce the RMSE from 85.61 to 54.57 for predicting power consumption. In Part 3 of this series, we will be working on a case study analyzing the time series data generated by call centers, essentially working towards analyzing the (dreaded) increment in abandonment rates. Stay tuned... Until next time :)
[ { "code": null, "e": 355, "s": 172, "text": "Welcome to Part 2 of Time Series Analysis! In this post, we will be working our way through modeling time series data. This is a continuation of my previous post on Time Series Data." }, { "code": null, "e": 888, "s": 355, "text": "In our previous blog post, we talked about what time series data is, how to format such data to maximize its utility, and how to handle missing data. We also learned how to resample time series data by the month, week, year, etc, and calculate rolling means. We dived into concepts such as trends, seasonality, first-order differencing, and autocorrelation. If you are familiar with most of the stuff, you are good to go. In case you need a refresher, you can do a quick google search for these topics or read my previous post here." }, { "code": null, "e": 1195, "s": 888, "text": "There are other, undoubtedly better, packages available for time series forecastings, such as ARIMA or Facebook’s proprietory software Prophet. However, this article was inspired by a friend’s take-home assignment that required her to use only Scikit, Numpy, and Pandas (or face instant disqualification!)." }, { "code": null, "e": 1408, "s": 1195, "text": "We will be working with the publicly available dataset Open Power System Data. You can download the data here. It contains electricity consumption, wind power production, and solar power production for 2006–2017." }, { "code": null, "e": 1521, "s": 1408, "text": "url='https://raw.githubusercontent.com/jenfly/opsd/master/opsd_germany_daily.csv'data = pd.read_csv(url,sep=\",\")" }, { "code": null, "e": 1601, "s": 1521, "text": "After setting the Date column as the index, this is how our dataset looks like:" }, { "code": null, "e": 1730, "s": 1601, "text": "# to explicitly convert the date column to type DATETIMEdata['Date'] = pd.to_datetime(data['Date'])data = data.set_index('Date')" }, { "code": null, "e": 1829, "s": 1730, "text": "Our aim is to predict Consumption (ideally for future unseen dates) from this time series dataset." }, { "code": null, "e": 1935, "s": 1829, "text": "We will be using 10 years of data for training i.e. 2006–2016 and last year’s data for testing i.e. 2017." }, { "code": null, "e": 2111, "s": 1935, "text": "In order to evaluate how good our model is, we would be using R-squared and Root Mean Squared Error (but will be printing all relevant metrics for you to take the final call)." }, { "code": null, "e": 2264, "s": 2111, "text": "In order to print all performance metrics relevant to a regression task (such as MAE and R-square), we will be defining the regression_results function." }, { "code": null, "e": 3022, "s": 2264, "text": "import sklearn.metrics as metricsdef regression_results(y_true, y_pred): # Regression metrics explained_variance=metrics.explained_variance_score(y_true, y_pred) mean_absolute_error=metrics.mean_absolute_error(y_true, y_pred) mse=metrics.mean_squared_error(y_true, y_pred) mean_squared_log_error=metrics.mean_squared_log_error(y_true, y_pred) median_absolute_error=metrics.median_absolute_error(y_true, y_pred) r2=metrics.r2_score(y_true, y_pred) print('explained_variance: ', round(explained_variance,4)) print('mean_squared_log_error: ', round(mean_squared_log_error,4)) print('r2: ', round(r2,4)) print('MAE: ', round(mean_absolute_error,4)) print('MSE: ', round(mse,4)) print('RMSE: ', round(np.sqrt(mse),4))" }, { "code": null, "e": 3120, "s": 3022, "text": "As a baseline, we choose a simplistic model, one that predicts today’s consumption value based on" }, { "code": null, "e": 3155, "s": 3120, "text": "yesterday’s consumption value and;" }, { "code": null, "e": 3234, "s": 3155, "text": "difference between yesterday and the day before yesterday’s consumption value." }, { "code": null, "e": 3714, "s": 3234, "text": "# creating new dataframe from consumption columndata_consumption = data[['Consumption']]# inserting new column with yesterday's consumption valuesdata_consumption.loc[:,'Yesterday'] = data_consumption.loc[:,'Consumption'].shift()# inserting another column with difference between yesterday and day before yesterday's consumption values.data_consumption.loc[:,'Yesterday_Diff'] = data_consumption.loc[:,'Yesterday'].diff()# dropping NAsdata_consumption = data_consumption.dropna()" }, { "code": null, "e": 3953, "s": 3714, "text": "X_train = data_consumption[:'2016'].drop(['Consumption'], axis = 1)y_train = data_consumption.loc[:'2016', 'Consumption']X_test = data_consumption['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption.loc['2017', 'Consumption']" }, { "code": null, "e": 4087, "s": 3953, "text": "A question that often comes up during data science interviews is: Which cross-validation technique would you use on time-series data?" }, { "code": null, "e": 4539, "s": 4087, "text": "You may be tempted to gravitate towards the all-time-favorite K-Fold Cross-Validation (believe me, up until recently — don’t ask how recently! — I did not know there exist CV techniques other than K-fold). Unfortunately, that would not be the correct answer. The reason being, it does not take into account that time-series data has some natural ordering to it and the randomization in standard k-fold cross-validation does not preserve that ordering." }, { "code": null, "e": 4648, "s": 4539, "text": "A better alternative for cross validation on time series data (than K-fold CV) is Forward Chaining strategy." }, { "code": null, "e": 4728, "s": 4648, "text": "In forward chaining, say with 3 folds, the train and validation sets look like:" }, { "code": null, "e": 4765, "s": 4728, "text": "fold 1: training [1], validation [2]" }, { "code": null, "e": 4804, "s": 4765, "text": "fold 2: training [1 2], validation [3]" }, { "code": null, "e": 4845, "s": 4804, "text": "fold 3: training [1 2 3], validation [4]" }, { "code": null, "e": 4962, "s": 4845, "text": "where 1, 2, 3, 4 represent the year. This way successive training sets are supersets of those that come before them." }, { "code": null, "e": 5064, "s": 4962, "text": "Luckily for us, sklearn has a provision for implementing such train test split using TimeSeriesSplit." }, { "code": null, "e": 5116, "s": 5064, "text": "from sklearn.model_selection import TimeSeriesSplit" }, { "code": null, "e": 5326, "s": 5116, "text": "The TimeSerieSplit function takes as input the number of splits. Since our training data has 11 unique years (2006 -2016), we would be setting n_splits = 10. This way we have neat training and validation sets:" }, { "code": null, "e": 5369, "s": 5326, "text": "fold 1: training [2006], validation [2007]" }, { "code": null, "e": 5417, "s": 5369, "text": "fold 2: training [2006 2007], validation [2008]" }, { "code": null, "e": 5470, "s": 5417, "text": "fold 3: training [2006 2007 2008], validation [2009]" }, { "code": null, "e": 5528, "s": 5470, "text": "fold 4: training [2006 2007 2008 2009], validation [2010]" }, { "code": null, "e": 5591, "s": 5528, "text": "fold 5: training [2006 2007 2008 2009 2010], validation [2011]" }, { "code": null, "e": 5659, "s": 5591, "text": "fold 6: training [2006 2007 2008 2009 2010 2011], validation [2012]" }, { "code": null, "e": 5732, "s": 5659, "text": "fold 7: training [2006 2007 2008 2009 2010 2011 2012], validation [2013]" }, { "code": null, "e": 5810, "s": 5732, "text": "fold 8: training [2006 2007 2008 2009 2010 2011 2012 2013], validation [2014]" }, { "code": null, "e": 5893, "s": 5810, "text": "fold 9: training [2006 2007 2008 2009 2010 2011 2012 2013 2014], validation [2015]" }, { "code": null, "e": 5982, "s": 5893, "text": "fold 10: training [2006 2007 2008 2009 2010 2011 2012 2013 2014 2015], validation [2016]" }, { "code": null, "e": 6791, "s": 5982, "text": "# Spot Check Algorithmsmodels = []models.append(('LR', LinearRegression()))models.append(('NN', MLPRegressor(solver = 'lbfgs'))) #neural networkmodels.append(('KNN', KNeighborsRegressor())) models.append(('RF', RandomForestRegressor(n_estimators = 10))) # Ensemble method - collection of many decision treesmodels.append(('SVR', SVR(gamma='auto'))) # kernel = linear# Evaluate each model in turnresults = []names = []for name, model in models: # TimeSeries Cross validation tscv = TimeSeriesSplit(n_splits=10) cv_results = cross_val_score(model, X_train, y_train, cv=tscv, scoring='r2') results.append(cv_results) names.append(name) print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std())) # Compare Algorithmsplt.boxplot(results, labels=names)plt.title('Algorithm Comparison')plt.show()" }, { "code": null, "e": 7060, "s": 6791, "text": "Both KNN and RF perform equally well. But I personally prefer RF since this ensemble model (combine multiple ‘individual’ (diverse) models together and deliver superior prediction power.) can almost work out of the box and that is one reason why they are very popular." }, { "code": null, "e": 7148, "s": 7060, "text": "I discussed the need for grid searching hyperparameters in one of my previous articles." }, { "code": null, "e": 7280, "s": 7148, "text": "An optimal combination of hyperparameters maximizes a model’s performance without leading to a high variance problem (overfitting)." }, { "code": null, "e": 7338, "s": 7280, "text": "The Python code for performing grid-search is as follows:" }, { "code": null, "e": 7784, "s": 7338, "text": "from sklearn.model_selection import GridSearchCVmodel = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=10)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train, y_train)best_score = gsearch.best_score_best_model = gsearch.best_estimator_" }, { "code": null, "e": 7988, "s": 7784, "text": "If you notice the code above, we have defined a custom scorer by setting scoring = rmse_scoreinstead of using one of the common scoring metrics defined in sklearn. We define our custom scorer as follows:" }, { "code": null, "e": 8319, "s": 7988, "text": "from sklearn.metrics import make_scorerdef rmse(actual, predict):predict = np.array(predict) actual = np.array(actual)distance = predict - actualsquare_distance = distance ** 2mean_square_distance = square_distance.mean()score = np.sqrt(mean_square_distance)return scorermse_score = make_scorer(rmse, greater_is_better = False)" }, { "code": null, "e": 8411, "s": 8319, "text": "y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred)" }, { "code": null, "e": 8488, "s": 8411, "text": "This is not bad for starters. Let’s see if we can further improve our model." }, { "code": null, "e": 8639, "s": 8488, "text": "Up until now, we have been using values at (t-1)th day to predict values on t date. Now, let us also use values from (t-2)days to predict consumption:" }, { "code": null, "e": 9061, "s": 8639, "text": "# creating copy of original dataframedata_consumption_2o = data_consumption.copy()# inserting column with yesterday-1 valuesdata_consumption_2o['Yesterday-1'] = data_consumption_2o['Yesterday'].shift()# inserting column with difference in yesterday-1 and yesterday-2 values.data_consumption_2o['Yesterday-1_Diff'] = data_consumption_2o['Yesterday-1'].diff()# dropping NAsdata_consumption_2o = data_consumption_2o.dropna()" }, { "code": null, "e": 9318, "s": 9061, "text": "X_train_2o = data_consumption_2o[:'2016'].drop(['Consumption'], axis = 1)y_train_2o = data_consumption_2o.loc[:'2016', 'Consumption']X_test = data_consumption_2o['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption_2o.loc['2017', 'Consumption']" }, { "code": null, "e": 9813, "s": 9318, "text": "model = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=10)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train_2o, y_train_2o)best_score = gsearch.best_score_best_model = gsearch.best_estimator_y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred)" }, { "code": null, "e": 9932, "s": 9813, "text": "Great news!! We have significantly brought down the RMSE and MAE values, whereas the R-squared value has also gone up." }, { "code": null, "e": 10048, "s": 9932, "text": "Let us see if adding the value of solar production is beneficial in some way to predicting electricity consumption." }, { "code": null, "e": 10180, "s": 10048, "text": "data_consumption_2o_solar = data_consumption_2o.join(data[['Solar']])data_consumption_2o_solar = data_consumption_2o_solar.dropna()" }, { "code": null, "e": 10978, "s": 10180, "text": "X_train_2o_solar = data_consumption_2o_solar[:'2016'].drop(['Consumption'], axis = 1)y_train_2o_solar = data_consumption_2o_solar.loc[:'2016', 'Consumption']X_test = data_consumption_2o_solar['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption_2o_solar.loc['2017', 'Consumption']model = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=5)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train_2o_solar, y_train_2o_solar)best_score = gsearch.best_score_best_model = gsearch.best_estimator_y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred)" }, { "code": null, "e": 11029, "s": 10978, "text": "Voila, the model’s performance is even better now." }, { "code": null, "e": 11335, "s": 11029, "text": "imp = best_model.feature_importances_features = X_train_2o_solar.columnsindices = np.argsort(imp)plt.title('Feature Importances')plt.barh(range(len(indices)), imp[indices], color='b', align='center')plt.yticks(range(len(indices)), [features[i] for i in indices])plt.xlabel('Relative Importance')plt.show()" }, { "code": null, "e": 11463, "s": 11335, "text": "As we can see, the amount of solar production is not as strong a predictor of power consumption as other time-based predictors." }, { "code": null, "e": 11891, "s": 11463, "text": "If you followed the narrative in Part 1 of my previous blog post, you would remember that our dataset has some seasonal element to it, weekly seasonality to be more precise. Thus, it would make more sense to feed as input to the model, consumption value in the week prior to the given date. That means, if the model is trying to predict the consumption value on Jan 8, it must be fed information about the consumption on Jan 1." }, { "code": null, "e": 12152, "s": 11891, "text": "data_consumption_2o_solar_weeklyShift = data_consumption_2o_solar.copy()data_consumption_2o_solar_weeklyShift['Last_Week'] = data_consumption_2o_solar['Consumption'].shift(7)data_consumption_2o_solar_weeklyShift = data_consumption_2o_solar_weeklyShift.dropna()" }, { "code": null, "e": 13047, "s": 12152, "text": "X_train_2o_solar_weeklyShift = data_consumption_2o_solar_weeklyShift[:'2016'].drop(['Consumption'], axis = 1)y_train_2o_solar_weeklyShift = data_consumption_2o_solar_weeklyShift.loc[:'2016', 'Consumption']X_test = data_consumption_2o_solar_weeklyShift['2017'].drop(['Consumption'], axis = 1)y_test = data_consumption_2o_solar_weeklyShift.loc['2017', 'Consumption']model = RandomForestRegressor()param_search = { 'n_estimators': [20, 50, 100], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [i for i in range(5,15)]}tscv = TimeSeriesSplit(n_splits=10)gsearch = GridSearchCV(estimator=model, cv=tscv, param_grid=param_search, scoring = rmse_score)gsearch.fit(X_train_2o_solar_weeklyShift, y_train_2o_solar_weeklyShift)best_score = gsearch.best_score_best_model = gsearch.best_estimator_y_true = y_test.valuesy_pred = best_model.predict(X_test)regression_results(y_true, y_pred)" }, { "code": null, "e": 13211, "s": 13047, "text": "And we did it again.. The errors have been reduced further and r-square increased. We could keep on adding more relevant features but I guess you get the idea now!" }, { "code": null, "e": 13324, "s": 13211, "text": "As we rightly hypothesized, the value on (t-7)th day is a much stronger predictor than the value on (t-1)th day." }, { "code": null, "e": 13572, "s": 13324, "text": "In this article, we learned how to model time series data, conduct cross-validation on time series data, and fine-tune our model hyperparameters. We also successfully managed to reduce the RMSE from 85.61 to 54.57 for predicting power consumption." }, { "code": null, "e": 13789, "s": 13572, "text": "In Part 3 of this series, we will be working on a case study analyzing the time series data generated by call centers, essentially working towards analyzing the (dreaded) increment in abandonment rates. Stay tuned..." } ]
What is C++ Standard Error Stream (cerr)?
std::cerr is an object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog). As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in the header <iostream> with external linkage and static duration: it lasts the entire duration of the program. You can use this object to write to the screen. For example, if you want to write "Hello" to the screen, you'd write − Live Demo #include<iostream> int main() { std::cerr << "Hello"; return 0; } Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using − $ g++ hello.cpp Run it using − $ ./a.out This will give the output − Hello
[ { "code": null, "e": 1405, "s": 1062, "text": "std::cerr is an object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog)." }, { "code": null, "e": 1733, "s": 1405, "text": "As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in the header <iostream> with external linkage and static duration: it lasts the entire duration of the program." }, { "code": null, "e": 1852, "s": 1733, "text": "You can use this object to write to the screen. For example, if you want to write \"Hello\" to the screen, you'd write −" }, { "code": null, "e": 1862, "s": 1852, "text": "Live Demo" }, { "code": null, "e": 1934, "s": 1862, "text": "#include<iostream>\nint main() {\n std::cerr << \"Hello\";\n return 0;\n}" }, { "code": null, "e": 2071, "s": 1934, "text": "Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −" }, { "code": null, "e": 2087, "s": 2071, "text": "$ g++ hello.cpp" }, { "code": null, "e": 2102, "s": 2087, "text": "Run it using −" }, { "code": null, "e": 2112, "s": 2102, "text": "$ ./a.out" }, { "code": null, "e": 2140, "s": 2112, "text": "This will give the output −" }, { "code": null, "e": 2146, "s": 2140, "text": "Hello" } ]
Print cousins of a given node in Binary Tree
04 Jul, 2022 Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.Example: Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7 The idea to first find level of given node using the approach discussed here. Once we have found level, we can print all nodes at a given level using the approach discussed here. The only thing to take care of is, sibling should not be printed. To handle this, we change the printing function to first check for sibling and print node only if it is not sibling. Below is the implementation of above idea. C++ C Java Python3 C# Javascript // C++ program to print cousins of a node#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; Node *left, *right;}; // A utility function to create a new// Binary Tree NodeNode *newNode(int item){ Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* It returns level of the node if it ispresent in tree, otherwise returns 0.*/int getLevel(Node *root, Node *node, int level){ // base cases if (root == NULL) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root->left, node, level + 1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root->right, node, level + 1);} /* Print nodes at a given level such thatsibling of node is not printed if it exists */void printGivenLevel(Node* root, Node *node, int level){ // Base cases if (root == NULL || level < 2) return; // If current node is parent of a node // with given level if (level == 2) { if (root->left == node || root->right == node) return; if (root->left) cout << root->left->data << " "; if (root->right) cout << root->right->data; } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root->left, node, level - 1); printGivenLevel(root->right, node, level - 1); }} // This function prints cousins of a given nodevoid printCousins(Node *root, Node *node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver Codeint main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); printCousins(root, root->left->right); return 0;} // This code is contributed// by Akanksha Rai // C program to print cousins of a node#include <stdio.h>#include <stdlib.h> // A Binary Tree Nodestruct Node{ int data; Node *left, *right;}; // A utility function to create a new Binary// Tree NodeNode *newNode(int item){ Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* It returns level of the node if it is present in tree, otherwise returns 0.*/int getLevel(Node *root, Node *node, int level){ // base cases if (root == NULL) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root->left, node, level+1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root->right, node, level+1);} /* Print nodes at a given level such that sibling of node is not printed if it exists */void printGivenLevel(Node* root, Node *node, int level){ // Base cases if (root == NULL || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root->left == node || root->right == node) return; if (root->left) printf("%d ", root->left->data); if (root->right) printf("%d ", root->right->data); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root->left, node, level-1); printGivenLevel(root->right, node, level-1); }} // This function prints cousins of a given nodevoid printCousins(Node *root, Node *node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver Program to test above functionsint main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); printCousins(root, root->left->right); return 0;} // Java program to print cousins of a nodeclass GfG { // A Binary Tree Nodestatic class Node{ int data; Node left, right;} // A utility function to create a new Binary// Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* It returns level of the node if it is presentin tree, otherwise returns 0.*/static int getLevel(Node root, Node node, int level){ // base cases if (root == null) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root.left, node, level+1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root.right, node, level+1);} /* Print nodes at a given level such that sibling ofnode is not printed if it exists */static void printGivenLevel(Node root, Node node, int level){ // Base cases if (root == null || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root.left == node || root.right == node) return; if (root.left != null) System.out.print(root.left.data + " "); if (root.right != null) System.out.print(root.right.data + " "); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root.left, node, level-1); printGivenLevel(root.right, node, level-1); }} // This function prints cousins of a given nodestatic void printCousins(Node root, Node node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver Program to test above functionspublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.right = newNode(15); root.right.left = newNode(6); root.right.right = newNode(7); root.right.left.right = newNode(8); printCousins(root, root.left.right);}} # Python3 program to print cousins of a node # A utility function to create a new# Binary Tree Nodeclass newNode: def __init__(self, item): self.data = item self.left = self.right = None # It returns level of the node if it is# present in tree, otherwise returns 0.def getLevel(root, node, level): # base cases if (root == None): return 0 if (root == node): return level # If node is present in left subtree downlevel = getLevel(root.left, node, level + 1) if (downlevel != 0): return downlevel # If node is not present in left subtree return getLevel(root.right, node, level + 1) # Print nodes at a given level such that# sibling of node is not printed if# it existsdef printGivenLevel(root, node, level): # Base cases if (root == None or level < 2): return # If current node is parent of a # node with given level if (level == 2): if (root.left == node or root.right == node): return if (root.left): print(root.left.data, end = " ") if (root.right): print(root.right.data, end = " ") # Recur for left and right subtrees else if (level > 2): printGivenLevel(root.left, node, level - 1) printGivenLevel(root.right, node, level - 1) # This function prints cousins of a given nodedef printCousins(root, node): # Get level of given node level = getLevel(root, node, 1) # Print nodes of given level. printGivenLevel(root, node, level) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.right.right = newNode(15) root.right.left = newNode(6) root.right.right = newNode(7) root.right.left.right = newNode(8) printCousins(root, root.left.right) # This code is contributed by PranchalK // C# program to print cousins of a nodeusing System; public class GfG{ // A Binary Tree Nodeclass Node{ public int data; public Node left, right;} // A utility function to create // a new Binary Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* It returns level of the nodeif it is present in tree, otherwise returns 0.*/static int getLevel(Node root, Node node, int level){ // base cases if (root == null) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root.left, node, level + 1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root.right, node, level + 1);} /* Print nodes at a given levelsuch that sibling of node is not printed if it exists */static void printGivenLevel(Node root, Node node, int level){ // Base cases if (root == null || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root.left == node || root.right == node) return; if (root.left != null) Console.Write(root.left.data + " "); if (root.right != null) Console.Write(root.right.data + " "); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root.left, node, level - 1); printGivenLevel(root.right, node, level - 1); }} // This function prints cousins of a given nodestatic void printCousins(Node root, Node node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver codepublic static void Main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.right = newNode(15); root.right.left = newNode(6); root.right.right = newNode(7); root.right.left.right = newNode(8); printCousins(root, root.left.right);}} // This code is contributed Rajput-Ji <script> // JavaScript program to print cousins of a node // A Binary Tree Nodeclass Node{ constructor() { this.data=0; this.left= null; this.right = null; }} // A utility function to create // a new Binary Tree Nodefunction newNode(item){ var temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* It returns level of the nodeif it is present in tree, otherwise returns 0.*/function getLevel(root, node, level){ // base cases if (root == null) return 0; if (root == node) return level; // If node is present in left subtree var downlevel = getLevel(root.left, node, level + 1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root.right, node, level + 1);} /* Print nodes at a given levelsuch that sibling of node is not printed if it exists */function printGivenLevel(root, node, level){ // Base cases if (root == null || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root.left == node || root.right == node) return; if (root.left != null) document.write(root.left.data + " "); if (root.right != null) document.write(root.right.data + " "); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root.left, node, level - 1); printGivenLevel(root.right, node, level - 1); }} // This function prints cousins of a given nodefunction printCousins(root, node){ // Get level of given node var level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.left.right.right = newNode(15);root.right.left = newNode(6);root.right.right = newNode(7);root.right.left.right = newNode(8);printCousins(root, root.left.right); </script> 6 7 Time Complexity : O(n) Can we solve this problem using single traversal? Please refer below article Print cousins of a given node in Binary Tree | Single Traversal This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. prerna saini PranchalKatiyar Akanksha_Rai Rajput-Ji rutvik_56 simmytarika5 surinderdawra388 hardikkoriintern Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 171, "s": 54, "text": "Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.Example: " }, { "code": null, "e": 341, "s": 171, "text": "Input : root of below tree \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n and pointer to a node say 5.\n\nOutput : 6, 7" }, { "code": null, "e": 703, "s": 341, "text": "The idea to first find level of given node using the approach discussed here. Once we have found level, we can print all nodes at a given level using the approach discussed here. The only thing to take care of is, sibling should not be printed. To handle this, we change the printing function to first check for sibling and print node only if it is not sibling." }, { "code": null, "e": 747, "s": 703, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 751, "s": 747, "text": "C++" }, { "code": null, "e": 753, "s": 751, "text": "C" }, { "code": null, "e": 758, "s": 753, "text": "Java" }, { "code": null, "e": 766, "s": 758, "text": "Python3" }, { "code": null, "e": 769, "s": 766, "text": "C#" }, { "code": null, "e": 780, "s": 769, "text": "Javascript" }, { "code": "// C++ program to print cousins of a node#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; Node *left, *right;}; // A utility function to create a new// Binary Tree NodeNode *newNode(int item){ Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* It returns level of the node if it ispresent in tree, otherwise returns 0.*/int getLevel(Node *root, Node *node, int level){ // base cases if (root == NULL) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root->left, node, level + 1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root->right, node, level + 1);} /* Print nodes at a given level such thatsibling of node is not printed if it exists */void printGivenLevel(Node* root, Node *node, int level){ // Base cases if (root == NULL || level < 2) return; // If current node is parent of a node // with given level if (level == 2) { if (root->left == node || root->right == node) return; if (root->left) cout << root->left->data << \" \"; if (root->right) cout << root->right->data; } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root->left, node, level - 1); printGivenLevel(root->right, node, level - 1); }} // This function prints cousins of a given nodevoid printCousins(Node *root, Node *node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver Codeint main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); printCousins(root, root->left->right); return 0;} // This code is contributed// by Akanksha Rai", "e": 2987, "s": 780, "text": null }, { "code": "// C program to print cousins of a node#include <stdio.h>#include <stdlib.h> // A Binary Tree Nodestruct Node{ int data; Node *left, *right;}; // A utility function to create a new Binary// Tree NodeNode *newNode(int item){ Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* It returns level of the node if it is present in tree, otherwise returns 0.*/int getLevel(Node *root, Node *node, int level){ // base cases if (root == NULL) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root->left, node, level+1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root->right, node, level+1);} /* Print nodes at a given level such that sibling of node is not printed if it exists */void printGivenLevel(Node* root, Node *node, int level){ // Base cases if (root == NULL || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root->left == node || root->right == node) return; if (root->left) printf(\"%d \", root->left->data); if (root->right) printf(\"%d \", root->right->data); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root->left, node, level-1); printGivenLevel(root->right, node, level-1); }} // This function prints cousins of a given nodevoid printCousins(Node *root, Node *node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver Program to test above functionsint main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); printCousins(root, root->left->right); return 0;}", "e": 5138, "s": 2987, "text": null }, { "code": "// Java program to print cousins of a nodeclass GfG { // A Binary Tree Nodestatic class Node{ int data; Node left, right;} // A utility function to create a new Binary// Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* It returns level of the node if it is presentin tree, otherwise returns 0.*/static int getLevel(Node root, Node node, int level){ // base cases if (root == null) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root.left, node, level+1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root.right, node, level+1);} /* Print nodes at a given level such that sibling ofnode is not printed if it exists */static void printGivenLevel(Node root, Node node, int level){ // Base cases if (root == null || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root.left == node || root.right == node) return; if (root.left != null) System.out.print(root.left.data + \" \"); if (root.right != null) System.out.print(root.right.data + \" \"); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root.left, node, level-1); printGivenLevel(root.right, node, level-1); }} // This function prints cousins of a given nodestatic void printCousins(Node root, Node node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver Program to test above functionspublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.right = newNode(15); root.right.left = newNode(6); root.right.right = newNode(7); root.right.left.right = newNode(8); printCousins(root, root.left.right);}}", "e": 7301, "s": 5138, "text": null }, { "code": "# Python3 program to print cousins of a node # A utility function to create a new# Binary Tree Nodeclass newNode: def __init__(self, item): self.data = item self.left = self.right = None # It returns level of the node if it is# present in tree, otherwise returns 0.def getLevel(root, node, level): # base cases if (root == None): return 0 if (root == node): return level # If node is present in left subtree downlevel = getLevel(root.left, node, level + 1) if (downlevel != 0): return downlevel # If node is not present in left subtree return getLevel(root.right, node, level + 1) # Print nodes at a given level such that# sibling of node is not printed if# it existsdef printGivenLevel(root, node, level): # Base cases if (root == None or level < 2): return # If current node is parent of a # node with given level if (level == 2): if (root.left == node or root.right == node): return if (root.left): print(root.left.data, end = \" \") if (root.right): print(root.right.data, end = \" \") # Recur for left and right subtrees else if (level > 2): printGivenLevel(root.left, node, level - 1) printGivenLevel(root.right, node, level - 1) # This function prints cousins of a given nodedef printCousins(root, node): # Get level of given node level = getLevel(root, node, 1) # Print nodes of given level. printGivenLevel(root, node, level) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.right.right = newNode(15) root.right.left = newNode(6) root.right.right = newNode(7) root.right.left.right = newNode(8) printCousins(root, root.left.right) # This code is contributed by PranchalK", "e": 9266, "s": 7301, "text": null }, { "code": "// C# program to print cousins of a nodeusing System; public class GfG{ // A Binary Tree Nodeclass Node{ public int data; public Node left, right;} // A utility function to create // a new Binary Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* It returns level of the nodeif it is present in tree, otherwise returns 0.*/static int getLevel(Node root, Node node, int level){ // base cases if (root == null) return 0; if (root == node) return level; // If node is present in left subtree int downlevel = getLevel(root.left, node, level + 1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root.right, node, level + 1);} /* Print nodes at a given levelsuch that sibling of node is not printed if it exists */static void printGivenLevel(Node root, Node node, int level){ // Base cases if (root == null || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root.left == node || root.right == node) return; if (root.left != null) Console.Write(root.left.data + \" \"); if (root.right != null) Console.Write(root.right.data + \" \"); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root.left, node, level - 1); printGivenLevel(root.right, node, level - 1); }} // This function prints cousins of a given nodestatic void printCousins(Node root, Node node){ // Get level of given node int level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver codepublic static void Main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.right = newNode(15); root.right.left = newNode(6); root.right.right = newNode(7); root.right.left.right = newNode(8); printCousins(root, root.left.right);}} // This code is contributed Rajput-Ji", "e": 11506, "s": 9266, "text": null }, { "code": "<script> // JavaScript program to print cousins of a node // A Binary Tree Nodeclass Node{ constructor() { this.data=0; this.left= null; this.right = null; }} // A utility function to create // a new Binary Tree Nodefunction newNode(item){ var temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* It returns level of the nodeif it is present in tree, otherwise returns 0.*/function getLevel(root, node, level){ // base cases if (root == null) return 0; if (root == node) return level; // If node is present in left subtree var downlevel = getLevel(root.left, node, level + 1); if (downlevel != 0) return downlevel; // If node is not present in left subtree return getLevel(root.right, node, level + 1);} /* Print nodes at a given levelsuch that sibling of node is not printed if it exists */function printGivenLevel(root, node, level){ // Base cases if (root == null || level < 2) return; // If current node is parent of a node with // given level if (level == 2) { if (root.left == node || root.right == node) return; if (root.left != null) document.write(root.left.data + \" \"); if (root.right != null) document.write(root.right.data + \" \"); } // Recur for left and right subtrees else if (level > 2) { printGivenLevel(root.left, node, level - 1); printGivenLevel(root.right, node, level - 1); }} // This function prints cousins of a given nodefunction printCousins(root, node){ // Get level of given node var level = getLevel(root, node, 1); // Print nodes of given level. printGivenLevel(root, node, level);} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.left.right.right = newNode(15);root.right.left = newNode(6);root.right.right = newNode(7);root.right.left.right = newNode(8);printCousins(root, root.left.right); </script>", "e": 13571, "s": 11506, "text": null }, { "code": null, "e": 13575, "s": 13571, "text": "6 7" }, { "code": null, "e": 13598, "s": 13575, "text": "Time Complexity : O(n)" }, { "code": null, "e": 13739, "s": 13598, "text": "Can we solve this problem using single traversal? Please refer below article Print cousins of a given node in Binary Tree | Single Traversal" }, { "code": null, "e": 14006, "s": 13739, "text": "This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 14019, "s": 14006, "text": "prerna saini" }, { "code": null, "e": 14035, "s": 14019, "text": "PranchalKatiyar" }, { "code": null, "e": 14048, "s": 14035, "text": "Akanksha_Rai" }, { "code": null, "e": 14058, "s": 14048, "text": "Rajput-Ji" }, { "code": null, "e": 14068, "s": 14058, "text": "rutvik_56" }, { "code": null, "e": 14081, "s": 14068, "text": "simmytarika5" }, { "code": null, "e": 14098, "s": 14081, "text": "surinderdawra388" }, { "code": null, "e": 14115, "s": 14098, "text": "hardikkoriintern" }, { "code": null, "e": 14120, "s": 14115, "text": "Tree" }, { "code": null, "e": 14125, "s": 14120, "text": "Tree" } ]
Logistic Regression in Julia
15 Dec, 2020 Logistic Regression, as the name suggests is completely opposite in functionality. Logistic Regression is basically a predictive algorithm in Machine Learning used for binary classification. It predicts the probability of a class and then classifies it based on the predictor variables’ values. The dependent variable(y) in logistic regression, is binary and takes 2 possible values 0 or 1. For example: If we want to check if the mail is spam or not. Then y will have values – 1 for spam and 0 for not spam. Logistic regression is analogous to linear regression in some aspects, just that in linear regression y is a continuous variable, whereas in logistic regression y needs to lie between 0 and 1. As, y is nothing but the predicted value and predicted value is nothing but the probability of y equals to 1, P(y = 1). We know, the equation for linear regression: Now, we know that this equation yields a continuous value of y. So as to restrict the predicted value of y in the 0 – 1 range, we apply the sigmoid function. The sigmoid function is, Computing the value of y from the above equation and then putting in the linear regression equation, we get: Hence, we finally get the equation for Logistic Regression. Using this equation, we can find the value of the probability of y when the value of x is known. In the above equation, b0 is the intercept and b1 is the slope matrix for all values of x. Collectively, we can refer to all as regression coefficients. To learn more I will take the example of the Churn Modelling Data, a well-known dataset to predict a customer has churned out or not based on a number of features. Let’s start with it in Julia. In this step, we will import all the required packages we will be using. Don’t be afraid if you miss any package, you can definitely add it simultaneously. Julia # Import the packagesimport Pkg; Pkg.add("Lathe")using Lathe import Pkg;Pkg.add("DataFrames")using DataFrames import Pkg; Pkg.add("Plots")using Plots; import Pkg; Pkg.add("GLM")using GLM import Pkg; Pkg.add("StatsBase")using StatsBase import Pkg; Pkg.add("MLBase")using MLBase import Pkg; Pkg.add("ROCAnalysis")using ROCAnalysis import Pkg; Pkg.add("CSV")using CSV println("Successfully imported the packages!!") Output: Successfully imported the packages!! To read the data we use the CSV.file function and then convert it into data frame using DataFrame function. Julia # Load the datadf = DataFrame(CSV.File("churn modelling.csv"))first(df, 5) Output: Julia # Summary of dataframeprintln(size(df))describe(df) Output: The dependent variable, y in this case is the last column (‘Exited’). The first column is just the row numbers and the variable from the second column are predictors or independent variables. Also, the size of our dataset is 10,000 rows and 14 columns. From the summary, we find that the dataset has no missing or null values. The column names don’t have any spaces or special characters in them, hence we can go further without any problem. Julia select!(df, Not([:RowNumber, :CustomerId, :Surname, :Geography, :Gender]))first(df, 5) Output: Julia # Train test splitusing Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(df, .75); We use the glm function for logistic regression. Julia # Train logistic regression modelfm = @formula(Exited ~ CreditScore + Age + Tenure + Balance + NumOfProducts + HasCrCard + IsActiveMember + EstimatedSalary)logit = glm(fm, train, Binomial(), ProbitLink()) Output: Once, we have built our model and trained it, we would evaluate the model on test data to see how accurately it works. Julia # Predict the target variable on test data prediction = predict(logit, test) Output: The glm model gives us the probability score of class 1. After getting the probability score we need to classify it as 0 or 1 based n the threshold score. Usually, the threshold is considered 0.5. With the help of the above code, we got the probability scores. Now, let’s convert these into classes 0 or 1. For probability > 0.5 will be given class 1, otherwise 0. Julia # Converting probability score to classesprediction_class = [if x < 0.5 0 else 1 end for x in prediction]; prediction_df = DataFrame(y_actual = test.Exited, y_predicted = prediction_class, prob_predicted = prediction);prediction_df.correctly_classified = prediction_df.y_actual .== prediction_df.y_predicted Output: After, predicting the classes of our test data, the next step is to evaluate the model by analyzing the accuracy. By Accuracy, we mean the total number of classes our model predicted correctly. Julia # Finding the Accuracy Scoreaccuracy = mean(prediction_df.correctly_classified) Output: 0.7996820349761526 So, our model yields an accuracy of approximately 80% which is a good score. Now, to get better insights of accuracy we analyze the confusion matrix. The confusion matrix is just another way to evaluate the performance of any classification model. Julia # confusion matrix confusion_matrix = MLBase.roc(prediction_df.y_actual, prediction_df.y_predicted) Output: ROCNums{Int64} p = 523 n = 1993 tp = 69 tn = 1943 fp = 50 fn = 454 The above output informs us that due to class imbalance our model classifies maximum observations as class 0. This is the reason for a moderate accuracy of 80%. Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Dec, 2020" }, { "code": null, "e": 323, "s": 28, "text": "Logistic Regression, as the name suggests is completely opposite in functionality. Logistic Regression is basically a predictive algorithm in Machine Learning used for binary classification. It predicts the probability of a class and then classifies it based on the predictor variables’ values." }, { "code": null, "e": 537, "s": 323, "text": "The dependent variable(y) in logistic regression, is binary and takes 2 possible values 0 or 1. For example: If we want to check if the mail is spam or not. Then y will have values – 1 for spam and 0 for not spam." }, { "code": null, "e": 850, "s": 537, "text": "Logistic regression is analogous to linear regression in some aspects, just that in linear regression y is a continuous variable, whereas in logistic regression y needs to lie between 0 and 1. As, y is nothing but the predicted value and predicted value is nothing but the probability of y equals to 1, P(y = 1)." }, { "code": null, "e": 895, "s": 850, "text": "We know, the equation for linear regression:" }, { "code": null, "e": 1078, "s": 895, "text": "Now, we know that this equation yields a continuous value of y. So as to restrict the predicted value of y in the 0 – 1 range, we apply the sigmoid function. The sigmoid function is," }, { "code": null, "e": 1187, "s": 1078, "text": "Computing the value of y from the above equation and then putting in the linear regression equation, we get:" }, { "code": null, "e": 1498, "s": 1187, "text": "Hence, we finally get the equation for Logistic Regression. Using this equation, we can find the value of the probability of y when the value of x is known. In the above equation, b0 is the intercept and b1 is the slope matrix for all values of x. Collectively, we can refer to all as regression coefficients." }, { "code": null, "e": 1692, "s": 1498, "text": "To learn more I will take the example of the Churn Modelling Data, a well-known dataset to predict a customer has churned out or not based on a number of features. Let’s start with it in Julia." }, { "code": null, "e": 1848, "s": 1692, "text": "In this step, we will import all the required packages we will be using. Don’t be afraid if you miss any package, you can definitely add it simultaneously." }, { "code": null, "e": 1854, "s": 1848, "text": "Julia" }, { "code": "# Import the packagesimport Pkg; Pkg.add(\"Lathe\")using Lathe import Pkg;Pkg.add(\"DataFrames\")using DataFrames import Pkg; Pkg.add(\"Plots\")using Plots; import Pkg; Pkg.add(\"GLM\")using GLM import Pkg; Pkg.add(\"StatsBase\")using StatsBase import Pkg; Pkg.add(\"MLBase\")using MLBase import Pkg; Pkg.add(\"ROCAnalysis\")using ROCAnalysis import Pkg; Pkg.add(\"CSV\")using CSV println(\"Successfully imported the packages!!\")", "e": 2275, "s": 1854, "text": null }, { "code": null, "e": 2283, "s": 2275, "text": "Output:" }, { "code": null, "e": 2320, "s": 2283, "text": "Successfully imported the packages!!" }, { "code": null, "e": 2428, "s": 2320, "text": "To read the data we use the CSV.file function and then convert it into data frame using DataFrame function." }, { "code": null, "e": 2434, "s": 2428, "text": "Julia" }, { "code": "# Load the datadf = DataFrame(CSV.File(\"churn modelling.csv\"))first(df, 5)", "e": 2509, "s": 2434, "text": null }, { "code": null, "e": 2517, "s": 2509, "text": "Output:" }, { "code": null, "e": 2523, "s": 2517, "text": "Julia" }, { "code": "# Summary of dataframeprintln(size(df))describe(df)", "e": 2575, "s": 2523, "text": null }, { "code": null, "e": 2583, "s": 2575, "text": "Output:" }, { "code": null, "e": 3025, "s": 2583, "text": "The dependent variable, y in this case is the last column (‘Exited’). The first column is just the row numbers and the variable from the second column are predictors or independent variables. Also, the size of our dataset is 10,000 rows and 14 columns. From the summary, we find that the dataset has no missing or null values. The column names don’t have any spaces or special characters in them, hence we can go further without any problem." }, { "code": null, "e": 3031, "s": 3025, "text": "Julia" }, { "code": "select!(df, Not([:RowNumber, :CustomerId, :Surname, :Geography, :Gender]))first(df, 5)", "e": 3118, "s": 3031, "text": null }, { "code": null, "e": 3126, "s": 3118, "text": "Output:" }, { "code": null, "e": 3132, "s": 3126, "text": "Julia" }, { "code": "# Train test splitusing Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(df, .75);", "e": 3227, "s": 3132, "text": null }, { "code": null, "e": 3276, "s": 3227, "text": "We use the glm function for logistic regression." }, { "code": null, "e": 3282, "s": 3276, "text": "Julia" }, { "code": "# Train logistic regression modelfm = @formula(Exited ~ CreditScore + Age + Tenure + Balance + NumOfProducts + HasCrCard + IsActiveMember + EstimatedSalary)logit = glm(fm, train, Binomial(), ProbitLink())", "e": 3515, "s": 3282, "text": null }, { "code": null, "e": 3523, "s": 3515, "text": "Output:" }, { "code": null, "e": 3642, "s": 3523, "text": "Once, we have built our model and trained it, we would evaluate the model on test data to see how accurately it works." }, { "code": null, "e": 3648, "s": 3642, "text": "Julia" }, { "code": "# Predict the target variable on test data prediction = predict(logit, test)", "e": 3725, "s": 3648, "text": null }, { "code": null, "e": 3733, "s": 3725, "text": "Output:" }, { "code": null, "e": 3930, "s": 3733, "text": "The glm model gives us the probability score of class 1. After getting the probability score we need to classify it as 0 or 1 based n the threshold score. Usually, the threshold is considered 0.5." }, { "code": null, "e": 4098, "s": 3930, "text": "With the help of the above code, we got the probability scores. Now, let’s convert these into classes 0 or 1. For probability > 0.5 will be given class 1, otherwise 0." }, { "code": null, "e": 4104, "s": 4098, "text": "Julia" }, { "code": "# Converting probability score to classesprediction_class = [if x < 0.5 0 else 1 end for x in prediction]; prediction_df = DataFrame(y_actual = test.Exited, y_predicted = prediction_class, prob_predicted = prediction);prediction_df.correctly_classified = prediction_df.y_actual .== prediction_df.y_predicted", "e": 4464, "s": 4104, "text": null }, { "code": null, "e": 4472, "s": 4464, "text": "Output:" }, { "code": null, "e": 4586, "s": 4472, "text": "After, predicting the classes of our test data, the next step is to evaluate the model by analyzing the accuracy." }, { "code": null, "e": 4666, "s": 4586, "text": "By Accuracy, we mean the total number of classes our model predicted correctly." }, { "code": null, "e": 4672, "s": 4666, "text": "Julia" }, { "code": "# Finding the Accuracy Scoreaccuracy = mean(prediction_df.correctly_classified)", "e": 4752, "s": 4672, "text": null }, { "code": null, "e": 4760, "s": 4752, "text": "Output:" }, { "code": null, "e": 4779, "s": 4760, "text": "0.7996820349761526" }, { "code": null, "e": 4929, "s": 4779, "text": "So, our model yields an accuracy of approximately 80% which is a good score. Now, to get better insights of accuracy we analyze the confusion matrix." }, { "code": null, "e": 5027, "s": 4929, "text": "The confusion matrix is just another way to evaluate the performance of any classification model." }, { "code": null, "e": 5033, "s": 5027, "text": "Julia" }, { "code": "# confusion matrix confusion_matrix = MLBase.roc(prediction_df.y_actual, prediction_df.y_predicted)", "e": 5163, "s": 5033, "text": null }, { "code": null, "e": 5171, "s": 5163, "text": "Output:" }, { "code": null, "e": 5250, "s": 5171, "text": "ROCNums{Int64}\n p = 523\n n = 1993\n tp = 69\n tn = 1943\n fp = 50\n fn = 454" }, { "code": null, "e": 5411, "s": 5250, "text": "The above output informs us that due to class imbalance our model classifies maximum observations as class 0. This is the reason for a moderate accuracy of 80%." }, { "code": null, "e": 5418, "s": 5411, "text": "Picked" }, { "code": null, "e": 5424, "s": 5418, "text": "Julia" } ]
Minimum Spanning Tree using Priority Queue and Array List
05 Nov, 2021 Given a bi-directed weighted (positive) graph without self-loops, the task is to generate the minimum spanning tree of the graph.Examples: Input: N = 9, E = 14, edges = {{0, 1, 4}, {0, 7, 8}, {1, 2, 8}, {1, 7, 11}, {2, 3, 7}, {2, 8, 2}, {2, 5, 4}, {3, 4, 9}, {3, 5, 14}, {4, 5, 10}, {5, 6, 2}, {6, 7, 1}, {6, 8, 6}, {7, 8, 7}} Output: ((A, B), Cost) ((6, 7), 1) ((6, 5), 2) ((1, 0), 4) ((2, 3), 7) ((5, 2), 4) ((3, 4), 9) ((2, 1), 8) ((2, 8), 2) An undirected graph consisting of all the vertices V and (V-1) edges has been generatedInput: N = 6, E = 14, edges = {{0, 2, 103}, {0, 1, 158}, {0, 2, 2}, {0, 5, 17}, {1, 3, 42}, {2, 4, 187}, {3, 0, 14}, {3, 2, 158}, {3, 5, 106}, {3, 4, 95}, {5, 1, 144}, {5, 2, 194}, {5, 3, 118}, {5, 3, 58}} Output: ((A, B), Cost) ((0, 2), 2) ((0, 3), 14) ((0, 5), 17) ((3, 1), 42) ((3, 4), 95) Approach First, the edge having minimum cost/weight is found in the given graph. The two initial vertices (vertex A, B of minimum cost edge) is added to visited/added set. Now, all the connected edges with newly added vertex are added to priority queue. The least cost vertex (add all the connected edges of pop vertex to priority queue) is popped from the priority queue and repeat until number of edges is equal to vertices-1. By using priority queue time complexity will be reduced to (O(E log V)) where E is the number of edges and V is the number of vertices. Pair class is also used to store the weights. Below is the implementation of the above approach: Java // Java implementation of the approachimport java.io.*;import java.util.*;import java.lang.Comparable;public class MST { // Pair class with implemented comparable static class Pair<U extends Comparable<U>, V extends Comparable<V> > implements Comparable<Pair<U, V> > { public final U a; public final V b; private Pair(U a, V b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>)o; if (!a.equals(pair.a)) return false; return b.equals(pair.b); } // Overriding so that objects in map // could find the object key @Override public int hashCode() { return 31 * a.hashCode() + b.hashCode(); } @Override public String toString() { return "(" + a + ", " + b + ")"; } @Override public int compareTo(Pair<U, V> o) { return getV().compareTo(o.getV()); } private U getU() { return a; } private V getV() { return b; } } static class Graph { int vertices; ArrayList[] edges; // This variable keeps the least cost edge static Pair<Pair<Integer, Integer>, Integer> minCostEdge; Graph(int vertices) { minCostEdge = new Pair<>(new Pair<>(1, 1), Integer.MAX_VALUE); this.vertices = vertices; edges = new ArrayList[vertices + 1]; for (int i = 0; i <= vertices; i++) { edges[i] = new ArrayList<Pair<Integer, Integer> >(); } } void addEdge(int a, int b, int weight) { edges[a].add(new Pair<>(b, weight)); // Since its undirected, adding the // edges to both the vertices edges[b].add(new Pair<>(a, weight)); if (weight < minCostEdge.b) { minCostEdge = new Pair<>(new Pair<>(a, b), weight); } } void MST() { // Priority queue for applying heap PriorityQueue<Pair<Pair<Integer, Integer>, Integer> > priorityQueue = new PriorityQueue<>(); // Adding all the connected vertices // of MinCostEdge vertex A to PQ Iterator<Pair<Integer, Integer> > iterator = edges[minCostEdge.a.a].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair = iterator.next(); priorityQueue.add( new Pair<>( new Pair<>(minCostEdge.a.a, pair.a), pair.b)); } // Adding all the connected vertices // of MinCostEdge vertex B to PQ iterator = edges[minCostEdge.a.b].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair = iterator.next(); priorityQueue.add( new Pair<>( new Pair<>(minCostEdge.a.b, pair.a), pair.b)); } // Set to check vertex is added or not Set<Integer> addedVertices = new HashSet<>(); // Set contains all the added edges and cost from source Set<Pair<Pair<Integer, Integer>, Integer> > addedEdges = new HashSet<>(); // Using the greedy approach to find // the least costing edge to the GRAPH while (addedEdges.size() < vertices - 1) { // Polling from priority queue Pair<Pair<Integer, Integer>, Integer> pair = priorityQueue.poll(); // Checking whether the vertex A is added or not if (!addedVertices.contains(pair.a.a)) { addedVertices.add(pair.a.a); addedEdges.add(pair); // Adding all the connected vertices with vertex A iterator = edges[pair.a.a].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair1 = iterator.next(); priorityQueue.add( new Pair<>( new Pair<>(pair.a.a, pair1.a), pair1.b)); } } // Checking whether the vertex B is added or not if (!addedVertices.contains(pair.a.b)) { addedVertices.add(pair.a.b); addedEdges.add(pair); // Adding all the connected vertices with vertex B iterator = edges[pair.a.b].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair1 = iterator.next(); priorityQueue .add( new Pair<>( new Pair<>(pair.a.b, pair1.a), pair1.b)); } } } // Printing the MST Iterator<Pair<Pair<Integer, Integer>, Integer> > iterator1 = addedEdges.iterator(); System.out.println("((A" + ", " + "B)" + ", " + "Cost)"); while (iterator1.hasNext()) { System.out.println(iterator1.next()); } } } // Driver code public static void main(String[] args) throws IOException { // Initializing the graph Graph g = new Graph(9); g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // Applying MST g.MST(); }} ((A, B), Cost) ((6, 7), 1) ((6, 5), 2) ((1, 0), 4) ((2, 3), 7) ((5, 2), 4) ((3, 4), 9) ((2, 1), 8) ((2, 8), 2) simranarora5sos anikakapoor abhishek0719kadiyan MST Data Structures Graph Java Data Structures Java Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Nov, 2021" }, { "code": null, "e": 193, "s": 52, "text": "Given a bi-directed weighted (positive) graph without self-loops, the task is to generate the minimum spanning tree of the graph.Examples: " }, { "code": null, "e": 502, "s": 193, "text": "Input: N = 9, E = 14, edges = {{0, 1, 4}, {0, 7, 8}, {1, 2, 8}, {1, 7, 11}, {2, 3, 7}, {2, 8, 2}, {2, 5, 4}, {3, 4, 9}, {3, 5, 14}, {4, 5, 10}, {5, 6, 2}, {6, 7, 1}, {6, 8, 6}, {7, 8, 7}} Output: ((A, B), Cost) ((6, 7), 1) ((6, 5), 2) ((1, 0), 4) ((2, 3), 7) ((5, 2), 4) ((3, 4), 9) ((2, 1), 8) ((2, 8), 2) " }, { "code": null, "e": 884, "s": 502, "text": "An undirected graph consisting of all the vertices V and (V-1) edges has been generatedInput: N = 6, E = 14, edges = {{0, 2, 103}, {0, 1, 158}, {0, 2, 2}, {0, 5, 17}, {1, 3, 42}, {2, 4, 187}, {3, 0, 14}, {3, 2, 158}, {3, 5, 106}, {3, 4, 95}, {5, 1, 144}, {5, 2, 194}, {5, 3, 118}, {5, 3, 58}} Output: ((A, B), Cost) ((0, 2), 2) ((0, 3), 14) ((0, 5), 17) ((3, 1), 42) ((3, 4), 95) " }, { "code": null, "e": 897, "s": 886, "text": "Approach " }, { "code": null, "e": 969, "s": 897, "text": "First, the edge having minimum cost/weight is found in the given graph." }, { "code": null, "e": 1060, "s": 969, "text": "The two initial vertices (vertex A, B of minimum cost edge) is added to visited/added set." }, { "code": null, "e": 1142, "s": 1060, "text": "Now, all the connected edges with newly added vertex are added to priority queue." }, { "code": null, "e": 1317, "s": 1142, "text": "The least cost vertex (add all the connected edges of pop vertex to priority queue) is popped from the priority queue and repeat until number of edges is equal to vertices-1." }, { "code": null, "e": 1453, "s": 1317, "text": "By using priority queue time complexity will be reduced to (O(E log V)) where E is the number of edges and V is the number of vertices." }, { "code": null, "e": 1499, "s": 1453, "text": "Pair class is also used to store the weights." }, { "code": null, "e": 1551, "s": 1499, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1556, "s": 1551, "text": "Java" }, { "code": "// Java implementation of the approachimport java.io.*;import java.util.*;import java.lang.Comparable;public class MST { // Pair class with implemented comparable static class Pair<U extends Comparable<U>, V extends Comparable<V> > implements Comparable<Pair<U, V> > { public final U a; public final V b; private Pair(U a, V b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>)o; if (!a.equals(pair.a)) return false; return b.equals(pair.b); } // Overriding so that objects in map // could find the object key @Override public int hashCode() { return 31 * a.hashCode() + b.hashCode(); } @Override public String toString() { return \"(\" + a + \", \" + b + \")\"; } @Override public int compareTo(Pair<U, V> o) { return getV().compareTo(o.getV()); } private U getU() { return a; } private V getV() { return b; } } static class Graph { int vertices; ArrayList[] edges; // This variable keeps the least cost edge static Pair<Pair<Integer, Integer>, Integer> minCostEdge; Graph(int vertices) { minCostEdge = new Pair<>(new Pair<>(1, 1), Integer.MAX_VALUE); this.vertices = vertices; edges = new ArrayList[vertices + 1]; for (int i = 0; i <= vertices; i++) { edges[i] = new ArrayList<Pair<Integer, Integer> >(); } } void addEdge(int a, int b, int weight) { edges[a].add(new Pair<>(b, weight)); // Since its undirected, adding the // edges to both the vertices edges[b].add(new Pair<>(a, weight)); if (weight < minCostEdge.b) { minCostEdge = new Pair<>(new Pair<>(a, b), weight); } } void MST() { // Priority queue for applying heap PriorityQueue<Pair<Pair<Integer, Integer>, Integer> > priorityQueue = new PriorityQueue<>(); // Adding all the connected vertices // of MinCostEdge vertex A to PQ Iterator<Pair<Integer, Integer> > iterator = edges[minCostEdge.a.a].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair = iterator.next(); priorityQueue.add( new Pair<>( new Pair<>(minCostEdge.a.a, pair.a), pair.b)); } // Adding all the connected vertices // of MinCostEdge vertex B to PQ iterator = edges[minCostEdge.a.b].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair = iterator.next(); priorityQueue.add( new Pair<>( new Pair<>(minCostEdge.a.b, pair.a), pair.b)); } // Set to check vertex is added or not Set<Integer> addedVertices = new HashSet<>(); // Set contains all the added edges and cost from source Set<Pair<Pair<Integer, Integer>, Integer> > addedEdges = new HashSet<>(); // Using the greedy approach to find // the least costing edge to the GRAPH while (addedEdges.size() < vertices - 1) { // Polling from priority queue Pair<Pair<Integer, Integer>, Integer> pair = priorityQueue.poll(); // Checking whether the vertex A is added or not if (!addedVertices.contains(pair.a.a)) { addedVertices.add(pair.a.a); addedEdges.add(pair); // Adding all the connected vertices with vertex A iterator = edges[pair.a.a].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair1 = iterator.next(); priorityQueue.add( new Pair<>( new Pair<>(pair.a.a, pair1.a), pair1.b)); } } // Checking whether the vertex B is added or not if (!addedVertices.contains(pair.a.b)) { addedVertices.add(pair.a.b); addedEdges.add(pair); // Adding all the connected vertices with vertex B iterator = edges[pair.a.b].listIterator(); while (iterator.hasNext()) { Pair<Integer, Integer> pair1 = iterator.next(); priorityQueue .add( new Pair<>( new Pair<>(pair.a.b, pair1.a), pair1.b)); } } } // Printing the MST Iterator<Pair<Pair<Integer, Integer>, Integer> > iterator1 = addedEdges.iterator(); System.out.println(\"((A\" + \", \" + \"B)\" + \", \" + \"Cost)\"); while (iterator1.hasNext()) { System.out.println(iterator1.next()); } } } // Driver code public static void main(String[] args) throws IOException { // Initializing the graph Graph g = new Graph(9); g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // Applying MST g.MST(); }}", "e": 8182, "s": 1556, "text": null }, { "code": null, "e": 8293, "s": 8182, "text": "((A, B), Cost)\n((6, 7), 1)\n((6, 5), 2)\n((1, 0), 4)\n((2, 3), 7)\n((5, 2), 4)\n((3, 4), 9)\n((2, 1), 8)\n((2, 8), 2)" }, { "code": null, "e": 8311, "s": 8295, "text": "simranarora5sos" }, { "code": null, "e": 8323, "s": 8311, "text": "anikakapoor" }, { "code": null, "e": 8343, "s": 8323, "text": "abhishek0719kadiyan" }, { "code": null, "e": 8347, "s": 8343, "text": "MST" }, { "code": null, "e": 8363, "s": 8347, "text": "Data Structures" }, { "code": null, "e": 8369, "s": 8363, "text": "Graph" }, { "code": null, "e": 8374, "s": 8369, "text": "Java" }, { "code": null, "e": 8390, "s": 8374, "text": "Data Structures" }, { "code": null, "e": 8395, "s": 8390, "text": "Java" }, { "code": null, "e": 8401, "s": 8395, "text": "Graph" } ]
JRE in Java
26 Oct, 2021 Java Runtime Environment (JRE) is an open-access software distribution that has a Java class library, specific tools, and a separate JVM. JRE is one of the interrelated components in the Java Development Kit (JDK). It is the most common environment available on devices for running Java programs. Java source code is compiled and converted to Java bytecode. If you want to run this bytecode on any platform, you need JRE. The JRE loads classes check memory access and get system resources. JRE acts as a software layer on top of the operating system. Integration libraries include Java Database Connectivity (JDBC) Java Naming, Interface Definition Language (IDL) Directory Interface (JNDI) Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) Remote Method Invocation (RMI) Scripting Java Virtual Machine (JVM) consists of Java HotSpot Client and Server Virtual Machine. User interface libraries include Swing, Java 2D, Abstract Window Toolkit (AWT), Accessibility, Image I/O, Print Service, Sound, drag, and drop (DnD), and input methods. Lang and util base libraries, which include lang and util, zip, Collections, Concurrency Utilities, management, Java Archive (JAR), instrument, reflection, versioning, Preferences API, Ref Objects, Logging, and Regular Expressions. Other base libraries, including Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, international support, input/output (I/O), Beans, Java Override Mechanism, Security, Serialization, extension mechanism, and Java for XML Processing (XML JAXP). Deployment technologies such as Java Web Start, deployment, and Java plug-in. Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with each other to create a sustainable runtime environment that enables Java-based applications to run seamlessly on any operating system. The JRE runtime architecture consists of the following elements as listed: ClassLoaderByteCode verifierInterpreter ClassLoader ByteCode verifier Interpreter Now let us brief about them as follows: ClassLoader: Java ClassLoader dynamically loads all the classes necessary to run a Java program. Because classes are only loaded into memory whenever they are needed, the JRE uses ClassLoader will automate this process when needed. Bytecode Verifier: The bytecode checker ensures the format and precision of Java code before passing it to the interpreter. If the code violates system integrity or access rights, the class is considered corrupt and will not load. Interpreter: After loading the byte code successfully, the Java interpreter creates an object of the Java virtual machine that allows the Java program to run natively on the underlying machine. JRE has an object of JVM with it, development tools, and library classes. To understand the working of Java Runtime Environment let us see an example of a simple java program that prints “GeeksForGeeks”. Example: Java // Java classclass GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println("GeeksForGeeks"); }} GeeksForGeeks Once you write your java program, you must save it with a file name with a “.java” extension. Then after you Compile your program. The output of the Java compiler is byte code which is a platform-independent code. After compiling, the compiler generates a .class file that contains the byte code. Bytecode is platform-independent that runs on all devices which contain Java Runtime Environment (JRE). java-basics Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Oct, 2021" }, { "code": null, "e": 605, "s": 54, "text": "Java Runtime Environment (JRE) is an open-access software distribution that has a Java class library, specific tools, and a separate JVM. JRE is one of the interrelated components in the Java Development Kit (JDK). It is the most common environment available on devices for running Java programs. Java source code is compiled and converted to Java bytecode. If you want to run this bytecode on any platform, you need JRE. The JRE loads classes check memory access and get system resources. JRE acts as a software layer on top of the operating system." }, { "code": null, "e": 669, "s": 605, "text": "Integration libraries include Java Database Connectivity (JDBC)" }, { "code": null, "e": 718, "s": 669, "text": "Java Naming, Interface Definition Language (IDL)" }, { "code": null, "e": 745, "s": 718, "text": "Directory Interface (JNDI)" }, { "code": null, "e": 814, "s": 745, "text": "Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP)" }, { "code": null, "e": 845, "s": 814, "text": "Remote Method Invocation (RMI)" }, { "code": null, "e": 855, "s": 845, "text": "Scripting" }, { "code": null, "e": 942, "s": 855, "text": "Java Virtual Machine (JVM) consists of Java HotSpot Client and Server Virtual Machine." }, { "code": null, "e": 1111, "s": 942, "text": "User interface libraries include Swing, Java 2D, Abstract Window Toolkit (AWT), Accessibility, Image I/O, Print Service, Sound, drag, and drop (DnD), and input methods." }, { "code": null, "e": 1346, "s": 1111, "text": "Lang and util base libraries, which include lang and util, zip, Collections, Concurrency Utilities, management, Java Archive (JAR), instrument, reflection, versioning, Preferences API, Ref Objects, Logging, and Regular Expressions." }, { "code": null, "e": 1620, "s": 1346, "text": "Other base libraries, including Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, international support, input/output (I/O), Beans, Java Override Mechanism, Security, Serialization, extension mechanism, and Java for XML Processing (XML JAXP)." }, { "code": null, "e": 1698, "s": 1620, "text": "Deployment technologies such as Java Web Start, deployment, and Java plug-in." }, { "code": null, "e": 1991, "s": 1698, "text": "Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with each other to create a sustainable runtime environment that enables Java-based applications to run seamlessly on any operating system. The JRE runtime architecture consists of the following elements as listed:" }, { "code": null, "e": 2031, "s": 1991, "text": "ClassLoaderByteCode verifierInterpreter" }, { "code": null, "e": 2043, "s": 2031, "text": "ClassLoader" }, { "code": null, "e": 2061, "s": 2043, "text": "ByteCode verifier" }, { "code": null, "e": 2073, "s": 2061, "text": "Interpreter" }, { "code": null, "e": 2113, "s": 2073, "text": "Now let us brief about them as follows:" }, { "code": null, "e": 2347, "s": 2113, "text": "ClassLoader: Java ClassLoader dynamically loads all the classes necessary to run a Java program. Because classes are only loaded into memory whenever they are needed, the JRE uses ClassLoader will automate this process when needed. " }, { "code": null, "e": 2580, "s": 2347, "text": "Bytecode Verifier: The bytecode checker ensures the format and precision of Java code before passing it to the interpreter. If the code violates system integrity or access rights, the class is considered corrupt and will not load. " }, { "code": null, "e": 2774, "s": 2580, "text": "Interpreter: After loading the byte code successfully, the Java interpreter creates an object of the Java virtual machine that allows the Java program to run natively on the underlying machine." }, { "code": null, "e": 2980, "s": 2774, "text": "JRE has an object of JVM with it, development tools, and library classes. To understand the working of Java Runtime Environment let us see an example of a simple java program that prints “GeeksForGeeks”. " }, { "code": null, "e": 2989, "s": 2980, "text": "Example:" }, { "code": null, "e": 2994, "s": 2989, "text": "Java" }, { "code": "// Java classclass GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println(\"GeeksForGeeks\"); }}", "e": 3178, "s": 2994, "text": null }, { "code": null, "e": 3192, "s": 3178, "text": "GeeksForGeeks" }, { "code": null, "e": 3593, "s": 3192, "text": "Once you write your java program, you must save it with a file name with a “.java” extension. Then after you Compile your program. The output of the Java compiler is byte code which is a platform-independent code. After compiling, the compiler generates a .class file that contains the byte code. Bytecode is platform-independent that runs on all devices which contain Java Runtime Environment (JRE)." }, { "code": null, "e": 3605, "s": 3593, "text": "java-basics" }, { "code": null, "e": 3612, "s": 3605, "text": "Picked" }, { "code": null, "e": 3617, "s": 3612, "text": "Java" }, { "code": null, "e": 3622, "s": 3617, "text": "Java" } ]
vnstat command in Linux with Examples
29 Nov, 2021 vnstat is a command-line tool in Linux that is generally used by system administrators in order to monitor network parameters such as bandwidth consumption or maybe some traffic flowing in or out. It monitors the traffic on the network interfaces of the system. In case of RedHat based Linux yum install vnstat In case of a ubuntu or debian Linux apt install vnstat 1. To get basic stats of all network interfaces vnstat This command will print all the basic stats of the network interfaces connected to the system. 2. To monitor a specific interface vnstat -i wlo1 This will monitor and display the stats of the specified interface that is wlo1. 3. To get the daily stats of an interface vnstat -d -i wlo1 This will print the daily stats of the specified interface which is wlo1. 4. To get the hourly stats of an interface vnstat -h -i wlo1 This will print the hourly stats of the specified interface which is wlo1. 5. To display the monthly stats of a interface vnstat -m -i wlo1 This command will display the monthly stats of the specified interface. 6. To save output to a XML file vnstat --xml -i wlo1 >output.xml The command will create an XML file with name output.xml and will have the output of the command in XML format. 7. To save output to a JSON file vnstat --json -i wlo1 >output.json This command will create a JSON file with name output.json and will have the output of the command in JSON format. 8. To save output to a text file vnstat --oneline -i wlo1 >output.txt This command will create a text file with name output.txt and will have the output in a one-line format. 9. To calculate traffic on the current interface vnstat -tr This command will display the traffic on the current network interface in use. 10. To display vnstat help vnstat --help This command will display the vnstat help section. surinderdawra388 linux-command Linux-networking-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples Introduction to Linux Operating System SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples Array Basics in Shell Scripting | Set 1 chmod command in Linux with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2021" }, { "code": null, "e": 292, "s": 28, "text": "vnstat is a command-line tool in Linux that is generally used by system administrators in order to monitor network parameters such as bandwidth consumption or maybe some traffic flowing in or out. It monitors the traffic on the network interfaces of the system. " }, { "code": null, "e": 324, "s": 292, "text": "In case of RedHat based Linux " }, { "code": null, "e": 343, "s": 324, "text": "yum install vnstat" }, { "code": null, "e": 380, "s": 343, "text": "In case of a ubuntu or debian Linux " }, { "code": null, "e": 400, "s": 380, "text": "apt install vnstat " }, { "code": null, "e": 449, "s": 400, "text": "1. To get basic stats of all network interfaces " }, { "code": null, "e": 456, "s": 449, "text": "vnstat" }, { "code": null, "e": 552, "s": 456, "text": "This command will print all the basic stats of the network interfaces connected to the system. " }, { "code": null, "e": 588, "s": 552, "text": "2. To monitor a specific interface " }, { "code": null, "e": 603, "s": 588, "text": "vnstat -i wlo1" }, { "code": null, "e": 685, "s": 603, "text": "This will monitor and display the stats of the specified interface that is wlo1. " }, { "code": null, "e": 728, "s": 685, "text": "3. To get the daily stats of an interface " }, { "code": null, "e": 746, "s": 728, "text": "vnstat -d -i wlo1" }, { "code": null, "e": 821, "s": 746, "text": "This will print the daily stats of the specified interface which is wlo1. " }, { "code": null, "e": 865, "s": 821, "text": "4. To get the hourly stats of an interface " }, { "code": null, "e": 883, "s": 865, "text": "vnstat -h -i wlo1" }, { "code": null, "e": 959, "s": 883, "text": "This will print the hourly stats of the specified interface which is wlo1. " }, { "code": null, "e": 1007, "s": 959, "text": "5. To display the monthly stats of a interface " }, { "code": null, "e": 1025, "s": 1007, "text": "vnstat -m -i wlo1" }, { "code": null, "e": 1098, "s": 1025, "text": "This command will display the monthly stats of the specified interface. " }, { "code": null, "e": 1131, "s": 1098, "text": "6. To save output to a XML file " }, { "code": null, "e": 1164, "s": 1131, "text": "vnstat --xml -i wlo1 >output.xml" }, { "code": null, "e": 1277, "s": 1164, "text": "The command will create an XML file with name output.xml and will have the output of the command in XML format. " }, { "code": null, "e": 1311, "s": 1277, "text": "7. To save output to a JSON file " }, { "code": null, "e": 1346, "s": 1311, "text": "vnstat --json -i wlo1 >output.json" }, { "code": null, "e": 1462, "s": 1346, "text": "This command will create a JSON file with name output.json and will have the output of the command in JSON format. " }, { "code": null, "e": 1496, "s": 1462, "text": "8. To save output to a text file " }, { "code": null, "e": 1533, "s": 1496, "text": "vnstat --oneline -i wlo1 >output.txt" }, { "code": null, "e": 1639, "s": 1533, "text": "This command will create a text file with name output.txt and will have the output in a one-line format. " }, { "code": null, "e": 1689, "s": 1639, "text": "9. To calculate traffic on the current interface " }, { "code": null, "e": 1700, "s": 1689, "text": "vnstat -tr" }, { "code": null, "e": 1780, "s": 1700, "text": "This command will display the traffic on the current network interface in use. " }, { "code": null, "e": 1808, "s": 1780, "text": "10. To display vnstat help " }, { "code": null, "e": 1822, "s": 1808, "text": "vnstat --help" }, { "code": null, "e": 1873, "s": 1822, "text": "This command will display the vnstat help section." }, { "code": null, "e": 1890, "s": 1873, "text": "surinderdawra388" }, { "code": null, "e": 1904, "s": 1890, "text": "linux-command" }, { "code": null, "e": 1930, "s": 1904, "text": "Linux-networking-commands" }, { "code": null, "e": 1941, "s": 1930, "text": "Linux-Unix" }, { "code": null, "e": 2039, "s": 1941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2065, "s": 2039, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2100, "s": 2065, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2137, "s": 2100, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2176, "s": 2137, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2205, "s": 2176, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2242, "s": 2205, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2276, "s": 2242, "text": "mv command in Linux with examples" }, { "code": null, "e": 2316, "s": 2276, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2353, "s": 2316, "text": "chmod command in Linux with examples" } ]
Different ways to print elements of vector
03 Aug, 2021 Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. The elements of vectors are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time. By using overloading << Operator: By overloading the << operator as template function at global scope, all the elements of the vector can be printed by iterating one by one. Below is the C++ program to implement the above concept: C++ // C++ program to print the elements// of the vector#include <iostream>#include <vector>using namespace std; template <typename S>ostream& operator<<(ostream& os, const vector<S>& vector){ // Printing all the elements // using << for (auto element : vector) { os << element << " "; } return os;} // Driver Codeint main(){ // vector containing integer elements vector<int> A = { 10, 20, 30, 40, 50, 60 }; cout << A << endl; return 0;} 10 20 30 40 50 60 Printing in a comma-separated manner: By avoiding overloading of the << operator and by creating a separate function, a custom separator can be provided to print the contents of the vector Below is the C++ program to implement the above approach: C++ // C++ program to print the elements// of the vector using separators#include <iostream>#include <vector>using namespace std; template <typename S> // with_separator() function accepts// two arguments i.e., a vector and// a separator stringvoid with_separator(const vector<S>& vec, string sep = " "){ // Iterating over all elements of vector for (auto elem : vec) { cout << elem << sep; } cout << endl;} // Driver Codeint main(){ // Vector containing integer items vector<int> int_vec{ 10, 20, 30, 40, 50, 60 }; // Printing all elements in vector with_separator(int_vec, ", "); // Vector containing string vector<string> str_vec{ "One", "Two", "Three", "Four", "Five" }; // Printing all elements in vector with_separator(str_vec, ", "); return 0;} 10, 20, 30, 40, 50, 60, One, Two, Three, Four, Five, By using indexing: By using the index of the elements in the vector, all the elements can be printed. Below is the C++ program to implement the above concept: C++ // C++ program to print the elements// of the vector by using the index#include <iostream>#include <vector>using namespace std; template <typename S>void using_index(const vector<S>& vector, string sep = " "){ // Iterating vector by using index for (int i = 0; i < vector.size(); i++) { // Printing the element at // index 'i' of vector cout << vector[i] << sep; } cout << endl;} // Driver Codeint main(){ // Vector containing all integers // elements vector<int> int_vec{ 10, 20, 30, 40, 50, 60 }; // calling using_index() method using_index(int_vec); return 0;} 10 20 30 40 50 60 Printing all elements without for loop by providing element type: All the elements of a vector can be printed using an STL algorithm copy(). All the elements of a vector can be copied to the output stream by providing elements type while calling the copy() algorithm. Below is the C++ program to implement the above approach: C++ // C++ program to print the elements// of the vector by using iterators#include <iostream>#include <iterator>#include <vector>using namespace std; // Driver Codeint main(){ // Vector containing all integer // elements vector<int> vec_of_nums{ 10, 20, 30, 40, 50, 60 }; // Printing all elements in vector // Element type provided int while // calling copy() copy(vec_of_nums.begin(), vec_of_nums.end(), ostream_iterator<int>(cout, " ")); return 0;} 10 20 30 40 50 60 Using (experimental::make_ostream_joiner) without providing element type: In the Method-1 program, it is observed that while calling the copy() algorithm, the type of elements is specifically provided in the vector. But using C++ 17 experimental::make_ostream_joiner, it is possible to print all elements of a vector without specifying the type of elements in the vector while calling copy(). Below is the C++ program to implement the above approach: C++ // C++ program to print the elements// of the vector#include <experimental/iterator>#include <iostream>#include <vector>using namespace std; // Driver Codeint main(){ // Vector containing integers vector<int> int_vec = { 10, 20, 30, 40, 50, 60 }; // Printing all elements in vector // Element type not provided while // calling copy() copy(int_vec.begin(), int_vec.end(), experimental::make_ostream_joiner(cout, " ")); cout << endl; return 0;} 10 20 30 40 50 60 By using the Lambda function: The lambda function can be used on each element of the vector and inside the function, the element can be printed without providing the type of the element. Below is the C++ program to implement the above approach: C++ // C++ program to print the elements// of the vectors#include <algorithm>#include <iostream>#include <vector> // Driver Codeint main(){ // Vector containing all // integer items vector<int> int_vec{ 10, 20, 30, 40, 50, 60 }; // Printing all elements in // vector for_each(int_vec.begin(), int_vec.end(), [](const auto& elem) { // printing one by one element // separated with space cout << elem << " "; }); return 0;} 10 20 30 40 50 60 sweetyty kapoorsagar226 arorakashish0911 cpp-containers-library cpp-vector C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 640, "s": 28, "text": "Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. The elements of vectors are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time." }, { "code": null, "e": 814, "s": 640, "text": "By using overloading << Operator: By overloading the << operator as template function at global scope, all the elements of the vector can be printed by iterating one by one." }, { "code": null, "e": 871, "s": 814, "text": "Below is the C++ program to implement the above concept:" }, { "code": null, "e": 875, "s": 871, "text": "C++" }, { "code": "// C++ program to print the elements// of the vector#include <iostream>#include <vector>using namespace std; template <typename S>ostream& operator<<(ostream& os, const vector<S>& vector){ // Printing all the elements // using << for (auto element : vector) { os << element << \" \"; } return os;} // Driver Codeint main(){ // vector containing integer elements vector<int> A = { 10, 20, 30, 40, 50, 60 }; cout << A << endl; return 0;}", "e": 1385, "s": 875, "text": null }, { "code": null, "e": 1404, "s": 1385, "text": "10 20 30 40 50 60 " }, { "code": null, "e": 1593, "s": 1404, "text": "Printing in a comma-separated manner: By avoiding overloading of the << operator and by creating a separate function, a custom separator can be provided to print the contents of the vector" }, { "code": null, "e": 1652, "s": 1593, "text": "Below is the C++ program to implement the above approach: " }, { "code": null, "e": 1656, "s": 1652, "text": "C++" }, { "code": "// C++ program to print the elements// of the vector using separators#include <iostream>#include <vector>using namespace std; template <typename S> // with_separator() function accepts// two arguments i.e., a vector and// a separator stringvoid with_separator(const vector<S>& vec, string sep = \" \"){ // Iterating over all elements of vector for (auto elem : vec) { cout << elem << sep; } cout << endl;} // Driver Codeint main(){ // Vector containing integer items vector<int> int_vec{ 10, 20, 30, 40, 50, 60 }; // Printing all elements in vector with_separator(int_vec, \", \"); // Vector containing string vector<string> str_vec{ \"One\", \"Two\", \"Three\", \"Four\", \"Five\" }; // Printing all elements in vector with_separator(str_vec, \", \"); return 0;}", "e": 2552, "s": 1656, "text": null }, { "code": null, "e": 2606, "s": 2552, "text": "10, 20, 30, 40, 50, 60,\nOne, Two, Three, Four, Five, " }, { "code": null, "e": 2708, "s": 2606, "text": "By using indexing: By using the index of the elements in the vector, all the elements can be printed." }, { "code": null, "e": 2765, "s": 2708, "text": "Below is the C++ program to implement the above concept:" }, { "code": null, "e": 2769, "s": 2765, "text": "C++" }, { "code": "// C++ program to print the elements// of the vector by using the index#include <iostream>#include <vector>using namespace std; template <typename S>void using_index(const vector<S>& vector, string sep = \" \"){ // Iterating vector by using index for (int i = 0; i < vector.size(); i++) { // Printing the element at // index 'i' of vector cout << vector[i] << sep; } cout << endl;} // Driver Codeint main(){ // Vector containing all integers // elements vector<int> int_vec{ 10, 20, 30, 40, 50, 60 }; // calling using_index() method using_index(int_vec); return 0;}", "e": 3426, "s": 2769, "text": null }, { "code": null, "e": 3445, "s": 3426, "text": "10 20 30 40 50 60 " }, { "code": null, "e": 3714, "s": 3445, "text": "Printing all elements without for loop by providing element type: All the elements of a vector can be printed using an STL algorithm copy(). All the elements of a vector can be copied to the output stream by providing elements type while calling the copy() algorithm." }, { "code": null, "e": 3772, "s": 3714, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 3776, "s": 3772, "text": "C++" }, { "code": "// C++ program to print the elements// of the vector by using iterators#include <iostream>#include <iterator>#include <vector>using namespace std; // Driver Codeint main(){ // Vector containing all integer // elements vector<int> vec_of_nums{ 10, 20, 30, 40, 50, 60 }; // Printing all elements in vector // Element type provided int while // calling copy() copy(vec_of_nums.begin(), vec_of_nums.end(), ostream_iterator<int>(cout, \" \")); return 0;}", "e": 4294, "s": 3776, "text": null }, { "code": null, "e": 4313, "s": 4294, "text": "10 20 30 40 50 60 " }, { "code": null, "e": 4706, "s": 4313, "text": "Using (experimental::make_ostream_joiner) without providing element type: In the Method-1 program, it is observed that while calling the copy() algorithm, the type of elements is specifically provided in the vector. But using C++ 17 experimental::make_ostream_joiner, it is possible to print all elements of a vector without specifying the type of elements in the vector while calling copy()." }, { "code": null, "e": 4764, "s": 4706, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 4768, "s": 4764, "text": "C++" }, { "code": "// C++ program to print the elements// of the vector#include <experimental/iterator>#include <iostream>#include <vector>using namespace std; // Driver Codeint main(){ // Vector containing integers vector<int> int_vec = { 10, 20, 30, 40, 50, 60 }; // Printing all elements in vector // Element type not provided while // calling copy() copy(int_vec.begin(), int_vec.end(), experimental::make_ostream_joiner(cout, \" \")); cout << endl; return 0;}", "e": 5281, "s": 4768, "text": null }, { "code": null, "e": 5300, "s": 5281, "text": "10 20 30 40 50 60 " }, { "code": null, "e": 5487, "s": 5300, "text": "By using the Lambda function: The lambda function can be used on each element of the vector and inside the function, the element can be printed without providing the type of the element." }, { "code": null, "e": 5545, "s": 5487, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 5549, "s": 5545, "text": "C++" }, { "code": "// C++ program to print the elements// of the vectors#include <algorithm>#include <iostream>#include <vector> // Driver Codeint main(){ // Vector containing all // integer items vector<int> int_vec{ 10, 20, 30, 40, 50, 60 }; // Printing all elements in // vector for_each(int_vec.begin(), int_vec.end(), [](const auto& elem) { // printing one by one element // separated with space cout << elem << \" \"; }); return 0;}", "e": 6099, "s": 5549, "text": null }, { "code": null, "e": 6118, "s": 6099, "text": "10 20 30 40 50 60 " }, { "code": null, "e": 6127, "s": 6118, "text": "sweetyty" }, { "code": null, "e": 6142, "s": 6127, "text": "kapoorsagar226" }, { "code": null, "e": 6159, "s": 6142, "text": "arorakashish0911" }, { "code": null, "e": 6182, "s": 6159, "text": "cpp-containers-library" }, { "code": null, "e": 6193, "s": 6182, "text": "cpp-vector" }, { "code": null, "e": 6197, "s": 6193, "text": "C++" }, { "code": null, "e": 6210, "s": 6197, "text": "C++ Programs" }, { "code": null, "e": 6214, "s": 6210, "text": "CPP" } ]
How to calculate the number of days between two dates in javascript?
20 Jul, 2021 Calculating the number of days between two dates in JavaScript required to use date object for any kind of calculation. For that, first, get the internal millisecond value of the date using the in-built JavaScript getTime() function. As soon as both the dates get converted, proceed further by subtracting the later one from the earlier one which in turn returns the difference in milliseconds. Later, the final result can be calculated by dividing the difference (which is in milliseconds) of both the dates by the number of milliseconds in one day. Syntax: Date.getTime() Approach 1: Define two dates using new Date(). Calculate the time difference of two dates using date2.getTime() – date1.getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24) Print the final result using document.write(). Example 1: The following JavaScript program will illustrate the solution javascript <script type = "text/javascript" > // JavaScript program to illustrate // calculation of no. of days between two date // To set two dates to two variables var date1 = new Date("06/30/2019");var date2 = new Date("07/30/2019"); // To calculate the time difference of two datesvar Difference_In_Time = date2.getTime() - date1.getTime(); // To calculate the no. of days between two datesvar Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24); //To display the final no. of days (result)document.write("Total number of days between dates <br>" + date1 + "<br> and <br>" + date2 + " is: <br> " + Difference_In_Days); </script> Output: Total number of days between dates Sun Jun 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time) and Tue Jul 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time) is: 30 Approach 2: Defined the present date by using the new date() which will give the present date and the Christmas date by date.getFullYear() (this will get the year, 0-11 are the months in JavaScript). if condition in order to calculate the total number of days if the Christmas has been passed already (this will calculate the no. of days between the present date and the Christmas of the next year). Use Math.round(christmas() – present_date.getTime()) Divided one day’s milliseconds to Calculate the result in milliseconds and then converting into days Example 2: This example we calculated the number of days until Christmas day. javascript <script type = "text/javascript" > // One day Time in ms (milliseconds) var one_day = 1000 * 60 * 60 * 24 // To set present_dates to two variablesvar present_date = new Date(); // 0-11 is Month in JavaScriptvar christmas_day = new Date(present_date.getFullYear(), 11, 25) // To Calculate next year's Christmas if passed already.if (present_date.getMonth() == 11 && present_date.getdate() > 25) christmas_day.setFullYear(christmas_day.getFullYear() + 1) // To Calculate the result in milliseconds and then converting into daysvar Result = Math.round(christmas_day.getTime() - present_date.getTime()) / (one_day); // To remove the decimals from the (Result) resulting days valuevar Final_Result = Result.toFixed(0); //To display the final_result valuedocument.write("Number of days remaining till christmas <br>" + present_date + "<br> and <br>" + christmas_day + " is: <br> " + Final_Result); </script> Output: Number of days remaining till christmas Sun Jun 30 2019 11:33:51 GMT-0700 (Pacific Daylight Time) and Wed Dec 25 2019 00:00:00 GMT-0800 (Pacific Standard Time) is: 178 JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. arorakashish0911 JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jul, 2021" }, { "code": null, "e": 615, "s": 54, "text": "Calculating the number of days between two dates in JavaScript required to use date object for any kind of calculation. For that, first, get the internal millisecond value of the date using the in-built JavaScript getTime() function. As soon as both the dates get converted, proceed further by subtracting the later one from the earlier one which in turn returns the difference in milliseconds. Later, the final result can be calculated by dividing the difference (which is in milliseconds) of both the dates by the number of milliseconds in one day. Syntax: " }, { "code": null, "e": 630, "s": 615, "text": "Date.getTime()" }, { "code": null, "e": 644, "s": 630, "text": "Approach 1: " }, { "code": null, "e": 679, "s": 644, "text": "Define two dates using new Date()." }, { "code": null, "e": 763, "s": 679, "text": "Calculate the time difference of two dates using date2.getTime() – date1.getTime();" }, { "code": null, "e": 901, "s": 763, "text": "Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)" }, { "code": null, "e": 948, "s": 901, "text": "Print the final result using document.write()." }, { "code": null, "e": 1023, "s": 948, "text": "Example 1: The following JavaScript program will illustrate the solution " }, { "code": null, "e": 1034, "s": 1023, "text": "javascript" }, { "code": "<script type = \"text/javascript\" > // JavaScript program to illustrate // calculation of no. of days between two date // To set two dates to two variables var date1 = new Date(\"06/30/2019\");var date2 = new Date(\"07/30/2019\"); // To calculate the time difference of two datesvar Difference_In_Time = date2.getTime() - date1.getTime(); // To calculate the no. of days between two datesvar Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24); //To display the final no. of days (result)document.write(\"Total number of days between dates <br>\" + date1 + \"<br> and <br>\" + date2 + \" is: <br> \" + Difference_In_Days); </script>", "e": 1730, "s": 1034, "text": null }, { "code": null, "e": 1740, "s": 1730, "text": "Output: " }, { "code": null, "e": 1905, "s": 1740, "text": "Total number of days between dates \nSun Jun 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time)\nand \nTue Jul 30 2019 00:00:00 GMT-0700 (Pacific Daylight Time) is: \n30" }, { "code": null, "e": 1919, "s": 1905, "text": "Approach 2: " }, { "code": null, "e": 2107, "s": 1919, "text": "Defined the present date by using the new date() which will give the present date and the Christmas date by date.getFullYear() (this will get the year, 0-11 are the months in JavaScript)." }, { "code": null, "e": 2307, "s": 2107, "text": "if condition in order to calculate the total number of days if the Christmas has been passed already (this will calculate the no. of days between the present date and the Christmas of the next year)." }, { "code": null, "e": 2461, "s": 2307, "text": "Use Math.round(christmas() – present_date.getTime()) Divided one day’s milliseconds to Calculate the result in milliseconds and then converting into days" }, { "code": null, "e": 2541, "s": 2461, "text": "Example 2: This example we calculated the number of days until Christmas day. " }, { "code": null, "e": 2552, "s": 2541, "text": "javascript" }, { "code": "<script type = \"text/javascript\" > // One day Time in ms (milliseconds) var one_day = 1000 * 60 * 60 * 24 // To set present_dates to two variablesvar present_date = new Date(); // 0-11 is Month in JavaScriptvar christmas_day = new Date(present_date.getFullYear(), 11, 25) // To Calculate next year's Christmas if passed already.if (present_date.getMonth() == 11 && present_date.getdate() > 25) christmas_day.setFullYear(christmas_day.getFullYear() + 1) // To Calculate the result in milliseconds and then converting into daysvar Result = Math.round(christmas_day.getTime() - present_date.getTime()) / (one_day); // To remove the decimals from the (Result) resulting days valuevar Final_Result = Result.toFixed(0); //To display the final_result valuedocument.write(\"Number of days remaining till christmas <br>\" + present_date + \"<br> and <br>\" + christmas_day + \" is: <br> \" + Final_Result); </script>", "e": 3517, "s": 2552, "text": null }, { "code": null, "e": 3527, "s": 3517, "text": "Output: " }, { "code": null, "e": 3698, "s": 3527, "text": "Number of days remaining till christmas \nSun Jun 30 2019 11:33:51 GMT-0700 (Pacific Daylight Time)\nand \nWed Dec 25 2019 00:00:00 GMT-0800 (Pacific Standard Time) is: \n178" }, { "code": null, "e": 3919, "s": 3700, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 3936, "s": 3919, "text": "arorakashish0911" }, { "code": null, "e": 3952, "s": 3936, "text": "JavaScript-Misc" }, { "code": null, "e": 3959, "s": 3952, "text": "Picked" }, { "code": null, "e": 3970, "s": 3959, "text": "JavaScript" }, { "code": null, "e": 3987, "s": 3970, "text": "Web Technologies" } ]
const_cast in C++ | Type Casting operators
23 Aug, 2018 C++ supports following 4 types of casting operators: 1. const_cast2. static_cast3. dynamic_cast4. reinterpret_cast 1. const_castconst_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class members inside a const member function. Consider the following code snippet. Inside const member function fun(), ‘this’ is treated by the compiler as ‘const student* const this’, i.e. ‘this’ is a constant pointer to a constant object, thus compiler doesn’t allow to change the data members through ‘this’ pointer. const_cast changes the type of ‘this’ pointer to ‘student* const this’. #include <iostream>using namespace std; class student{private: int roll;public: // constructor student(int r):roll(r) {} // A const function that changes roll with the help of const_cast void fun() const { ( const_cast <student*> (this) )->roll = 5; } int getRoll() { return roll; }}; int main(void){ student s(3); cout << "Old roll number: " << s.getRoll() << endl; s.fun(); cout << "New roll number: " << s.getRoll() << endl; return 0;} Output: Old roll number: 3 New roll number: 5 2) const_cast can be used to pass const data to a function that doesn’t receive const. For example, in the following program fun() receives a normal pointer, but a pointer to a const can be passed with the help of const_cast. #include <iostream>using namespace std; int fun(int* ptr){ return (*ptr + 10);} int main(void){ const int val = 10; const int *ptr = &val; int *ptr1 = const_cast <int *>(ptr); cout << fun(ptr1); return 0;} Output: 20 3) It is undefined behavior to modify a value which is initially declared as const. Consider the following program. The output of the program is undefined. The variable ‘val’ is a const variable and the call ‘fun(ptr1)’ tries to modify ‘val’ using const_cast. #include <iostream>using namespace std; int fun(int* ptr){ *ptr = *ptr + 10; return (*ptr);} int main(void){ const int val = 10; const int *ptr = &val; int *ptr1 = const_cast <int *>(ptr); fun(ptr1); cout << val; return 0;} Output: Undefined Behavior It it fine to modify a value which is not initially declared as const. For example, in the above program, if we remove const from declaration of val, the program will produce 20 as output. #include <iostream>using namespace std; int fun(int* ptr){ *ptr = *ptr + 10; return (*ptr);} int main(void){ int val = 10; const int *ptr = &val; int *ptr1 = const_cast <int *>(ptr); fun(ptr1); cout << val; return 0;} 4) const_cast is considered safer than simple type casting. It’safer in the sense that the casting won’t happen if the type of cast is not same as original object. For example, the following program fails in compilation because ‘int *’ is being typecasted to ‘char *’ #include <iostream>using namespace std; int main(void){ int a1 = 40; const int* b1 = &a1; char* c1 = const_cast <char *> (b1); // compiler error *c1 = 'A'; return 0;} output: prog.cpp: In function ‘int main()’: prog.cpp:8: error: invalid const_cast from type 'const int*' to type 'char*' 5) const_cast can also be used to cast away volatile attribute. For example, in the following program, the typeid of b1 is PVKi (pointer to a volatile and constant integer) and typeid of c1 is Pi (Pointer to integer) #include <iostream>#include <typeinfo>using namespace std; int main(void){ int a1 = 40; const volatile int* b1 = &a1; cout << "typeid of b1 " << typeid(b1).name() << '\n'; int* c1 = const_cast <int *> (b1); cout << "typeid of c1 " << typeid(c1).name() << '\n'; return 0;} Output: typeid of b1 PVKi typeid of c1 Pi ExercisePredict the output of following programs. If there are compilation errors, then fix them. Question 1 #include <iostream>using namespace std; int main(void){ int a1 = 40; const int* b1 = &a1; char* c1 = (char *)(b1); *c1 = 'A'; return 0;} Question 2 #include <iostream>using namespace std; class student{private: const int roll;public: // constructor student(int r):roll(r) {} // A const function that changes roll with the help of const_cast void fun() const { ( const_cast <student*> (this) )->roll = 5; } int getRoll() { return roll; }}; int main(void){ student s(3); cout << "Old roll number: " << s.getRoll() << endl; s.fun(); cout << "New roll number: " << s.getRoll() << endl; return 0;} —Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ Left Shift and Right Shift Operators in C/C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2018" }, { "code": null, "e": 105, "s": 52, "text": "C++ supports following 4 types of casting operators:" }, { "code": null, "e": 167, "s": 105, "text": "1. const_cast2. static_cast3. dynamic_cast4. reinterpret_cast" }, { "code": null, "e": 295, "s": 167, "text": "1. const_castconst_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast." }, { "code": null, "e": 733, "s": 295, "text": "1) const_cast can be used to change non-const class members inside a const member function. Consider the following code snippet. Inside const member function fun(), ‘this’ is treated by the compiler as ‘const student* const this’, i.e. ‘this’ is a constant pointer to a constant object, thus compiler doesn’t allow to change the data members through ‘this’ pointer. const_cast changes the type of ‘this’ pointer to ‘student* const this’." }, { "code": "#include <iostream>using namespace std; class student{private: int roll;public: // constructor student(int r):roll(r) {} // A const function that changes roll with the help of const_cast void fun() const { ( const_cast <student*> (this) )->roll = 5; } int getRoll() { return roll; }}; int main(void){ student s(3); cout << \"Old roll number: \" << s.getRoll() << endl; s.fun(); cout << \"New roll number: \" << s.getRoll() << endl; return 0;}", "e": 1231, "s": 733, "text": null }, { "code": null, "e": 1239, "s": 1231, "text": "Output:" }, { "code": null, "e": 1277, "s": 1239, "text": "Old roll number: 3\nNew roll number: 5" }, { "code": null, "e": 1503, "s": 1277, "text": "2) const_cast can be used to pass const data to a function that doesn’t receive const. For example, in the following program fun() receives a normal pointer, but a pointer to a const can be passed with the help of const_cast." }, { "code": "#include <iostream>using namespace std; int fun(int* ptr){ return (*ptr + 10);} int main(void){ const int val = 10; const int *ptr = &val; int *ptr1 = const_cast <int *>(ptr); cout << fun(ptr1); return 0;}", "e": 1729, "s": 1503, "text": null }, { "code": null, "e": 1737, "s": 1729, "text": "Output:" }, { "code": null, "e": 1740, "s": 1737, "text": "20" }, { "code": null, "e": 2000, "s": 1740, "text": "3) It is undefined behavior to modify a value which is initially declared as const. Consider the following program. The output of the program is undefined. The variable ‘val’ is a const variable and the call ‘fun(ptr1)’ tries to modify ‘val’ using const_cast." }, { "code": "#include <iostream>using namespace std; int fun(int* ptr){ *ptr = *ptr + 10; return (*ptr);} int main(void){ const int val = 10; const int *ptr = &val; int *ptr1 = const_cast <int *>(ptr); fun(ptr1); cout << val; return 0;}", "e": 2250, "s": 2000, "text": null }, { "code": null, "e": 2258, "s": 2250, "text": "Output:" }, { "code": null, "e": 2279, "s": 2258, "text": " Undefined Behavior " }, { "code": null, "e": 2468, "s": 2279, "text": "It it fine to modify a value which is not initially declared as const. For example, in the above program, if we remove const from declaration of val, the program will produce 20 as output." }, { "code": "#include <iostream>using namespace std; int fun(int* ptr){ *ptr = *ptr + 10; return (*ptr);} int main(void){ int val = 10; const int *ptr = &val; int *ptr1 = const_cast <int *>(ptr); fun(ptr1); cout << val; return 0;}", "e": 2712, "s": 2468, "text": null }, { "code": null, "e": 2980, "s": 2712, "text": "4) const_cast is considered safer than simple type casting. It’safer in the sense that the casting won’t happen if the type of cast is not same as original object. For example, the following program fails in compilation because ‘int *’ is being typecasted to ‘char *’" }, { "code": "#include <iostream>using namespace std; int main(void){ int a1 = 40; const int* b1 = &a1; char* c1 = const_cast <char *> (b1); // compiler error *c1 = 'A'; return 0;}", "e": 3163, "s": 2980, "text": null }, { "code": null, "e": 3171, "s": 3163, "text": "output:" }, { "code": null, "e": 3284, "s": 3171, "text": "prog.cpp: In function ‘int main()’:\nprog.cpp:8: error: invalid const_cast from type 'const int*' to type 'char*'" }, { "code": null, "e": 3501, "s": 3284, "text": "5) const_cast can also be used to cast away volatile attribute. For example, in the following program, the typeid of b1 is PVKi (pointer to a volatile and constant integer) and typeid of c1 is Pi (Pointer to integer)" }, { "code": "#include <iostream>#include <typeinfo>using namespace std; int main(void){ int a1 = 40; const volatile int* b1 = &a1; cout << \"typeid of b1 \" << typeid(b1).name() << '\\n'; int* c1 = const_cast <int *> (b1); cout << \"typeid of c1 \" << typeid(c1).name() << '\\n'; return 0;}", "e": 3792, "s": 3501, "text": null }, { "code": null, "e": 3800, "s": 3792, "text": "Output:" }, { "code": null, "e": 3835, "s": 3800, "text": "typeid of b1 PVKi\ntypeid of c1 Pi\n" }, { "code": null, "e": 3933, "s": 3835, "text": "ExercisePredict the output of following programs. If there are compilation errors, then fix them." }, { "code": null, "e": 3944, "s": 3933, "text": "Question 1" }, { "code": "#include <iostream>using namespace std; int main(void){ int a1 = 40; const int* b1 = &a1; char* c1 = (char *)(b1); *c1 = 'A'; return 0;}", "e": 4097, "s": 3944, "text": null }, { "code": null, "e": 4108, "s": 4097, "text": "Question 2" }, { "code": "#include <iostream>using namespace std; class student{private: const int roll;public: // constructor student(int r):roll(r) {} // A const function that changes roll with the help of const_cast void fun() const { ( const_cast <student*> (this) )->roll = 5; } int getRoll() { return roll; }}; int main(void){ student s(3); cout << \"Old roll number: \" << s.getRoll() << endl; s.fun(); cout << \"New roll number: \" << s.getRoll() << endl; return 0;}", "e": 4612, "s": 4108, "text": null }, { "code": null, "e": 4754, "s": 4612, "text": "—Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 4765, "s": 4754, "text": "C Language" }, { "code": null, "e": 4769, "s": 4765, "text": "C++" }, { "code": null, "e": 4773, "s": 4769, "text": "CPP" }, { "code": null, "e": 4871, "s": 4773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4888, "s": 4871, "text": "Substring in C++" }, { "code": null, "e": 4910, "s": 4888, "text": "Function Pointer in C" }, { "code": null, "e": 4955, "s": 4910, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5001, "s": 4955, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 5026, "s": 5001, "text": "std::string class in C++" }, { "code": null, "e": 5044, "s": 5026, "text": "Vector in C++ STL" }, { "code": null, "e": 5087, "s": 5044, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 5133, "s": 5087, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 5176, "s": 5133, "text": "Set in C++ Standard Template Library (STL)" } ]
Jython – Introduction and Installation
10 May, 2020 It’s not hidden that Java is a powerful and Python is a simple and easy language. To get them both together, Jython was introduced so it is both powerful and simple. It is a pure Java implementation of Python. It uses Python’s syntax and Java’s environment. It allows using features of Python in Java environment or to import Java classes in Python codes and hence, is very flexible. Jython can run on almost any platform which provides flexibility in application deployment and it also provides many libraries with many more APIs. It is really beneficial for those who create applications in Java and are new to Python. Python has three implementations: Cpython(mostly used) Jython IronPython Download your copy from www.jython.org It will be combined as a cross-platform executable JAR file If you don’t have Java installed in your system you will need to grab a copy of it. you can download it from www.java.com and install it. Double click on the JAR file and install it with “All” features installed Find the jython.bat(windows) or jython.sh(Mac OS) file in the same folder where you installed Jython Place this folder within your PATH environment variable After all this has done you will be able to open up the command prompt, type jython and then hit the “enter” key To install Jython in Linux type the below command in the terminal. sudo apt install jython After typing this command provide your sudo password and that’s it. Linux will handle the rest. After installation, check whether Jython is installed correctly or not. See the below image for checking. Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 May, 2020" }, { "code": null, "e": 585, "s": 53, "text": "It’s not hidden that Java is a powerful and Python is a simple and easy language. To get them both together, Jython was introduced so it is both powerful and simple. It is a pure Java implementation of Python. It uses Python’s syntax and Java’s environment. It allows using features of Python in Java environment or to import Java classes in Python codes and hence, is very flexible. Jython can run on almost any platform which provides flexibility in application deployment and it also provides many libraries with many more APIs." }, { "code": null, "e": 708, "s": 585, "text": "It is really beneficial for those who create applications in Java and are new to Python. Python has three implementations:" }, { "code": null, "e": 729, "s": 708, "text": "Cpython(mostly used)" }, { "code": null, "e": 736, "s": 729, "text": "Jython" }, { "code": null, "e": 747, "s": 736, "text": "IronPython" }, { "code": null, "e": 786, "s": 747, "text": "Download your copy from www.jython.org" }, { "code": null, "e": 846, "s": 786, "text": "It will be combined as a cross-platform executable JAR file" }, { "code": null, "e": 984, "s": 846, "text": "If you don’t have Java installed in your system you will need to grab a copy of it. you can download it from www.java.com and install it." }, { "code": null, "e": 1058, "s": 984, "text": "Double click on the JAR file and install it with “All” features installed" }, { "code": null, "e": 1159, "s": 1058, "text": "Find the jython.bat(windows) or jython.sh(Mac OS) file in the same folder where you installed Jython" }, { "code": null, "e": 1215, "s": 1159, "text": "Place this folder within your PATH environment variable" }, { "code": null, "e": 1328, "s": 1215, "text": "After all this has done you will be able to open up the command prompt, type jython and then hit the “enter” key" }, { "code": null, "e": 1395, "s": 1328, "text": "To install Jython in Linux type the below command in the terminal." }, { "code": null, "e": 1419, "s": 1395, "text": "sudo apt install jython" }, { "code": null, "e": 1621, "s": 1419, "text": "After typing this command provide your sudo password and that’s it. Linux will handle the rest. After installation, check whether Jython is installed correctly or not. See the below image for checking." }, { "code": null, "e": 1642, "s": 1621, "text": "Python-Miscellaneous" }, { "code": null, "e": 1649, "s": 1642, "text": "Python" } ]
Python – API.get_user() in Tweepy
08 Jun, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The get_user() method of the API class in Tweepy module is used to get the information of the specified user. Syntax : API.get_user(id / user_id / screen_name) Parameter : Only use one of the 3 options:id : specifies the ID or the screen name of the useruser_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen namescreen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID Returns : an object of the class User Example 1 : # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # using get_user with id_id = "103770785"user = api.get_user(_id) # printing the name of the userprint("The id " + _id + " corresponds to the user with the name : " + user.name) Output : The id 103770785 corresponds to the user with the name : Twitter India Example 2 : Sometimes the user_id and the screen_name of 2 different users might be the same, so we need to explicitly mention either the user_id or the screen_name. # using get_user with user_iduser_id = "57741058"user = api.get_user(user_id) # printing the name of the userprint("The user id " + user_id + " corresponds to the user with the name : " + user.name) # using get_user with screen_namescreen_name = "geeksforgeeks"user = api.get_user(screen_name) # printing the name of the userprint("\nThe screen name " + screen_name + " corresponds to the user with the name : " + user.name) Output : The user id 57741058 corresponds to the user with the name : GeeksforGeeks The screen name geeksforgeeks corresponds to the user with the name : GeeksforGeeks Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2020" }, { "code": null, "e": 453, "s": 53, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 563, "s": 453, "text": "The get_user() method of the API class in Tweepy module is used to get the information of the specified user." }, { "code": null, "e": 613, "s": 563, "text": "Syntax : API.get_user(id / user_id / screen_name)" }, { "code": null, "e": 957, "s": 613, "text": "Parameter : Only use one of the 3 options:id : specifies the ID or the screen name of the useruser_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen namescreen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID" }, { "code": null, "e": 995, "s": 957, "text": "Returns : an object of the class User" }, { "code": null, "e": 1007, "s": 995, "text": "Example 1 :" }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # using get_user with id_id = \"103770785\"user = api.get_user(_id) # printing the name of the userprint(\"The id \" + _id + \" corresponds to the user with the name : \" + user.name)", "e": 1603, "s": 1007, "text": null }, { "code": null, "e": 1612, "s": 1603, "text": "Output :" }, { "code": null, "e": 1684, "s": 1612, "text": "The id 103770785 corresponds to the user with the name : Twitter India\n" }, { "code": null, "e": 1850, "s": 1684, "text": "Example 2 : Sometimes the user_id and the screen_name of 2 different users might be the same, so we need to explicitly mention either the user_id or the screen_name." }, { "code": "# using get_user with user_iduser_id = \"57741058\"user = api.get_user(user_id) # printing the name of the userprint(\"The user id \" + user_id + \" corresponds to the user with the name : \" + user.name) # using get_user with screen_namescreen_name = \"geeksforgeeks\"user = api.get_user(screen_name) # printing the name of the userprint(\"\\nThe screen name \" + screen_name + \" corresponds to the user with the name : \" + user.name)", "e": 2298, "s": 1850, "text": null }, { "code": null, "e": 2307, "s": 2298, "text": "Output :" }, { "code": null, "e": 2468, "s": 2307, "text": "The user id 57741058 corresponds to the user with the name : GeeksforGeeks\n\nThe screen name geeksforgeeks corresponds to the user with the name : GeeksforGeeks\n" }, { "code": null, "e": 2482, "s": 2468, "text": "Python-Tweepy" }, { "code": null, "e": 2489, "s": 2482, "text": "Python" } ]
Sort given Array using at most N cyclic shift on any subarray - GeeksforGeeks
21 Dec, 2021 Given an array arr[] containing N integers, with duplicates. The task is to sort the array in increasing order using at most N cyclic shift on any sub-array. Cyclic shift on any sub-array means cut out any subarray from the given array, use cyclic shift (rotate) in it by any offset, and put it back into the same place of the array. Print the number of such shifting required to sort the array. There can be multiple possibilities. Examples: Input: arr[] = [1, 3, 2, 8, 5]Output: 2Explanation: Consider segment from index = 1 to index = 2. [1, 3, 2, 8, 5]. Now rotate this segment by 1 offset. The new array becomes, [1, 2, 3, 8, 5]. Then consider segment from index = 3 to index = 4, [1, 2, 3, 8, 5]. Rotate it by 1 offset, the new array becomes, [1, 2, 3, 5, 8]. Input: arr[] = [2, 4, 1, 3]Output: 2Explanation: From index = 0 to index = 2, [2, 4, 1, 3]. Rotate this segment by 2 offset on left, the new array becomes, [1, 2, 4, 3]. Taking second segment from index = 2 to index = 3 of offset 1, rotate it the new array becomes, [1, 2, 4, 3]. Approach: There can be two cases: Case when the array is already sorted: Then we do not need to perform any shifting operationCase when the array is not sorted: For that follow the steps mentioned below:Create a variable count = 0 to store the total number of counts.Iterate from i = 0 to i = N-2. And for each iteration do the following operations:Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.Mark that position right to perform cyclic shift from i to right by offset 1.If no such right value exists then simply move to the next iteration.Otherwise, rotate the array from i to right by 1 position and increment count by 1.Return the value of count as your answer. Case when the array is already sorted: Then we do not need to perform any shifting operation Case when the array is not sorted: For that follow the steps mentioned below:Create a variable count = 0 to store the total number of counts.Iterate from i = 0 to i = N-2. And for each iteration do the following operations:Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.Mark that position right to perform cyclic shift from i to right by offset 1.If no such right value exists then simply move to the next iteration.Otherwise, rotate the array from i to right by 1 position and increment count by 1.Return the value of count as your answer. Create a variable count = 0 to store the total number of counts. Iterate from i = 0 to i = N-2. And for each iteration do the following operations:Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.Mark that position right to perform cyclic shift from i to right by offset 1. Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i]. Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal. Mark that position right to perform cyclic shift from i to right by offset 1. If no such right value exists then simply move to the next iteration. Otherwise, rotate the array from i to right by 1 position and increment count by 1. Return the value of count as your answer. Below is the C++ implementation for the above approach: C++ Java Python3 C# Javascript // C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to Sort given Array using// at most N cyclic shift on any subarrayint ShiftingSort(vector<int>& arr, int n){ vector<int> temp(arr.begin(), arr.end()); sort(temp.begin(), temp.end()); // Variable to store count of // shifting operations int count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr == temp) { return 0; } else { // Run a loop from 0 to n-2 index for (int index1 = 0; index1 < n - 1; index1++) { int minval = arr[index1]; int left = index1; int right = -1; // Loop from i+1 to n-1 // to find the minimum value for (int index2 = index1 + 1; index2 < n; index2++) { if (minval > arr[index2]) { minval = arr[index2]; right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; int index = right; int tempval = arr[right]; // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr[index] = arr[index - 1]; index--; } arr[index] = tempval; } } } // Return the total operations return count;} // Driver codeint main(){ vector<int> arr{ 1, 3, 2, 8, 5 }; int N = 5; cout << ShiftingSort(arr, N) << "\n"; return 0;} // Java code to implement the above approachimport java.util.*; public class GFG{ // Function to Sort given Array using// at most N cyclic shift on any subarraystatic int ShiftingSort(ArrayList<Integer> arr, int n){ ArrayList<Integer> temp = new ArrayList<Integer>(); for(int i = 0; i < arr.size(); i++) { temp.add(arr.get(i)); } Collections.sort(temp); // Variable to store count of // shifting operations int count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr.equals(temp)) { return 0; } else { // Run a loop from 0 to n-2 index for (int index1 = 0; index1 < n - 1; index1++) { int minval = arr.get(index1); int left = index1; int right = -1; // Loop from i+1 to n-1 // to find the minimum value for (int index2 = index1 + 1; index2 < n; index2++) { if (minval > arr.get(index2)) { minval = arr.get(index2); right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; int index = right; int tempval = arr.get(right); // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr.set(index, arr.get(index - 1)); index--; } arr.set(index, tempval); } } } // Return the total operations return count;} // Driver codepublic static void main(String args[]){ ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(3); arr.add(2); arr.add(8); arr.add(5); int N = 5; System.out.println(ShiftingSort(arr, N));}} // This code is contributed by Samim Hossain Mondal. # Python Program to implement# the above approach # Function to Sort given Array using# at most N cyclic shift on any subarraydef ShiftingSort(arr, n): temp = arr.copy() temp.sort() # Variable to store count of # shifting operations count = 0 # If the vector arr is already sorted # the 0 operations shift required if (arr == temp): return 0 else: # Run a loop from 0 to n-2 index for index1 in range(n - 1): minval = arr[index1] left = index1 right = -1 # Loop from i+1 to n-1 # to find the minimum value for index2 in range(index1 + 1, n): if (minval > arr[index2]): minval = arr[index2] right = index2 # Check if the shifting is required if (right != -1): # Increment count operations count += 1 index = right tempval = arr[right] # Loop for shifting the array arr # from index = left to index = right while (index > left): arr[index] = arr[index - 1] index -= 1 arr[index] = tempval # Return the total operations return count # Driver codearr = [1, 3, 2, 8, 5]N = 5print(ShiftingSort(arr, N)) # This code is contributed by gfgking // C# code to implement the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to Sort given Array using// at most N cyclic shift on any subarraystatic int ShiftingSort(ArrayList arr, int n){ ArrayList temp = new ArrayList(); for(int i = 0; i < arr.Count; i++) { temp.Add(arr[i]); } temp.Sort(); // Variable to store count of // shifting operations int count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr.Equals(temp)) { return 0; } else { // Run a loop from 0 to n-2 index for (int index1 = 0; index1 < n - 1; index1++) { int minval = (int)arr[index1]; int left = index1; int right = -1; // Loop from i+1 to n-1 // to find the minimum value for (int index2 = index1 + 1; index2 < n; index2++) { if (minval > (int)arr[index2]) { minval = (int)arr[index2]; right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; int index = right; int tempval = (int)arr[right]; // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr[index] = arr[index - 1]; index--; } arr[index] = tempval; } } } // Return the total operations return count;} // Driver codepublic static void Main(){ ArrayList arr = new ArrayList(); arr.Add(1); arr.Add(3); arr.Add(2); arr.Add(8); arr.Add(5); int N = 5; Console.Write(ShiftingSort(arr, N));}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript Program to implement // the above approach // Function to Sort given Array using // at most N cyclic shift on any subarray function ShiftingSort(arr, n) { let temp = [...arr]; temp.sort(function (a, b) { return a - b }) // Variable to store count of // shifting operations let count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr == temp) { return 0; } else { // Run a loop from 0 to n-2 index for (let index1 = 0; index1 < n - 1; index1++) { let minval = arr[index1]; let left = index1; let right = -1; // Loop from i+1 to n-1 // to find the minimum value for (let index2 = index1 + 1; index2 < n; index2++) { if (minval > arr[index2]) { minval = arr[index2]; right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; let index = right; let tempval = arr[right]; // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr[index] = arr[index - 1]; index--; } arr[index] = tempval; } } } // Return the total operations return count; } // Driver code let arr = [1, 3, 2, 8, 5]; let N = 5; document.write(ShiftingSort(arr, N) + '<br>'); // This code is contributed by Potta Lokesh </script> 2 Time Complexity: O(N2)Space Complexity: O(1) lokeshpotta20 gfgking samim2000 simranarora5sos rotation subarray Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element
[ { "code": null, "e": 26041, "s": 26013, "text": "\n21 Dec, 2021" }, { "code": null, "e": 26200, "s": 26041, "text": "Given an array arr[] containing N integers, with duplicates. The task is to sort the array in increasing order using at most N cyclic shift on any sub-array. " }, { "code": null, "e": 26377, "s": 26200, "text": "Cyclic shift on any sub-array means cut out any subarray from the given array, use cyclic shift (rotate) in it by any offset, and put it back into the same place of the array. " }, { "code": null, "e": 26476, "s": 26377, "text": "Print the number of such shifting required to sort the array. There can be multiple possibilities." }, { "code": null, "e": 26486, "s": 26476, "text": "Examples:" }, { "code": null, "e": 26809, "s": 26486, "text": "Input: arr[] = [1, 3, 2, 8, 5]Output: 2Explanation: Consider segment from index = 1 to index = 2. [1, 3, 2, 8, 5]. Now rotate this segment by 1 offset. The new array becomes, [1, 2, 3, 8, 5]. Then consider segment from index = 3 to index = 4, [1, 2, 3, 8, 5]. Rotate it by 1 offset, the new array becomes, [1, 2, 3, 5, 8]." }, { "code": null, "e": 27089, "s": 26809, "text": "Input: arr[] = [2, 4, 1, 3]Output: 2Explanation: From index = 0 to index = 2, [2, 4, 1, 3]. Rotate this segment by 2 offset on left, the new array becomes, [1, 2, 4, 3]. Taking second segment from index = 2 to index = 3 of offset 1, rotate it the new array becomes, [1, 2, 4, 3]." }, { "code": null, "e": 27123, "s": 27089, "text": "Approach: There can be two cases:" }, { "code": null, "e": 27915, "s": 27123, "text": "Case when the array is already sorted: Then we do not need to perform any shifting operationCase when the array is not sorted: For that follow the steps mentioned below:Create a variable count = 0 to store the total number of counts.Iterate from i = 0 to i = N-2. And for each iteration do the following operations:Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.Mark that position right to perform cyclic shift from i to right by offset 1.If no such right value exists then simply move to the next iteration.Otherwise, rotate the array from i to right by 1 position and increment count by 1.Return the value of count as your answer." }, { "code": null, "e": 28008, "s": 27915, "text": "Case when the array is already sorted: Then we do not need to perform any shifting operation" }, { "code": null, "e": 28708, "s": 28008, "text": "Case when the array is not sorted: For that follow the steps mentioned below:Create a variable count = 0 to store the total number of counts.Iterate from i = 0 to i = N-2. And for each iteration do the following operations:Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.Mark that position right to perform cyclic shift from i to right by offset 1.If no such right value exists then simply move to the next iteration.Otherwise, rotate the array from i to right by 1 position and increment count by 1.Return the value of count as your answer." }, { "code": null, "e": 28773, "s": 28708, "text": "Create a variable count = 0 to store the total number of counts." }, { "code": null, "e": 29139, "s": 28773, "text": "Iterate from i = 0 to i = N-2. And for each iteration do the following operations:Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i].Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal.Mark that position right to perform cyclic shift from i to right by offset 1." }, { "code": null, "e": 29257, "s": 29139, "text": "Create a variable minVal to store the minimum value found in this iteration and initiate it with the value of arr[i]." }, { "code": null, "e": 29347, "s": 29257, "text": "Start iterating from i+1 to N-1. If the current value is less than minVal, update minVal." }, { "code": null, "e": 29425, "s": 29347, "text": "Mark that position right to perform cyclic shift from i to right by offset 1." }, { "code": null, "e": 29495, "s": 29425, "text": "If no such right value exists then simply move to the next iteration." }, { "code": null, "e": 29579, "s": 29495, "text": "Otherwise, rotate the array from i to right by 1 position and increment count by 1." }, { "code": null, "e": 29621, "s": 29579, "text": "Return the value of count as your answer." }, { "code": null, "e": 29677, "s": 29621, "text": "Below is the C++ implementation for the above approach:" }, { "code": null, "e": 29681, "s": 29677, "text": "C++" }, { "code": null, "e": 29686, "s": 29681, "text": "Java" }, { "code": null, "e": 29694, "s": 29686, "text": "Python3" }, { "code": null, "e": 29697, "s": 29694, "text": "C#" }, { "code": null, "e": 29708, "s": 29697, "text": "Javascript" }, { "code": "// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to Sort given Array using// at most N cyclic shift on any subarrayint ShiftingSort(vector<int>& arr, int n){ vector<int> temp(arr.begin(), arr.end()); sort(temp.begin(), temp.end()); // Variable to store count of // shifting operations int count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr == temp) { return 0; } else { // Run a loop from 0 to n-2 index for (int index1 = 0; index1 < n - 1; index1++) { int minval = arr[index1]; int left = index1; int right = -1; // Loop from i+1 to n-1 // to find the minimum value for (int index2 = index1 + 1; index2 < n; index2++) { if (minval > arr[index2]) { minval = arr[index2]; right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; int index = right; int tempval = arr[right]; // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr[index] = arr[index - 1]; index--; } arr[index] = tempval; } } } // Return the total operations return count;} // Driver codeint main(){ vector<int> arr{ 1, 3, 2, 8, 5 }; int N = 5; cout << ShiftingSort(arr, N) << \"\\n\"; return 0;}", "e": 31418, "s": 29708, "text": null }, { "code": "// Java code to implement the above approachimport java.util.*; public class GFG{ // Function to Sort given Array using// at most N cyclic shift on any subarraystatic int ShiftingSort(ArrayList<Integer> arr, int n){ ArrayList<Integer> temp = new ArrayList<Integer>(); for(int i = 0; i < arr.size(); i++) { temp.add(arr.get(i)); } Collections.sort(temp); // Variable to store count of // shifting operations int count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr.equals(temp)) { return 0; } else { // Run a loop from 0 to n-2 index for (int index1 = 0; index1 < n - 1; index1++) { int minval = arr.get(index1); int left = index1; int right = -1; // Loop from i+1 to n-1 // to find the minimum value for (int index2 = index1 + 1; index2 < n; index2++) { if (minval > arr.get(index2)) { minval = arr.get(index2); right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; int index = right; int tempval = arr.get(right); // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr.set(index, arr.get(index - 1)); index--; } arr.set(index, tempval); } } } // Return the total operations return count;} // Driver codepublic static void main(String args[]){ ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(3); arr.add(2); arr.add(8); arr.add(5); int N = 5; System.out.println(ShiftingSort(arr, N));}} // This code is contributed by Samim Hossain Mondal.", "e": 33427, "s": 31418, "text": null }, { "code": "# Python Program to implement# the above approach # Function to Sort given Array using# at most N cyclic shift on any subarraydef ShiftingSort(arr, n): temp = arr.copy() temp.sort() # Variable to store count of # shifting operations count = 0 # If the vector arr is already sorted # the 0 operations shift required if (arr == temp): return 0 else: # Run a loop from 0 to n-2 index for index1 in range(n - 1): minval = arr[index1] left = index1 right = -1 # Loop from i+1 to n-1 # to find the minimum value for index2 in range(index1 + 1, n): if (minval > arr[index2]): minval = arr[index2] right = index2 # Check if the shifting is required if (right != -1): # Increment count operations count += 1 index = right tempval = arr[right] # Loop for shifting the array arr # from index = left to index = right while (index > left): arr[index] = arr[index - 1] index -= 1 arr[index] = tempval # Return the total operations return count # Driver codearr = [1, 3, 2, 8, 5]N = 5print(ShiftingSort(arr, N)) # This code is contributed by gfgking", "e": 34823, "s": 33427, "text": null }, { "code": "// C# code to implement the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to Sort given Array using// at most N cyclic shift on any subarraystatic int ShiftingSort(ArrayList arr, int n){ ArrayList temp = new ArrayList(); for(int i = 0; i < arr.Count; i++) { temp.Add(arr[i]); } temp.Sort(); // Variable to store count of // shifting operations int count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr.Equals(temp)) { return 0; } else { // Run a loop from 0 to n-2 index for (int index1 = 0; index1 < n - 1; index1++) { int minval = (int)arr[index1]; int left = index1; int right = -1; // Loop from i+1 to n-1 // to find the minimum value for (int index2 = index1 + 1; index2 < n; index2++) { if (minval > (int)arr[index2]) { minval = (int)arr[index2]; right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; int index = right; int tempval = (int)arr[right]; // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr[index] = arr[index - 1]; index--; } arr[index] = tempval; } } } // Return the total operations return count;} // Driver codepublic static void Main(){ ArrayList arr = new ArrayList(); arr.Add(1); arr.Add(3); arr.Add(2); arr.Add(8); arr.Add(5); int N = 5; Console.Write(ShiftingSort(arr, N));}} // This code is contributed by Samim Hossain Mondal.", "e": 36826, "s": 34823, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to Sort given Array using // at most N cyclic shift on any subarray function ShiftingSort(arr, n) { let temp = [...arr]; temp.sort(function (a, b) { return a - b }) // Variable to store count of // shifting operations let count = 0; // If the vector arr is already sorted // the 0 operations shift required if (arr == temp) { return 0; } else { // Run a loop from 0 to n-2 index for (let index1 = 0; index1 < n - 1; index1++) { let minval = arr[index1]; let left = index1; let right = -1; // Loop from i+1 to n-1 // to find the minimum value for (let index2 = index1 + 1; index2 < n; index2++) { if (minval > arr[index2]) { minval = arr[index2]; right = index2; } } // Check if the shifting is required if (right != -1) { // Increment count operations count++; let index = right; let tempval = arr[right]; // Loop for shifting the array arr // from index = left to index = right while (index > left) { arr[index] = arr[index - 1]; index--; } arr[index] = tempval; } } } // Return the total operations return count; } // Driver code let arr = [1, 3, 2, 8, 5]; let N = 5; document.write(ShiftingSort(arr, N) + '<br>'); // This code is contributed by Potta Lokesh </script>", "e": 38992, "s": 36826, "text": null }, { "code": null, "e": 38994, "s": 38992, "text": "2" }, { "code": null, "e": 39039, "s": 38994, "text": "Time Complexity: O(N2)Space Complexity: O(1)" }, { "code": null, "e": 39053, "s": 39039, "text": "lokeshpotta20" }, { "code": null, "e": 39061, "s": 39053, "text": "gfgking" }, { "code": null, "e": 39071, "s": 39061, "text": "samim2000" }, { "code": null, "e": 39087, "s": 39071, "text": "simranarora5sos" }, { "code": null, "e": 39096, "s": 39087, "text": "rotation" }, { "code": null, "e": 39105, "s": 39096, "text": "subarray" }, { "code": null, "e": 39112, "s": 39105, "text": "Arrays" }, { "code": null, "e": 39120, "s": 39112, "text": "Sorting" }, { "code": null, "e": 39127, "s": 39120, "text": "Arrays" }, { "code": null, "e": 39135, "s": 39127, "text": "Sorting" }, { "code": null, "e": 39233, "s": 39135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39260, "s": 39233, "text": "Count pairs with given sum" }, { "code": null, "e": 39291, "s": 39260, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 39316, "s": 39291, "text": "Window Sliding Technique" }, { "code": null, "e": 39354, "s": 39316, "text": "Reversal algorithm for array rotation" } ]
unordered_set clear() function in C++ STL - GeeksforGeeks
20 Aug, 2021 The unordered_set::clear() function is a built-in function in C++ STL which is used to clear an unordered_set container. That is, this function removes all of the elements from an unordered_set and empties it. All of the iterators, pointers, and references to the container are invalidated. This reduces the size of the container to zero. Syntax: unordered_set_name.clear() Parameter: This function does not accepts any parameter.Return Value: This function does not returns any value.Below programs illustrate the unordered_set::clear() function:Program 1: CPP // C++ program to illustrate the// unordered_set::clear() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> sampleSet; // Inserting elements sampleSet.insert(5); sampleSet.insert(10); sampleSet.insert(15); sampleSet.insert(20); sampleSet.insert(25); // displaying all elements of sampleSet cout << "sampleSet contains: "; for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { cout << *itr << " "; } // clear the set sampleSet.clear(); // size after clearing cout << "\nSize of set after clearing elements: " << sampleSet.size(); return 0;} sampleSet contains: 25 20 15 5 10 Size of set after clearing elements: 0 Program 2: CPP // C++ program to illustrate the// unordered_set::clear() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet; // Inserting elements sampleSet.insert("Welcome"); sampleSet.insert("To"); sampleSet.insert("GeeksforGeeks"); sampleSet.insert("Computer Science Portal"); sampleSet.insert("For Geeks"); // displaying all elements of sampleSet cout << "sampleSet contains: "; for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { cout << *itr << " "; } // clear the set sampleSet.clear(); // size after clearing cout << "\nSize of set after clearing elements: " << sampleSet.size(); return 0;} sampleSet contains: For Geeks GeeksforGeeks Computer Science Portal Welcome To Size of set after clearing elements: 0 anikakapoor natu CPP-Functions cpp-unordered_set cpp-unordered_set-functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++
[ { "code": null, "e": 25759, "s": 25731, "text": "\n20 Aug, 2021" }, { "code": null, "e": 26099, "s": 25759, "text": "The unordered_set::clear() function is a built-in function in C++ STL which is used to clear an unordered_set container. That is, this function removes all of the elements from an unordered_set and empties it. All of the iterators, pointers, and references to the container are invalidated. This reduces the size of the container to zero. " }, { "code": null, "e": 26109, "s": 26099, "text": "Syntax: " }, { "code": null, "e": 26136, "s": 26109, "text": "unordered_set_name.clear()" }, { "code": null, "e": 26322, "s": 26136, "text": "Parameter: This function does not accepts any parameter.Return Value: This function does not returns any value.Below programs illustrate the unordered_set::clear() function:Program 1: " }, { "code": null, "e": 26326, "s": 26322, "text": "CPP" }, { "code": "// C++ program to illustrate the// unordered_set::clear() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<int> sampleSet; // Inserting elements sampleSet.insert(5); sampleSet.insert(10); sampleSet.insert(15); sampleSet.insert(20); sampleSet.insert(25); // displaying all elements of sampleSet cout << \"sampleSet contains: \"; for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { cout << *itr << \" \"; } // clear the set sampleSet.clear(); // size after clearing cout << \"\\nSize of set after clearing elements: \" << sampleSet.size(); return 0;}", "e": 27004, "s": 26326, "text": null }, { "code": null, "e": 27078, "s": 27004, "text": "sampleSet contains: 25 20 15 5 10 \nSize of set after clearing elements: 0" }, { "code": null, "e": 27090, "s": 27078, "text": "Program 2: " }, { "code": null, "e": 27094, "s": 27090, "text": "CPP" }, { "code": "// C++ program to illustrate the// unordered_set::clear() function #include <iostream>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet; // Inserting elements sampleSet.insert(\"Welcome\"); sampleSet.insert(\"To\"); sampleSet.insert(\"GeeksforGeeks\"); sampleSet.insert(\"Computer Science Portal\"); sampleSet.insert(\"For Geeks\"); // displaying all elements of sampleSet cout << \"sampleSet contains: \"; for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { cout << *itr << \" \"; } // clear the set sampleSet.clear(); // size after clearing cout << \"\\nSize of set after clearing elements: \" << sampleSet.size(); return 0;}", "e": 27830, "s": 27094, "text": null }, { "code": null, "e": 27949, "s": 27830, "text": "sampleSet contains: For Geeks GeeksforGeeks Computer Science Portal Welcome To \nSize of set after clearing elements: 0" }, { "code": null, "e": 27961, "s": 27949, "text": "anikakapoor" }, { "code": null, "e": 27966, "s": 27961, "text": "natu" }, { "code": null, "e": 27980, "s": 27966, "text": "CPP-Functions" }, { "code": null, "e": 27998, "s": 27980, "text": "cpp-unordered_set" }, { "code": null, "e": 28026, "s": 27998, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 28030, "s": 28026, "text": "C++" }, { "code": null, "e": 28034, "s": 28030, "text": "CPP" }, { "code": null, "e": 28132, "s": 28034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28151, "s": 28132, "text": "Inheritance in C++" }, { "code": null, "e": 28194, "s": 28151, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28218, "s": 28194, "text": "C++ Classes and Objects" }, { "code": null, "e": 28245, "s": 28218, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28269, "s": 28245, "text": "Virtual Function in C++" }, { "code": null, "e": 28300, "s": 28269, "text": "Templates in C++ with Examples" }, { "code": null, "e": 28320, "s": 28300, "text": "Constructors in C++" }, { "code": null, "e": 28348, "s": 28320, "text": "Operator Overloading in C++" }, { "code": null, "e": 28376, "s": 28348, "text": "Socket Programming in C/C++" } ]
How to turn off PHP Notices ? - GeeksforGeeks
16 Oct, 2019 In PHP, Notices are the undefined variables indicated in the PHP project on a set of lines or particular lines. It usually does not affect or break the functionality of the code written. When PHP notices detect errors, it will display like this: PHP Notice: Use of undefined constant name - assumed 'name' in line number PHP editing differs from the versions of it. Hence, methods to turn off PHP notices are as follows: Method 1: It is the most easy and convenient way to turn off the notices. The notices can be disabled through settings the php.ini file. In the current file, search for the line of code error_reporting. There will be a line of Default Value: E_ALL as shown below: Replace this line of code with Default Value: E_ALL & ~E_NOTICE.It will display all the errors except for the notices. Make sure the part is enabled and then restart or refresh the server for PHP. In some versions of PHP, the default value is set to Default Value: E_ALL & ~E_NOTICE. Method 2: To turn the notices off, a line of code can be added to the PHP file, at the beginning of the code of the file. For example gfg.phpThe following code would looks something like this <?php // Open a file$file = fopen("gfg.txt", "w") or die("Unable to open file!"); // Store the string into variable$txt = "GeeksforGeeks \n"; // Write the text content to the filefwrite($file, $txt); // Store the string into variable$txt = "Welcome to Geeks! \n"; // Write the text content to the filefwrite($file, $txt); // Close the filefclose($file); ?> Add this line at the start of the code: error_reporting(E_ERROR | E_WARNING | E_PARSE); <?php error_reporting(E_ERROR | E_WARNING | E_PARSE); // Open a file$file = fopen("gfg.txt", "w") or die("Unable to open file!"); // Store the string into variable$txt = "GeeksforGeeks \n"; // Write the text content to the filefwrite($file, $txt); // Store the string into variable$txt = "Welcome to Geeks! \n"; // Write the text content to the filefwrite($file, $txt); // Close the filefclose($file); ?> It will display the errors, warnings, and compile-time parse errors. Method 3: The ‘@’ can be added to any operator to make PHP Notices silent while performing current operation:@$mid= $_POST[‘mid’]; PHP-basics Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to call PHP function on the click of a Button ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 26103, "s": 26075, "text": "\n16 Oct, 2019" }, { "code": null, "e": 26349, "s": 26103, "text": "In PHP, Notices are the undefined variables indicated in the PHP project on a set of lines or particular lines. It usually does not affect or break the functionality of the code written. When PHP notices detect errors, it will display like this:" }, { "code": null, "e": 26424, "s": 26349, "text": "PHP Notice: Use of undefined constant name - assumed 'name' in line number" }, { "code": null, "e": 26524, "s": 26424, "text": "PHP editing differs from the versions of it. Hence, methods to turn off PHP notices are as follows:" }, { "code": null, "e": 26788, "s": 26524, "text": "Method 1: It is the most easy and convenient way to turn off the notices. The notices can be disabled through settings the php.ini file. In the current file, search for the line of code error_reporting. There will be a line of Default Value: E_ALL as shown below:" }, { "code": null, "e": 27072, "s": 26788, "text": "Replace this line of code with Default Value: E_ALL & ~E_NOTICE.It will display all the errors except for the notices. Make sure the part is enabled and then restart or refresh the server for PHP. In some versions of PHP, the default value is set to Default Value: E_ALL & ~E_NOTICE." }, { "code": null, "e": 27264, "s": 27072, "text": "Method 2: To turn the notices off, a line of code can be added to the PHP file, at the beginning of the code of the file. For example gfg.phpThe following code would looks something like this" }, { "code": "<?php // Open a file$file = fopen(\"gfg.txt\", \"w\") or die(\"Unable to open file!\"); // Store the string into variable$txt = \"GeeksforGeeks \\n\"; // Write the text content to the filefwrite($file, $txt); // Store the string into variable$txt = \"Welcome to Geeks! \\n\"; // Write the text content to the filefwrite($file, $txt); // Close the filefclose($file); ?>", "e": 27636, "s": 27264, "text": null }, { "code": null, "e": 27676, "s": 27636, "text": "Add this line at the start of the code:" }, { "code": null, "e": 27724, "s": 27676, "text": "error_reporting(E_ERROR | E_WARNING | E_PARSE);" }, { "code": "<?php error_reporting(E_ERROR | E_WARNING | E_PARSE); // Open a file$file = fopen(\"gfg.txt\", \"w\") or die(\"Unable to open file!\"); // Store the string into variable$txt = \"GeeksforGeeks \\n\"; // Write the text content to the filefwrite($file, $txt); // Store the string into variable$txt = \"Welcome to Geeks! \\n\"; // Write the text content to the filefwrite($file, $txt); // Close the filefclose($file); ?>", "e": 28146, "s": 27724, "text": null }, { "code": null, "e": 28215, "s": 28146, "text": "It will display the errors, warnings, and compile-time parse errors." }, { "code": null, "e": 28346, "s": 28215, "text": "Method 3: The ‘@’ can be added to any operator to make PHP Notices silent while performing current operation:@$mid= $_POST[‘mid’];" }, { "code": null, "e": 28357, "s": 28346, "text": "PHP-basics" }, { "code": null, "e": 28364, "s": 28357, "text": "Picked" }, { "code": null, "e": 28368, "s": 28364, "text": "PHP" }, { "code": null, "e": 28381, "s": 28368, "text": "PHP Programs" }, { "code": null, "e": 28398, "s": 28381, "text": "Web Technologies" }, { "code": null, "e": 28425, "s": 28398, "text": "Web technologies Questions" }, { "code": null, "e": 28429, "s": 28425, "text": "PHP" }, { "code": null, "e": 28527, "s": 28429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28577, "s": 28527, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28617, "s": 28577, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28678, "s": 28617, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28728, "s": 28678, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 28773, "s": 28728, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28823, "s": 28773, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28863, "s": 28823, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28924, "s": 28863, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28976, "s": 28924, "text": "How to call PHP function on the click of a Button ?" } ]
C# Hashtable with Examples - GeeksforGeeks
29 Jul, 2021 A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It generally optimized the lookup by calculating the hash code of every key and store into another basket automatically and when you accessing the value from the hashtable at that time it matches the hashcode with the specified key. It is the non-generic type of collection which is defined in System.Collections namespace. Important Points: In Hashtable, the key cannot be null, but value can be. In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable. The capacity of a Hashtable is the number of elements that Hashtable can hold. A hash function is provided by each key object in the Hashtable. The Hashtable class implements the IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, and ICloneable interfaces. In hashtable, you can store elements of the same type and of the different types. The elements of hashtable that is a key/value pair are stored in DictionaryEntry, so you can also cast the key/value pairs to a DictionaryEntry. In Hashtable, key must be unique. Duplicate keys are not allowed. Hashtable class provides 16 different types of constructors which are used to create a hashtable, here we only use Hashtable() constructor. To read more about Hashtable’s constructors you can refer to C# | Hashtable Class This constructor is used to create an instance of the Hashtable class which is empty and having the default initial capacity, load factor, hash code provider, and comparer. Now, let’s see how to create a hashtable using Hashtable() constructor: Step 1: Include System.Collections namespace in your program with the help of using keyword: using System.Collections; Step 2: Create a hashtable using Hashtable class as shown below: Hashtable hashtable_name = new Hashtable(); Step 3: If you want to add a key/value pair in your hashtable, then use Add() method to add elements in your hashtable. And you can also store a key/value pair in your hashtable without using Add() method. Example: C# // C# program to illustrate how// to create a hashtableusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable1 = new Hashtable(); // Adding key/value pair // in the hashtable // Using Add() method my_hashtable1.Add("A1", "Welcome"); my_hashtable1.Add("A2", "to"); my_hashtable1.Add("A3", "GeeksforGeeks"); Console.WriteLine("Key and Value pairs from my_hashtable1:"); foreach(DictionaryEntry ele1 in my_hashtable1) { Console.WriteLine("{0} and {1} ", ele1.Key, ele1.Value); } // Create another hashtable // Using Hashtable class // and adding key/value pairs // without using Add method Hashtable my_hashtable2 = new Hashtable() { {1, "hello"}, {2, 234}, {3, 230.45}, {4, null}}; Console.WriteLine("Key and Value pairs from my_hashtable2:"); foreach(var ele2 in my_hashtable2.Keys) { Console.WriteLine("{0}and {1}", ele2, my_hashtable2[ele2]); } }} Key and Value pairs from my_hashtable1: A3 and GeeksforGeeks A2 and to A1 and Welcome Key and Value pairs from my_hashtable2: 4and 3and 230.45 2and 234 1and hello In Hashtable, you are allowed to remove elements from the hashtable. The Hashtable class provides two different methods to remove elements and the methods are: Clear : This method is used to remove all the objects from the hashtable. Remove : This method is used to remove the element with the specified key from the hashtable. Example: C# // C# program to illustrate how// remove elements from the hashtableusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable = new Hashtable(); // Adding key/value pair // in the hashtable // Using Add() method my_hashtable.Add("A1", "Welcome"); my_hashtable.Add("A2", "to"); my_hashtable.Add("A3", "GeeksforGeeks"); // Using remove method // remove A2 key/value pair my_hashtable.Remove("A2"); Console.WriteLine("Key and Value pairs :"); foreach(DictionaryEntry ele1 in my_hashtable) { Console.WriteLine("{0} and {1} ", ele1.Key, ele1.Value); } // Before using Clear method Console.WriteLine("Total number of elements present"+ " in my_hashtable:{0}", my_hashtable.Count); my_hashtable.Clear(); // After using Clear method Console.WriteLine("Total number of elements present in"+ " my_hashtable:{0}", my_hashtable.Count); }} Key and Value pairs : A3 and GeeksforGeeks A1 and Welcome Total number of elements present in my_hashtable:2 Total number of elements present in my_hashtable:0 In hashtable, you can check whether the given pair is present or not using the following methods: Contains: This method is used to check whether the Hashtable contains a specific key. ContainsKey: This method is also used to check whether the Hashtable contains a specific key. ContainsValue: This method is used to check whether the Hashtable contains a specific value. Example: C# // C# program to illustrate how// to check key/value present// in the hashtable or notusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable = new Hashtable(); // Adding key/value pair in the hashtable // Using Add() method my_hashtable.Add("A1", "Welcome"); my_hashtable.Add("A2", "to"); my_hashtable.Add("A3", "GeeksforGeeks"); // Determine whether the given // key present or not // using Contains method Console.WriteLine(my_hashtable.Contains("A3")); Console.WriteLine(my_hashtable.Contains(12)); Console.WriteLine(); // Determine whether the given // key present or not // using ContainsKey method Console.WriteLine(my_hashtable.ContainsKey("A1")); Console.WriteLine(my_hashtable.ContainsKey(1)); Console.WriteLine(); // Determine whether the given // value present or not // using ContainsValue method Console.WriteLine(my_hashtable.ContainsValue("geeks")); Console.WriteLine(my_hashtable.ContainsValue("to")); }} True False True False False True arorakashish0911 CSharp-Collections-Hashtable CSharp-Collections-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# | Delegates C# | Arrays of Strings C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 26551, "s": 26523, "text": "\n29 Jul, 2021" }, { "code": null, "e": 27075, "s": 26551, "text": "A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It generally optimized the lookup by calculating the hash code of every key and store into another basket automatically and when you accessing the value from the hashtable at that time it matches the hashcode with the specified key. It is the non-generic type of collection which is defined in System.Collections namespace. " }, { "code": null, "e": 27094, "s": 27075, "text": "Important Points: " }, { "code": null, "e": 27150, "s": 27094, "text": "In Hashtable, the key cannot be null, but value can be." }, { "code": null, "e": 27245, "s": 27150, "text": "In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable." }, { "code": null, "e": 27324, "s": 27245, "text": "The capacity of a Hashtable is the number of elements that Hashtable can hold." }, { "code": null, "e": 27389, "s": 27324, "text": "A hash function is provided by each key object in the Hashtable." }, { "code": null, "e": 27531, "s": 27389, "text": "The Hashtable class implements the IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, and ICloneable interfaces." }, { "code": null, "e": 27613, "s": 27531, "text": "In hashtable, you can store elements of the same type and of the different types." }, { "code": null, "e": 27758, "s": 27613, "text": "The elements of hashtable that is a key/value pair are stored in DictionaryEntry, so you can also cast the key/value pairs to a DictionaryEntry." }, { "code": null, "e": 27824, "s": 27758, "text": "In Hashtable, key must be unique. Duplicate keys are not allowed." }, { "code": null, "e": 28291, "s": 27824, "text": "Hashtable class provides 16 different types of constructors which are used to create a hashtable, here we only use Hashtable() constructor. To read more about Hashtable’s constructors you can refer to C# | Hashtable Class This constructor is used to create an instance of the Hashtable class which is empty and having the default initial capacity, load factor, hash code provider, and comparer. Now, let’s see how to create a hashtable using Hashtable() constructor:" }, { "code": null, "e": 28385, "s": 28291, "text": "Step 1: Include System.Collections namespace in your program with the help of using keyword: " }, { "code": null, "e": 28411, "s": 28385, "text": "using System.Collections;" }, { "code": null, "e": 28477, "s": 28411, "text": "Step 2: Create a hashtable using Hashtable class as shown below: " }, { "code": null, "e": 28521, "s": 28477, "text": "Hashtable hashtable_name = new Hashtable();" }, { "code": null, "e": 28728, "s": 28521, "text": "Step 3: If you want to add a key/value pair in your hashtable, then use Add() method to add elements in your hashtable. And you can also store a key/value pair in your hashtable without using Add() method. " }, { "code": null, "e": 28738, "s": 28728, "text": "Example: " }, { "code": null, "e": 28741, "s": 28738, "text": "C#" }, { "code": "// C# program to illustrate how// to create a hashtableusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable1 = new Hashtable(); // Adding key/value pair // in the hashtable // Using Add() method my_hashtable1.Add(\"A1\", \"Welcome\"); my_hashtable1.Add(\"A2\", \"to\"); my_hashtable1.Add(\"A3\", \"GeeksforGeeks\"); Console.WriteLine(\"Key and Value pairs from my_hashtable1:\"); foreach(DictionaryEntry ele1 in my_hashtable1) { Console.WriteLine(\"{0} and {1} \", ele1.Key, ele1.Value); } // Create another hashtable // Using Hashtable class // and adding key/value pairs // without using Add method Hashtable my_hashtable2 = new Hashtable() { {1, \"hello\"}, {2, 234}, {3, 230.45}, {4, null}}; Console.WriteLine(\"Key and Value pairs from my_hashtable2:\"); foreach(var ele2 in my_hashtable2.Keys) { Console.WriteLine(\"{0}and {1}\", ele2, my_hashtable2[ele2]); } }}", "e": 30079, "s": 28741, "text": null }, { "code": null, "e": 30246, "s": 30079, "text": "Key and Value pairs from my_hashtable1:\nA3 and GeeksforGeeks \nA2 and to \nA1 and Welcome \nKey and Value pairs from my_hashtable2:\n4and \n3and 230.45\n2and 234\n1and hello" }, { "code": null, "e": 30408, "s": 30248, "text": "In Hashtable, you are allowed to remove elements from the hashtable. The Hashtable class provides two different methods to remove elements and the methods are:" }, { "code": null, "e": 30482, "s": 30408, "text": "Clear : This method is used to remove all the objects from the hashtable." }, { "code": null, "e": 30576, "s": 30482, "text": "Remove : This method is used to remove the element with the specified key from the hashtable." }, { "code": null, "e": 30585, "s": 30576, "text": "Example:" }, { "code": null, "e": 30588, "s": 30585, "text": "C#" }, { "code": "// C# program to illustrate how// remove elements from the hashtableusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable = new Hashtable(); // Adding key/value pair // in the hashtable // Using Add() method my_hashtable.Add(\"A1\", \"Welcome\"); my_hashtable.Add(\"A2\", \"to\"); my_hashtable.Add(\"A3\", \"GeeksforGeeks\"); // Using remove method // remove A2 key/value pair my_hashtable.Remove(\"A2\"); Console.WriteLine(\"Key and Value pairs :\"); foreach(DictionaryEntry ele1 in my_hashtable) { Console.WriteLine(\"{0} and {1} \", ele1.Key, ele1.Value); } // Before using Clear method Console.WriteLine(\"Total number of elements present\"+ \" in my_hashtable:{0}\", my_hashtable.Count); my_hashtable.Clear(); // After using Clear method Console.WriteLine(\"Total number of elements present in\"+ \" my_hashtable:{0}\", my_hashtable.Count); }}", "e": 31738, "s": 30588, "text": null }, { "code": null, "e": 31900, "s": 31738, "text": "Key and Value pairs :\nA3 and GeeksforGeeks \nA1 and Welcome \nTotal number of elements present in my_hashtable:2\nTotal number of elements present in my_hashtable:0" }, { "code": null, "e": 32000, "s": 31902, "text": "In hashtable, you can check whether the given pair is present or not using the following methods:" }, { "code": null, "e": 32086, "s": 32000, "text": "Contains: This method is used to check whether the Hashtable contains a specific key." }, { "code": null, "e": 32180, "s": 32086, "text": "ContainsKey: This method is also used to check whether the Hashtable contains a specific key." }, { "code": null, "e": 32273, "s": 32180, "text": "ContainsValue: This method is used to check whether the Hashtable contains a specific value." }, { "code": null, "e": 32283, "s": 32273, "text": "Example: " }, { "code": null, "e": 32286, "s": 32283, "text": "C#" }, { "code": "// C# program to illustrate how// to check key/value present// in the hashtable or notusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Create a hashtable // Using Hashtable class Hashtable my_hashtable = new Hashtable(); // Adding key/value pair in the hashtable // Using Add() method my_hashtable.Add(\"A1\", \"Welcome\"); my_hashtable.Add(\"A2\", \"to\"); my_hashtable.Add(\"A3\", \"GeeksforGeeks\"); // Determine whether the given // key present or not // using Contains method Console.WriteLine(my_hashtable.Contains(\"A3\")); Console.WriteLine(my_hashtable.Contains(12)); Console.WriteLine(); // Determine whether the given // key present or not // using ContainsKey method Console.WriteLine(my_hashtable.ContainsKey(\"A1\")); Console.WriteLine(my_hashtable.ContainsKey(1)); Console.WriteLine(); // Determine whether the given // value present or not // using ContainsValue method Console.WriteLine(my_hashtable.ContainsValue(\"geeks\")); Console.WriteLine(my_hashtable.ContainsValue(\"to\")); }}", "e": 33509, "s": 32286, "text": null }, { "code": null, "e": 33544, "s": 33509, "text": "True\nFalse\n\nTrue\nFalse\n\nFalse\nTrue" }, { "code": null, "e": 33563, "s": 33546, "text": "arorakashish0911" }, { "code": null, "e": 33592, "s": 33563, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 33621, "s": 33592, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 33624, "s": 33621, "text": "C#" }, { "code": null, "e": 33722, "s": 33624, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33776, "s": 33722, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 33818, "s": 33776, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 33880, "s": 33818, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 33908, "s": 33880, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 33923, "s": 33908, "text": "C# | Delegates" }, { "code": null, "e": 33946, "s": 33923, "text": "C# | Arrays of Strings" }, { "code": null, "e": 33968, "s": 33946, "text": "C# | Abstract Classes" }, { "code": null, "e": 34014, "s": 33968, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 34037, "s": 34014, "text": "Extension Method in C#" } ]
How to add two Hexadecimal numbers? - GeeksforGeeks
27 Jan, 2021 Given two numeric Hexadecimal numbers str1 and str2, the task is to add the two hexadecimal numbers. Hexadecimal Number system, often shortened to “hex”, is a number system made up from 16 symbols. it uses 10 symbols from decimal number system which are represented by 0-9 and six extra symbols A – F which represent decimal 10 – 15. Examples: Input: str1 = “01B”, str2 = “378”Output: 393Explanation:B (11 in decimal) + 8 =19 (13 in hex), hence addition bit = 3, carry = 11 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 00 + 3 + 0 (carry) = 3, hence addition bit = 3, carry = 001B + 378 = 393 Input: str1 = “AD”, str2 = “1B”Output: C8Explanation:D(13 in Dec) + B(11 in Dec) = 24(18 in hex), hence addition bit = 8, carry = 1A(10 in Dec) + 1 + 1 (carry)= 12 (C in hex), addition bit = C carry = 0AD + 1B = C8 Approaches: Using a map template to find and store the values. Using inbuilt functions to find the sum. The idea is to use a map template to store the mapped values that are hexadecimal to decimal and decimal to hexadecimal. Iterate until one of the given string reaches its length.Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition.Perform the same operation on the remaining length of the other string (if both the strings have different lengths).Return the value that has been added. Iterate until one of the given string reaches its length. Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition. Perform the same operation on the remaining length of the other string (if both the strings have different lengths). Return the value that has been added. Below is the implementation of the above approach: C++ // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Map for converting hexadecimal// values to decimalmap<char, int> hex_value_of_dec(void){ // Map the values to decimal values map<char, int> m{ { '0', 0 }, { '1', 1 }, { '2', 2 }, { '3', 3 }, { '4', 4 }, { '5', 5 }, { '6', 6 }, { '7', 7 }, { '8', 8 }, { '9', 9 }, { 'A', 10 }, { 'B', 11 }, { 'C', 12 }, { 'D', 13 }, { 'E', 14 }, { 'F', 15 } }; return m;} // Map for converting decimal values// to hexadecimalmap<int, char> dec_value_of_hex(void){ // Map the values to the // hexadecimal values map<int, char> m{ { 0, '0' }, { 1, '1' }, { 2, '2' }, { 3, '3' }, { 4, '4' }, { 5, '5' }, { 6, '6' }, { 7, '7' }, { 8, '8' }, { 9, '9' }, { 10, 'A' }, { 11, 'B' }, { 12, 'C' }, { 13, 'D' }, { 14, 'E' }, { 15, 'F' } }; return m;} // Function to add the two hexadecimal numbersstring Add_Hex(string a, string b){ map<char, int> m = hex_value_of_dec(); map<int, char> k = dec_value_of_hex(); // Check if length of string first is // greater than or equal to string second if (a.length() < b.length()) swap(a, b); // Store length of both strings int l1 = a.length(), l2 = b.length(); string ans = ""; // Initialize carry as zero int carry = 0, i, j; // Traverse till second string // get traversal completely for (i = l1 - 1, j = l2 - 1; j >= 0; i--, j--) { // Decimal value of element at a[i] // Decimal value of element at b[i] int sum = m[a[i]] + m[b[j]] + carry; // Hexadecimal value of sum%16 // to get addition bit int addition_bit = k[sum % 16]; // Add addition_bit to answer ans.push_back(addition_bit); // Update carry carry = sum / 16; } // Traverse remaining element // of string a while (i >= 0) { // Decimal value of element // at a[i] int sum = m[a[i]] + carry; // Hexadecimal value of sum%16 // to get addition bit int addition_bit = k[sum % 16]; // Add addition_bit to answer ans.push_back(addition_bit); // Update carry carry = sum / 16; i--; } // Check if still carry remains if (carry) { ans.push_back(k[carry]); } // Reverse the final string // for desired output reverse(ans.begin(), ans.end()); // Return the answer return ans;} // Driver Codeint main(void){ // Initialize the hexadecimal values string str1 = "1B", str2 = "AD"; // Function call cout << Add_Hex(str1, str2) << endl;} Time Complexity: O(max(N, M)), where the length of the string first and second is N and M.Auxiliary Space: O(max(N, M)), where the length of the string first and second is N and M. In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. To convert the numbers make use of the hex() function. The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal. In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. To convert the numbers make use of the hex() function. The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal. Below is the implementation of the above approach: Python3 # Program to add two hexadecimal numbers. # Driver code# Declaring the variablesstr1 = "1B"str2 = "AD" # Calculating hexadecimal value using functionsum = hex(int(str1, 16) + int(str2, 16)) # Printing resultprint(sum[2:]) Output: C8 aditya_taparia base-conversion Numbers Hash Mathematical Strings Hash Strings Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Counting frequencies of array elements Most frequent element in an array Double Hashing Sorting a Map by value in C++ STL Longest Consecutive Subsequence Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26123, "s": 26095, "text": "\n27 Jan, 2021" }, { "code": null, "e": 26225, "s": 26123, "text": "Given two numeric Hexadecimal numbers str1 and str2, the task is to add the two hexadecimal numbers. " }, { "code": null, "e": 26458, "s": 26225, "text": "Hexadecimal Number system, often shortened to “hex”, is a number system made up from 16 symbols. it uses 10 symbols from decimal number system which are represented by 0-9 and six extra symbols A – F which represent decimal 10 – 15." }, { "code": null, "e": 26468, "s": 26458, "text": "Examples:" }, { "code": null, "e": 26724, "s": 26468, "text": "Input: str1 = “01B”, str2 = “378”Output: 393Explanation:B (11 in decimal) + 8 =19 (13 in hex), hence addition bit = 3, carry = 11 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 00 + 3 + 0 (carry) = 3, hence addition bit = 3, carry = 001B + 378 = 393" }, { "code": null, "e": 26941, "s": 26724, "text": "Input: str1 = “AD”, str2 = “1B”Output: C8Explanation:D(13 in Dec) + B(11 in Dec) = 24(18 in hex), hence addition bit = 8, carry = 1A(10 in Dec) + 1 + 1 (carry)= 12 (C in hex), addition bit = C carry = 0AD + 1B = C8 " }, { "code": null, "e": 26954, "s": 26941, "text": "Approaches: " }, { "code": null, "e": 27005, "s": 26954, "text": "Using a map template to find and store the values." }, { "code": null, "e": 27046, "s": 27005, "text": "Using inbuilt functions to find the sum." }, { "code": null, "e": 27167, "s": 27046, "text": "The idea is to use a map template to store the mapped values that are hexadecimal to decimal and decimal to hexadecimal." }, { "code": null, "e": 27487, "s": 27167, "text": "Iterate until one of the given string reaches its length.Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition.Perform the same operation on the remaining length of the other string (if both the strings have different lengths).Return the value that has been added." }, { "code": null, "e": 27545, "s": 27487, "text": "Iterate until one of the given string reaches its length." }, { "code": null, "e": 27655, "s": 27545, "text": "Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition." }, { "code": null, "e": 27772, "s": 27655, "text": "Perform the same operation on the remaining length of the other string (if both the strings have different lengths)." }, { "code": null, "e": 27810, "s": 27772, "text": "Return the value that has been added." }, { "code": null, "e": 27861, "s": 27810, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27865, "s": 27861, "text": "C++" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Map for converting hexadecimal// values to decimalmap<char, int> hex_value_of_dec(void){ // Map the values to decimal values map<char, int> m{ { '0', 0 }, { '1', 1 }, { '2', 2 }, { '3', 3 }, { '4', 4 }, { '5', 5 }, { '6', 6 }, { '7', 7 }, { '8', 8 }, { '9', 9 }, { 'A', 10 }, { 'B', 11 }, { 'C', 12 }, { 'D', 13 }, { 'E', 14 }, { 'F', 15 } }; return m;} // Map for converting decimal values// to hexadecimalmap<int, char> dec_value_of_hex(void){ // Map the values to the // hexadecimal values map<int, char> m{ { 0, '0' }, { 1, '1' }, { 2, '2' }, { 3, '3' }, { 4, '4' }, { 5, '5' }, { 6, '6' }, { 7, '7' }, { 8, '8' }, { 9, '9' }, { 10, 'A' }, { 11, 'B' }, { 12, 'C' }, { 13, 'D' }, { 14, 'E' }, { 15, 'F' } }; return m;} // Function to add the two hexadecimal numbersstring Add_Hex(string a, string b){ map<char, int> m = hex_value_of_dec(); map<int, char> k = dec_value_of_hex(); // Check if length of string first is // greater than or equal to string second if (a.length() < b.length()) swap(a, b); // Store length of both strings int l1 = a.length(), l2 = b.length(); string ans = \"\"; // Initialize carry as zero int carry = 0, i, j; // Traverse till second string // get traversal completely for (i = l1 - 1, j = l2 - 1; j >= 0; i--, j--) { // Decimal value of element at a[i] // Decimal value of element at b[i] int sum = m[a[i]] + m[b[j]] + carry; // Hexadecimal value of sum%16 // to get addition bit int addition_bit = k[sum % 16]; // Add addition_bit to answer ans.push_back(addition_bit); // Update carry carry = sum / 16; } // Traverse remaining element // of string a while (i >= 0) { // Decimal value of element // at a[i] int sum = m[a[i]] + carry; // Hexadecimal value of sum%16 // to get addition bit int addition_bit = k[sum % 16]; // Add addition_bit to answer ans.push_back(addition_bit); // Update carry carry = sum / 16; i--; } // Check if still carry remains if (carry) { ans.push_back(k[carry]); } // Reverse the final string // for desired output reverse(ans.begin(), ans.end()); // Return the answer return ans;} // Driver Codeint main(void){ // Initialize the hexadecimal values string str1 = \"1B\", str2 = \"AD\"; // Function call cout << Add_Hex(str1, str2) << endl;}", "e": 30739, "s": 27865, "text": null }, { "code": null, "e": 30920, "s": 30739, "text": "Time Complexity: O(max(N, M)), where the length of the string first and second is N and M.Auxiliary Space: O(max(N, M)), where the length of the string first and second is N and M." }, { "code": null, "e": 31535, "s": 30920, "text": "In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. To convert the numbers make use of the hex() function. The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal." }, { "code": null, "e": 31636, "s": 31535, "text": "In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. " }, { "code": null, "e": 31798, "s": 31636, "text": "To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. " }, { "code": null, "e": 31854, "s": 31798, "text": "To convert the numbers make use of the hex() function. " }, { "code": null, "e": 32002, "s": 31854, "text": "The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form." }, { "code": null, "e": 32154, "s": 32002, "text": " Use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal." }, { "code": null, "e": 32205, "s": 32154, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 32213, "s": 32205, "text": "Python3" }, { "code": "# Program to add two hexadecimal numbers. # Driver code# Declaring the variablesstr1 = \"1B\"str2 = \"AD\" # Calculating hexadecimal value using functionsum = hex(int(str1, 16) + int(str2, 16)) # Printing resultprint(sum[2:])", "e": 32435, "s": 32213, "text": null }, { "code": null, "e": 32443, "s": 32435, "text": "Output:" }, { "code": null, "e": 32446, "s": 32443, "text": "C8" }, { "code": null, "e": 32461, "s": 32446, "text": "aditya_taparia" }, { "code": null, "e": 32477, "s": 32461, "text": "base-conversion" }, { "code": null, "e": 32485, "s": 32477, "text": "Numbers" }, { "code": null, "e": 32490, "s": 32485, "text": "Hash" }, { "code": null, "e": 32503, "s": 32490, "text": "Mathematical" }, { "code": null, "e": 32511, "s": 32503, "text": "Strings" }, { "code": null, "e": 32516, "s": 32511, "text": "Hash" }, { "code": null, "e": 32524, "s": 32516, "text": "Strings" }, { "code": null, "e": 32537, "s": 32524, "text": "Mathematical" }, { "code": null, "e": 32545, "s": 32537, "text": "Numbers" }, { "code": null, "e": 32643, "s": 32545, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32682, "s": 32643, "text": "Counting frequencies of array elements" }, { "code": null, "e": 32716, "s": 32682, "text": "Most frequent element in an array" }, { "code": null, "e": 32731, "s": 32716, "text": "Double Hashing" }, { "code": null, "e": 32765, "s": 32731, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 32797, "s": 32765, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 32827, "s": 32797, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32887, "s": 32827, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32902, "s": 32887, "text": "C++ Data Types" }, { "code": null, "e": 32945, "s": 32902, "text": "Set in C++ Standard Template Library (STL)" } ]
Edit distance and LCS (Longest Common Subsequence) - GeeksforGeeks
12 May, 2021 In standard Edit Distance where we are allowed 3 operations, insert, delete, and replace. Consider a variation of edit distance where we are allowed only two operations insert and delete, find edit distance in this variation. Examples: Input : str1 = "cat", st2 = "cut" Output : 2 We are allowed to insert and delete. We delete 'a' from "cat" and insert "u" to make it "cut". Input : str1 = "acb", st2 = "ab" Output : 1 We can convert "acb" to "ab" by removing 'c'. One solution is to simply modify the Edit Distance Solution by making two recursive calls instead of three. An interesting solution is based on LCS. 1) Find LCS of two strings. Let the length of LCS be x. 2) Let the length of the first string be m and the length of the second string be n. Our result is (m – x) + (n – x). We basically need to do (m – x) delete operations and (n – x) insert operations. C++ Java Python 3 C# PHP Javascript // CPP program to find Edit Distance (when only two// operations are allowed, insert and delete) using LCS.#include<bits/stdc++.h>using namespace std; int editDistanceWith2Ops(string &X, string &Y){ // Find LCS int m = X.length(), n = Y.length(); int L[m+1][n+1]; for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } int lcs = L[m][n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs);} /* Driver program to test above function */int main(){ string X = "abc", Y = "acd"; cout << editDistanceWith2Ops(X, Y); return 0;} //Java program to find Edit Distance (when only two// operations are allowed, insert and delete) using LCS. class GFG { static int editDistanceWith2Ops(String X, String Y) { // Find LCS int m = X.length(), n = Y.length(); int L[][] = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i][j] = 0; } else if (X.charAt(i - 1) == Y.charAt(j - 1)) { L[i][j] = L[i - 1][j - 1] + 1; } else { L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } } int lcs = L[m][n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs); } /* Driver program to test above function */ public static void main(String[] args) { String X = "abc", Y = "acd"; System.out.println(editDistanceWith2Ops(X, Y)); }}/* This Java code is contributed by 29AjayKumar*/ # Python 3 program to find Edit Distance# (when only two operations are allowed,# insert and delete) using LCS. def editDistanceWith2Ops(X, Y): # Find LCS m = len(X) n = len(Y) L = [[0 for x in range(n + 1)] for y in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif (X[i - 1] == Y[j - 1]): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) lcs = L[m][n] # Edit distance is delete operations + # insert operations. return (m - lcs) + (n - lcs) # Driver Codeif __name__ == "__main__": X = "abc" Y = "acd" print(editDistanceWith2Ops(X, Y)) # This code is contributed by ita_c // C# program to find Edit Distance// (when only two operations are// allowed, insert and delete) using LCS.using System; class GFG{ static int editDistanceWith2Ops(String X, String Y){ // Find LCS int m = X.Length, n = Y.Length; int [ , ]L = new int[m + 1 , n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i , j] = 0; } else if (X[i - 1] == Y[j - 1]) { L[i , j] = L[i - 1 , j - 1] + 1; } else { L[i , j] = Math.Max(L[i - 1 , j], L[i , j - 1]); } } } int lcs = L[m , n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs);} // Driver Codepublic static void Main(){ String X = "abc", Y = "acd"; Console.Write(editDistanceWith2Ops(X, Y));}} // This code is contributed// by 29AjayKumar <?php// PHP program to find Edit Distance// (when only two operations are allowed,// insert and delete) using LCS. function editDistanceWith2Ops($X, $Y){ // Find LCS $m = strlen($X); $n = strlen($Y); $L[$m + 1][$n + 1]; for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } $lcs = $L[$m][$n]; // Edit distance is delete operations + // insert operations. return ($m - $lcs) + ($n - $lcs);} // Driver Code$X = "abc"; $Y = "acd";echo editDistanceWith2Ops($X, $Y); // This code is contributed// by Akanksha Rai?> <script>//Javascript program to find Edit Distance (when only two// operations are allowed, insert and delete) using LCS. function editDistanceWith2Ops(X,Y) { // Find LCS let m = X.length, n = Y.length; let L = new Array(m + 1); for(let i=0;i<L.length;i++) { L[i]=new Array(n+1); for(let j=0;j<L[i].length;j++) { L[i][j]=0; } } for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i][j] = 0; } else if (X[i-1] == Y[j-1]) { L[i][j] = L[i - 1][j - 1] + 1; } else { L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } } let lcs = L[m][n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs); } /* Driver program to test above function */ let X = "abc", Y = "acd"; document.write(editDistanceWith2Ops(X, Y)); // This code is contributed by rag2127</script> Output: 2 Time Complexity: O(m * n) Auxiliary Space: O(m * n) 29AjayKumar Akanksha_Rai ukasp mithunbharadwaj02 rag2127 edit-distance LCS Dynamic Programming Strings Strings Dynamic Programming LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Optimal Substructure Property in Dynamic Programming | DP-2 Optimal Binary Search Tree | DP-24 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 25943, "s": 25915, "text": "\n12 May, 2021" }, { "code": null, "e": 26171, "s": 25943, "text": "In standard Edit Distance where we are allowed 3 operations, insert, delete, and replace. Consider a variation of edit distance where we are allowed only two operations insert and delete, find edit distance in this variation. " }, { "code": null, "e": 26183, "s": 26171, "text": "Examples: " }, { "code": null, "e": 26415, "s": 26183, "text": "Input : str1 = \"cat\", st2 = \"cut\"\nOutput : 2\nWe are allowed to insert and delete. We delete 'a'\nfrom \"cat\" and insert \"u\" to make it \"cut\".\n\nInput : str1 = \"acb\", st2 = \"ab\"\nOutput : 1\nWe can convert \"acb\" to \"ab\" by removing 'c'. " }, { "code": null, "e": 26821, "s": 26415, "text": "One solution is to simply modify the Edit Distance Solution by making two recursive calls instead of three. An interesting solution is based on LCS. 1) Find LCS of two strings. Let the length of LCS be x. 2) Let the length of the first string be m and the length of the second string be n. Our result is (m – x) + (n – x). We basically need to do (m – x) delete operations and (n – x) insert operations. " }, { "code": null, "e": 26825, "s": 26821, "text": "C++" }, { "code": null, "e": 26830, "s": 26825, "text": "Java" }, { "code": null, "e": 26839, "s": 26830, "text": "Python 3" }, { "code": null, "e": 26842, "s": 26839, "text": "C#" }, { "code": null, "e": 26846, "s": 26842, "text": "PHP" }, { "code": null, "e": 26857, "s": 26846, "text": "Javascript" }, { "code": "// CPP program to find Edit Distance (when only two// operations are allowed, insert and delete) using LCS.#include<bits/stdc++.h>using namespace std; int editDistanceWith2Ops(string &X, string &Y){ // Find LCS int m = X.length(), n = Y.length(); int L[m+1][n+1]; for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } int lcs = L[m][n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs);} /* Driver program to test above function */int main(){ string X = \"abc\", Y = \"acd\"; cout << editDistanceWith2Ops(X, Y); return 0;}", "e": 27696, "s": 26857, "text": null }, { "code": "//Java program to find Edit Distance (when only two// operations are allowed, insert and delete) using LCS. class GFG { static int editDistanceWith2Ops(String X, String Y) { // Find LCS int m = X.length(), n = Y.length(); int L[][] = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i][j] = 0; } else if (X.charAt(i - 1) == Y.charAt(j - 1)) { L[i][j] = L[i - 1][j - 1] + 1; } else { L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } } int lcs = L[m][n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs); } /* Driver program to test above function */ public static void main(String[] args) { String X = \"abc\", Y = \"acd\"; System.out.println(editDistanceWith2Ops(X, Y)); }}/* This Java code is contributed by 29AjayKumar*/", "e": 28755, "s": 27696, "text": null }, { "code": "# Python 3 program to find Edit Distance# (when only two operations are allowed,# insert and delete) using LCS. def editDistanceWith2Ops(X, Y): # Find LCS m = len(X) n = len(Y) L = [[0 for x in range(n + 1)] for y in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif (X[i - 1] == Y[j - 1]): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) lcs = L[m][n] # Edit distance is delete operations + # insert operations. return (m - lcs) + (n - lcs) # Driver Codeif __name__ == \"__main__\": X = \"abc\" Y = \"acd\" print(editDistanceWith2Ops(X, Y)) # This code is contributed by ita_c", "e": 29574, "s": 28755, "text": null }, { "code": "// C# program to find Edit Distance// (when only two operations are// allowed, insert and delete) using LCS.using System; class GFG{ static int editDistanceWith2Ops(String X, String Y){ // Find LCS int m = X.Length, n = Y.Length; int [ , ]L = new int[m + 1 , n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i , j] = 0; } else if (X[i - 1] == Y[j - 1]) { L[i , j] = L[i - 1 , j - 1] + 1; } else { L[i , j] = Math.Max(L[i - 1 , j], L[i , j - 1]); } } } int lcs = L[m , n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs);} // Driver Codepublic static void Main(){ String X = \"abc\", Y = \"acd\"; Console.Write(editDistanceWith2Ops(X, Y));}} // This code is contributed// by 29AjayKumar", "e": 30614, "s": 29574, "text": null }, { "code": "<?php// PHP program to find Edit Distance// (when only two operations are allowed,// insert and delete) using LCS. function editDistanceWith2Ops($X, $Y){ // Find LCS $m = strlen($X); $n = strlen($Y); $L[$m + 1][$n + 1]; for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } $lcs = $L[$m][$n]; // Edit distance is delete operations + // insert operations. return ($m - $lcs) + ($n - $lcs);} // Driver Code$X = \"abc\"; $Y = \"acd\";echo editDistanceWith2Ops($X, $Y); // This code is contributed// by Akanksha Rai?>", "e": 31465, "s": 30614, "text": null }, { "code": "<script>//Javascript program to find Edit Distance (when only two// operations are allowed, insert and delete) using LCS. function editDistanceWith2Ops(X,Y) { // Find LCS let m = X.length, n = Y.length; let L = new Array(m + 1); for(let i=0;i<L.length;i++) { L[i]=new Array(n+1); for(let j=0;j<L[i].length;j++) { L[i][j]=0; } } for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i][j] = 0; } else if (X[i-1] == Y[j-1]) { L[i][j] = L[i - 1][j - 1] + 1; } else { L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } } let lcs = L[m][n]; // Edit distance is delete operations + // insert operations. return (m - lcs) + (n - lcs); } /* Driver program to test above function */ let X = \"abc\", Y = \"acd\"; document.write(editDistanceWith2Ops(X, Y)); // This code is contributed by rag2127</script>", "e": 32603, "s": 31465, "text": null }, { "code": null, "e": 32611, "s": 32603, "text": "Output:" }, { "code": null, "e": 32613, "s": 32611, "text": "2" }, { "code": null, "e": 32666, "s": 32613, "text": "Time Complexity: O(m * n) Auxiliary Space: O(m * n) " }, { "code": null, "e": 32678, "s": 32666, "text": "29AjayKumar" }, { "code": null, "e": 32691, "s": 32678, "text": "Akanksha_Rai" }, { "code": null, "e": 32697, "s": 32691, "text": "ukasp" }, { "code": null, "e": 32715, "s": 32697, "text": "mithunbharadwaj02" }, { "code": null, "e": 32723, "s": 32715, "text": "rag2127" }, { "code": null, "e": 32737, "s": 32723, "text": "edit-distance" }, { "code": null, "e": 32741, "s": 32737, "text": "LCS" }, { "code": null, "e": 32761, "s": 32741, "text": "Dynamic Programming" }, { "code": null, "e": 32769, "s": 32761, "text": "Strings" }, { "code": null, "e": 32777, "s": 32769, "text": "Strings" }, { "code": null, "e": 32797, "s": 32777, "text": "Dynamic Programming" }, { "code": null, "e": 32801, "s": 32797, "text": "LCS" }, { "code": null, "e": 32899, "s": 32801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32942, "s": 32899, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 33002, "s": 32942, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 33037, "s": 33002, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 33058, "s": 33037, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 33114, "s": 33058, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 33160, "s": 33114, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33185, "s": 33160, "text": "Reverse a string in Java" }, { "code": null, "e": 33245, "s": 33185, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33260, "s": 33245, "text": "C++ Data Types" } ]
jQuery UI dialog destroy() Method - GeeksforGeeks
13 Jan, 2021 destroy() Method is used to destroy the dialog. This method does not accept any argument Syntax: $( ".selector" ).dialog("destroy"); Approach: First, add jQuery UI scripts needed for your project. <link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script> Example: HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").dialog({ autoOpen: false, }); $("#geeks").click(function () { $("#gfg").dialog("destroy"); }); }); </script></head> <body> <div id="gfg"> Jquery UI| destroy dialog method </div> <button id="geeks">Open Dialog</button></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-UI HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 52596, "s": 52568, "text": "\n13 Jan, 2021" }, { "code": null, "e": 52685, "s": 52596, "text": "destroy() Method is used to destroy the dialog. This method does not accept any argument" }, { "code": null, "e": 52693, "s": 52685, "text": "Syntax:" }, { "code": null, "e": 52729, "s": 52693, "text": "$( \".selector\" ).dialog(\"destroy\");" }, { "code": null, "e": 52793, "s": 52729, "text": "Approach: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 53034, "s": 52793, "text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>" }, { "code": null, "e": 53043, "s": 53034, "text": "Example:" }, { "code": null, "e": 53048, "s": 53043, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").dialog({ autoOpen: false, }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"destroy\"); }); }); </script></head> <body> <div id=\"gfg\"> Jquery UI| destroy dialog method </div> <button id=\"geeks\">Open Dialog</button></body> </html>", "e": 53757, "s": 53048, "text": null }, { "code": null, "e": 53765, "s": 53757, "text": "Output:" }, { "code": null, "e": 53902, "s": 53765, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 53912, "s": 53902, "text": "jQuery-UI" }, { "code": null, "e": 53917, "s": 53912, "text": "HTML" }, { "code": null, "e": 53924, "s": 53917, "text": "JQuery" }, { "code": null, "e": 53941, "s": 53924, "text": "Web Technologies" }, { "code": null, "e": 53946, "s": 53941, "text": "HTML" }, { "code": null, "e": 54044, "s": 53946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54106, "s": 54044, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 54156, "s": 54106, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 54204, "s": 54156, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 54264, "s": 54204, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 54317, "s": 54264, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 54363, "s": 54317, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 54392, "s": 54363, "text": "Form validation using jQuery" }, { "code": null, "e": 54455, "s": 54392, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 54532, "s": 54455, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
How to sorting an array without using loops in Node.js ? - GeeksforGeeks
31 Aug, 2020 The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() Method of JavaScript API, however, a string of code can’t be passed to get it executed. Syntax: setInterval(timerFunction, millisecondsTime); Parameter: It accepts two parameters which are mentioned above and described below: timerFunction <function>: It is the function to be executed. millisecondsTime <Time>: It indicates a period of time between each execution. The setTimeout() method is used to schedule code execution after waiting for a specified number of milliseconds. It is somewhat like window.setTimeout() Method of JavaScript API, however a string of code can’t be passed to get it executed. Syntax: setTimeout(timerFunction, millisecondsTime); Parameter: It accepts two parameters which are mentioned above and described below: timerFunction <function>: It is the function to be executed. timerFunction <function>: It is the function to be executed. millisecondsTime <Time>: It indicates a period of time between each execution. millisecondsTime <Time>: It indicates a period of time between each execution. Examples: Input: Array = [ 46, 55, 2, 100, 0, 500 ] Output: [0, 2, 46, 55, 100, 500] Input: Array = [8, 9, 2, 7, 18, 5, 25] Output: [ 2, 5, 7, 8, 9, 18, 25 ] Approach: The sorting requires visiting each element and then performing some operations, which requires for loop to visit those elements. Now here, we can use setInterval() method to visit all those elements, and perform those operations. The below code illustrates the above approach in JavaScript Language. File Name: Index.js const arr = [46, 55, 2, 100, 0, 500];const l = arr.length;var arr1 = [];var j = 0; var myVar1 = setInterval(myTimer1, 1); function myTimer1() { const min = Math.min.apply(null, arr); arr1.push(min); // arr[arr.indexOf(min)]=Math.max.apply(null, arr); arr.splice(arr.indexOf(min), 1); j++; if(j == l){ clearInterval(myVar1); console.log(arr1); }} Run Index.js file either on the online compiler or follow the following: node index.js Output: [0, 2, 46, 55, 100, 500] [0, 2, 46, 55, 100, 500] Node.js-Misc JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 26805, "s": 26777, "text": "\n31 Aug, 2020" }, { "code": null, "e": 27032, "s": 26805, "text": "The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() Method of JavaScript API, however, a string of code can’t be passed to get it executed." }, { "code": null, "e": 27040, "s": 27032, "text": "Syntax:" }, { "code": null, "e": 27086, "s": 27040, "text": "setInterval(timerFunction, millisecondsTime);" }, { "code": null, "e": 27170, "s": 27086, "text": "Parameter: It accepts two parameters which are mentioned above and described below:" }, { "code": null, "e": 27231, "s": 27170, "text": "timerFunction <function>: It is the function to be executed." }, { "code": null, "e": 27310, "s": 27231, "text": "millisecondsTime <Time>: It indicates a period of time between each execution." }, { "code": null, "e": 27550, "s": 27310, "text": "The setTimeout() method is used to schedule code execution after waiting for a specified number of milliseconds. It is somewhat like window.setTimeout() Method of JavaScript API, however a string of code can’t be passed to get it executed." }, { "code": null, "e": 27558, "s": 27550, "text": "Syntax:" }, { "code": null, "e": 27603, "s": 27558, "text": "setTimeout(timerFunction, millisecondsTime);" }, { "code": null, "e": 27687, "s": 27603, "text": "Parameter: It accepts two parameters which are mentioned above and described below:" }, { "code": null, "e": 27748, "s": 27687, "text": "timerFunction <function>: It is the function to be executed." }, { "code": null, "e": 27809, "s": 27748, "text": "timerFunction <function>: It is the function to be executed." }, { "code": null, "e": 27888, "s": 27809, "text": "millisecondsTime <Time>: It indicates a period of time between each execution." }, { "code": null, "e": 27967, "s": 27888, "text": "millisecondsTime <Time>: It indicates a period of time between each execution." }, { "code": null, "e": 27977, "s": 27967, "text": "Examples:" }, { "code": null, "e": 28127, "s": 27977, "text": "Input: Array = [ 46, 55, 2, 100, 0, 500 ]\nOutput: [0, 2, 46, 55, 100, 500]\n\nInput: Array = [8, 9, 2, 7, 18, 5, 25]\nOutput: [ 2, 5, 7, 8, 9, 18, 25 ]\n" }, { "code": null, "e": 28266, "s": 28127, "text": "Approach: The sorting requires visiting each element and then performing some operations, which requires for loop to visit those elements." }, { "code": null, "e": 28367, "s": 28266, "text": "Now here, we can use setInterval() method to visit all those elements, and perform those operations." }, { "code": null, "e": 28437, "s": 28367, "text": "The below code illustrates the above approach in JavaScript Language." }, { "code": null, "e": 28457, "s": 28437, "text": "File Name: Index.js" }, { "code": "const arr = [46, 55, 2, 100, 0, 500];const l = arr.length;var arr1 = [];var j = 0; var myVar1 = setInterval(myTimer1, 1); function myTimer1() { const min = Math.min.apply(null, arr); arr1.push(min); // arr[arr.indexOf(min)]=Math.max.apply(null, arr); arr.splice(arr.indexOf(min), 1); j++; if(j == l){ clearInterval(myVar1); console.log(arr1); }}", "e": 28838, "s": 28457, "text": null }, { "code": null, "e": 28911, "s": 28838, "text": "Run Index.js file either on the online compiler or follow the following:" }, { "code": null, "e": 28925, "s": 28911, "text": "node index.js" }, { "code": null, "e": 28933, "s": 28925, "text": "Output:" }, { "code": null, "e": 28959, "s": 28933, "text": "[0, 2, 46, 55, 100, 500]\n" }, { "code": null, "e": 28985, "s": 28959, "text": "[0, 2, 46, 55, 100, 500]\n" }, { "code": null, "e": 28998, "s": 28985, "text": "Node.js-Misc" }, { "code": null, "e": 29009, "s": 28998, "text": "JavaScript" }, { "code": null, "e": 29017, "s": 29009, "text": "Node.js" }, { "code": null, "e": 29034, "s": 29017, "text": "Web Technologies" }, { "code": null, "e": 29132, "s": 29034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29172, "s": 29132, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29233, "s": 29172, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29274, "s": 29233, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29296, "s": 29274, "text": "JavaScript | Promises" }, { "code": null, "e": 29350, "s": 29296, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29383, "s": 29350, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29431, "s": 29383, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29464, "s": 29431, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 29494, "s": 29464, "text": "Node.js fs.writeFile() Method" } ]
React-Bootstrap Spinner Component - GeeksforGeeks
30 Apr, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. Spinner Component provides a way to show the loading effect. We can use it to show the loading state, whenever required in our application. We can use the following approach in ReactJS to use the react-bootstrap Spinner Component. Spinner Props: animation: It is used to define the type of animation for the spinner. as: It can be used as a custom element type for this component. children: It is used to wrap child elements or components, this component can be used. role: In the menu component, it is the ARIA accessible role applied to it. size: It is used to define the size of the component. variant: It is used to define the visual style of our spinner component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Spinner from 'react-bootstrap/Spinner'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Spinner Component</h4> With Border Animation: <Spinner animation="border" variant="primary" /> <br/> With Grow Animation: <Spinner animation="grow" variant="warning" /> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/spinners/ React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26384, "s": 26071, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Spinner Component provides a way to show the loading effect. We can use it to show the loading state, whenever required in our application. We can use the following approach in ReactJS to use the react-bootstrap Spinner Component." }, { "code": null, "e": 26399, "s": 26384, "text": "Spinner Props:" }, { "code": null, "e": 26470, "s": 26399, "text": "animation: It is used to define the type of animation for the spinner." }, { "code": null, "e": 26534, "s": 26470, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 26621, "s": 26534, "text": "children: It is used to wrap child elements or components, this component can be used." }, { "code": null, "e": 26696, "s": 26621, "text": "role: In the menu component, it is the ARIA accessible role applied to it." }, { "code": null, "e": 26750, "s": 26696, "text": "size: It is used to define the size of the component." }, { "code": null, "e": 26823, "s": 26750, "text": "variant: It is used to define the visual style of our spinner component." }, { "code": null, "e": 26907, "s": 26823, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 26957, "s": 26907, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 27052, "s": 26957, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 27116, "s": 27052, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 27148, "s": 27116, "text": "npx create-react-app foldername" }, { "code": null, "e": 27261, "s": 27148, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 27361, "s": 27261, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 27375, "s": 27361, "text": "cd foldername" }, { "code": null, "e": 27530, "s": 27375, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 27635, "s": 27530, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 27686, "s": 27635, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 27738, "s": 27686, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27756, "s": 27738, "text": "Project Structure" }, { "code": null, "e": 27886, "s": 27756, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27893, "s": 27886, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Spinner from 'react-bootstrap/Spinner'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Spinner Component</h4> With Border Animation: <Spinner animation=\"border\" variant=\"primary\" /> <br/> With Grow Animation: <Spinner animation=\"grow\" variant=\"warning\" /> </div> );}", "e": 28344, "s": 27893, "text": null }, { "code": null, "e": 28457, "s": 28344, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28467, "s": 28457, "text": "npm start" }, { "code": null, "e": 28566, "s": 28467, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28632, "s": 28566, "text": "Reference: https://react-bootstrap.github.io/components/spinners/" }, { "code": null, "e": 28648, "s": 28632, "text": "React-Bootstrap" }, { "code": null, "e": 28656, "s": 28648, "text": "ReactJS" }, { "code": null, "e": 28673, "s": 28656, "text": "Web Technologies" }, { "code": null, "e": 28771, "s": 28673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28798, "s": 28771, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28840, "s": 28798, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28878, "s": 28840, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28913, "s": 28878, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28971, "s": 28913, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 29011, "s": 28971, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29044, "s": 29011, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29089, "s": 29044, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29139, "s": 29089, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
DoubleAdder reset() method in Java with Examples - GeeksforGeeks
28 Jan, 2019 The java.DoubleAdder.reset() is an inbuilt method in java that resets variables maintaining the sum to zero. When the object of the class is created its initial value is zero. Syntax: public void reset() Parameters: This method does not accepts any parameter. Return Value: The method returns the reset value. Below programs illustrate the above method: Program 1: // Program to demonstrate the reset() method import java.lang.*;import java.util.concurrent.atomic.DoubleAdder; public class GFG { public static void main(String args[]) { DoubleAdder num = new DoubleAdder(); // add operation on num num.add(42); num.add(10); // reset operation on variable num num.reset(); // Print after add operation System.out.println(" the current value is: " + num); }} the current value is: 0.0 Program 2: // Program to demonstrate the reset() method import java.lang.*;import java.util.concurrent.atomic.DoubleAdder; public class GFG { public static void main(String args[]) { DoubleAdder num = new DoubleAdder(); // add operation on num num.add(10); // reset operation on variable num num.reset(); // Print after add operation System.out.println(" the current value is: " + num); }} the current value is: 0.0 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/DoubleAdder.html#reset– Java-DoubleAdder Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26161, "s": 26133, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26337, "s": 26161, "text": "The java.DoubleAdder.reset() is an inbuilt method in java that resets variables maintaining the sum to zero. When the object of the class is created its initial value is zero." }, { "code": null, "e": 26345, "s": 26337, "text": "Syntax:" }, { "code": null, "e": 26366, "s": 26345, "text": "public void reset()\n" }, { "code": null, "e": 26422, "s": 26366, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 26472, "s": 26422, "text": "Return Value: The method returns the reset value." }, { "code": null, "e": 26516, "s": 26472, "text": "Below programs illustrate the above method:" }, { "code": null, "e": 26527, "s": 26516, "text": "Program 1:" }, { "code": "// Program to demonstrate the reset() method import java.lang.*;import java.util.concurrent.atomic.DoubleAdder; public class GFG { public static void main(String args[]) { DoubleAdder num = new DoubleAdder(); // add operation on num num.add(42); num.add(10); // reset operation on variable num num.reset(); // Print after add operation System.out.println(\" the current value is: \" + num); }}", "e": 26992, "s": 26527, "text": null }, { "code": null, "e": 27019, "s": 26992, "text": "the current value is: 0.0\n" }, { "code": null, "e": 27030, "s": 27019, "text": "Program 2:" }, { "code": "// Program to demonstrate the reset() method import java.lang.*;import java.util.concurrent.atomic.DoubleAdder; public class GFG { public static void main(String args[]) { DoubleAdder num = new DoubleAdder(); // add operation on num num.add(10); // reset operation on variable num num.reset(); // Print after add operation System.out.println(\" the current value is: \" + num); }}", "e": 27475, "s": 27030, "text": null }, { "code": null, "e": 27502, "s": 27475, "text": "the current value is: 0.0\n" }, { "code": null, "e": 27607, "s": 27502, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/DoubleAdder.html#reset–" }, { "code": null, "e": 27624, "s": 27607, "text": "Java-DoubleAdder" }, { "code": null, "e": 27639, "s": 27624, "text": "Java-Functions" }, { "code": null, "e": 27644, "s": 27639, "text": "Java" }, { "code": null, "e": 27649, "s": 27644, "text": "Java" }, { "code": null, "e": 27747, "s": 27649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27798, "s": 27747, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27828, "s": 27798, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27847, "s": 27828, "text": "Interfaces in Java" }, { "code": null, "e": 27862, "s": 27847, "text": "Stream In Java" }, { "code": null, "e": 27893, "s": 27862, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27911, "s": 27893, "text": "ArrayList in Java" }, { "code": null, "e": 27943, "s": 27911, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27963, "s": 27943, "text": "Stack Class in Java" }, { "code": null, "e": 27995, "s": 27963, "text": "Multidimensional Arrays in Java" } ]
Usage of Enum and Switch Keyword in Java - GeeksforGeeks
28 Feb, 2022 An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default. enum constants are accessed using dot syntax. An enum class can have attributes and methods, in addition to constants. You cannot create objects of an enum class, and it cannot extend other classes. An enum class can only implement interfaces. Example: Java // Java Program to show working of Enum// Keyword when declared outside the Class enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;} public class temp { // Driver method public static void main(String[] args) { Days x = Days.FRIDAY; System.out.println(x); }} FRIDAY The Switch statement is helpful when a user has a number of choices and wants to perform a different task for each choice. The Switch statement allows the testing of a variable for equality against a list of values. Each value is known as a case. A switch Case statement is generally used with a break statement but it is optional. Example: Java // Java Program to show working// of Switch statement public class Example_Switch { public static void main(String[] args) { // Declare a variable for switch statement int num = 50; // Switch keyword switch (num) { // Case statements case 10: System.out.println("10"); break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; // Default case statement default: System.out.println("Other than 10, 20 or 30"); } }} Other than 10, 20 or 30 We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive. Below are some examples to show working of Enum with Switch statement. Example 1: Use of Enum with Switch statement when Enum is outside the main class Java // Java Program to show the// working of Enum keyword// with Switch statement // Enum keyword declared outside main classenum Cars { BMW, JEEP, AUDI, VOLKSWAGEN, NANO, FIAT;} // Main classpublic class Main { public static void main(String args[]) { // Declaring Enum variable Cars c; c = Cars.AUDI; // Switch keyword switch (c) { // Case statements case BMW: System.out.println("You choose BMW !"); break; case JEEP: System.out.println("You choose JEEP !"); break; case AUDI: System.out.println("You choose AUDI !"); break; case VOLKSWAGEN: System.out.println("You choose VOLKSWAGEN !"); break; case NANO: System.out.println("You choose NANO !"); break; case FIAT: System.out.println("You choose FIAT !"); default: System.out.println("NEW BRAND'S CAR."); break; } }} You choose AUDI ! In the above example, we show how the Enum keyword works along with Switch case statements when Enum is declared outside the main class. Example 2: Use of Enum with Switch statement when Enum is within the main class Java // Java Program to Show// working of Enum keyword// with Switch statement // Main classpublic class MainClass { // Declaring Enum keyword // inside main class enum Webseries { GOT, Breakingbad, Lucifer, Boys, Mirzapur, Moneyheist; } public static void main(String[] args) { // Declaring and Assigning choice to variable 'wb' Webseries wb = Webseries.Mirzapur; // Switch Keyword switch (wb) { // Case statements case GOT: System.out.println("Game of Thrones selected"); break; case Breakingbad: System.out.println("Breaking Bad selected"); break; case Lucifer: System.out.println("Lucifer selected"); break; case Boys: System.out.println("Boys selected"); break; case Mirzapur: System.out.println("Mirzapur selected"); break; case Moneyheist: System.out.println("Money Heist selected"); break; default: System.out.println("You are outdated !!!"); break; } }} Mirzapur selected In the above example, we show how the Enum keyword works along with Switch case statements when Enum is declared within main class. nishkarshgandhi philipmallin Java-keyword Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n28 Feb, 2022" }, { "code": null, "e": 25515, "s": 25225, "text": "An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. " }, { "code": null, "e": 25572, "s": 25515, "text": "enum constants are public, static, and final by default." }, { "code": null, "e": 25618, "s": 25572, "text": "enum constants are accessed using dot syntax." }, { "code": null, "e": 25691, "s": 25618, "text": "An enum class can have attributes and methods, in addition to constants." }, { "code": null, "e": 25771, "s": 25691, "text": "You cannot create objects of an enum class, and it cannot extend other classes." }, { "code": null, "e": 25816, "s": 25771, "text": "An enum class can only implement interfaces." }, { "code": null, "e": 25825, "s": 25816, "text": "Example:" }, { "code": null, "e": 25830, "s": 25825, "text": "Java" }, { "code": "// Java Program to show working of Enum// Keyword when declared outside the Class enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;} public class temp { // Driver method public static void main(String[] args) { Days x = Days.FRIDAY; System.out.println(x); }}", "e": 26163, "s": 25830, "text": null }, { "code": null, "e": 26170, "s": 26163, "text": "FRIDAY" }, { "code": null, "e": 26503, "s": 26170, "text": "The Switch statement is helpful when a user has a number of choices and wants to perform a different task for each choice. The Switch statement allows the testing of a variable for equality against a list of values. Each value is known as a case. A switch Case statement is generally used with a break statement but it is optional. " }, { "code": null, "e": 26512, "s": 26503, "text": "Example:" }, { "code": null, "e": 26517, "s": 26512, "text": "Java" }, { "code": "// Java Program to show working// of Switch statement public class Example_Switch { public static void main(String[] args) { // Declare a variable for switch statement int num = 50; // Switch keyword switch (num) { // Case statements case 10: System.out.println(\"10\"); break; case 20: System.out.println(\"20\"); break; case 30: System.out.println(\"30\"); break; // Default case statement default: System.out.println(\"Other than 10, 20 or 30\"); } }}", "e": 27129, "s": 26517, "text": null }, { "code": null, "e": 27153, "s": 27129, "text": "Other than 10, 20 or 30" }, { "code": null, "e": 27349, "s": 27153, "text": "We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive. Below are some examples to show working of Enum with Switch statement." }, { "code": null, "e": 27430, "s": 27349, "text": "Example 1: Use of Enum with Switch statement when Enum is outside the main class" }, { "code": null, "e": 27435, "s": 27430, "text": "Java" }, { "code": "// Java Program to show the// working of Enum keyword// with Switch statement // Enum keyword declared outside main classenum Cars { BMW, JEEP, AUDI, VOLKSWAGEN, NANO, FIAT;} // Main classpublic class Main { public static void main(String args[]) { // Declaring Enum variable Cars c; c = Cars.AUDI; // Switch keyword switch (c) { // Case statements case BMW: System.out.println(\"You choose BMW !\"); break; case JEEP: System.out.println(\"You choose JEEP !\"); break; case AUDI: System.out.println(\"You choose AUDI !\"); break; case VOLKSWAGEN: System.out.println(\"You choose VOLKSWAGEN !\"); break; case NANO: System.out.println(\"You choose NANO !\"); break; case FIAT: System.out.println(\"You choose FIAT !\"); default: System.out.println(\"NEW BRAND'S CAR.\"); break; } }}", "e": 28472, "s": 27435, "text": null }, { "code": null, "e": 28490, "s": 28472, "text": "You choose AUDI !" }, { "code": null, "e": 28627, "s": 28490, "text": "In the above example, we show how the Enum keyword works along with Switch case statements when Enum is declared outside the main class." }, { "code": null, "e": 28707, "s": 28627, "text": "Example 2: Use of Enum with Switch statement when Enum is within the main class" }, { "code": null, "e": 28712, "s": 28707, "text": "Java" }, { "code": "// Java Program to Show// working of Enum keyword// with Switch statement // Main classpublic class MainClass { // Declaring Enum keyword // inside main class enum Webseries { GOT, Breakingbad, Lucifer, Boys, Mirzapur, Moneyheist; } public static void main(String[] args) { // Declaring and Assigning choice to variable 'wb' Webseries wb = Webseries.Mirzapur; // Switch Keyword switch (wb) { // Case statements case GOT: System.out.println(\"Game of Thrones selected\"); break; case Breakingbad: System.out.println(\"Breaking Bad selected\"); break; case Lucifer: System.out.println(\"Lucifer selected\"); break; case Boys: System.out.println(\"Boys selected\"); break; case Mirzapur: System.out.println(\"Mirzapur selected\"); break; case Moneyheist: System.out.println(\"Money Heist selected\"); break; default: System.out.println(\"You are outdated !!!\"); break; } }}", "e": 29882, "s": 28712, "text": null }, { "code": null, "e": 29900, "s": 29882, "text": "Mirzapur selected" }, { "code": null, "e": 30032, "s": 29900, "text": "In the above example, we show how the Enum keyword works along with Switch case statements when Enum is declared within main class." }, { "code": null, "e": 30048, "s": 30032, "text": "nishkarshgandhi" }, { "code": null, "e": 30061, "s": 30048, "text": "philipmallin" }, { "code": null, "e": 30074, "s": 30061, "text": "Java-keyword" }, { "code": null, "e": 30079, "s": 30074, "text": "Java" }, { "code": null, "e": 30084, "s": 30079, "text": "Java" }, { "code": null, "e": 30182, "s": 30084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30197, "s": 30182, "text": "Stream In Java" }, { "code": null, "e": 30218, "s": 30197, "text": "Constructors in Java" }, { "code": null, "e": 30237, "s": 30218, "text": "Exceptions in Java" }, { "code": null, "e": 30267, "s": 30237, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30313, "s": 30267, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30330, "s": 30313, "text": "Generics in Java" }, { "code": null, "e": 30351, "s": 30330, "text": "Introduction to Java" }, { "code": null, "e": 30394, "s": 30351, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30430, "s": 30394, "text": "Internal Working of HashMap in Java" } ]
Setting up Java Competitive Programming Environment - GeeksforGeeks
10 May, 2022 An operating system is required to be installed on your system. here we will be discussing the setup in windows. However, you can choose any operating system. Install JDK (Java Development Kit) JDK, is a program that allows you to write Java code from the comfort of your desktop. It contains a variety of tools that are very useful for creating, running, and optimizing your Java code. Follow the steps to download JDK: Download the latest version of JDK. After downloading, install the JDK by following through the prompts after running the installer. There are quite a number of good text editors available these days like VS Code, Sublime Text, Atom, Notepad++, etc. However, this article will use Sublime Text 3 because it being lightweight, minimally aesthetic, and high functionalities. Download sublime text and install it to set up a java build system. Step A: Setting up a Java Build System Follow the steps below to set up the build system for JAVA so that you can compile java code where here e will be demonstrating over windows operating systems Go to command prompt and type “where java” and copy the path of the JDK bin folder which looks like “C:\Program Files\Java\jdk1.8.0_251\bin\”Now, open the sublime text and go to Tools > Build System > New Build System.A new file must appear where now you need to paste the JSON object below in that fileReplace the path variable with the path that you got in Step 1 Go to command prompt and type “where java” and copy the path of the JDK bin folder which looks like “C:\Program Files\Java\jdk1.8.0_251\bin\” Now, open the sublime text and go to Tools > Build System > New Build System. A new file must appear where now you need to paste the JSON object below in that file Replace the path variable with the path that you got in Step 1 { "cmd": ["javac", "$file_name", "&&", "java" ,"$file_base_name"], "selector": "source.java", "file_regex": "^\\s*File \"(...*?)\", line ([0-9]*)", "path" : "C:\\Program Files\\Java\\jdk1.8.0_251\\bin\\", "shell":true } Now follow these three simple steps Save the file by pressing CTRL + S and save by giving a name for example “MYJAVA” to the build system at the folder which is prompted.Remember that the file extension of the build system should be “sublime-build” otherwise you will not be able to see the option for the build system which you created.Go to Tools > Build System, you must see a build system with the name with which you saved the file in Step 4, in this case, “MYJAVA”.Mark that build system as tick by clicking on it. Save the file by pressing CTRL + S and save by giving a name for example “MYJAVA” to the build system at the folder which is prompted. Remember that the file extension of the build system should be “sublime-build” otherwise you will not be able to see the option for the build system which you created. Go to Tools > Build System, you must see a build system with the name with which you saved the file in Step 4, in this case, “MYJAVA”. Mark that build system as tick by clicking on it. If the above steps are followed then the build system is ready to use. Now the task is in Step B: Set up the sublime tabs 1. During contests, it becomes tedious to switch between the tabs, so you can set up the tabs so that you can view each one. Follow the steps to take so: Close all the tabs if any file opened. Go to View > layout > Columns 3. You will see the layout something like below. 2. Be in the first column and go to View > Groups > Max Column 2. You will see the layout something like below. 3. In this set up the left window will contain the code file and the right upper window will contain the input file and the left lower window will contain the output file as we will see further. Illustration: Write the hello world program 1. Create a folder that will contain three files, a java file named hello.java, an input file named input.txt which will be used for taking inputs, and an output file used for storing the outputs named output.txt, make sure all the three files are in the same folder. 2. In the screen set up that we did earlier go to file > open file and open the java file in the left window and open the input file in the right upper window and open the output file in the right lower window. Something like below 3. Paste the below standard template for JAVA containing the hello world program in the java file make sure that the file name and the class name are the same and make the class public. The code will take a string input from “input.txt” and will print it in the “output.txt” by appending it to “world!”. Example: Java // Java Program that is been setup in Sublime Text// for Competitive Coding // Importing input output classesimport java.io.*;// Importing Scanner class from java.util packageimport java.util.Scanner; // Main Classclass hello { // Main driver method public static void main(String[] args) { // Setting up the input stream // You can use buffered reader too Scanner read = new Scanner(System.in); // If You Are Running Your Code // in Sublime Text then set The // System Out to output.txt and // Input Stream to input.txt // otherwise leave it as standard // ones for ONLINE JUDGE if (System.getProperty("ONLINE_JUDGE") == null) { // Try block to check for exceptions try { // Sets the Output Stream // to output.txt System.setOut(new PrintStream( new FileOutputStream("output.txt"))); // Change the input stream // to input.txt read = new Scanner(new File("input.txt")); } // Catch block to handle the exceptions catch (Exception e) { } } // Your Code Start Here // Read input String inp = read.nextLine(); // Print output System.out.println(inp + " World!"); }} Output: Write something like “Hello” in the “input.txt”. Make sure you have selected the correct build system that we built earlier in Tools > Build System. Now hit CTRL + B or go to Tools > Build to compile your code. Your code must compile and something should get printed in your “output.txt” file. Something like below. If a window like the above is seen then your setup is complete and ready to code JAVA in sublime and submit your code on ONLINE JUDGES without worrying about changing the input and output streams as it is already been taken care of. One can go to preferences and change the font or theme as you like. rajrk2024 Java-Competitive-Programming Competitive Programming Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Check whether bitwise AND of a number with any subset of an array is zero or not Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26255, "s": 26227, "text": "\n10 May, 2022" }, { "code": null, "e": 26676, "s": 26255, "text": "An operating system is required to be installed on your system. here we will be discussing the setup in windows. However, you can choose any operating system. Install JDK (Java Development Kit) JDK, is a program that allows you to write Java code from the comfort of your desktop. It contains a variety of tools that are very useful for creating, running, and optimizing your Java code. Follow the steps to download JDK:" }, { "code": null, "e": 26712, "s": 26676, "text": "Download the latest version of JDK." }, { "code": null, "e": 26809, "s": 26712, "text": "After downloading, install the JDK by following through the prompts after running the installer." }, { "code": null, "e": 27117, "s": 26809, "text": "There are quite a number of good text editors available these days like VS Code, Sublime Text, Atom, Notepad++, etc. However, this article will use Sublime Text 3 because it being lightweight, minimally aesthetic, and high functionalities. Download sublime text and install it to set up a java build system." }, { "code": null, "e": 27156, "s": 27117, "text": "Step A: Setting up a Java Build System" }, { "code": null, "e": 27315, "s": 27156, "text": "Follow the steps below to set up the build system for JAVA so that you can compile java code where here e will be demonstrating over windows operating systems" }, { "code": null, "e": 27681, "s": 27315, "text": "Go to command prompt and type “where java” and copy the path of the JDK bin folder which looks like “C:\\Program Files\\Java\\jdk1.8.0_251\\bin\\”Now, open the sublime text and go to Tools > Build System > New Build System.A new file must appear where now you need to paste the JSON object below in that fileReplace the path variable with the path that you got in Step 1" }, { "code": null, "e": 27823, "s": 27681, "text": "Go to command prompt and type “where java” and copy the path of the JDK bin folder which looks like “C:\\Program Files\\Java\\jdk1.8.0_251\\bin\\”" }, { "code": null, "e": 27901, "s": 27823, "text": "Now, open the sublime text and go to Tools > Build System > New Build System." }, { "code": null, "e": 27987, "s": 27901, "text": "A new file must appear where now you need to paste the JSON object below in that file" }, { "code": null, "e": 28050, "s": 27987, "text": "Replace the path variable with the path that you got in Step 1" }, { "code": null, "e": 28275, "s": 28050, "text": "{ \n\"cmd\": [\"javac\", \"$file_name\", \"&&\", \"java\" ,\"$file_base_name\"], \n\"selector\": \"source.java\",\n\"file_regex\": \"^\\\\s*File \\\"(...*?)\\\", line ([0-9]*)\", \n\"path\" : \"C:\\\\Program Files\\\\Java\\\\jdk1.8.0_251\\\\bin\\\\\",\n\"shell\":true\n}" }, { "code": null, "e": 28311, "s": 28275, "text": "Now follow these three simple steps" }, { "code": null, "e": 28796, "s": 28311, "text": "Save the file by pressing CTRL + S and save by giving a name for example “MYJAVA” to the build system at the folder which is prompted.Remember that the file extension of the build system should be “sublime-build” otherwise you will not be able to see the option for the build system which you created.Go to Tools > Build System, you must see a build system with the name with which you saved the file in Step 4, in this case, “MYJAVA”.Mark that build system as tick by clicking on it." }, { "code": null, "e": 28931, "s": 28796, "text": "Save the file by pressing CTRL + S and save by giving a name for example “MYJAVA” to the build system at the folder which is prompted." }, { "code": null, "e": 29099, "s": 28931, "text": "Remember that the file extension of the build system should be “sublime-build” otherwise you will not be able to see the option for the build system which you created." }, { "code": null, "e": 29234, "s": 29099, "text": "Go to Tools > Build System, you must see a build system with the name with which you saved the file in Step 4, in this case, “MYJAVA”." }, { "code": null, "e": 29284, "s": 29234, "text": "Mark that build system as tick by clicking on it." }, { "code": null, "e": 29374, "s": 29284, "text": "If the above steps are followed then the build system is ready to use. Now the task is in" }, { "code": null, "e": 29406, "s": 29374, "text": "Step B: Set up the sublime tabs" }, { "code": null, "e": 29560, "s": 29406, "text": "1. During contests, it becomes tedious to switch between the tabs, so you can set up the tabs so that you can view each one. Follow the steps to take so:" }, { "code": null, "e": 29599, "s": 29560, "text": "Close all the tabs if any file opened." }, { "code": null, "e": 29678, "s": 29599, "text": "Go to View > layout > Columns 3. You will see the layout something like below." }, { "code": null, "e": 29790, "s": 29678, "text": "2. Be in the first column and go to View > Groups > Max Column 2. You will see the layout something like below." }, { "code": null, "e": 29985, "s": 29790, "text": "3. In this set up the left window will contain the code file and the right upper window will contain the input file and the left lower window will contain the output file as we will see further." }, { "code": null, "e": 30029, "s": 29985, "text": "Illustration: Write the hello world program" }, { "code": null, "e": 30297, "s": 30029, "text": "1. Create a folder that will contain three files, a java file named hello.java, an input file named input.txt which will be used for taking inputs, and an output file used for storing the outputs named output.txt, make sure all the three files are in the same folder." }, { "code": null, "e": 30529, "s": 30297, "text": "2. In the screen set up that we did earlier go to file > open file and open the java file in the left window and open the input file in the right upper window and open the output file in the right lower window. Something like below" }, { "code": null, "e": 30833, "s": 30529, "text": "3. Paste the below standard template for JAVA containing the hello world program in the java file make sure that the file name and the class name are the same and make the class public. The code will take a string input from “input.txt” and will print it in the “output.txt” by appending it to “world!”." }, { "code": null, "e": 30842, "s": 30833, "text": "Example:" }, { "code": null, "e": 30847, "s": 30842, "text": "Java" }, { "code": "// Java Program that is been setup in Sublime Text// for Competitive Coding // Importing input output classesimport java.io.*;// Importing Scanner class from java.util packageimport java.util.Scanner; // Main Classclass hello { // Main driver method public static void main(String[] args) { // Setting up the input stream // You can use buffered reader too Scanner read = new Scanner(System.in); // If You Are Running Your Code // in Sublime Text then set The // System Out to output.txt and // Input Stream to input.txt // otherwise leave it as standard // ones for ONLINE JUDGE if (System.getProperty(\"ONLINE_JUDGE\") == null) { // Try block to check for exceptions try { // Sets the Output Stream // to output.txt System.setOut(new PrintStream( new FileOutputStream(\"output.txt\"))); // Change the input stream // to input.txt read = new Scanner(new File(\"input.txt\")); } // Catch block to handle the exceptions catch (Exception e) { } } // Your Code Start Here // Read input String inp = read.nextLine(); // Print output System.out.println(inp + \" World!\"); }}", "e": 32227, "s": 30847, "text": null }, { "code": null, "e": 32238, "s": 32230, "text": "Output:" }, { "code": null, "e": 32289, "s": 32240, "text": "Write something like “Hello” in the “input.txt”." }, { "code": null, "e": 32389, "s": 32289, "text": "Make sure you have selected the correct build system that we built earlier in Tools > Build System." }, { "code": null, "e": 32451, "s": 32389, "text": "Now hit CTRL + B or go to Tools > Build to compile your code." }, { "code": null, "e": 32556, "s": 32451, "text": "Your code must compile and something should get printed in your “output.txt” file. Something like below." }, { "code": null, "e": 32859, "s": 32558, "text": "If a window like the above is seen then your setup is complete and ready to code JAVA in sublime and submit your code on ONLINE JUDGES without worrying about changing the input and output streams as it is already been taken care of. One can go to preferences and change the font or theme as you like." }, { "code": null, "e": 32871, "s": 32861, "text": "rajrk2024" }, { "code": null, "e": 32900, "s": 32871, "text": "Java-Competitive-Programming" }, { "code": null, "e": 32924, "s": 32900, "text": "Competitive Programming" }, { "code": null, "e": 32929, "s": 32924, "text": "Java" }, { "code": null, "e": 32934, "s": 32929, "text": "Java" }, { "code": null, "e": 33032, "s": 32934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33065, "s": 33032, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 33111, "s": 33065, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 33192, "s": 33111, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 33250, "s": 33192, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 33291, "s": 33250, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 33306, "s": 33291, "text": "Arrays in Java" }, { "code": null, "e": 33350, "s": 33306, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33372, "s": 33350, "text": "For-each loop in Java" }, { "code": null, "e": 33423, "s": 33372, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
atexit() function in C/C++ - GeeksforGeeks
04 Feb, 2021 The function pointed by atexit() is automatically called without arguments when the program terminates normally. In case more than one function has been specified by different calls to the atexit() function, all are executed in the order of a stack (i.e. the last function specified is the first to be executed at exit). A single function can be registered to be executed at exit more than once. Syntax : extern "C" int atexit (void (*func)(void)) noexcept; extern "C++" int atexit (void (*func)(void)) noexcept Note: extern refers that the name will refer, to the same object in the entire program .Parameters : The function accepts a single mandatory parameter func which specifies the pointer to the function to be called on normal program termination(Function to be called). Return Value : The function returns following values: Zero, if the function registration is successful Non zero, if the function registration failed Below programs illustrate the above-mentioned function:Program 1: CPP // C++ program to illustrate// atexit() function#include <bits/stdc++.h>using namespace std; // Returns no value, and takes nothing as a parametervoid done(){ cout << "Exiting Successfully" << "\n"; // Executed second}// Driver Codeint main(){ int value; value = atexit(done); if (value != 0) { cout << "atexit () function registration failed"; exit(1); } cout << " Registration successful" << "\n"; // Executed First return 0;} Registration successful Exiting Successfully If atexit function is called more than once, then all the specified functions will be executed in a reverse manner, same as of the functioning of the stack. Program 2: CPP // C++ program to illustrate// more than one atexit function#include <bits/stdc++.h>using namespace std; // Executed last, in a Reverse mannervoid first(){ cout << "Exit first" << endl;} // Executed thirdvoid second(){ cout << "Exit Second" << endl;} // Executed Secondvoid third(){ cout << "Exit Third" << endl;} // Executed firstvoid fourth(){ cout << "Exit Fourth" << endl;}// Driver Codeint main(){ int value1, value2, value3, value4; value1 = atexit(first); value2 = atexit(second); value3 = atexit(third); value4 = atexit(fourth); if ((value1 != 0) or (value2 != 0) or (value3 != 0) or (value4 != 0)) { cout << "atexit() function registration Failed" << endl; exit(1); } // Executed at the starting cout << "Registration successful" << endl; return 0;} Registration successful Exit Fourth Exit Third Exit Second Exit first Program 3 : CPP // C++ program to illustrate// atexit() function when it throws an exception.#include <bits/stdc++.h>using namespace std; void shows_Exception(){ int y = 50, z = 0; // Program will terminate here int x = y / z; // Cannot get printed as the program // has terminated cout << "Divided by zero";}// Driver Codeint main(){ int value; value = atexit(shows_Exception); if (value != 0) { cout << "atexit() function registration failed"; exit(1); } // Executed at the starting cout << "Registration successful" << endl; return 0;} Note: If a registered function throws an exception which cannot be handled, then the terminate() function is called. lissette5 C-Library CPP-Functions C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25453, "s": 25425, "text": "\n04 Feb, 2021" }, { "code": null, "e": 25860, "s": 25453, "text": "The function pointed by atexit() is automatically called without arguments when the program terminates normally. In case more than one function has been specified by different calls to the atexit() function, all are executed in the order of a stack (i.e. the last function specified is the first to be executed at exit). A single function can be registered to be executed at exit more than once. Syntax : " }, { "code": null, "e": 25967, "s": 25860, "text": "extern \"C\" int atexit (void (*func)(void)) noexcept;\nextern \"C++\" int atexit (void (*func)(void)) noexcept" }, { "code": null, "e": 26290, "s": 25967, "text": "Note: extern refers that the name will refer, to the same object in the entire program .Parameters : The function accepts a single mandatory parameter func which specifies the pointer to the function to be called on normal program termination(Function to be called). Return Value : The function returns following values: " }, { "code": null, "e": 26339, "s": 26290, "text": "Zero, if the function registration is successful" }, { "code": null, "e": 26385, "s": 26339, "text": "Non zero, if the function registration failed" }, { "code": null, "e": 26453, "s": 26385, "text": "Below programs illustrate the above-mentioned function:Program 1: " }, { "code": null, "e": 26457, "s": 26453, "text": "CPP" }, { "code": "// C++ program to illustrate// atexit() function#include <bits/stdc++.h>using namespace std; // Returns no value, and takes nothing as a parametervoid done(){ cout << \"Exiting Successfully\" << \"\\n\"; // Executed second}// Driver Codeint main(){ int value; value = atexit(done); if (value != 0) { cout << \"atexit () function registration failed\"; exit(1); } cout << \" Registration successful\" << \"\\n\"; // Executed First return 0;}", "e": 26938, "s": 26457, "text": null }, { "code": null, "e": 26983, "s": 26938, "text": "Registration successful\nExiting Successfully" }, { "code": null, "e": 27155, "s": 26985, "text": "If atexit function is called more than once, then all the specified functions will be executed in a reverse manner, same as of the functioning of the stack. Program 2: " }, { "code": null, "e": 27159, "s": 27155, "text": "CPP" }, { "code": "// C++ program to illustrate// more than one atexit function#include <bits/stdc++.h>using namespace std; // Executed last, in a Reverse mannervoid first(){ cout << \"Exit first\" << endl;} // Executed thirdvoid second(){ cout << \"Exit Second\" << endl;} // Executed Secondvoid third(){ cout << \"Exit Third\" << endl;} // Executed firstvoid fourth(){ cout << \"Exit Fourth\" << endl;}// Driver Codeint main(){ int value1, value2, value3, value4; value1 = atexit(first); value2 = atexit(second); value3 = atexit(third); value4 = atexit(fourth); if ((value1 != 0) or (value2 != 0) or (value3 != 0) or (value4 != 0)) { cout << \"atexit() function registration Failed\" << endl; exit(1); } // Executed at the starting cout << \"Registration successful\" << endl; return 0;}", "e": 27981, "s": 27159, "text": null }, { "code": null, "e": 28051, "s": 27981, "text": "Registration successful\nExit Fourth\nExit Third\nExit Second\nExit first" }, { "code": null, "e": 28067, "s": 28053, "text": "Program 3 : " }, { "code": null, "e": 28071, "s": 28067, "text": "CPP" }, { "code": "// C++ program to illustrate// atexit() function when it throws an exception.#include <bits/stdc++.h>using namespace std; void shows_Exception(){ int y = 50, z = 0; // Program will terminate here int x = y / z; // Cannot get printed as the program // has terminated cout << \"Divided by zero\";}// Driver Codeint main(){ int value; value = atexit(shows_Exception); if (value != 0) { cout << \"atexit() function registration failed\"; exit(1); } // Executed at the starting cout << \"Registration successful\" << endl; return 0;}", "e": 28649, "s": 28071, "text": null }, { "code": null, "e": 28768, "s": 28649, "text": "Note: If a registered function throws an exception which cannot be handled, then the terminate() function is called. " }, { "code": null, "e": 28778, "s": 28768, "text": "lissette5" }, { "code": null, "e": 28788, "s": 28778, "text": "C-Library" }, { "code": null, "e": 28802, "s": 28788, "text": "CPP-Functions" }, { "code": null, "e": 28813, "s": 28802, "text": "C Language" }, { "code": null, "e": 28817, "s": 28813, "text": "C++" }, { "code": null, "e": 28821, "s": 28817, "text": "CPP" }, { "code": null, "e": 28919, "s": 28821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28957, "s": 28919, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28983, "s": 28957, "text": "Exception Handling in C++" }, { "code": null, "e": 29003, "s": 28983, "text": "Multithreading in C" }, { "code": null, "e": 29025, "s": 29003, "text": "'this' pointer in C++" }, { "code": null, "e": 29066, "s": 29025, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29084, "s": 29066, "text": "Vector in C++ STL" }, { "code": null, "e": 29103, "s": 29084, "text": "Inheritance in C++" }, { "code": null, "e": 29149, "s": 29103, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29192, "s": 29149, "text": "Map in C++ Standard Template Library (STL)" } ]
How to create Chess pattern background using HTML and CSS ? - GeeksforGeeks
18 Aug, 2020 Chess patterns are simply certain tactical positions which regularly occur in games. It can be easily design by using the pseudo selector of CSS. This type of pattern can be used to create confusing illusions. Approach: The approach is to use repeating linear gradient property to create a pattern that will be repeated to the defined height and width. HTML Code: In this section, we will design the basic structure of the chess pattern. HTML <!DOCTYPE html><html> <head> <title>Chess Pattern</title></head> <body> <div class="geeks"></div></body> </html> CSS Code: For CSS, follow the below given steps. Step 1: Set the position of div to fixed and apply some height and width. Step 2: Now use before selector and apply repeating linear-gradient property with black and white color and angle set as 45deg. Step 3: Now use after selector with the same properties as used in before just change the angle to -45 deg. Step 4: Set the mix-blend mode to difference so that it can overlay on the background. Tip: You can also use 0 deg in before and 90 deg in after to make perfect square chess like boxes. The output of the same will also be attached below. CSS <style> .geeks { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; } .geeks::before { content: ""; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 45deg, #000 0, #000 40px, #fff 40px, #fff 80px); } .geeks::after { content: ""; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( -45deg, #000 0, #000 40px, #fff 40px, #fff 80px); mix-blend-mode: difference; }</style> Complete Code: (With angles 45 deg and -45 deg): It is the combination of the above two sections of code to design a chess pattern. HTML <!DOCTYPE html><html> <head> <title>Chess Pattern</title></head> <style> .geeks { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; } .geeks::before { content: ""; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 45deg, #000 0, #000 40px, #fff 40px, #fff 80px); } .geeks::after { content: ""; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( -45deg, #000 0, #000 40px, #fff 40px, #fff 80px); mix-blend-mode: difference; }</style> <body> <div class="geeks"></div></body> </html> Output: While using angles as 45 and -45 deg: Complete Code:(with angles 0 deg and 90 deg) It is the combination of the above two sections of code. HTML <!DOCTYPE html><html> <head> <title>Chess Pattern</title> <style> .geeks { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; } .geeks::before { content: ""; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 0deg, #000 0, #000 40px, #fff 40px, #fff 80px); } .geeks::after { content: ""; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 90deg, #000 0, #000 40px, #fff 40px, #fff 80px); mix-blend-mode: difference; } </style></head> <body> <div class="geeks"></div></body> </html> Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set space between the flexbox ? Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 26819, "s": 26791, "text": "\n18 Aug, 2020" }, { "code": null, "e": 27029, "s": 26819, "text": "Chess patterns are simply certain tactical positions which regularly occur in games. It can be easily design by using the pseudo selector of CSS. This type of pattern can be used to create confusing illusions." }, { "code": null, "e": 27172, "s": 27029, "text": "Approach: The approach is to use repeating linear gradient property to create a pattern that will be repeated to the defined height and width." }, { "code": null, "e": 27257, "s": 27172, "text": "HTML Code: In this section, we will design the basic structure of the chess pattern." }, { "code": null, "e": 27262, "s": 27257, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Chess Pattern</title></head> <body> <div class=\"geeks\"></div></body> </html>", "e": 27384, "s": 27262, "text": null }, { "code": null, "e": 27433, "s": 27384, "text": "CSS Code: For CSS, follow the below given steps." }, { "code": null, "e": 27507, "s": 27433, "text": "Step 1: Set the position of div to fixed and apply some height and width." }, { "code": null, "e": 27635, "s": 27507, "text": "Step 2: Now use before selector and apply repeating linear-gradient property with black and white color and angle set as 45deg." }, { "code": null, "e": 27743, "s": 27635, "text": "Step 3: Now use after selector with the same properties as used in before just change the angle to -45 deg." }, { "code": null, "e": 27830, "s": 27743, "text": "Step 4: Set the mix-blend mode to difference so that it can overlay on the background." }, { "code": null, "e": 27981, "s": 27830, "text": "Tip: You can also use 0 deg in before and 90 deg in after to make perfect square chess like boxes. The output of the same will also be attached below." }, { "code": null, "e": 27985, "s": 27981, "text": "CSS" }, { "code": "<style> .geeks { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; } .geeks::before { content: \"\"; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 45deg, #000 0, #000 40px, #fff 40px, #fff 80px); } .geeks::after { content: \"\"; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( -45deg, #000 0, #000 40px, #fff 40px, #fff 80px); mix-blend-mode: difference; }</style>", "e": 28616, "s": 27985, "text": null }, { "code": null, "e": 28748, "s": 28616, "text": "Complete Code: (With angles 45 deg and -45 deg): It is the combination of the above two sections of code to design a chess pattern." }, { "code": null, "e": 28753, "s": 28748, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Chess Pattern</title></head> <style> .geeks { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; } .geeks::before { content: \"\"; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 45deg, #000 0, #000 40px, #fff 40px, #fff 80px); } .geeks::after { content: \"\"; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( -45deg, #000 0, #000 40px, #fff 40px, #fff 80px); mix-blend-mode: difference; }</style> <body> <div class=\"geeks\"></div></body> </html>", "e": 29515, "s": 28753, "text": null }, { "code": null, "e": 29523, "s": 29515, "text": "Output:" }, { "code": null, "e": 29561, "s": 29523, "text": "While using angles as 45 and -45 deg:" }, { "code": null, "e": 29663, "s": 29561, "text": "Complete Code:(with angles 0 deg and 90 deg) It is the combination of the above two sections of code." }, { "code": null, "e": 29668, "s": 29663, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Chess Pattern</title> <style> .geeks { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; } .geeks::before { content: \"\"; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 0deg, #000 0, #000 40px, #fff 40px, #fff 80px); } .geeks::after { content: \"\"; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient( 90deg, #000 0, #000 40px, #fff 40px, #fff 80px); mix-blend-mode: difference; } </style></head> <body> <div class=\"geeks\"></div></body> </html>", "e": 30540, "s": 29668, "text": null }, { "code": null, "e": 30677, "s": 30540, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 30686, "s": 30677, "text": "CSS-Misc" }, { "code": null, "e": 30696, "s": 30686, "text": "HTML-Misc" }, { "code": null, "e": 30700, "s": 30696, "text": "CSS" }, { "code": null, "e": 30705, "s": 30700, "text": "HTML" }, { "code": null, "e": 30722, "s": 30705, "text": "Web Technologies" }, { "code": null, "e": 30749, "s": 30722, "text": "Web technologies Questions" }, { "code": null, "e": 30754, "s": 30749, "text": "HTML" }, { "code": null, "e": 30852, "s": 30754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30889, "s": 30852, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30926, "s": 30889, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30987, "s": 30926, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 31026, "s": 30987, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31067, "s": 31026, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 31127, "s": 31067, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31180, "s": 31127, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31241, "s": 31180, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31291, "s": 31241, "text": "How to Insert Form Data into Database using PHP ?" } ]
Perl - Arrays vs Lists - GeeksforGeeks
22 Jun, 2020 Perl is a general-purpose, interpreted, dynamic programming languages. Perl has three basic data types namely, scalars, arrays and hashes. The list is a sequence of scalar values. However, the list is not a data structure in Perl. There are limited operations that can be performed on the list in Perl. Since no variable refers to this list, lists cannot be used for operations other than printing. Example: (10, 20, 30); ("this", "is", "a", "list", "in", "perl"); A Simple list is one that contains homogeneous elements. # declaration without variable referencingprint("List declared and printed: ");print join(' ', 10, 20, 30, 40, 50);print("\n\n"); # qw() forms list by extracting words # out of the string using space as a delimiter.print("List declared using qw(): ");print join(' ', qw(this is gfg));print("\n\n"); # indexingprint("Accessing element at index 2: ");print((10, 20, 30, 40, 50)[2]);print("\n\n"); # rangeprint("Range function on list\n");print join(' ', 1..6);print("\n\n"); # loopprint("Iterating over list elements:\n ");foreach $element (1..6){ print("$element\t");}print("\n\n"); # splicingprint("Splicing list\n");print("Spliced elements: ");print join(' ', (1..6)[1..3]);print("\n\n"); Output: List declared and printed: 10 20 30 40 50 List declared using qw(): this is gfg Accessing element at index 2: 30 Range function on list 1 2 3 4 5 6 Iterating over list elements: 1 2 3 4 5 6 Splicing list Spliced elements: 2 3 4 A complex list is one that contains heterogeneous elements. print("complex", 10, 20, "list"); Output: complex1020list If nested lists exist, it is merged to form one single list without any nesting. print(2, 3, 4, (5, 6));print("\n");print(2, 3, 4, 5, 6);print("\n");print((2, 3, 4), 5, 6);print("\n"); Output: 23456 23456 23456 Array is a Perl data structure. Array in Perl is a variable that contains the list. Array variables are prefixed with ‘@’ sign. Arrays have a wide range of application in Perl. There is no restriction to the type of operation that can be performed on arrays. Arrays in Perl can be 2D but lists cannot be two dimensional. Example: @num = (10, 20, 30); @str = ("this", "is", "a", "list", "in", "perl"); # declaration@array = (10, 20, 30, 40, 50);print("Declared array\n");print join(' ', @array);print("\n\n"); # accessing particular elementprint("Accessing element at index 2 \n");print(@array[2]);print("\n\n"); # pushprint("Pushing two elements in to the array\n"); ## returns total no. of elements in updated arraypush(@array, (60, 70)); print join(' ', @array);print("\n\n"); # popprint("Popping elements from array\n");print("Popped element: "); ## returns the popped elements of the arrayprint(pop(@array)); print("\n");print join(' ', @array);print("\n\n"); # shiftprint("Shift element in an array\n");shift(@array);print join(' ', @array);print("\n\n"); # unshiftprint("Unshift element in an array\n");unshift(@array, 10);print join(' ', @array);print("\n\n"); # splicing the arrayprint("Splice an array\n");print("Spliced elements: ");print join(' ', splice @array, 3, 2 );print("\nArray after being spliced: ");print join(' ', @array);print("\n\n"); # reversing the arrayprint("Reverse elements in an array\n");print join(' ', reverse @array);print("\n\n"); # loopprint("Iterate over elements in an array\n");foreach $element (@array){ print("$element\t");}print("\n\n"); # rangeprint("Range function\n");@array1 = (1..5);print("@array1\t");print("\n\n"); Output: Declared array 10 20 30 40 50 Accessing element at index 2 30 Pushing two elements in to the array 10 20 30 40 50 60 70 Popping elements from array Popped element: 70 10 20 30 40 50 60 Shift element in an array 20 30 40 50 60 Unshift element in an array 10 20 30 40 50 60 Splice an array Spliced elements: 40 50 Array after being spliced: 10 20 30 60 Reverse elements in an array 60 30 20 10 Iterate over elements in an array 10 20 30 60 Range function 1 2 3 4 5 Perl allows the creation of a Two-dimensional array. @array = ( [ 10, 20, 30 ], [ "ana", "joe", "ester" ], [ "Welcome to gfg" ] ); for $array_ref( @array ) { print("[ @$array_ref ], \n");} Output: [ 10 20 30 ], [ ana joe ester ], [ Welcome to gfg ], Below is a table of differences between Arrays and List: Often list and array are considered to be same in Perl. But there are differences between the two. While list is not a data structure in Perl, arrays are variables that refer to lists in Perl. In practical applications, we work with arrays. Perl-Arrays perl-list Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Polymorphism in OOPs Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | length() Function Perl | join() Function Perl | Basic Syntax of a Perl Program Perl | substitution Operator Perl | Regex Cheat Sheet
[ { "code": null, "e": 25367, "s": 25339, "text": "\n22 Jun, 2020" }, { "code": null, "e": 25506, "s": 25367, "text": "Perl is a general-purpose, interpreted, dynamic programming languages. Perl has three basic data types namely, scalars, arrays and hashes." }, { "code": null, "e": 25766, "s": 25506, "text": "The list is a sequence of scalar values. However, the list is not a data structure in Perl. There are limited operations that can be performed on the list in Perl. Since no variable refers to this list, lists cannot be used for operations other than printing." }, { "code": null, "e": 25775, "s": 25766, "text": "Example:" }, { "code": null, "e": 25833, "s": 25775, "text": "(10, 20, 30);\n(\"this\", \"is\", \"a\", \"list\", \"in\", \"perl\");\n" }, { "code": null, "e": 25890, "s": 25833, "text": "A Simple list is one that contains homogeneous elements." }, { "code": "# declaration without variable referencingprint(\"List declared and printed: \");print join(' ', 10, 20, 30, 40, 50);print(\"\\n\\n\"); # qw() forms list by extracting words # out of the string using space as a delimiter.print(\"List declared using qw(): \");print join(' ', qw(this is gfg));print(\"\\n\\n\"); # indexingprint(\"Accessing element at index 2: \");print((10, 20, 30, 40, 50)[2]);print(\"\\n\\n\"); # rangeprint(\"Range function on list\\n\");print join(' ', 1..6);print(\"\\n\\n\"); # loopprint(\"Iterating over list elements:\\n \");foreach $element (1..6){ print(\"$element\\t\");}print(\"\\n\\n\"); # splicingprint(\"Splicing list\\n\");print(\"Spliced elements: \");print join(' ', (1..6)[1..3]);print(\"\\n\\n\");", "e": 26588, "s": 25890, "text": null }, { "code": null, "e": 26596, "s": 26588, "text": "Output:" }, { "code": null, "e": 26850, "s": 26596, "text": "List declared and printed: 10 20 30 40 50\n\nList declared using qw(): this is gfg\n\nAccessing element at index 2: 30\n\nRange function on list\n1 2 3 4 5 6\n\nIterating over list elements:\n 1 2 3 4 5 6 \n\nSplicing list\nSpliced elements: 2 3 4\n" }, { "code": null, "e": 26910, "s": 26850, "text": "A complex list is one that contains heterogeneous elements." }, { "code": "print(\"complex\", 10, 20, \"list\");", "e": 26944, "s": 26910, "text": null }, { "code": null, "e": 26952, "s": 26944, "text": "Output:" }, { "code": null, "e": 26969, "s": 26952, "text": "complex1020list\n" }, { "code": null, "e": 27050, "s": 26969, "text": "If nested lists exist, it is merged to form one single list without any nesting." }, { "code": "print(2, 3, 4, (5, 6));print(\"\\n\");print(2, 3, 4, 5, 6);print(\"\\n\");print((2, 3, 4), 5, 6);print(\"\\n\");", "e": 27154, "s": 27050, "text": null }, { "code": null, "e": 27162, "s": 27154, "text": "Output:" }, { "code": null, "e": 27180, "s": 27162, "text": "23456\n23456\n23456" }, { "code": null, "e": 27501, "s": 27180, "text": "Array is a Perl data structure. Array in Perl is a variable that contains the list. Array variables are prefixed with ‘@’ sign. Arrays have a wide range of application in Perl. There is no restriction to the type of operation that can be performed on arrays. Arrays in Perl can be 2D but lists cannot be two dimensional." }, { "code": null, "e": 27510, "s": 27501, "text": "Example:" }, { "code": null, "e": 27582, "s": 27510, "text": "@num = (10, 20, 30);\n@str = (\"this\", \"is\", \"a\", \"list\", \"in\", \"perl\");\n" }, { "code": "# declaration@array = (10, 20, 30, 40, 50);print(\"Declared array\\n\");print join(' ', @array);print(\"\\n\\n\"); # accessing particular elementprint(\"Accessing element at index 2 \\n\");print(@array[2]);print(\"\\n\\n\"); # pushprint(\"Pushing two elements in to the array\\n\"); ## returns total no. of elements in updated arraypush(@array, (60, 70)); print join(' ', @array);print(\"\\n\\n\"); # popprint(\"Popping elements from array\\n\");print(\"Popped element: \"); ## returns the popped elements of the arrayprint(pop(@array)); print(\"\\n\");print join(' ', @array);print(\"\\n\\n\"); # shiftprint(\"Shift element in an array\\n\");shift(@array);print join(' ', @array);print(\"\\n\\n\"); # unshiftprint(\"Unshift element in an array\\n\");unshift(@array, 10);print join(' ', @array);print(\"\\n\\n\"); # splicing the arrayprint(\"Splice an array\\n\");print(\"Spliced elements: \");print join(' ', splice @array, 3, 2 );print(\"\\nArray after being spliced: \");print join(' ', @array);print(\"\\n\\n\"); # reversing the arrayprint(\"Reverse elements in an array\\n\");print join(' ', reverse @array);print(\"\\n\\n\"); # loopprint(\"Iterate over elements in an array\\n\");foreach $element (@array){ print(\"$element\\t\");}print(\"\\n\\n\"); # rangeprint(\"Range function\\n\");@array1 = (1..5);print(\"@array1\\t\");print(\"\\n\\n\");", "e": 28860, "s": 27582, "text": null }, { "code": null, "e": 28868, "s": 28860, "text": "Output:" }, { "code": null, "e": 29360, "s": 28868, "text": "Declared array\n10 20 30 40 50\n\nAccessing element at index 2 \n30\n\nPushing two elements in to the array\n10 20 30 40 50 60 70\n\nPopping elements from array\nPopped element: 70\n10 20 30 40 50 60\n\nShift element in an array\n20 30 40 50 60\n\nUnshift element in an array\n10 20 30 40 50 60\n\nSplice an array\nSpliced elements: 40 50\nArray after being spliced: 10 20 30 60\n\nReverse elements in an array\n60 30 20 10\n\nIterate over elements in an array\n10 20 30 60 \n\nRange function\n1 2 3 4 5 \n\n" }, { "code": null, "e": 29413, "s": 29360, "text": "Perl allows the creation of a Two-dimensional array." }, { "code": "@array = ( [ 10, 20, 30 ], [ \"ana\", \"joe\", \"ester\" ], [ \"Welcome to gfg\" ] ); for $array_ref( @array ) { print(\"[ @$array_ref ], \\n\");}", "e": 29573, "s": 29413, "text": null }, { "code": null, "e": 29581, "s": 29573, "text": "Output:" }, { "code": null, "e": 29635, "s": 29581, "text": "[ 10 20 30 ],\n[ ana joe ester ],\n[ Welcome to gfg ],\n" }, { "code": null, "e": 29692, "s": 29635, "text": "Below is a table of differences between Arrays and List:" }, { "code": null, "e": 29933, "s": 29692, "text": "Often list and array are considered to be same in Perl. But there are differences between the two. While list is not a data structure in Perl, arrays are variables that refer to lists in Perl. In practical applications, we work with arrays." }, { "code": null, "e": 29945, "s": 29933, "text": "Perl-Arrays" }, { "code": null, "e": 29955, "s": 29945, "text": "perl-list" }, { "code": null, "e": 29962, "s": 29955, "text": "Picked" }, { "code": null, "e": 29967, "s": 29962, "text": "Perl" }, { "code": null, "e": 29972, "s": 29967, "text": "Perl" }, { "code": null, "e": 30070, "s": 29972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30112, "s": 30070, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 30140, "s": 30112, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 30154, "s": 30140, "text": "Perl | Arrays" }, { "code": null, "e": 30195, "s": 30154, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 30228, "s": 30195, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 30253, "s": 30228, "text": "Perl | length() Function" }, { "code": null, "e": 30276, "s": 30253, "text": "Perl | join() Function" }, { "code": null, "e": 30314, "s": 30276, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 30343, "s": 30314, "text": "Perl | substitution Operator" } ]
Python | Vowel indices in String - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python Strings, we can have a problem in which we need to extract indices of vowels in it. This kind of application is common in day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loopThis is one way in which this task can be performed. In this we use brute force to perform this task. In this we iterate for each string element and test for vowel. # Python3 code to demonstrate working of # Vowel indices in String# Using loop # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + test_str) # Vowel indices in String# Using loopres = []for ele in range(len(test_str)): if test_str[ele] in "aeiou": res.append(ele) # printing result print("The vowel indices are : " + str(res)) The original string is : geeksforgeeks The vowel indices are : [1, 2, 6, 9, 10] Method #2 : Using enumerate() + list comprehensionThe combination of above methods can also be used to perform this task. In this, we access the index using enumerate() and list comprehension is used to check for vowels. # Python3 code to demonstrate working of # Vowel indices in String# Using list comprehension + enumerate() # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + test_str) # Vowel indices in String# Using list comprehension + enumerate()res = [idx for idx, ele in enumerate(test_str) if ele in "aeiou"] # printing result print("The vowel indices are : " + str(res)) The original string is : geeksforgeeks The vowel indices are : [1, 2, 6, 9, 10] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25780, "s": 25537, "text": "Sometimes, while working with Python Strings, we can have a problem in which we need to extract indices of vowels in it. This kind of application is common in day-day programming. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 25967, "s": 25780, "text": "Method #1 : Using loopThis is one way in which this task can be performed. In this we use brute force to perform this task. In this we iterate for each string element and test for vowel." }, { "code": "# Python3 code to demonstrate working of # Vowel indices in String# Using loop # initializing stringtest_str = \"geeksforgeeks\" # printing original stringprint(\"The original string is : \" + test_str) # Vowel indices in String# Using loopres = []for ele in range(len(test_str)): if test_str[ele] in \"aeiou\": res.append(ele) # printing result print(\"The vowel indices are : \" + str(res)) ", "e": 26366, "s": 25967, "text": null }, { "code": null, "e": 26447, "s": 26366, "text": "The original string is : geeksforgeeks\nThe vowel indices are : [1, 2, 6, 9, 10]\n" }, { "code": null, "e": 26670, "s": 26449, "text": "Method #2 : Using enumerate() + list comprehensionThe combination of above methods can also be used to perform this task. In this, we access the index using enumerate() and list comprehension is used to check for vowels." }, { "code": "# Python3 code to demonstrate working of # Vowel indices in String# Using list comprehension + enumerate() # initializing stringtest_str = \"geeksforgeeks\" # printing original stringprint(\"The original string is : \" + test_str) # Vowel indices in String# Using list comprehension + enumerate()res = [idx for idx, ele in enumerate(test_str) if ele in \"aeiou\"] # printing result print(\"The vowel indices are : \" + str(res)) ", "e": 27096, "s": 26670, "text": null }, { "code": null, "e": 27177, "s": 27096, "text": "The original string is : geeksforgeeks\nThe vowel indices are : [1, 2, 6, 9, 10]\n" }, { "code": null, "e": 27200, "s": 27177, "text": "Python string-programs" }, { "code": null, "e": 27207, "s": 27200, "text": "Python" }, { "code": null, "e": 27223, "s": 27207, "text": "Python Programs" }, { "code": null, "e": 27321, "s": 27223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27353, "s": 27321, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27395, "s": 27353, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27437, "s": 27395, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27493, "s": 27437, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27520, "s": 27493, "text": "Python Classes and Objects" }, { "code": null, "e": 27542, "s": 27520, "text": "Defaultdict in Python" }, { "code": null, "e": 27581, "s": 27542, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27627, "s": 27581, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27665, "s": 27627, "text": "Python | Convert a list to dictionary" } ]
Weighted sum of the characters of a string in an array | Set 2 - GeeksforGeeks
28 May, 2021 You are given an array of strings str[], the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’s alphabetical values with the position of the string in the array.Examples: Input: str[] = {“sahil”, “shashanak”, “sanjit”, “abhinav”, “mohit”}, s = “abhinav” Output: 228 Sum of alphabetical values of “abhinav” = 1 + 2 + 8 + 9 + 14 + 1 + 22 = 57 Position of “abhinav” in str is 4, 57 x 4 = 228 Input: str[] = {“geeksforgeeks”, “algorithms”, “stack”}, s = “algorithms” Output: 244 Approach: In SET 1, we saw an approach where every time a query is being executed, the position of the string has to be found with a single traversal of str[]. This can be optimized when there are a number of queries using a hash table. Create a hash map of all the strings present in str[] along with their respective positions in the array. Then for every query s, check if s is present in the map. If yes then calculate the sum of the alphabetical values of s and store it in sum. Print sum * pos where pos is the value associated with s in map i.e. its position in str[]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the required string scoreint strScore(string str[], string s, int n){ // create a hash map of strings in str unordered_map<string, int> m; // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m[str[i]] = i + 1; // If given string is not present in str[] if (m.find(s) == m.end()) return 0; int score = 0; for (int i = 0; i < s.length(); i++) score += s[i] - 'a' + 1; // Multiply sum of alphabets with position score = score * m[s]; return score;} // Driver codeint main(){ string str[] = { "geeksforgeeks", "algorithms", "stack" }; string s = "algorithms"; int n = sizeof(str) / sizeof(str[0]); int score = strScore(str, s, n); cout << score; return 0;} // Java implementation of the approachimport java.util.HashMap;import java.util.Map; class GfG{ // Function to return the required string score static int strScore(String str[], String s, int n) { // create a hash map of strings in str HashMap<String, Integer> m = new HashMap<>(); // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m.put(str[i], i + 1); // If given string is not present in str[] if (!m.containsKey(s)) return 0; int score = 0; for (int i = 0; i < s.length(); i++) score += s.charAt(i) - 'a' + 1; // Multiply sum of alphabets with position score = score * m.get(s); return score; } // Driver code public static void main(String []args) { String str[] = { "geeksforgeeks", "algorithms", "stack" }; String s = "algorithms"; int n = str.length; System.out.println(strScore(str, s, n)); }} // This code is contributed by Rituraj Jain # Python3 implementation of the approach # Function to return the required# string scoredef strScore(string, s, n) : # create a hash map of strings in str m = {} # Store every string in the map # along with its position in the array for i in range(n) : m[string[i]] = i + 1 # If given string is not present in str[] if s not in m.keys() : return 0 score = 0 for i in range(len(s)) : score += ord(s[i]) - ord('a') + 1 # Multiply sum of alphabets # with position score = score * m[s] return score # Driver codeif __name__ == "__main__" : string = [ "geeksforgeeks", "algorithms", "stack" ] s = "algorithms" n = len(string) score = strScore(string, s, n); print(score) # This code is contributed by Ryuga // C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Function to return the required string score static int strScore(string [] str, string s, int n) { // create a hash map of strings in str Dictionary<string, int> m = new Dictionary<string, int>(); // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m[str[i]] = i + 1; // If given string is not present in str[] if (!m.ContainsKey(s)) return 0; int score = 0; for (int i = 0; i < s.Length; i++) score += s[i] - 'a' + 1; // Multiply sum of alphabets with position score = score * m[s]; return score; } // Driver code public static void Main() { string [] str = { "geeksforgeeks", "algorithms", "stack" }; string s = "algorithms"; int n = str.Length; Console.WriteLine(strScore(str, s, n)); }} // This code is contributed by ihritik <script> // JavaScript Program to implement// the above approach // Function to return the required string score function strScore(str, s, n) { // create a hash map of strings in str let m = new Map(); // Store every string in the map // along with its position in the array for (let i = 0; i < n; i++) m.set(str[i], i + 1); // If given string is not present in str[] if (!m.has(s)) return 0; let score = 0; for (let i = 0; i < s.length; i++) score += s[i].charCodeAt() - 'a'.charCodeAt() + 1; // Multiply sum of alphabets with position score = score * m.get(s); return score; } // Driver Code let str = [ "geeksforgeeks", "algorithms", "stack" ]; let s = "algorithms"; let n = str.length; document.write(strScore(str, s, n)); </script> 244 ankthon rituraj_jain ihritik susmitakundugoaldanga Hash Pattern Searching Searching Strings Searching Hash Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hashing | Set 2 (Separate Chaining) Sort string of characters Counting frequencies of array elements Most frequent element in an array Sorting a Map by value in C++ STL KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 26769, "s": 26741, "text": "\n28 May, 2021" }, { "code": null, "e": 27032, "s": 26769, "text": "You are given an array of strings str[], the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’s alphabetical values with the position of the string in the array.Examples: " }, { "code": null, "e": 27338, "s": 27032, "text": "Input: str[] = {“sahil”, “shashanak”, “sanjit”, “abhinav”, “mohit”}, s = “abhinav” Output: 228 Sum of alphabetical values of “abhinav” = 1 + 2 + 8 + 9 + 14 + 1 + 22 = 57 Position of “abhinav” in str is 4, 57 x 4 = 228 Input: str[] = {“geeksforgeeks”, “algorithms”, “stack”}, s = “algorithms” Output: 244 " }, { "code": null, "e": 27579, "s": 27340, "text": "Approach: In SET 1, we saw an approach where every time a query is being executed, the position of the string has to be found with a single traversal of str[]. This can be optimized when there are a number of queries using a hash table. " }, { "code": null, "e": 27685, "s": 27579, "text": "Create a hash map of all the strings present in str[] along with their respective positions in the array." }, { "code": null, "e": 27826, "s": 27685, "text": "Then for every query s, check if s is present in the map. If yes then calculate the sum of the alphabetical values of s and store it in sum." }, { "code": null, "e": 27918, "s": 27826, "text": "Print sum * pos where pos is the value associated with s in map i.e. its position in str[]." }, { "code": null, "e": 27971, "s": 27918, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27975, "s": 27971, "text": "C++" }, { "code": null, "e": 27980, "s": 27975, "text": "Java" }, { "code": null, "e": 27988, "s": 27980, "text": "Python3" }, { "code": null, "e": 27991, "s": 27988, "text": "C#" }, { "code": null, "e": 28002, "s": 27991, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the required string scoreint strScore(string str[], string s, int n){ // create a hash map of strings in str unordered_map<string, int> m; // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m[str[i]] = i + 1; // If given string is not present in str[] if (m.find(s) == m.end()) return 0; int score = 0; for (int i = 0; i < s.length(); i++) score += s[i] - 'a' + 1; // Multiply sum of alphabets with position score = score * m[s]; return score;} // Driver codeint main(){ string str[] = { \"geeksforgeeks\", \"algorithms\", \"stack\" }; string s = \"algorithms\"; int n = sizeof(str) / sizeof(str[0]); int score = strScore(str, s, n); cout << score; return 0;}", "e": 28890, "s": 28002, "text": null }, { "code": "// Java implementation of the approachimport java.util.HashMap;import java.util.Map; class GfG{ // Function to return the required string score static int strScore(String str[], String s, int n) { // create a hash map of strings in str HashMap<String, Integer> m = new HashMap<>(); // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m.put(str[i], i + 1); // If given string is not present in str[] if (!m.containsKey(s)) return 0; int score = 0; for (int i = 0; i < s.length(); i++) score += s.charAt(i) - 'a' + 1; // Multiply sum of alphabets with position score = score * m.get(s); return score; } // Driver code public static void main(String []args) { String str[] = { \"geeksforgeeks\", \"algorithms\", \"stack\" }; String s = \"algorithms\"; int n = str.length; System.out.println(strScore(str, s, n)); }} // This code is contributed by Rituraj Jain", "e": 30040, "s": 28890, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the required# string scoredef strScore(string, s, n) : # create a hash map of strings in str m = {} # Store every string in the map # along with its position in the array for i in range(n) : m[string[i]] = i + 1 # If given string is not present in str[] if s not in m.keys() : return 0 score = 0 for i in range(len(s)) : score += ord(s[i]) - ord('a') + 1 # Multiply sum of alphabets # with position score = score * m[s] return score # Driver codeif __name__ == \"__main__\" : string = [ \"geeksforgeeks\", \"algorithms\", \"stack\" ] s = \"algorithms\" n = len(string) score = strScore(string, s, n); print(score) # This code is contributed by Ryuga", "e": 30839, "s": 30040, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Function to return the required string score static int strScore(string [] str, string s, int n) { // create a hash map of strings in str Dictionary<string, int> m = new Dictionary<string, int>(); // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m[str[i]] = i + 1; // If given string is not present in str[] if (!m.ContainsKey(s)) return 0; int score = 0; for (int i = 0; i < s.Length; i++) score += s[i] - 'a' + 1; // Multiply sum of alphabets with position score = score * m[s]; return score; } // Driver code public static void Main() { string [] str = { \"geeksforgeeks\", \"algorithms\", \"stack\" }; string s = \"algorithms\"; int n = str.Length; Console.WriteLine(strScore(str, s, n)); }} // This code is contributed by ihritik", "e": 31971, "s": 30839, "text": null }, { "code": "<script> // JavaScript Program to implement// the above approach // Function to return the required string score function strScore(str, s, n) { // create a hash map of strings in str let m = new Map(); // Store every string in the map // along with its position in the array for (let i = 0; i < n; i++) m.set(str[i], i + 1); // If given string is not present in str[] if (!m.has(s)) return 0; let score = 0; for (let i = 0; i < s.length; i++) score += s[i].charCodeAt() - 'a'.charCodeAt() + 1; // Multiply sum of alphabets with position score = score * m.get(s); return score; } // Driver Code let str = [ \"geeksforgeeks\", \"algorithms\", \"stack\" ]; let s = \"algorithms\"; let n = str.length; document.write(strScore(str, s, n)); </script>", "e": 32940, "s": 31971, "text": null }, { "code": null, "e": 32944, "s": 32940, "text": "244" }, { "code": null, "e": 32954, "s": 32946, "text": "ankthon" }, { "code": null, "e": 32967, "s": 32954, "text": "rituraj_jain" }, { "code": null, "e": 32975, "s": 32967, "text": "ihritik" }, { "code": null, "e": 32997, "s": 32975, "text": "susmitakundugoaldanga" }, { "code": null, "e": 33002, "s": 32997, "text": "Hash" }, { "code": null, "e": 33020, "s": 33002, "text": "Pattern Searching" }, { "code": null, "e": 33030, "s": 33020, "text": "Searching" }, { "code": null, "e": 33038, "s": 33030, "text": "Strings" }, { "code": null, "e": 33048, "s": 33038, "text": "Searching" }, { "code": null, "e": 33053, "s": 33048, "text": "Hash" }, { "code": null, "e": 33061, "s": 33053, "text": "Strings" }, { "code": null, "e": 33079, "s": 33061, "text": "Pattern Searching" }, { "code": null, "e": 33177, "s": 33079, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33213, "s": 33177, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 33239, "s": 33213, "text": "Sort string of characters" }, { "code": null, "e": 33278, "s": 33239, "text": "Counting frequencies of array elements" }, { "code": null, "e": 33312, "s": 33278, "text": "Most frequent element in an array" }, { "code": null, "e": 33346, "s": 33312, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 33382, "s": 33346, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 33425, "s": 33382, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 33467, "s": 33425, "text": "Check if a string is substring of another" }, { "code": null, "e": 33505, "s": 33467, "text": "Naive algorithm for Pattern Searching" } ]
Permutation of numbers such that sum of two consecutive numbers is a perfect square - GeeksforGeeks
27 Nov, 2018 Prerequisite: Hamiltonian Cycle Given an integer n(>=2), find a permutation of numbers from 1 to n such that the sum of two consecutive numbers of that permutation is a perfect square. If that kind of permutation is not possible to print “No Solution”. Examples: Input : 17 Output : [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17] Explanation : 16+9 = 25 = 5*5, 9+7 = 16 = 4*4, 7+2 = 9 = 3*3 and so on. Input: 20 Output: No Solution Input : 25 Output : [2, 23, 13, 12, 24, 25, 11, 14, 22, 3, 1, 8, 17, 19, 6, 10, 15, 21, 4, 5, 20, 16, 9, 7, 18] Method:We can represent a graph, where numbers from 1 to n are the nodes of the graph and there is an edge between ith and jth node if (i+j) is a perfect square. Then we can search if there is any Hamiltonian Path in the graph. If there is at least one path then we print a path otherwise we print “No Solution”. Approach: 1. First list up all the perfect square numbers which we can get by adding two numbers. We can get at max (2*n-1). so we will take only the squares up to (2*n-1). 2. Take an adjacency matrix to represent the graph. 3. For each number from 1 to n find out numbers with which it can add upto a perfect square number. Fill respective cells of the adjacency matrix by 1. 4. Now find if there is any Hamiltonian path in the graph using backtracking as discussed earlier. Python3 # Python3 program for Sum-square series using# hamiltonian path concept and backtracking # Function to check wheter we can add number# v with the path in the position pos.def issafe(v, graph, path, pos): # if there is no edge between v and the # last element of the path formed so far # return false. if (graph[path[pos - 1]][v] == 0): return False # Otherwise if there is an edge between # v and last element of the path formed so # far, then check all the elements of the # path. If v is already in the path return # false. for i in range(pos): if (path[i] == v): return False # If none of the previous cases satisfies # then we can add v to the path in the # position pos. Hence return true. return True # Function to form a path based on the graph.def formpath(graph, path, pos): # If all the elements are included in the # path i.e. length of the path is n then # return true i.e. path formed. n = len(graph) - 1 if (pos == n + 1): return True # This loop checks for each element if it # can be fitted as the next element of the # path and recursively finds the next # element of the path. for v in range(1, n + 1): if issafe(v, graph, path, pos): path[pos] = v # Recurs for next element of the path. if (formpath(graph, path, pos + 1) == True): return True # If adding v does not give a solution # then remove it from path path[pos] = -1 # if any vertex cannot be added with the # formed path then return false and # backtracks. return False # Function to find out sum-square series.def hampath(n): # base case: if n = 1 there is no solution if n == 1: return 'No Solution' # Make an array of perfect squares from 1 # to (2 * n-1) l = list() for i in range(1, int((2 * n-1) ** 0.5) + 1): l.append(i**2) # Form the graph where sum of two adjacent # vertices is a perfect square graph = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(1, n + 1): for ele in l: if ((ele-i) > 0 and (ele-i) <= n and (2 * i != ele)): graph[i][ele - i] = 1 graph[ele - i][i] = 1 # strating from 1 upto n check for each # element i if any path can be formed # after taking i as the first element. for j in range(1, n + 1): path = [-1 for k in range(n + 1)] path[1] = j # If starting from j we can form any path # then we will return the path if formpath(graph, path, 2) == True: return path[1:] # If no path can be formed at all return # no solution. return 'No Solution' # Driver Functionprint(17, '->', hampath(17))print(20, '->', hampath(20))print(25, '->', hampath(25)) Output: 17 -> [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17] 20 -> No Solution 25 -> [2, 23, 13, 12, 24, 25, 11, 14, 22, 3, 1, 8, 17, 19, 6, 10, 15, 21, 4, 5, 20, 16, 9, 7, 18] Discussion:This backtracking algorithm takes exponential time to find Hamiltonian Path. Hence the time complexity of this algorithm is exponential.In the last part of the hampath(n) function if we just print the path rather returning it then it will print all possible Hamiltonian Path i.e. all possible representations.Actually we will first get a representation like this for n = 15. For n<15 there is no representation. For n = 18, 19, 20, 21, 22, 24 there is also no Hamiltonian Path. For rest of the numbers it works well. Reference: Numberphile maths-perfect-square number-theory Graph number-theory Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Path in a Directed Acyclic Graph Best First Search (Informed Search) Graph Coloring | Set 2 (Greedy Algorithm) Maximum Bipartite Matching Graph Coloring | Set 1 (Introduction and Applications) Find if there is a path between two vertices in a directed graph Find minimum s-t cut in a flow network Eulerian path and circuit for undirected graph Real-time application of Data Structures Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
[ { "code": null, "e": 26335, "s": 26307, "text": "\n27 Nov, 2018" }, { "code": null, "e": 26367, "s": 26335, "text": "Prerequisite: Hamiltonian Cycle" }, { "code": null, "e": 26588, "s": 26367, "text": "Given an integer n(>=2), find a permutation of numbers from 1 to n such that the sum of two consecutive numbers of that permutation is a perfect square. If that kind of permutation is not possible to print “No Solution”." }, { "code": null, "e": 26598, "s": 26588, "text": "Examples:" }, { "code": null, "e": 26907, "s": 26598, "text": "Input : 17\nOutput : [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17]\nExplanation : 16+9 = 25 = 5*5, 9+7 = 16 = 4*4, 7+2 = 9 = 3*3 and so on.\n\nInput: 20\nOutput: No Solution\n\nInput : 25\nOutput : [2, 23, 13, 12, 24, 25, 11, 14, 22, 3, 1, 8, \n 17, 19, 6, 10, 15, 21, 4, 5, 20, 16, 9, 7, 18]\n" }, { "code": null, "e": 27220, "s": 26907, "text": "Method:We can represent a graph, where numbers from 1 to n are the nodes of the graph and there is an edge between ith and jth node if (i+j) is a perfect square. Then we can search if there is any Hamiltonian Path in the graph. If there is at least one path then we print a path otherwise we print “No Solution”." }, { "code": null, "e": 27230, "s": 27220, "text": "Approach:" }, { "code": null, "e": 27721, "s": 27230, "text": "1. First list up all the perfect square numbers \n which we can get by adding two numbers.\n We can get at max (2*n-1). so we will take \n only the squares up to (2*n-1).\n2. Take an adjacency matrix to represent the graph.\n3. For each number from 1 to n find out numbers with \n which it can add upto a perfect square number.\n Fill respective cells of the adjacency matrix by 1.\n4. Now find if there is any Hamiltonian path in the \n graph using backtracking as discussed earlier. \n" }, { "code": null, "e": 27729, "s": 27721, "text": "Python3" }, { "code": "# Python3 program for Sum-square series using# hamiltonian path concept and backtracking # Function to check wheter we can add number# v with the path in the position pos.def issafe(v, graph, path, pos): # if there is no edge between v and the # last element of the path formed so far # return false. if (graph[path[pos - 1]][v] == 0): return False # Otherwise if there is an edge between # v and last element of the path formed so # far, then check all the elements of the # path. If v is already in the path return # false. for i in range(pos): if (path[i] == v): return False # If none of the previous cases satisfies # then we can add v to the path in the # position pos. Hence return true. return True # Function to form a path based on the graph.def formpath(graph, path, pos): # If all the elements are included in the # path i.e. length of the path is n then # return true i.e. path formed. n = len(graph) - 1 if (pos == n + 1): return True # This loop checks for each element if it # can be fitted as the next element of the # path and recursively finds the next # element of the path. for v in range(1, n + 1): if issafe(v, graph, path, pos): path[pos] = v # Recurs for next element of the path. if (formpath(graph, path, pos + 1) == True): return True # If adding v does not give a solution # then remove it from path path[pos] = -1 # if any vertex cannot be added with the # formed path then return false and # backtracks. return False # Function to find out sum-square series.def hampath(n): # base case: if n = 1 there is no solution if n == 1: return 'No Solution' # Make an array of perfect squares from 1 # to (2 * n-1) l = list() for i in range(1, int((2 * n-1) ** 0.5) + 1): l.append(i**2) # Form the graph where sum of two adjacent # vertices is a perfect square graph = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(1, n + 1): for ele in l: if ((ele-i) > 0 and (ele-i) <= n and (2 * i != ele)): graph[i][ele - i] = 1 graph[ele - i][i] = 1 # strating from 1 upto n check for each # element i if any path can be formed # after taking i as the first element. for j in range(1, n + 1): path = [-1 for k in range(n + 1)] path[1] = j # If starting from j we can form any path # then we will return the path if formpath(graph, path, 2) == True: return path[1:] # If no path can be formed at all return # no solution. return 'No Solution' # Driver Functionprint(17, '->', hampath(17))print(20, '->', hampath(20))print(25, '->', hampath(25))", "e": 30729, "s": 27729, "text": null }, { "code": null, "e": 30737, "s": 30729, "text": "Output:" }, { "code": null, "e": 30928, "s": 30737, "text": "17 -> [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17]\n20 -> No Solution\n25 -> [2, 23, 13, 12, 24, 25, 11, 14, 22, 3, 1, 8, 17, 19, 6, 10, \n 15, 21, 4, 5, 20, 16, 9, 7, 18]\n" }, { "code": null, "e": 31456, "s": 30928, "text": "Discussion:This backtracking algorithm takes exponential time to find Hamiltonian Path. Hence the time complexity of this algorithm is exponential.In the last part of the hampath(n) function if we just print the path rather returning it then it will print all possible Hamiltonian Path i.e. all possible representations.Actually we will first get a representation like this for n = 15. For n<15 there is no representation. For n = 18, 19, 20, 21, 22, 24 there is also no Hamiltonian Path. For rest of the numbers it works well." }, { "code": null, "e": 31479, "s": 31456, "text": "Reference: Numberphile" }, { "code": null, "e": 31500, "s": 31479, "text": "maths-perfect-square" }, { "code": null, "e": 31514, "s": 31500, "text": "number-theory" }, { "code": null, "e": 31520, "s": 31514, "text": "Graph" }, { "code": null, "e": 31534, "s": 31520, "text": "number-theory" }, { "code": null, "e": 31540, "s": 31534, "text": "Graph" }, { "code": null, "e": 31638, "s": 31540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31679, "s": 31638, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 31715, "s": 31679, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 31757, "s": 31715, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 31784, "s": 31757, "text": "Maximum Bipartite Matching" }, { "code": null, "e": 31839, "s": 31784, "text": "Graph Coloring | Set 1 (Introduction and Applications)" }, { "code": null, "e": 31904, "s": 31839, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 31943, "s": 31904, "text": "Find minimum s-t cut in a flow network" }, { "code": null, "e": 31990, "s": 31943, "text": "Eulerian path and circuit for undirected graph" }, { "code": null, "e": 32031, "s": 31990, "text": "Real-time application of Data Structures" } ]
Number Theory | Generators of finite cyclic group under addition - GeeksforGeeks
19 Apr, 2021 Given a number n, find all generators of cyclic additive group under modulo n. Generator of a set {0, 1, ... n-1} is an element x such that x is smaller than n, and using x (and addition operation), we can generate all elements of the set.Examples: Input : 10 Output : 1 3 7 9 The set to be generated is {0, 1, .. 9} By adding 1, single or more times, we can create all elements from 0 to 9. Similarly using 3, we can generate all elements. 30 % 10 = 0, 21 % 10 = 1, 12 % 10 = 2, ... Same is true for 7 and 9. Input : 24 Output : 1 5 7 11 13 17 19 23 A simple solution is to run a loop from 1 to n-1 and for every element check if it is generator. To check generator, we keep adding element and we check if we can generate all numbers until remainder starts repeating.An Efficient solution is based on the fact that a number x is generator if x is relatively prime to n, i.e., gcd(n, x) =1.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // A simple C++ program to find all generators#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} // Print generators of nint printGenerators(unsigned int n){ // 1 is always a generator cout << "1 "; for (int i=2; i < n; i++) // A number x is generator of GCD is 1 if (gcd(i, n) == 1) cout << i << " ";} // Driver program to test above functionint main(){ int n = 10; printGenerators(n); return 0;} // A simple Java program to find all generators class GFG { // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} // Print generators of nstatic void printGenerators(int n){ // 1 is always a generator System.out.println("1 "); for (int i=2; i < n; i++) // A number x is generator of GCD is 1 if (gcd(i, n) == 1) System.out.println(i +" ");} // Driver program to test above functionpublic static void main(String args[]){ int n = 10; printGenerators(n);}} # Python3 program to find all generators # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b; return gcd(b % a, a); # Print generators of ndef printGenerators(n): # 1 is always a generator print("1", end = " "); for i in range(2, n): # A number x is generator # of GCD is 1 if (gcd(i, n) == 1): print(i, end = " "); # Driver Coden = 10;printGenerators(n); # This code is contributed by mits // A simple C# program to find all generatorsusing System; class GFG{ // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Print generators of nstatic void printGenerators(int n){ // 1 is always a generator Console.Write("1 "); for (int i = 2; i < n; i++) // A number x is generator of GCD is 1 if (gcd(i, n) == 1) Console.Write(i +" ");} // Driver codepublic static void Main(String []args){ int n = 10; printGenerators(n);}} // This code contributed by Rajput-Ji <?php// PHP program to find all generators // Function to return gcd of a and b function gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Print generators of nfunction printGenerators($n){ // 1 is always a generator echo "1 "; for ($i = 2; $i < $n; $i++) // A number x is generator // of GCD is 1 if (gcd($i, $n) == 1) echo $i, " ";} // Driver program to test// above function $n = 10; printGenerators($n); // This code is contributed by Ajit?> <script> // A simple Javascript program to// find all generators // Function to return gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // Print generators of nfunction printGenerators(n){ // 1 is always a generator document.write("1 "); for(var i = 2; i < n; i++) // A number x is generator of // GCD is 1 if (gcd(i, n) == 1) document.write(i + " ");} // Driver Codevar n = 10; printGenerators(n); // This code is contributed by Kirti </script> Output : 1 3 7 9 How does this work? If we consider all remainders of n consecutive multiples of x, then some remainders would repeat if GCD of x and n is not 1. If some remainders repeat, then x cannot be a generator. Note that after n consecutive multiples, remainders would anyway repeat.Interesting Observation : Number of generators of a number n is equal to Φ(n) where Φ is Euler Totient Function.This article is contributed by Ujjwal Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar Kirti_Mangal Rajput-Ji Akanksha_Rai euler-totient number-theory Mathematical Misc Misc number-theory Mathematical Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program for Decimal to Binary Conversion Find all factors of a natural number | Set 1 Top 10 algorithms in Interview Questions Find all factors of a natural number | Set 1 vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions?
[ { "code": null, "e": 24319, "s": 24291, "text": "\n19 Apr, 2021" }, { "code": null, "e": 24570, "s": 24319, "text": "Given a number n, find all generators of cyclic additive group under modulo n. Generator of a set {0, 1, ... n-1} is an element x such that x is smaller than n, and using x (and addition operation), we can generate all elements of the set.Examples: " }, { "code": null, "e": 24875, "s": 24570, "text": "Input : 10\nOutput : 1 3 7 9\nThe set to be generated is {0, 1, .. 9}\nBy adding 1, single or more times, we \ncan create all elements from 0 to 9.\nSimilarly using 3, we can generate all\nelements.\n30 % 10 = 0, 21 % 10 = 1, 12 % 10 = 2, ...\nSame is true for 7 and 9.\n\nInput : 24\nOutput : 1 5 7 11 13 17 19 23" }, { "code": null, "e": 25264, "s": 24877, "text": "A simple solution is to run a loop from 1 to n-1 and for every element check if it is generator. To check generator, we keep adding element and we check if we can generate all numbers until remainder starts repeating.An Efficient solution is based on the fact that a number x is generator if x is relatively prime to n, i.e., gcd(n, x) =1.Below is the implementation of above approach: " }, { "code": null, "e": 25268, "s": 25264, "text": "C++" }, { "code": null, "e": 25273, "s": 25268, "text": "Java" }, { "code": null, "e": 25281, "s": 25273, "text": "Python3" }, { "code": null, "e": 25284, "s": 25281, "text": "C#" }, { "code": null, "e": 25288, "s": 25284, "text": "PHP" }, { "code": null, "e": 25299, "s": 25288, "text": "Javascript" }, { "code": "// A simple C++ program to find all generators#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} // Print generators of nint printGenerators(unsigned int n){ // 1 is always a generator cout << \"1 \"; for (int i=2; i < n; i++) // A number x is generator of GCD is 1 if (gcd(i, n) == 1) cout << i << \" \";} // Driver program to test above functionint main(){ int n = 10; printGenerators(n); return 0;}", "e": 25851, "s": 25299, "text": null }, { "code": "// A simple Java program to find all generators class GFG { // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} // Print generators of nstatic void printGenerators(int n){ // 1 is always a generator System.out.println(\"1 \"); for (int i=2; i < n; i++) // A number x is generator of GCD is 1 if (gcd(i, n) == 1) System.out.println(i +\" \");} // Driver program to test above functionpublic static void main(String args[]){ int n = 10; printGenerators(n);}}", "e": 26421, "s": 25851, "text": null }, { "code": "# Python3 program to find all generators # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b; return gcd(b % a, a); # Print generators of ndef printGenerators(n): # 1 is always a generator print(\"1\", end = \" \"); for i in range(2, n): # A number x is generator # of GCD is 1 if (gcd(i, n) == 1): print(i, end = \" \"); # Driver Coden = 10;printGenerators(n); # This code is contributed by mits", "e": 26897, "s": 26421, "text": null }, { "code": "// A simple C# program to find all generatorsusing System; class GFG{ // Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Print generators of nstatic void printGenerators(int n){ // 1 is always a generator Console.Write(\"1 \"); for (int i = 2; i < n; i++) // A number x is generator of GCD is 1 if (gcd(i, n) == 1) Console.Write(i +\" \");} // Driver codepublic static void Main(String []args){ int n = 10; printGenerators(n);}} // This code contributed by Rajput-Ji", "e": 27482, "s": 26897, "text": null }, { "code": "<?php// PHP program to find all generators // Function to return gcd of a and b function gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Print generators of nfunction printGenerators($n){ // 1 is always a generator echo \"1 \"; for ($i = 2; $i < $n; $i++) // A number x is generator // of GCD is 1 if (gcd($i, $n) == 1) echo $i, \" \";} // Driver program to test// above function $n = 10; printGenerators($n); // This code is contributed by Ajit?>", "e": 28015, "s": 27482, "text": null }, { "code": "<script> // A simple Javascript program to// find all generators // Function to return gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // Print generators of nfunction printGenerators(n){ // 1 is always a generator document.write(\"1 \"); for(var i = 2; i < n; i++) // A number x is generator of // GCD is 1 if (gcd(i, n) == 1) document.write(i + \" \");} // Driver Codevar n = 10; printGenerators(n); // This code is contributed by Kirti </script>", "e": 28561, "s": 28015, "text": null }, { "code": null, "e": 28571, "s": 28561, "text": "Output : " }, { "code": null, "e": 28579, "s": 28571, "text": "1 3 7 9" }, { "code": null, "e": 29390, "s": 28579, "text": "How does this work? If we consider all remainders of n consecutive multiples of x, then some remainders would repeat if GCD of x and n is not 1. If some remainders repeat, then x cannot be a generator. Note that after n consecutive multiples, remainders would anyway repeat.Interesting Observation : Number of generators of a number n is equal to Φ(n) where Φ is Euler Totient Function.This article is contributed by Ujjwal Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29396, "s": 29390, "text": "jit_t" }, { "code": null, "e": 29409, "s": 29396, "text": "Mithun Kumar" }, { "code": null, "e": 29422, "s": 29409, "text": "Kirti_Mangal" }, { "code": null, "e": 29432, "s": 29422, "text": "Rajput-Ji" }, { "code": null, "e": 29445, "s": 29432, "text": "Akanksha_Rai" }, { "code": null, "e": 29459, "s": 29445, "text": "euler-totient" }, { "code": null, "e": 29473, "s": 29459, "text": "number-theory" }, { "code": null, "e": 29486, "s": 29473, "text": "Mathematical" }, { "code": null, "e": 29491, "s": 29486, "text": "Misc" }, { "code": null, "e": 29496, "s": 29491, "text": "Misc" }, { "code": null, "e": 29510, "s": 29496, "text": "number-theory" }, { "code": null, "e": 29523, "s": 29510, "text": "Mathematical" }, { "code": null, "e": 29528, "s": 29523, "text": "Misc" }, { "code": null, "e": 29626, "s": 29528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29635, "s": 29626, "text": "Comments" }, { "code": null, "e": 29648, "s": 29635, "text": "Old Comments" }, { "code": null, "e": 29672, "s": 29648, "text": "Merge two sorted arrays" }, { "code": null, "e": 29715, "s": 29672, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29729, "s": 29715, "text": "Prime Numbers" }, { "code": null, "e": 29770, "s": 29729, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 29815, "s": 29770, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 29856, "s": 29815, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 29901, "s": 29856, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 29955, "s": 29901, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 30016, "s": 29955, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" } ]
How to get the count of each distinct value in a column in MySQL?
Let us see an example to get the count of each distinct value in a column. Firstly, we will create a table. The CREATE command is used to create a table. mysql> create table DistinctDemo1 - > ( - > id int, - > name varchar(100) - > ); Query OK, 0 rows affected (0.43 sec) mysql> insert into DistinctDemo1 values(1,'John'); Query OK, 1 row affected (0.34 sec) mysql> insert into DistinctDemo1 values(2,'John'); Query OK, 1 row affected (0.20 sec) mysql> insert into DistinctDemo1 values(3,'John'); Query OK, 1 row affected (0.09 sec) mysql> insert into DistinctDemo1 values(4,'Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into DistinctDemo1 values(5,'David'); Query OK, 1 row affected (0.12 sec) mysql> select *from DistinctDemo1; The following is the output that displays all the records. +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | John | | 3 | John | | 4 | Carol | | 5 | David | +------+-------+ 5 rows in set (0.00 sec) The following is the syntax to get the count. mysql> SELECT name,COUNT(1) as OccurenceValue FROM DistinctDemo1 GROUP BY name ORDER BY OccurenceValue; Here is the output. +-------+----------------+ | name | OccurenceValue | +-------+----------------+ | Carol | 1 | | David | 1 | | John | 3 | +-------+----------------+ 3 rows in set (0.04 sec)
[ { "code": null, "e": 1170, "s": 1062, "text": "Let us see an example to get the count of each distinct value in a column. Firstly, we will create a table." }, { "code": null, "e": 1216, "s": 1170, "text": "The CREATE command is used to create a table." }, { "code": null, "e": 1346, "s": 1216, "text": "mysql> create table DistinctDemo1\n - > (\n - > id int,\n - > name varchar(100)\n - > );\nQuery OK, 0 rows affected (0.43 sec)" }, { "code": null, "e": 1787, "s": 1346, "text": "mysql> insert into DistinctDemo1 values(1,'John');\nQuery OK, 1 row affected (0.34 sec)\n\nmysql> insert into DistinctDemo1 values(2,'John');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DistinctDemo1 values(3,'John');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into DistinctDemo1 values(4,'Carol');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DistinctDemo1 values(5,'David');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1822, "s": 1787, "text": "mysql> select *from DistinctDemo1;" }, { "code": null, "e": 1881, "s": 1822, "text": "The following is the output that displays all the records." }, { "code": null, "e": 2060, "s": 1881, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | John |\n| 3 | John |\n| 4 | Carol |\n| 5 | David |\n+------+-------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 2106, "s": 2060, "text": "The following is the syntax to get the count." }, { "code": null, "e": 2210, "s": 2106, "text": "mysql> SELECT name,COUNT(1) as OccurenceValue FROM DistinctDemo1 GROUP BY name ORDER BY OccurenceValue;" }, { "code": null, "e": 2230, "s": 2210, "text": "Here is the output." }, { "code": null, "e": 2445, "s": 2230, "text": "+-------+----------------+\n| name | OccurenceValue |\n+-------+----------------+\n| Carol | 1 |\n| David | 1 |\n| John | 3 |\n+-------+----------------+\n3 rows in set (0.04 sec)\n" } ]
How to Measure Statistical Causality: A Transfer Entropy Approach with Financial Applications | by Thársis Souza, PhD | Towards Data Science
We’ve all heard the say “correlation does not imply causation”, but how can we quantify causation? This is an extremely difficult and often misleading task, particularly when trying to infer causality from observational data and we cannot perform controlled trials or A/B testing. Take for example the 2-dimensional system from Fig. 4.1. At a first glance, one could say that there is no clear relationship or causality between random variables x1 and x2. However, this apparent random system presents a very simple causal relationship defined by the following equations: A simple non-linearity introduced in the relationship between x2 and x1 was enough to introduce complexity into the system and potentially mislead a naive human. Fortunately, we can take advantage of statistics and information theory to uncover complex causal relationships from observational data (remember, this is still a very challenging task). The objectives of this Article are the following: Introduce a prediction-based definition of causality and its implementation using a vector auto-regression formulation. Introduce a probabilistic-definition of causality and its implementation using an information-theoretical framework. Simulate linear and nonlinear systems and uncover causal links with the proposed methods. Quantify information flow among global equity indexes further uncovering which indexes are driving the global financial markets. Discuss further applications including the impact of social media sentiment in financial and crypto markets. We also provide code to reproduce results as part of our Open Source Live Book Initiative. We quantify causality by using the notion of the causal relation introduced by Granger (Wiener 1956; Granger 1969), where a signal X is said to Granger-cause Y if the future realizations of Y can be better explained using the past information from X and Y rather than Y alone. The most common definitions of Granger-causality (G-causality) rely on the prediction of a future value of the variable Y by using the past values of X and Y itself. In that form, X is said to G-cause Y if the use of X improves the prediction of Y. Let be a random variable associated at time while represents the collection of random variables up to time . We consider and to be three stochastic processes. Let be a predictor for the value of the variable at time . We compare the expected value of a loss function with the error of two models: The expected value of the prediction error given only The expected value of the prediction error given and The expected value of the prediction error given only The expected value of the prediction error given and In both models, the functions f1(.) and f2(.) are chosen to minimize the expected value of the loss function. In most cases, these functions are retrieved with linear and, possibly, with nonlinear regressions, neural networks etc. Typical forms for g(.) are the l1- or l2-norms. We can now provide our first definition of statistical causality under the Granger causal notion as follows: Standard Granger-causality tests assume a functional form in the relationship among the causes and effects and are implemented by fitting autoregressive models (Wiener 1956; Granger 1969). Consider the linear vector-autoregressive (VAR) equations: where k is the number of lags considered. Alternatively, you can choose your DL/SVM/RF/GLM method of choice to fit the model. From Def. 4.1, X does not G-cause Y if and only if the prediction errors of X in the restricted Eq. (4.1)and unrestricted regression models Eq. (4.2) are equal (i.e., they are statistically indistinguishable). A one-way ANOVA test can be utilized to test if the residuals from Eqs. (4.1) and (4.2) differ from each other significantly. When more than one lag k is tested, a correction for multiple hypotheses testing should be applied, e.g. False Discovery Rate (FDR) or Bonferroni correction. A more general definition than Def. 4.1 that does not depend on assuming prediction functions can be formulated by considering conditional probabilities. A probabilistic definition of G-causality assumes that and are independent given the past information if and only if , where represents the conditional probability distribution. In other words, omitting past information from does not change the probability distribution of . This leads to our second definition of statistical causality as follows: Def. 4.2 does not assume any functional form in the coupling between X and Y. Nevertheless, it requires a method to assess their conditional dependency. In the next section, we will leverage an Information-Theoretical framework for that purpose. To compute G-Causality, we use the concept of Transfer Entropy. Since its introduction (Schreiber 2000), Transfer Entropy has been recognized as an important tool in the analysis of causal relationships in nonlinear systems (Hlavackovaschindler et al. 2007). It detects directional and dynamical information (Montalto 2014) while not assuming any particular functional form to describe interactions among systems. One can interpret this quantity as a measure of the dominant direction of the information flow. In other words, a positive result indicates a dominant information flow from X to Y compared to the other direction or, similarly, it indicates which system provides more predictive information about the other system (Michalowicz, Nichols, and Bucholtz 2013). It has been shown (Barnett, Barrett, and Seth 2009) that linear G-causality and Transfer Entropy are equivalent if all processes are jointly Gaussian. In particular, by assuming the standard measure (l2-norm loss function) of linear G-causality for the bi-variate case as follows: the following can be proved (Barnett, Barrett, and Seth 2009): This result provides a direct mapping between the Transfer Entropy and the linear G-causality implemented in the standard VAR framework. Hence, it is possible to estimate the TE both in its general form and with its equivalent form for linear G-causality. In this section, we construct simulated systems to couple random variables in a causal manner. We then quantify information flow using the methods studied in this Article. We first assume a linear system, where random variables have linear relationships defined as follow: We simulate this linear system with the following code: Fig. 4.2 represents the dependencies of the simulated linear system. We first define a function that calculates a bi-variate measure for G-causality as defined in Eq. (4.4) as follows: We use the function calc_te from the R package RTransferEntropy and the previously defined function Linear.GC to calculate pairwise information flow among the simulated variables as follows: The function FApply.Pairwise is an auxiliary function that simply applies a given function D.Func to all possible pairs of columns from a given matrix X as follows: Fig. 4.3 A) and B) show Granger-causality and Transfer Entropy among the system’s variables, respectively. A cell (x,y) presents the information flow from variable y to variable x. We observe that both the Granger-causality (linear) and Transfer Entropy (nonlinear) approaches presented similar results, i.e., both methods captured the system’s dependencies similarly. This result is expected as the system is purely linear and Transfer Entropy is able to capture both the linear and nonlinear interactions. We define a second system by introducing nonlinear interactions between x1 and the variables x2 and x5 as follows: We simulate this nonlinear system with the following code: Fig. 4.5 represents the dependencies of the simulated nonlinear system. We calculate Granger-causality and Transfer Entropy of the simulated nonlinear system as follows: From Fig. 4.6 A) and B), we observe that the nonlinear interactions introduced were not captured by the linear formulation of Granger-causality. While all linear interactions presented similar linear and nonlinear information flows, the two nonlinear interactions introduced into the system presented relatively higher nonlinear information flow compared to the linear formulation. The world’s financial markets form a complex, dynamic network in which individual markets interact with one another. This multitude of interactions can lead to highly significant and unexpected effects, and it is vital to understand precisely how various markets around the world influence one another (Junior, Mullokandov, and Kenett 2015). In this section, we use Transfer Entropy for the identification of dependency relations among international stock market indices. First, we select some of the major global indices for our analysis, namely the S&P 500, the FTSE 100, the DAX, the EURONEXT 100 and the IBOVESPA, which track the following markets, respectively, the US, the UK, Germany, Europe and Brazil. They are defined by the following tickers: tickers<-c("^GSPC", "^FTSE", "^GDAXI", "^N100", "^BVSP") Next, we will load log-returns of daily closing adjusted prices for the selected indices as follows (check here to have access to this dataset): library(xts)dataset<-as.xts(read.zoo('./data/global_indices_returns.csv', header=TRUE, index.column=1, sep=","))head(dataset)## X.GSPC X.FTSE X.GDAXI X.N100 X.BVSP## 2000-01-02 19:00:00 0.000000 NA 0.00000 0.00000 0.00000## 2000-01-03 19:00:00 -0.039099 0.00000 -0.02456 -0.04179 -0.06585## 2000-01-04 19:00:00 0.001920 -0.01969 -0.01297 -0.02726 0.02455## 2000-01-05 19:00:00 0.000955 -0.01366 -0.00418 -0.00842 -0.00853## 2000-01-06 19:00:00 0.026730 0.00889 0.04618 0.02296 0.01246## 2000-01-09 19:00:00 0.011128 0.01570 0.02109 0.01716 0.04279 The influence that one market plays in another is dynamic. Here, we will consider the time period from 01/01/2014 until 08/19/2019 and we will omit days with invalid returns due to missing data using the function NARV.omit from the package IDPmisc as follows: library(IDPmisc)dataset.post.crisis <- NaRV.omit(as.data.frame(dataset["2014-01-01/"])) We will calculate pairwise Transfer Entropy among all indices considered and construct a matrix such that each value in the position (i,j) will contain the Transfer Entropy from tickers[i] to tickers[j] as follows: # Calculate pairwise Transfer Entropy among global indicesTE.matrix<-FApply.Pairwise(dataset.post.crisis, calc_ete)rownames(TE.matrix)<-colnames(TE.matrix)<-tickers Fig. 4.8 displays the resulting Transfer Entropy matrix. We normalize the Transfer Entropy values by dividing it by the maximum value in the matrix such that all values range from 0 to 1. We observe that the international indices studied are highly interconnected in the period analyzed with the highest information flow going from the US market to the UK market (^GSPC -> ^FTSE). The second highest information flow is going in the opposite direction, i.e., from the UK market to the US market. That’s a result we would expect as the US and the UK markets are strongly coupled, historically. We also calculate the marginal contribution of each market to the total Transfer Entropy in the system by calculating the sum of Transfer Entropy for each row in the Transfer Entropy matrix, which we also normalize such that all values range from 0 to 1: TE.marginal<-apply(TE.matrix, 1, sum)TE.marginal.norm<-TE.marginal/sum(TE.marginal)print(TE.marginal.norm)## ^GSPC ^FTSE ^GDAXI ^N100 ^BVSP ## 0.346 0.215 0.187 0.117 0.135 We observe that the US is the most influential market in the time period studied with 34.6% of the total Transfer Entropy followed by the UK and Germany with 21.4% and 18.6%, respectively. Japan and Brazil are the least influential markets with normalized Transfer Entropies of 11.7% and 13.4%, respectively. An experiment left to the reader is to build a daily trading strategy that exploits information flow among international markets. The proposed thesis is that one could build a profitable strategy by placing bets on futures of market indices that receive significant information flow from markets that observed unexpected returns/movements. For an extended analysis with a broader set of indices see (Junior, Mullokandov, and Kenett 2015). The authors develop networks of international stock market indices using an information theoretical framework. They use 83 stock market indices of a diversity of countries, as well as their single day lagged values, to probe the correlation and the flow of information from one stock index to another taking into account different operating hours. They find that Transfer Entropy is an effective way to quantify the flow of information between indices, and that a high degree of information flow between indices lagged by one day coincides to same day correlation between them. Investors’ decisions are modulated not only by companies’ fundamentals but also by personal beliefs, peers influence and information generated from news and the Internet. Rational and irrational investor’s behavior and their relation with the market efficiency hypothesis (Fama 1970) have been largely debated in the economics and financial literature (Shleifer 2000). However, it was only recently that the availability of vast amounts of data from online systems paved the way for the large-scale investigation of investor’s collective behavior in financial markets. A research paper (Souza and Aste 2016) used some of the methods studied in this Article to uncover that information flows from social media to stock markets revealing that tweets are causing market movements through a nonlinear complex interaction. The authors provide empirical evidence that suggests social media and stock markets have a nonlinear causal relationship. They take advantage of an extensive data set composed of social media messages related to DJIA index components. By using information-theoretic measures to cope for possible nonlinear causal effects between social media and the stock market, the work points out stunning differences in the results with respect to linear coupling. Two main conclusions are drawn: First, social media significant causality on stocks’ returns are purely nonlinear in most cases; Second, social media dominates the directional coupling with stock market, an effect not observable within linear modeling. Results also serve as empirical guidance on model adequacy in the investigation of sociotechnical and financial systems. Fig. 4.9 shows the significant causality links found between social media and stocks’ returns considering both cases: nonlinear (Transfer Entropy) and linear G-causality (linear VAR framework). The linear analysis discovers only three stocks with significant causality: INTEL CORP., NIKE INC. and WALT DISNEY CO. The Nonlinear analysis discovers that several other stocks have significant causality. In addition to the 3 stocks identified with significant linear causality, other 8 stocks presented purely nonlinear causality. The low level of causality obtained under linear constraints is in-line with results from similar studies in the literature, where it was found that stocks’ returns show weak causality links (Alanyali, Moat, and Preis 2013, Antweiler and Frank (2004)) and social media sentiment analytics, at least when taken alone, have small or no predictive power (Ranco 2015) and do not have significant lead-time information about stock’s movements for the majority of the stocks (Zheludev, Smith, and Aste 2014). Contrariwise, results from the nonlinear analyses unveiled a much higher level of causality indicating that linear constraints may be neglecting the relationship between social media and stock markets. In summary, (Souza and Aste 2016) is a good example on how causality can be not only complex but also misleading further highlighting the importance of choice in the methodology used to quantify it. In (Keskin and Aste 2019), the authors use information-theoretic measures studied in this Article for non-linear causality detection applied to social media sentiment and cryptocurrency prices. Using these techniques on sentiment and price data over a 48-month period to August 2018, for four major cryptocurrencies, namely bitcoin (BTC), ripple (XRP), litecoin (LTC) and ethereum (ETH), the authors detect significant information transfer, on hourly timescales, in directions of both sentiment to price and of price to sentiment. The work reports the scale of non-linear causality to be an order of magnitude greater than linear causality. The information-theoretic investigation detected a significant non-linear causal relationship in BTC, LTC and XRP, over multiple timescales and in both the directions sentiment to price and price to sentiment. The effect was strongest and most consistent for BTC and LTC. Fig. 4.10 shows Transfer Entropy results between BTC sentiment and BTC prices. All analysis for this paper was performed using a Python package (PyCausality), which is available at https://github.com/ZacKeskin/PyCausality. Untangling cause and effect can be devilishly difficult. However, statistical tools can help us tell correlation from causation. In this Article, we introduced the notion of Granger-causality and its traditional implementation in a linear vector-autoregressive framework. We then defined information theoretical measures to quantify Transfer Entropy as a method to estimate statistical causality in nonlinear systems. We simulated linear and nonlinear systems further showing that the traditional linear G-causality approach failed to detect simple non-linearities introduced into the system while Transfer Entropy successfully detected such relationships. Finally, we showed how Transfer Entropy can be used to quantify relationships among global equity indexes. We also discussed further applications from the literature where Information Theoretical measures were used to quantify causal links between investor sentiment and movements in the equity and crypto markets. We hope you enjoyed this casual causal journey and remember: Quantify causality, responsibly.
[ { "code": null, "e": 453, "s": 172, "text": "We’ve all heard the say “correlation does not imply causation”, but how can we quantify causation? This is an extremely difficult and often misleading task, particularly when trying to infer causality from observational data and we cannot perform controlled trials or A/B testing." }, { "code": null, "e": 510, "s": 453, "text": "Take for example the 2-dimensional system from Fig. 4.1." }, { "code": null, "e": 744, "s": 510, "text": "At a first glance, one could say that there is no clear relationship or causality between random variables x1 and x2. However, this apparent random system presents a very simple causal relationship defined by the following equations:" }, { "code": null, "e": 906, "s": 744, "text": "A simple non-linearity introduced in the relationship between x2 and x1 was enough to introduce complexity into the system and potentially mislead a naive human." }, { "code": null, "e": 1093, "s": 906, "text": "Fortunately, we can take advantage of statistics and information theory to uncover complex causal relationships from observational data (remember, this is still a very challenging task)." }, { "code": null, "e": 1143, "s": 1093, "text": "The objectives of this Article are the following:" }, { "code": null, "e": 1263, "s": 1143, "text": "Introduce a prediction-based definition of causality and its implementation using a vector auto-regression formulation." }, { "code": null, "e": 1380, "s": 1263, "text": "Introduce a probabilistic-definition of causality and its implementation using an information-theoretical framework." }, { "code": null, "e": 1470, "s": 1380, "text": "Simulate linear and nonlinear systems and uncover causal links with the proposed methods." }, { "code": null, "e": 1599, "s": 1470, "text": "Quantify information flow among global equity indexes further uncovering which indexes are driving the global financial markets." }, { "code": null, "e": 1708, "s": 1599, "text": "Discuss further applications including the impact of social media sentiment in financial and crypto markets." }, { "code": null, "e": 1799, "s": 1708, "text": "We also provide code to reproduce results as part of our Open Source Live Book Initiative." }, { "code": null, "e": 2076, "s": 1799, "text": "We quantify causality by using the notion of the causal relation introduced by Granger (Wiener 1956; Granger 1969), where a signal X is said to Granger-cause Y if the future realizations of Y can be better explained using the past information from X and Y rather than Y alone." }, { "code": null, "e": 2325, "s": 2076, "text": "The most common definitions of Granger-causality (G-causality) rely on the prediction of a future value of the variable Y by using the past values of X and Y itself. In that form, X is said to G-cause Y if the use of X improves the prediction of Y." }, { "code": null, "e": 2758, "s": 2325, "text": "Let \n\n\n\n\n\n\n be a random variable associated at time \n\n\n\n while \n\n\n\n\n\n\n represents the collection of random variables up to time \n\n\n\n.\nWe consider \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n and \n\n\n\n\n\n\n to be three stochastic processes. \nLet \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n be a predictor for the value of the variable \n\n\n\n at time \n\n\n\n\n\n\n\n\n\n.\nWe compare the expected value of a loss function \n\n\n\n\n\n\n\n\n\n\n\n\n with the error \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n of two models: " }, { "code": null, "e": 3132, "s": 2758, "text": "\nThe expected value of the prediction error given only \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe expected value of the prediction error given \n\n\n\n\n\n\n and \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 3304, "s": 3132, "text": "The expected value of the prediction error given only \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 3504, "s": 3304, "text": "The expected value of the prediction error given \n\n\n\n\n\n\n and \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 3783, "s": 3504, "text": "In both models, the functions f1(.) and f2(.) are chosen to minimize the expected value of the loss function. In most cases, these functions are retrieved with linear and, possibly, with nonlinear regressions, neural networks etc. Typical forms for g(.) are the l1- or l2-norms." }, { "code": null, "e": 3892, "s": 3783, "text": "We can now provide our first definition of statistical causality under the Granger causal notion as follows:" }, { "code": null, "e": 4081, "s": 3892, "text": "Standard Granger-causality tests assume a functional form in the relationship among the causes and effects and are implemented by fitting autoregressive models (Wiener 1956; Granger 1969)." }, { "code": null, "e": 4140, "s": 4081, "text": "Consider the linear vector-autoregressive (VAR) equations:" }, { "code": null, "e": 4266, "s": 4140, "text": "where k is the number of lags considered. Alternatively, you can choose your DL/SVM/RF/GLM method of choice to fit the model." }, { "code": null, "e": 4760, "s": 4266, "text": "From Def. 4.1, X does not G-cause Y if and only if the prediction errors of X in the restricted Eq. (4.1)and unrestricted regression models Eq. (4.2) are equal (i.e., they are statistically indistinguishable). A one-way ANOVA test can be utilized to test if the residuals from Eqs. (4.1) and (4.2) differ from each other significantly. When more than one lag k is tested, a correction for multiple hypotheses testing should be applied, e.g. False Discovery Rate (FDR) or Bonferroni correction." }, { "code": null, "e": 4914, "s": 4760, "text": "A more general definition than Def. 4.1 that does not depend on assuming prediction functions can be formulated by considering conditional probabilities." }, { "code": null, "e": 5429, "s": 4914, "text": "A probabilistic definition of G-causality assumes that \n\n\n\n\n\n\n\n\n\n\n\n\n and \n\n\n\n\n\n\n are independent given the \npast information \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n if and only if\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n, \nwhere \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n represents the conditional probability distribution.\nIn other words, omitting past information from \n\n\n\n does not change the probability distribution of \n\n\n\n. This leads to our second definition of statistical causality as follows:" }, { "code": null, "e": 5675, "s": 5429, "text": "Def. 4.2 does not assume any functional form in the coupling between X and Y. Nevertheless, it requires a method to assess their conditional dependency. In the next section, we will leverage an Information-Theoretical framework for that purpose." }, { "code": null, "e": 6089, "s": 5675, "text": "To compute G-Causality, we use the concept of Transfer Entropy. Since its introduction (Schreiber 2000), Transfer Entropy has been recognized as an important tool in the analysis of causal relationships in nonlinear systems (Hlavackovaschindler et al. 2007). It detects directional and dynamical information (Montalto 2014) while not assuming any particular functional form to describe interactions among systems." }, { "code": null, "e": 6445, "s": 6089, "text": "One can interpret this quantity as a measure of the dominant direction of the information flow. In other words, a positive result indicates a dominant information flow from X to Y compared to the other direction or, similarly, it indicates which system provides more predictive information about the other system (Michalowicz, Nichols, and Bucholtz 2013)." }, { "code": null, "e": 6726, "s": 6445, "text": "It has been shown (Barnett, Barrett, and Seth 2009) that linear G-causality and Transfer Entropy are equivalent if all processes are jointly Gaussian. In particular, by assuming the standard measure (l2-norm loss function) of linear G-causality for the bi-variate case as follows:" }, { "code": null, "e": 6789, "s": 6726, "text": "the following can be proved (Barnett, Barrett, and Seth 2009):" }, { "code": null, "e": 7045, "s": 6789, "text": "This result provides a direct mapping between the Transfer Entropy and the linear G-causality implemented in the standard VAR framework. Hence, it is possible to estimate the TE both in its general form and with its equivalent form for linear G-causality." }, { "code": null, "e": 7217, "s": 7045, "text": "In this section, we construct simulated systems to couple random variables in a causal manner. We then quantify information flow using the methods studied in this Article." }, { "code": null, "e": 7318, "s": 7217, "text": "We first assume a linear system, where random variables have linear relationships defined as follow:" }, { "code": null, "e": 7374, "s": 7318, "text": "We simulate this linear system with the following code:" }, { "code": null, "e": 7443, "s": 7374, "text": "Fig. 4.2 represents the dependencies of the simulated linear system." }, { "code": null, "e": 7559, "s": 7443, "text": "We first define a function that calculates a bi-variate measure for G-causality as defined in Eq. (4.4) as follows:" }, { "code": null, "e": 7750, "s": 7559, "text": "We use the function calc_te from the R package RTransferEntropy and the previously defined function Linear.GC to calculate pairwise information flow among the simulated variables as follows:" }, { "code": null, "e": 7915, "s": 7750, "text": "The function FApply.Pairwise is an auxiliary function that simply applies a given function D.Func to all possible pairs of columns from a given matrix X as follows:" }, { "code": null, "e": 8423, "s": 7915, "text": "Fig. 4.3 A) and B) show Granger-causality and Transfer Entropy among the system’s variables, respectively. A cell (x,y) presents the information flow from variable y to variable x. We observe that both the Granger-causality (linear) and Transfer Entropy (nonlinear) approaches presented similar results, i.e., both methods captured the system’s dependencies similarly. This result is expected as the system is purely linear and Transfer Entropy is able to capture both the linear and nonlinear interactions." }, { "code": null, "e": 8538, "s": 8423, "text": "We define a second system by introducing nonlinear interactions between x1 and the variables x2 and x5 as follows:" }, { "code": null, "e": 8597, "s": 8538, "text": "We simulate this nonlinear system with the following code:" }, { "code": null, "e": 8669, "s": 8597, "text": "Fig. 4.5 represents the dependencies of the simulated nonlinear system." }, { "code": null, "e": 8767, "s": 8669, "text": "We calculate Granger-causality and Transfer Entropy of the simulated nonlinear system as follows:" }, { "code": null, "e": 9149, "s": 8767, "text": "From Fig. 4.6 A) and B), we observe that the nonlinear interactions introduced were not captured by the linear formulation of Granger-causality. While all linear interactions presented similar linear and nonlinear information flows, the two nonlinear interactions introduced into the system presented relatively higher nonlinear information flow compared to the linear formulation." }, { "code": null, "e": 9491, "s": 9149, "text": "The world’s financial markets form a complex, dynamic network in which individual markets interact with one another. This multitude of interactions can lead to highly significant and unexpected effects, and it is vital to understand precisely how various markets around the world influence one another (Junior, Mullokandov, and Kenett 2015)." }, { "code": null, "e": 9903, "s": 9491, "text": "In this section, we use Transfer Entropy for the identification of dependency relations among international stock market indices. First, we select some of the major global indices for our analysis, namely the S&P 500, the FTSE 100, the DAX, the EURONEXT 100 and the IBOVESPA, which track the following markets, respectively, the US, the UK, Germany, Europe and Brazil. They are defined by the following tickers:" }, { "code": null, "e": 9960, "s": 9903, "text": "tickers<-c(\"^GSPC\", \"^FTSE\", \"^GDAXI\", \"^N100\", \"^BVSP\")" }, { "code": null, "e": 10105, "s": 9960, "text": "Next, we will load log-returns of daily closing adjusted prices for the selected indices as follows (check here to have access to this dataset):" }, { "code": null, "e": 10741, "s": 10105, "text": "library(xts)dataset<-as.xts(read.zoo('./data/global_indices_returns.csv', header=TRUE, index.column=1, sep=\",\"))head(dataset)## X.GSPC X.FTSE X.GDAXI X.N100 X.BVSP## 2000-01-02 19:00:00 0.000000 NA 0.00000 0.00000 0.00000## 2000-01-03 19:00:00 -0.039099 0.00000 -0.02456 -0.04179 -0.06585## 2000-01-04 19:00:00 0.001920 -0.01969 -0.01297 -0.02726 0.02455## 2000-01-05 19:00:00 0.000955 -0.01366 -0.00418 -0.00842 -0.00853## 2000-01-06 19:00:00 0.026730 0.00889 0.04618 0.02296 0.01246## 2000-01-09 19:00:00 0.011128 0.01570 0.02109 0.01716 0.04279" }, { "code": null, "e": 11001, "s": 10741, "text": "The influence that one market plays in another is dynamic. Here, we will consider the time period from 01/01/2014 until 08/19/2019 and we will omit days with invalid returns due to missing data using the function NARV.omit from the package IDPmisc as follows:" }, { "code": null, "e": 11089, "s": 11001, "text": "library(IDPmisc)dataset.post.crisis <- NaRV.omit(as.data.frame(dataset[\"2014-01-01/\"]))" }, { "code": null, "e": 11304, "s": 11089, "text": "We will calculate pairwise Transfer Entropy among all indices considered and construct a matrix such that each value in the position (i,j) will contain the Transfer Entropy from tickers[i] to tickers[j] as follows:" }, { "code": null, "e": 11469, "s": 11304, "text": "# Calculate pairwise Transfer Entropy among global indicesTE.matrix<-FApply.Pairwise(dataset.post.crisis, calc_ete)rownames(TE.matrix)<-colnames(TE.matrix)<-tickers" }, { "code": null, "e": 12062, "s": 11469, "text": "Fig. 4.8 displays the resulting Transfer Entropy matrix. We normalize the Transfer Entropy values by dividing it by the maximum value in the matrix such that all values range from 0 to 1. We observe that the international indices studied are highly interconnected in the period analyzed with the highest information flow going from the US market to the UK market (^GSPC -> ^FTSE). The second highest information flow is going in the opposite direction, i.e., from the UK market to the US market. That’s a result we would expect as the US and the UK markets are strongly coupled, historically." }, { "code": null, "e": 12317, "s": 12062, "text": "We also calculate the marginal contribution of each market to the total Transfer Entropy in the system by calculating the sum of Transfer Entropy for each row in the Transfer Entropy matrix, which we also normalize such that all values range from 0 to 1:" }, { "code": null, "e": 12499, "s": 12317, "text": "TE.marginal<-apply(TE.matrix, 1, sum)TE.marginal.norm<-TE.marginal/sum(TE.marginal)print(TE.marginal.norm)## ^GSPC ^FTSE ^GDAXI ^N100 ^BVSP ## 0.346 0.215 0.187 0.117 0.135" }, { "code": null, "e": 12808, "s": 12499, "text": "We observe that the US is the most influential market in the time period studied with 34.6% of the total Transfer Entropy followed by the UK and Germany with 21.4% and 18.6%, respectively. Japan and Brazil are the least influential markets with normalized Transfer Entropies of 11.7% and 13.4%, respectively." }, { "code": null, "e": 13148, "s": 12808, "text": "An experiment left to the reader is to build a daily trading strategy that exploits information flow among international markets. The proposed thesis is that one could build a profitable strategy by placing bets on futures of market indices that receive significant information flow from markets that observed unexpected returns/movements." }, { "code": null, "e": 13825, "s": 13148, "text": "For an extended analysis with a broader set of indices see (Junior, Mullokandov, and Kenett 2015). The authors develop networks of international stock market indices using an information theoretical framework. They use 83 stock market indices of a diversity of countries, as well as their single day lagged values, to probe the correlation and the flow of information from one stock index to another taking into account different operating hours. They find that Transfer Entropy is an effective way to quantify the flow of information between indices, and that a high degree of information flow between indices lagged by one day coincides to same day correlation between them." }, { "code": null, "e": 14394, "s": 13825, "text": "Investors’ decisions are modulated not only by companies’ fundamentals but also by personal beliefs, peers influence and information generated from news and the Internet. Rational and irrational investor’s behavior and their relation with the market efficiency hypothesis (Fama 1970) have been largely debated in the economics and financial literature (Shleifer 2000). However, it was only recently that the availability of vast amounts of data from online systems paved the way for the large-scale investigation of investor’s collective behavior in financial markets." }, { "code": null, "e": 15470, "s": 14394, "text": "A research paper (Souza and Aste 2016) used some of the methods studied in this Article to uncover that information flows from social media to stock markets revealing that tweets are causing market movements through a nonlinear complex interaction. The authors provide empirical evidence that suggests social media and stock markets have a nonlinear causal relationship. They take advantage of an extensive data set composed of social media messages related to DJIA index components. By using information-theoretic measures to cope for possible nonlinear causal effects between social media and the stock market, the work points out stunning differences in the results with respect to linear coupling. Two main conclusions are drawn: First, social media significant causality on stocks’ returns are purely nonlinear in most cases; Second, social media dominates the directional coupling with stock market, an effect not observable within linear modeling. Results also serve as empirical guidance on model adequacy in the investigation of sociotechnical and financial systems." }, { "code": null, "e": 15997, "s": 15470, "text": "Fig. 4.9 shows the significant causality links found between social media and stocks’ returns considering both cases: nonlinear (Transfer Entropy) and linear G-causality (linear VAR framework). The linear analysis discovers only three stocks with significant causality: INTEL CORP., NIKE INC. and WALT DISNEY CO. The Nonlinear analysis discovers that several other stocks have significant causality. In addition to the 3 stocks identified with significant linear causality, other 8 stocks presented purely nonlinear causality." }, { "code": null, "e": 16702, "s": 15997, "text": "The low level of causality obtained under linear constraints is in-line with results from similar studies in the literature, where it was found that stocks’ returns show weak causality links (Alanyali, Moat, and Preis 2013, Antweiler and Frank (2004)) and social media sentiment analytics, at least when taken alone, have small or no predictive power (Ranco 2015) and do not have significant lead-time information about stock’s movements for the majority of the stocks (Zheludev, Smith, and Aste 2014). Contrariwise, results from the nonlinear analyses unveiled a much higher level of causality indicating that linear constraints may be neglecting the relationship between social media and stock markets." }, { "code": null, "e": 16901, "s": 16702, "text": "In summary, (Souza and Aste 2016) is a good example on how causality can be not only complex but also misleading further highlighting the importance of choice in the methodology used to quantify it." }, { "code": null, "e": 17095, "s": 16901, "text": "In (Keskin and Aste 2019), the authors use information-theoretic measures studied in this Article for non-linear causality detection applied to social media sentiment and cryptocurrency prices." }, { "code": null, "e": 17542, "s": 17095, "text": "Using these techniques on sentiment and price data over a 48-month period to August 2018, for four major cryptocurrencies, namely bitcoin (BTC), ripple (XRP), litecoin (LTC) and ethereum (ETH), the authors detect significant information transfer, on hourly timescales, in directions of both sentiment to price and of price to sentiment. The work reports the scale of non-linear causality to be an order of magnitude greater than linear causality." }, { "code": null, "e": 17893, "s": 17542, "text": "The information-theoretic investigation detected a significant non-linear causal relationship in BTC, LTC and XRP, over multiple timescales and in both the directions sentiment to price and price to sentiment. The effect was strongest and most consistent for BTC and LTC. Fig. 4.10 shows Transfer Entropy results between BTC sentiment and BTC prices." }, { "code": null, "e": 18037, "s": 17893, "text": "All analysis for this paper was performed using a Python package (PyCausality), which is available at https://github.com/ZacKeskin/PyCausality." }, { "code": null, "e": 18166, "s": 18037, "text": "Untangling cause and effect can be devilishly difficult. However, statistical tools can help us tell correlation from causation." }, { "code": null, "e": 18455, "s": 18166, "text": "In this Article, we introduced the notion of Granger-causality and its traditional implementation in a linear vector-autoregressive framework. We then defined information theoretical measures to quantify Transfer Entropy as a method to estimate statistical causality in nonlinear systems." }, { "code": null, "e": 18694, "s": 18455, "text": "We simulated linear and nonlinear systems further showing that the traditional linear G-causality approach failed to detect simple non-linearities introduced into the system while Transfer Entropy successfully detected such relationships." }, { "code": null, "e": 19009, "s": 18694, "text": "Finally, we showed how Transfer Entropy can be used to quantify relationships among global equity indexes. We also discussed further applications from the literature where Information Theoretical measures were used to quantify causal links between investor sentiment and movements in the equity and crypto markets." } ]
Android - Spelling Checker
The Android platform offers a spelling checker framework that lets you implement and access spell checking in your application. In order to use spelling checker , you need to implement SpellCheckerSessionListener interface and override its methods. Its syntax is given below − public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener { @Override public void onGetSuggestions(final SuggestionsInfo[] arg0) { // TODO Auto-generated method stub } @Override public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) { // TODO Auto-generated method stub } } Next thing you need to do is to create an object of SpellCheckerSession class. This object can be instantiated by calling newSpellCheckerSession method of TextServicesManager class. This class handles interaction between application and text services. You need to request system service to instantiate it. Its syntax is given below − private SpellCheckerSession mScs; final TextServicesManager tsm = (TextServicesManager) getSystemService( Context.TEXT_SERVICES_MANAGER_SERVICE); mScs = tsm.newSpellCheckerSession(null, null, this, true); The last thing you need to do is to call getSuggestions method to get suggestion for any text, you want. The suggestions will be passed onto the onGetSuggestions method from where you can do whatever you want. mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3); This method takes two parameters. First parameter is the string in the form of Text Info object, and second parameter is the cookie number used to distinguish suggestions. Apart from the the methods , there are other methods provided by the SpellCheckerSession class for better handling suggestions. These methods are listed below − cancel() Cancel pending and running spell check tasks close() Finish this session and allow TextServicesManagerService to disconnect the bound spell checker getSentenceSuggestions(TextInfo[] textInfos, int suggestionsLimit) Get suggestions from the specified sentences getSpellChecker() Get the spell checker service info this spell checker session has. isSessionDisconnected() True if the connection to a text service of this session is disconnected and not alive. Here is an example demonstrating the use of Spell Checker. It creates a basic spell checking application that allows you to write text and get suggestions. To experiment with this example , you can run this on an actual device or in an emulator. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.textservice.TextInfo; import android.view.textservice.TextServicesManager; import android.widget.Button; import android.widget.EditText; import android.view.textservice.SentenceSuggestionsInfo; import android.view.textservice.SpellCheckerSession; import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener; import android.view.textservice.SuggestionsInfo; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements SpellCheckerSessionListener { Button b1; TextView tv1; EditText ed1; private SpellCheckerSession mScs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); tv1=(TextView)findViewById(R.id.textView3); ed1=(EditText)findViewById(R.id.editText); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), ed1.getText().toString(),Toast.LENGTH_SHORT).show(); mScs.getSuggestions(new TextInfo(ed1.getText().toString()), 3); } }); } public void onResume() { super.onResume(); final TextServicesManager tsm = (TextServicesManager) getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); mScs = tsm.newSpellCheckerSession(null, null, this, true); } public void onPause() { super.onPause(); if (mScs != null) { mScs.close(); } } public void onGetSuggestions(final SuggestionsInfo[] arg0) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < arg0.length; ++i) { // Returned suggestions are contained in SuggestionsInfo final int len = arg0[i].getSuggestionsCount(); sb.append('\n'); for (int j = 0; j < len; ++j) { sb.append("," + arg0[i].getSuggestionAt(j)); } sb.append(" (" + len + ")"); } runOnUiThread(new Runnable() { public void run() { tv1.append(sb.toString()); } }); } @Override public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) { // TODO Auto-generated method stub } } Following is the modified content of the xml res/layout/main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="Spell checker " android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Suggestions" android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:hint="Enter Text" android:layout_above="@+id/button" android:layout_marginBottom="56dp" android:focusable="true" android:textColorHighlight="#ff7eff15" android:textColorHint="#ffff25e6" android:layout_alignRight="@+id/textview" android:layout_alignEnd="@+id/textview" android:layout_alignLeft="@+id/textview" android:layout_alignStart="@+id/textview" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Suggestions" android:id="@+id/textView3" android:textSize="25sp" android:layout_below="@+id/imageView" /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name="app_name">My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run ourr application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Now what you need to do is to enter any text in the field. For example, i have entered some text. Press the suggestions button. The following notification would appear in you AVD along with suggestions − Now change the text and press the button again, like i did. And this is what comes on screen. 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3735, "s": 3607, "text": "The Android platform offers a spelling checker framework that lets you implement and access spell checking in your application." }, { "code": null, "e": 3884, "s": 3735, "text": "In order to use spelling checker , you need to implement SpellCheckerSessionListener interface and override its methods. Its syntax is given below −" }, { "code": null, "e": 4243, "s": 3884, "text": "public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {\n @Override\n public void onGetSuggestions(final SuggestionsInfo[] arg0) {\n // TODO Auto-generated method stub\n }\n \n @Override\n public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {\n // TODO Auto-generated method stub\n }\n}" }, { "code": null, "e": 4577, "s": 4243, "text": "Next thing you need to do is to create an object of SpellCheckerSession class. This object can be instantiated by calling newSpellCheckerSession method of TextServicesManager class. This class handles interaction between application and text services. You need to request system service to instantiate it. Its syntax is given below −" }, { "code": null, "e": 4786, "s": 4577, "text": "private SpellCheckerSession mScs;\nfinal TextServicesManager tsm = (TextServicesManager) getSystemService(\nContext.TEXT_SERVICES_MANAGER_SERVICE);\nmScs = tsm.newSpellCheckerSession(null, null, this, true); \n" }, { "code": null, "e": 4996, "s": 4786, "text": "The last thing you need to do is to call getSuggestions method to get suggestion for any text, you want. The suggestions will be passed onto the onGetSuggestions method from where you can do whatever you want." }, { "code": null, "e": 5066, "s": 4996, "text": "mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3);" }, { "code": null, "e": 5238, "s": 5066, "text": "This method takes two parameters. First parameter is the string in the form of Text Info object, and second parameter is the cookie number used to distinguish suggestions." }, { "code": null, "e": 5399, "s": 5238, "text": "Apart from the the methods , there are other methods provided by the SpellCheckerSession class for better handling suggestions. These methods are listed below −" }, { "code": null, "e": 5408, "s": 5399, "text": "cancel()" }, { "code": null, "e": 5453, "s": 5408, "text": "Cancel pending and running spell check tasks" }, { "code": null, "e": 5461, "s": 5453, "text": "close()" }, { "code": null, "e": 5556, "s": 5461, "text": "Finish this session and allow TextServicesManagerService to disconnect the bound spell checker" }, { "code": null, "e": 5623, "s": 5556, "text": "getSentenceSuggestions(TextInfo[] textInfos, int suggestionsLimit)" }, { "code": null, "e": 5668, "s": 5623, "text": "Get suggestions from the specified sentences" }, { "code": null, "e": 5686, "s": 5668, "text": "getSpellChecker()" }, { "code": null, "e": 5753, "s": 5686, "text": "Get the spell checker service info this spell checker session has." }, { "code": null, "e": 5777, "s": 5753, "text": "isSessionDisconnected()" }, { "code": null, "e": 5865, "s": 5777, "text": "True if the connection to a text service of this session is disconnected and not alive." }, { "code": null, "e": 6021, "s": 5865, "text": "Here is an example demonstrating the use of Spell Checker. It creates a basic spell checking application that allows you to write text and get suggestions." }, { "code": null, "e": 6111, "s": 6021, "text": "To experiment with this example , you can run this on an actual device or in an emulator." }, { "code": null, "e": 6195, "s": 6111, "text": "Following is the content of the modified main activity file src/MainActivity.java. " }, { "code": null, "e": 8731, "s": 6195, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.textservice.TextInfo;\nimport android.view.textservice.TextServicesManager;\n\nimport android.widget.Button;\nimport android.widget.EditText;\n\nimport android.view.textservice.SentenceSuggestionsInfo;\nimport android.view.textservice.SpellCheckerSession;\nimport android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;\nimport android.view.textservice.SuggestionsInfo;\n\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity implements SpellCheckerSessionListener {\n Button b1;\n TextView tv1;\n EditText ed1;\n private SpellCheckerSession mScs;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1=(Button)findViewById(R.id.button);\n tv1=(TextView)findViewById(R.id.textView3);\n\n ed1=(EditText)findViewById(R.id.editText);\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(),\n ed1.getText().toString(),Toast.LENGTH_SHORT).show();\n mScs.getSuggestions(new TextInfo(ed1.getText().toString()), 3);\n }\n });\n }\n\n public void onResume() {\n super.onResume();\n final TextServicesManager tsm = (TextServicesManager)\n getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);\n mScs = tsm.newSpellCheckerSession(null, null, this, true);\n }\n\n public void onPause() {\n super.onPause();\n if (mScs != null) {\n mScs.close();\n }\n }\n\n public void onGetSuggestions(final SuggestionsInfo[] arg0) {\n final StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < arg0.length; ++i) {\n // Returned suggestions are contained in SuggestionsInfo\n final int len = arg0[i].getSuggestionsCount();\n sb.append('\\n');\n\n for (int j = 0; j < len; ++j) {\n sb.append(\",\" + arg0[i].getSuggestionAt(j));\n }\n\n sb.append(\" (\" + len + \")\");\n }\n\t\t\n runOnUiThread(new Runnable() {\n public void run() {\n tv1.append(sb.toString());\n }\n });\n }\n\n @Override\n public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {\n // TODO Auto-generated method stub\n }\n}" }, { "code": null, "e": 8797, "s": 8731, "text": "Following is the modified content of the xml res/layout/main.xml." }, { "code": null, "e": 11265, "s": 8797, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n \n <TextView android:text=\"Spell checker \" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Suggestions\"\n android:id=\"@+id/button\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:hint=\"Enter Text\"\n android:layout_above=\"@+id/button\"\n android:layout_marginBottom=\"56dp\"\n android:focusable=\"true\"\n android:textColorHighlight=\"#ff7eff15\"\n android:textColorHint=\"#ffff25e6\"\n android:layout_alignRight=\"@+id/textview\"\n android:layout_alignEnd=\"@+id/textview\"\n android:layout_alignLeft=\"@+id/textview\"\n android:layout_alignStart=\"@+id/textview\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Suggestions\"\n android:id=\"@+id/textView3\"\n android:textSize=\"25sp\"\n android:layout_below=\"@+id/imageView\" />\n\n</RelativeLayout>" }, { "code": null, "e": 11320, "s": 11265, "text": "Following is the content of the res/values/string.xml." }, { "code": null, "e": 11396, "s": 11320, "text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>" }, { "code": null, "e": 11450, "s": 11396, "text": "Following is the content of AndroidManifest.xml file." }, { "code": null, "e": 12155, "s": 11450, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 12549, "s": 12155, "text": "Let's try to run ourr application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −" }, { "code": null, "e": 12753, "s": 12549, "text": "Now what you need to do is to enter any text in the field. For example, i have entered some text. Press the suggestions button. The following notification would appear in you AVD along with suggestions −" }, { "code": null, "e": 12847, "s": 12753, "text": "Now change the text and press the button again, like i did. And this is what comes on screen." }, { "code": null, "e": 12882, "s": 12847, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12894, "s": 12882, "text": " Aditya Dua" }, { "code": null, "e": 12929, "s": 12894, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12943, "s": 12929, "text": " Sharad Kumar" }, { "code": null, "e": 12975, "s": 12943, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 12992, "s": 12975, "text": " Abhilash Nelson" }, { "code": null, "e": 13027, "s": 12992, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13044, "s": 13027, "text": " Abhilash Nelson" }, { "code": null, "e": 13079, "s": 13044, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13096, "s": 13079, "text": " Abhilash Nelson" }, { "code": null, "e": 13129, "s": 13096, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 13146, "s": 13129, "text": " Abhilash Nelson" }, { "code": null, "e": 13153, "s": 13146, "text": " Print" }, { "code": null, "e": 13164, "s": 13153, "text": " Add Notes" } ]
Find the smallest after deleting given elements - GeeksforGeeks
28 May, 2021 Given an array of integers, find the smallest number after deleting given elements. In case of repeating elements, we delete one instance (from the original array) for every instance present in the array containing elements to be deleted.Examples: Input : Array = {5, 12, 33, 4, 56, 12, 20} To Delete = {12, 4, 56, 5} Output : 12 After deleting given elements, array becomes {33, 12, 20} and minimum element becomes 12. Note that there are two occurrences of 12 and we delete one of them. Input : Array = {1, 20, 3, 4, 10} To Delete = {1, 4, 10} Output : 3 Approach : Insert all the numbers in the hash map which are to be deleted from the array, so that we can check if the element in the array is also present in the Delete-array in O(1) time. Initialize smallest number min to be INT_MAX. Traverse through the array. Check if the element is present in the hash map. If present, erase it from the hash map, else if not present compare it with min variable and change its value if the value of the element is less than the min value. C++ Java Python3 C# Javascript // C++ program to find the smallest number// from the array after n deletions#include "climits"#include "iostream"#include "unordered_map"using namespace std; // Returns minimum element from arr[0..m-1] after deleting// elements from del[0..n-1]int findSmallestAfterDel(int arr[], int m, int del[], int n){ // Hash Map of the numbers to be deleted unordered_map<int, int> mp; for (int i = 0; i < n; ++i) { // Increment the count of del[i] mp[del[i]]++; } // Initializing the smallestElement int smallestElement = INT_MAX; for (int i = 0; i < m; ++i) { // Search if the element is present if (mp.find(arr[i]) != mp.end()) { // Decrement its frequency mp[arr[i]]--; // If the frequency becomes 0, // erase it from the map if (mp[arr[i]] == 0) mp.erase(arr[i]); } // Else compare it smallestElement else smallestElement = min(smallestElement, arr[i]); } return smallestElement;} int main(){ int array[] = { 5, 12, 33, 4, 56, 12, 20 }; int m = sizeof(array) / sizeof(array[0]); int del[] = { 12, 4, 56, 5 }; int n = sizeof(del) / sizeof(del[0]); cout << findSmallestAfterDel(array, m, del, n); return 0;} // Java program to find the smallest number// from the array after n deletionsimport java.util.*; class GFG{ // Returns minimum element from arr[0..m-1]// after deleting elements from del[0..n-1]static int findSmallestAfterDel(int arr[], int m, int del[], int n){ // Hash Map of the numbers to be deleted HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < n; ++i) { // Increment the count of del[i] if(mp.containsKey(del[i])) { mp.put(del[i], mp.get(del[i]) + 1); } else { mp.put(del[i], 1); } } // Initializing the smallestElement int smallestElement = Integer.MAX_VALUE; for (int i = 0; i < m; ++i) { // Search if the element is present if (mp.containsKey(arr[i])) { // Decrement its frequency mp.put(arr[i], mp.get(arr[i]) - 1); // If the frequency becomes 0, // erase it from the map if (mp.get(arr[i]) == 0) mp.remove(arr[i]); } // Else compare it smallestElement else smallestElement = Math.min(smallestElement, arr[i]); } return smallestElement;} // Driver Codepublic static void main(String[] args){ int array[] = { 5, 12, 33, 4, 56, 12, 20 }; int m = array.length; int del[] = { 12, 4, 56, 5 }; int n = del.length; System.out.println(findSmallestAfterDel(array, m, del, n));}} // This code is contributed by 29AjayKumar # Python3 program to find the smallest# number from the array after n deletionsimport math as mt # Returns maximum element from arr[0..m-1]# after deleting elements from del[0..n-1]def findSmallestAfterDel(arr, m, dell, n): # Hash Map of the numbers # to be deleted mp = dict() for i in range(n): # Increment the count of del[i] if dell[i] in mp.keys(): mp[dell[i]] += 1 else: mp[dell[i]] = 1 # Initializing the SmallestElement SmallestElement = 10**9 for i in range(m): # Search if the element is present if (arr[i] in mp.keys()): # Decrement its frequency mp[arr[i]] -= 1 # If the frequency becomes 0, # erase it from the map if (mp[arr[i]] == 0): mp.pop(arr[i]) # Else compare it SmallestElement else: SmallestElement = min(SmallestElement, arr[i]) return SmallestElement # Driver codearray = [5, 12, 33, 4, 56, 12, 20]m = len(array) dell = [12, 4, 56, 5]n = len(dell) print(findSmallestAfterDel(array, m, dell, n)) # This code is contributed# by mohit kumar 29 // C# program to find the smallest number// from the array after n deletionsusing System;using System.Collections.Generic; class GFG{ // Returns minimum element from arr[0..m-1]// after deleting elements from del[0..n-1]static int findSmallestAfterDel(int []arr, int m, int []del, int n){ // Hash Map of the numbers to be deleted Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0; i < n; ++i) { // Increment the count of del[i] if(mp.ContainsKey(del[i])) { mp[del[i]] = mp[del[i]] + 1; } else { mp.Add(del[i], 1); } } // Initializing the smallestElement int smallestElement = int.MaxValue; for (int i = 0; i < m; ++i) { // Search if the element is present if (mp.ContainsKey(arr[i])) { // Decrement its frequency mp[arr[i]] = mp[arr[i]] - 1; // If the frequency becomes 0, // erase it from the map if (mp[arr[i]] == 0) mp.Remove(arr[i]); } // Else compare it smallestElement else smallestElement = Math.Min(smallestElement, arr[i]); } return smallestElement;} // Driver Codepublic static void Main(String[] args){ int []array = { 5, 12, 33, 4, 56, 12, 20 }; int m = array.Length; int []del = { 12, 4, 56, 5 }; int n = del.Length; Console.WriteLine(findSmallestAfterDel(array, m, del, n));}} // This code is contributed by Princi Singh <script> // JavaScript program to find the smallest number// from the array after n deletions // Returns minimum element from arr[0..m-1]// after deleting elements from del[0..n-1]function findSmallestAfterDel(arr,m,del,n){ // Hash Map of the numbers to be deleted let mp = new Map(); for (let i = 0; i < n; ++i) { // Increment the count of del[i] if(mp.has(del[i])) { mp.set(del[i], mp.get(del[i]) + 1); } else { mp.set(del[i], 1); } } // Initializing the smallestElement let smallestElement = Number.MAX_VALUE; for (let i = 0; i < m; ++i) { // Search if the element is present if (mp.has(arr[i])) { // Decrement its frequency mp.set(arr[i], mp.get(arr[i]) - 1); // If the frequency becomes 0, // erase it from the map if (mp.get(arr[i]) == 0) mp.delete(arr[i]); } // Else compare it smallestElement else smallestElement = Math.min(smallestElement, arr[i]); } return smallestElement;} // Driver Codelet array=[5, 12, 33, 4, 56, 12, 20];let m = array.length; let del=[12, 4, 56, 5];let n = del.length;document.write(findSmallestAfterDel(array, m, del, n)); // This code is contributed by patel2127 </script> 12 Time Complexity – O(N) imdhruvgupta mohit kumar 29 29AjayKumar princi singh patel2127 cpp-unordered_map frequency-counting Picked Technical Scripter 2018 Arrays Hash Searching Technical Scripter Arrays Searching Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26065, "s": 26037, "text": "\n28 May, 2021" }, { "code": null, "e": 26315, "s": 26065, "text": "Given an array of integers, find the smallest number after deleting given elements. In case of repeating elements, we delete one instance (from the original array) for every instance present in the array containing elements to be deleted.Examples: " }, { "code": null, "e": 26624, "s": 26315, "text": "Input : Array = {5, 12, 33, 4, 56, 12, 20} To Delete = {12, 4, 56, 5} Output : 12 After deleting given elements, array becomes {33, 12, 20} and minimum element becomes 12. Note that there are two occurrences of 12 and we delete one of them. Input : Array = {1, 20, 3, 4, 10} To Delete = {1, 4, 10} Output : 3" }, { "code": null, "e": 26639, "s": 26626, "text": "Approach : " }, { "code": null, "e": 26818, "s": 26639, "text": "Insert all the numbers in the hash map which are to be deleted from the array, so that we can check if the element in the array is also present in the Delete-array in O(1) time. " }, { "code": null, "e": 26865, "s": 26818, "text": "Initialize smallest number min to be INT_MAX. " }, { "code": null, "e": 26943, "s": 26865, "text": "Traverse through the array. Check if the element is present in the hash map. " }, { "code": null, "e": 27111, "s": 26943, "text": "If present, erase it from the hash map, else if not present compare it with min variable and change its value if the value of the element is less than the min value. " }, { "code": null, "e": 27117, "s": 27113, "text": "C++" }, { "code": null, "e": 27122, "s": 27117, "text": "Java" }, { "code": null, "e": 27130, "s": 27122, "text": "Python3" }, { "code": null, "e": 27133, "s": 27130, "text": "C#" }, { "code": null, "e": 27144, "s": 27133, "text": "Javascript" }, { "code": "// C++ program to find the smallest number// from the array after n deletions#include \"climits\"#include \"iostream\"#include \"unordered_map\"using namespace std; // Returns minimum element from arr[0..m-1] after deleting// elements from del[0..n-1]int findSmallestAfterDel(int arr[], int m, int del[], int n){ // Hash Map of the numbers to be deleted unordered_map<int, int> mp; for (int i = 0; i < n; ++i) { // Increment the count of del[i] mp[del[i]]++; } // Initializing the smallestElement int smallestElement = INT_MAX; for (int i = 0; i < m; ++i) { // Search if the element is present if (mp.find(arr[i]) != mp.end()) { // Decrement its frequency mp[arr[i]]--; // If the frequency becomes 0, // erase it from the map if (mp[arr[i]] == 0) mp.erase(arr[i]); } // Else compare it smallestElement else smallestElement = min(smallestElement, arr[i]); } return smallestElement;} int main(){ int array[] = { 5, 12, 33, 4, 56, 12, 20 }; int m = sizeof(array) / sizeof(array[0]); int del[] = { 12, 4, 56, 5 }; int n = sizeof(del) / sizeof(del[0]); cout << findSmallestAfterDel(array, m, del, n); return 0;}", "e": 28435, "s": 27144, "text": null }, { "code": "// Java program to find the smallest number// from the array after n deletionsimport java.util.*; class GFG{ // Returns minimum element from arr[0..m-1]// after deleting elements from del[0..n-1]static int findSmallestAfterDel(int arr[], int m, int del[], int n){ // Hash Map of the numbers to be deleted HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < n; ++i) { // Increment the count of del[i] if(mp.containsKey(del[i])) { mp.put(del[i], mp.get(del[i]) + 1); } else { mp.put(del[i], 1); } } // Initializing the smallestElement int smallestElement = Integer.MAX_VALUE; for (int i = 0; i < m; ++i) { // Search if the element is present if (mp.containsKey(arr[i])) { // Decrement its frequency mp.put(arr[i], mp.get(arr[i]) - 1); // If the frequency becomes 0, // erase it from the map if (mp.get(arr[i]) == 0) mp.remove(arr[i]); } // Else compare it smallestElement else smallestElement = Math.min(smallestElement, arr[i]); } return smallestElement;} // Driver Codepublic static void main(String[] args){ int array[] = { 5, 12, 33, 4, 56, 12, 20 }; int m = array.length; int del[] = { 12, 4, 56, 5 }; int n = del.length; System.out.println(findSmallestAfterDel(array, m, del, n));}} // This code is contributed by 29AjayKumar", "e": 30121, "s": 28435, "text": null }, { "code": "# Python3 program to find the smallest# number from the array after n deletionsimport math as mt # Returns maximum element from arr[0..m-1]# after deleting elements from del[0..n-1]def findSmallestAfterDel(arr, m, dell, n): # Hash Map of the numbers # to be deleted mp = dict() for i in range(n): # Increment the count of del[i] if dell[i] in mp.keys(): mp[dell[i]] += 1 else: mp[dell[i]] = 1 # Initializing the SmallestElement SmallestElement = 10**9 for i in range(m): # Search if the element is present if (arr[i] in mp.keys()): # Decrement its frequency mp[arr[i]] -= 1 # If the frequency becomes 0, # erase it from the map if (mp[arr[i]] == 0): mp.pop(arr[i]) # Else compare it SmallestElement else: SmallestElement = min(SmallestElement, arr[i]) return SmallestElement # Driver codearray = [5, 12, 33, 4, 56, 12, 20]m = len(array) dell = [12, 4, 56, 5]n = len(dell) print(findSmallestAfterDel(array, m, dell, n)) # This code is contributed# by mohit kumar 29", "e": 31357, "s": 30121, "text": null }, { "code": "// C# program to find the smallest number// from the array after n deletionsusing System;using System.Collections.Generic; class GFG{ // Returns minimum element from arr[0..m-1]// after deleting elements from del[0..n-1]static int findSmallestAfterDel(int []arr, int m, int []del, int n){ // Hash Map of the numbers to be deleted Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0; i < n; ++i) { // Increment the count of del[i] if(mp.ContainsKey(del[i])) { mp[del[i]] = mp[del[i]] + 1; } else { mp.Add(del[i], 1); } } // Initializing the smallestElement int smallestElement = int.MaxValue; for (int i = 0; i < m; ++i) { // Search if the element is present if (mp.ContainsKey(arr[i])) { // Decrement its frequency mp[arr[i]] = mp[arr[i]] - 1; // If the frequency becomes 0, // erase it from the map if (mp[arr[i]] == 0) mp.Remove(arr[i]); } // Else compare it smallestElement else smallestElement = Math.Min(smallestElement, arr[i]); } return smallestElement;} // Driver Codepublic static void Main(String[] args){ int []array = { 5, 12, 33, 4, 56, 12, 20 }; int m = array.Length; int []del = { 12, 4, 56, 5 }; int n = del.Length; Console.WriteLine(findSmallestAfterDel(array, m, del, n));}} // This code is contributed by Princi Singh", "e": 33033, "s": 31357, "text": null }, { "code": "<script> // JavaScript program to find the smallest number// from the array after n deletions // Returns minimum element from arr[0..m-1]// after deleting elements from del[0..n-1]function findSmallestAfterDel(arr,m,del,n){ // Hash Map of the numbers to be deleted let mp = new Map(); for (let i = 0; i < n; ++i) { // Increment the count of del[i] if(mp.has(del[i])) { mp.set(del[i], mp.get(del[i]) + 1); } else { mp.set(del[i], 1); } } // Initializing the smallestElement let smallestElement = Number.MAX_VALUE; for (let i = 0; i < m; ++i) { // Search if the element is present if (mp.has(arr[i])) { // Decrement its frequency mp.set(arr[i], mp.get(arr[i]) - 1); // If the frequency becomes 0, // erase it from the map if (mp.get(arr[i]) == 0) mp.delete(arr[i]); } // Else compare it smallestElement else smallestElement = Math.min(smallestElement, arr[i]); } return smallestElement;} // Driver Codelet array=[5, 12, 33, 4, 56, 12, 20];let m = array.length; let del=[12, 4, 56, 5];let n = del.length;document.write(findSmallestAfterDel(array, m, del, n)); // This code is contributed by patel2127 </script>", "e": 34486, "s": 33033, "text": null }, { "code": null, "e": 34489, "s": 34486, "text": "12" }, { "code": null, "e": 34515, "s": 34491, "text": "Time Complexity – O(N) " }, { "code": null, "e": 34528, "s": 34515, "text": "imdhruvgupta" }, { "code": null, "e": 34543, "s": 34528, "text": "mohit kumar 29" }, { "code": null, "e": 34555, "s": 34543, "text": "29AjayKumar" }, { "code": null, "e": 34568, "s": 34555, "text": "princi singh" }, { "code": null, "e": 34578, "s": 34568, "text": "patel2127" }, { "code": null, "e": 34596, "s": 34578, "text": "cpp-unordered_map" }, { "code": null, "e": 34615, "s": 34596, "text": "frequency-counting" }, { "code": null, "e": 34622, "s": 34615, "text": "Picked" }, { "code": null, "e": 34646, "s": 34622, "text": "Technical Scripter 2018" }, { "code": null, "e": 34653, "s": 34646, "text": "Arrays" }, { "code": null, "e": 34658, "s": 34653, "text": "Hash" }, { "code": null, "e": 34668, "s": 34658, "text": "Searching" }, { "code": null, "e": 34687, "s": 34668, "text": "Technical Scripter" }, { "code": null, "e": 34694, "s": 34687, "text": "Arrays" }, { "code": null, "e": 34704, "s": 34694, "text": "Searching" }, { "code": null, "e": 34709, "s": 34704, "text": "Hash" }, { "code": null, "e": 34807, "s": 34709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34834, "s": 34807, "text": "Count pairs with given sum" }, { "code": null, "e": 34865, "s": 34834, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34890, "s": 34865, "text": "Window Sliding Technique" }, { "code": null, "e": 34928, "s": 34890, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34949, "s": 34928, "text": "Next Greater Element" }, { "code": null, "e": 34985, "s": 34949, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 35012, "s": 34985, "text": "Count pairs with given sum" }, { "code": null, "e": 35043, "s": 35012, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 35077, "s": 35043, "text": "Hashing | Set 3 (Open Addressing)" } ]
Tensorflow.js tf.argMax() Function - GeeksforGeeks
18 May, 2021 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.argMax() function is used to return the indices for the maximum values of the specified Tensor along an axis. The output result has the same shape as input with the dimension along the axis removed. Syntax: tf.argMax (x, axis) Parameters: This function accepts two parameters which are illustrated below: x: The input tensor. axis: The specified dimension(s) to reduce. It is an optional parameter and its default value is 0. Return Value: It returns a Tensor of the indices of the maximum values along an axis. Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a some tensors const a = tf.tensor1d([1, 0]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([6, 3, 5, 12]); // Calling the .argMax() function over // the above tensorsa.argMax().print();b.argMax().print();c.argMax().print(); Output: Tensor 0 Tensor 1 Tensor 3 Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([9, 5, 2, 8], [2, 2]);const c = tf.tensor1d([6, 4, 7]); // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0; // Calling the .argMax() function over // the above tensorsa.argMax(axis1).print();b.argMax(axis2).print();c.argMax(axis3).print(); Output: Tensor 1 Tensor [0, 1] Tensor 2 Reference: https://js.tensorflow.org/api/latest/#argMax Tensorflow Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n18 May, 2021" }, { "code": null, "e": 26711, "s": 26545, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 26828, "s": 26711, "text": "The tf.argMax() function is used to return the indices for the maximum values of the specified Tensor along an axis." }, { "code": null, "e": 26917, "s": 26828, "text": "The output result has the same shape as input with the dimension along the axis removed." }, { "code": null, "e": 26925, "s": 26917, "text": "Syntax:" }, { "code": null, "e": 26945, "s": 26925, "text": "tf.argMax (x, axis)" }, { "code": null, "e": 27023, "s": 26945, "text": "Parameters: This function accepts two parameters which are illustrated below:" }, { "code": null, "e": 27044, "s": 27023, "text": "x: The input tensor." }, { "code": null, "e": 27144, "s": 27044, "text": "axis: The specified dimension(s) to reduce. It is an optional parameter and its default value is 0." }, { "code": null, "e": 27230, "s": 27144, "text": "Return Value: It returns a Tensor of the indices of the maximum values along an axis." }, { "code": null, "e": 27241, "s": 27230, "text": "Example 1:" }, { "code": null, "e": 27252, "s": 27241, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a some tensors const a = tf.tensor1d([1, 0]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([6, 3, 5, 12]); // Calling the .argMax() function over // the above tensorsa.argMax().print();b.argMax().print();c.argMax().print();", "e": 27577, "s": 27252, "text": null }, { "code": null, "e": 27585, "s": 27577, "text": "Output:" }, { "code": null, "e": 27621, "s": 27585, "text": "Tensor\n 0\nTensor\n 1\nTensor\n 3" }, { "code": null, "e": 27632, "s": 27621, "text": "Example 2:" }, { "code": null, "e": 27643, "s": 27632, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([9, 5, 2, 8], [2, 2]);const c = tf.tensor1d([6, 4, 7]); // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0; // Calling the .argMax() function over // the above tensorsa.argMax(axis1).print();b.argMax(axis2).print();c.argMax(axis3).print();", "e": 28078, "s": 27643, "text": null }, { "code": null, "e": 28086, "s": 28078, "text": "Output:" }, { "code": null, "e": 28127, "s": 28086, "text": "Tensor\n 1\nTensor\n [0, 1]\nTensor\n 2" }, { "code": null, "e": 28183, "s": 28127, "text": "Reference: https://js.tensorflow.org/api/latest/#argMax" }, { "code": null, "e": 28194, "s": 28183, "text": "Tensorflow" }, { "code": null, "e": 28208, "s": 28194, "text": "Tensorflow.js" }, { "code": null, "e": 28219, "s": 28208, "text": "JavaScript" }, { "code": null, "e": 28236, "s": 28219, "text": "Web Technologies" }, { "code": null, "e": 28334, "s": 28236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28374, "s": 28334, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28435, "s": 28374, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28476, "s": 28435, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28498, "s": 28476, "text": "JavaScript | Promises" }, { "code": null, "e": 28552, "s": 28498, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28592, "s": 28552, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28625, "s": 28592, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28668, "s": 28625, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28718, "s": 28668, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
array::begin() and array::end() in C++ STL - GeeksforGeeks
10 Feb, 2021 Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. begin() function is used to return an iterator pointing to the first element of the array container. begin() function returns a bidirectional iterator to the first element of the container.Syntax : arrayname.begin() Parameters : No parameters are passed. Returns : This function returns a bidirectional iterator pointing to the first element. Examples: Input : myarray{1, 2, 3, 4, 5}; Output : returns an iterator to the element 1 Input : myarray{8, 7}; Output : returns an iterator to the element 8 Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // CPP program to illustrate// Implementation of begin() function#include <array>#include <iostream>using namespace std; int main(){ // declaration of array container array<int, 5> myarray{ 1, 2, 3, 4, 5 }; // using begin() to print array for (auto it = myarray.begin(); it != myarray.end(); ++it) cout << ' ' << *it; return 0;} Output: 1 2 3 4 5 end() returns an iterator pointing to the past-the-end element in the array container. Syntax : arrayname.end() Parameters : No parameters are passed. Returns : This function returns a bidirectional iterator pointing to the past-the-end element. Examples: Input : myarray{1, 2, 3, 4, 5}; Output : returns an iterator to the element next to 5 i.e,. some garbage value Input : myarray{8, 7}; Output : returns an iterator to the element next to 7 i.e,. some garbage value Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // CPP program to illustrate// Implementation of end() function#include <array>#include <iostream>using namespace std; int main(){ // declaration of array container array<int, 5> myarray{ 1, 2, 3, 4, 5 }; // using end() to print array for (auto it = myarray.begin(); it != myarray.end(); ++it) cout << ' ' << *it; auto it = myarray.end(); cout << "\n myarray.end(): " << *it << " [some garbage value]"; return 0;} Output: 1 2 3 4 5 myarray.end(): 0 [some garbage value] klynsaha cpp-array STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++ Queue in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25343, "s": 25315, "text": "\n10 Feb, 2021" }, { "code": null, "e": 25530, "s": 25343, "text": "Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays." }, { "code": null, "e": 25729, "s": 25530, "text": "begin() function is used to return an iterator pointing to the first element of the array container. begin() function returns a bidirectional iterator to the first element of the container.Syntax : " }, { "code": null, "e": 25875, "s": 25729, "text": "arrayname.begin()\nParameters :\nNo parameters are passed.\n\nReturns :\nThis function returns a bidirectional\niterator pointing to the first element." }, { "code": null, "e": 25887, "s": 25875, "text": "Examples: " }, { "code": null, "e": 26046, "s": 25887, "text": "Input : myarray{1, 2, 3, 4, 5};\nOutput : returns an iterator to the element 1\n\nInput : myarray{8, 7}; \nOutput : returns an iterator to the element 8" }, { "code": null, "e": 26153, "s": 26046, "text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 26157, "s": 26153, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of begin() function#include <array>#include <iostream>using namespace std; int main(){ // declaration of array container array<int, 5> myarray{ 1, 2, 3, 4, 5 }; // using begin() to print array for (auto it = myarray.begin(); it != myarray.end(); ++it) cout << ' ' << *it; return 0;}", "e": 26518, "s": 26157, "text": null }, { "code": null, "e": 26527, "s": 26518, "text": "Output: " }, { "code": null, "e": 26537, "s": 26527, "text": "1 2 3 4 5" }, { "code": null, "e": 26635, "s": 26537, "text": "end() returns an iterator pointing to the past-the-end element in the array container. Syntax : " }, { "code": null, "e": 26786, "s": 26635, "text": "arrayname.end()\nParameters :\nNo parameters are passed.\n\nReturns :\nThis function returns a bidirectional\niterator pointing to the past-the-end element." }, { "code": null, "e": 26798, "s": 26786, "text": "Examples: " }, { "code": null, "e": 27014, "s": 26798, "text": "Input : myarray{1, 2, 3, 4, 5};\nOutput : returns an iterator to the element next to 5 i.e,. some garbage value\n\nInput : myarray{8, 7};\nOutput : returns an iterator to the element next to 7 i.e,. some garbage value" }, { "code": null, "e": 27121, "s": 27014, "text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 27125, "s": 27121, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of end() function#include <array>#include <iostream>using namespace std; int main(){ // declaration of array container array<int, 5> myarray{ 1, 2, 3, 4, 5 }; // using end() to print array for (auto it = myarray.begin(); it != myarray.end(); ++it) cout << ' ' << *it; auto it = myarray.end(); cout << \"\\n myarray.end(): \" << *it << \" [some garbage value]\"; return 0;}", "e": 27587, "s": 27125, "text": null }, { "code": null, "e": 27596, "s": 27587, "text": "Output: " }, { "code": null, "e": 27644, "s": 27596, "text": "1 2 3 4 5\nmyarray.end(): 0 [some garbage value]" }, { "code": null, "e": 27653, "s": 27644, "text": "klynsaha" }, { "code": null, "e": 27663, "s": 27653, "text": "cpp-array" }, { "code": null, "e": 27667, "s": 27663, "text": "STL" }, { "code": null, "e": 27671, "s": 27667, "text": "C++" }, { "code": null, "e": 27675, "s": 27671, "text": "STL" }, { "code": null, "e": 27679, "s": 27675, "text": "CPP" }, { "code": null, "e": 27777, "s": 27679, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27805, "s": 27777, "text": "Operator Overloading in C++" }, { "code": null, "e": 27825, "s": 27805, "text": "Polymorphism in C++" }, { "code": null, "e": 27858, "s": 27825, "text": "Friend class and function in C++" }, { "code": null, "e": 27882, "s": 27858, "text": "Sorting a vector in C++" }, { "code": null, "e": 27907, "s": 27882, "text": "std::string class in C++" }, { "code": null, "e": 27951, "s": 27907, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27975, "s": 27951, "text": "Inline Functions in C++" }, { "code": null, "e": 28020, "s": 27975, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 28073, "s": 28020, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
File opening modes(r versus r+) - GeeksforGeeks
14 Aug, 2019 A file has to be opened before the beginning of reading and writing operations. Opening a file creates a link between the operating system and the file function. Syntax for opening a file: FILE *fp; fp = fopen( " filename with extension ", " mode " ); Opening of file in detail:FILE: structure defined in stdio.h header file. FILE structure provides us the necessary information about a FILE.fp: file pointer which contains the address of the structure FILE.fopen(): this function will open file with name “filename” in specified “mode”. Different reading modes: rr+for binary files: rb, rb+, r+b r r+ for binary files: rb, rb+, r+b Difference: C program for opening file in r mode: #include <stdio.h> void main(){ FILE* fp; char ch; // Open file in Read mode fp = fopen("INPUT.txt", "r+"); // data in file: geeksforgeeks while (1) { ch = fgetc(fp); // Read a Character if (ch == EOF) // Check for End of File break; printf("%c", ch); } fclose(fp); // Close File after Reading} Output: geeksforgeeks Note: File opened should be closed in the program after processing. C program for opening file in r+ mode: #include <stdio.h> void main(){ FILE* fp; char ch; // Open file in Read mode fp = fopen("INPUT.txt", "r+"); // content of the file:geeksforgeeks while (1) { ch = fgetc(fp); // Read a Character if (ch == EOF) // Check for End of File break; printf("%c", ch); } fprintf(fp, " online reference."); fclose(fp); // Close File after Reading // content of the file: geeksforgeeks online reference. fp = fopen("INPUT.txt", "r+"); // Open file in r + mode while (1) { ch = fgetc(fp); // Read a Character if (ch == EOF) // Check for End of File break; printf("%c", ch); } fclose(fp);} Output: geeksforgeeks online reference rishiSingh2 File Handling C Programs File Handling Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string Handling multiple clients on server with multithreading using Socket Programming in C/C++ C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Regular expressions in C Create n-child process from same parent process using fork() in C Conditional wait and signal in multi-threading How to store words in an array in C?
[ { "code": null, "e": 26175, "s": 26147, "text": "\n14 Aug, 2019" }, { "code": null, "e": 26337, "s": 26175, "text": "A file has to be opened before the beginning of reading and writing operations. Opening a file creates a link between the operating system and the file function." }, { "code": null, "e": 26364, "s": 26337, "text": "Syntax for opening a file:" }, { "code": null, "e": 26431, "s": 26364, "text": " FILE *fp;\n fp = fopen( \" filename with extension \", \" mode \" );" }, { "code": null, "e": 26717, "s": 26431, "text": "Opening of file in detail:FILE: structure defined in stdio.h header file. FILE structure provides us the necessary information about a FILE.fp: file pointer which contains the address of the structure FILE.fopen(): this function will open file with name “filename” in specified “mode”." }, { "code": null, "e": 26742, "s": 26717, "text": "Different reading modes:" }, { "code": null, "e": 26776, "s": 26742, "text": "rr+for binary files: rb, rb+, r+b" }, { "code": null, "e": 26778, "s": 26776, "text": "r" }, { "code": null, "e": 26781, "s": 26778, "text": "r+" }, { "code": null, "e": 26812, "s": 26781, "text": "for binary files: rb, rb+, r+b" }, { "code": null, "e": 26824, "s": 26812, "text": "Difference:" }, { "code": null, "e": 26862, "s": 26824, "text": "C program for opening file in r mode:" }, { "code": "#include <stdio.h> void main(){ FILE* fp; char ch; // Open file in Read mode fp = fopen(\"INPUT.txt\", \"r+\"); // data in file: geeksforgeeks while (1) { ch = fgetc(fp); // Read a Character if (ch == EOF) // Check for End of File break; printf(\"%c\", ch); } fclose(fp); // Close File after Reading}", "e": 27220, "s": 26862, "text": null }, { "code": null, "e": 27228, "s": 27220, "text": "Output:" }, { "code": null, "e": 27242, "s": 27228, "text": "geeksforgeeks" }, { "code": null, "e": 27310, "s": 27242, "text": "Note: File opened should be closed in the program after processing." }, { "code": null, "e": 27349, "s": 27310, "text": "C program for opening file in r+ mode:" }, { "code": "#include <stdio.h> void main(){ FILE* fp; char ch; // Open file in Read mode fp = fopen(\"INPUT.txt\", \"r+\"); // content of the file:geeksforgeeks while (1) { ch = fgetc(fp); // Read a Character if (ch == EOF) // Check for End of File break; printf(\"%c\", ch); } fprintf(fp, \" online reference.\"); fclose(fp); // Close File after Reading // content of the file: geeksforgeeks online reference. fp = fopen(\"INPUT.txt\", \"r+\"); // Open file in r + mode while (1) { ch = fgetc(fp); // Read a Character if (ch == EOF) // Check for End of File break; printf(\"%c\", ch); } fclose(fp);}", "e": 28045, "s": 27349, "text": null }, { "code": null, "e": 28053, "s": 28045, "text": "Output:" }, { "code": null, "e": 28084, "s": 28053, "text": "geeksforgeeks online reference" }, { "code": null, "e": 28096, "s": 28084, "text": "rishiSingh2" }, { "code": null, "e": 28110, "s": 28096, "text": "File Handling" }, { "code": null, "e": 28121, "s": 28110, "text": "C Programs" }, { "code": null, "e": 28135, "s": 28121, "text": "File Handling" }, { "code": null, "e": 28233, "s": 28135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28274, "s": 28233, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28305, "s": 28274, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 28339, "s": 28305, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 28380, "s": 28339, "text": "C program to find the length of a string" }, { "code": null, "e": 28470, "s": 28380, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 28541, "s": 28470, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 28566, "s": 28541, "text": "Regular expressions in C" }, { "code": null, "e": 28632, "s": 28566, "text": "Create n-child process from same parent process using fork() in C" }, { "code": null, "e": 28679, "s": 28632, "text": "Conditional wait and signal in multi-threading" } ]
Print matrix in diagonal pattern - GeeksforGeeks
07 Feb, 2022 Given a matrix of n*n size, the task is to print its elements in a diagonal pattern. Input : mat[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output : 1 2 4 7 5 3 6 8 9. Explanation: Start from 1 Then from upward to downward diagonally i.e. 2 and 4 Then from downward to upward diagonally i.e 7, 5, 3 Then from up to down diagonally i.e 6, 8 Then down to up i.e. end at 9. Input : mat[4][4] = {{1, 2, 3, 10}, {4, 5, 6, 11}, {7, 8, 9, 12}, {13, 14, 15, 16}} Output: 1 2 4 7 5 3 10 6 8 13 14 9 11 12 15 16 . Explanation: Start from 1 Then from upward to downward diagonally i.e. 2 and 4 Then from downward to upward diagonally i.e 7, 5, 3 Then from upward to downward diagonally i.e. 10 6 8 13 Then from downward to upward diagonally i.e 14 9 11 Then from upward to downward diagonally i.e. 12 15 then end at 16 Approach: From the diagram it can be seen that every element is either printed diagonally upward or diagonally downward. Start from the index (0,0) and print the elements diagonally upward then change the direction, change the column and print diagonally downwards. This cycle continues until the last element is reached.Algorithm: Create variables i=0, j=0 to store the current indices of row and columnRun a loop from 0 to n*n, where n is side of the matrix.Use a flag isUp to decide whether the direction is upwards or downwards. Set isUp = true initially the direction is going upward.If isUp = 1 then start printing elements by incrementing column index and decrementing the row index.Similarly if isUp = 0, then decrement the column index and increment the row index.Move to the next column or row (next starting row and columnDo this till all the elements get traversed. Create variables i=0, j=0 to store the current indices of row and column Run a loop from 0 to n*n, where n is side of the matrix. Use a flag isUp to decide whether the direction is upwards or downwards. Set isUp = true initially the direction is going upward. If isUp = 1 then start printing elements by incrementing column index and decrementing the row index. Similarly if isUp = 0, then decrement the column index and increment the row index. Move to the next column or row (next starting row and column Do this till all the elements get traversed. Implementation: C++ Java Python 3 C# PHP Javascript // C++ program to print matrix in diagonal order#include <bits/stdc++.h>using namespace std;const int MAX = 100; void printMatrixDiagonal(int mat[MAX][MAX], int n){ // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up bool isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { cout << mat[i][j] << " "; k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) i = i + 2, j--; } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { cout << mat[i][j] << " "; k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) j = j + 2, i--; } // Revert the isUp to change the direction isUp = !isUp; }} int main(){ int mat[MAX][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); return 0;} // Java program to print matrix in diagonal orderclass GFG { static final int MAX = 100; static void printMatrixDiagonal(int mat[][], int n) { // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up boolean isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { System.out.print(mat[i][j] + " "); k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) { i = i + 2; j--; } } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { System.out.print(mat[i][j] + " "); k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) { j = j + 2; i--; } } // Revert the isUp to change the direction isUp = !isUp; } } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); }}// This code is contributed by Anant Agarwal. # Python 3 program to print matrix in diagonal orderMAX = 100 def printMatrixDiagonal(mat, n): # Initialize indexes of element to be printed next i = 0 j = 0 k = 0 # Direction is initially from down to up isUp = True # Traverse the matrix till all elements get traversed while k<n * n: # If isUp = True then traverse from downward # to upward if isUp: while i >= 0 and j<n : print(str(mat[i][j]), end = " ") k += 1 j += 1 i -= 1 # Set i and j according to direction if i < 0 and j <= n - 1: i = 0 if j == n: i = i + 2 j -= 1 # If isUp = 0 then traverse up to down else: while j >= 0 and i<n : print(mat[i][j], end = " ") k += 1 i += 1 j -= 1 # Set i and j according to direction if j < 0 and i <= n - 1: j = 0 if i == n: j = j + 2 i -= 1 # Revert the isUp to change the direction isUp = not isUp # Driver programif __name__ == "__main__": mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9] ] n = 3 printMatrixDiagonal(mat, n) # This code is contributed by Chitra Nayal // C# program to print matrix in diagonal orderusing System;class GFG { static int MAX = 100; static void printMatrixDiagonal(int[, ] mat, int n) { // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up bool isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { Console.Write(mat[i, j] + " "); k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) { i = i + 2; j--; } } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { Console.Write(mat[i, j] + " "); k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) { j = j + 2; i--; } } // Revert the isUp to change the direction isUp = !isUp; } } // Driver code public static void Main() { int[, ] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); }}// This code is contributed by vt_m. <?php// php program to print matrix// in diagonal order $MAX = 100; function printMatrixDiagonal($mat, $n){ // Initialize indexes of element // to be printed next $i = 0; $j = 0 ; // Direction is initially // from down to up $isUp = true; // Traverse the matrix till // all elements get traversed for ($k = 0;$k < $n * $n { // If isUp = true then traverse // from downward to upward if ($isUp) { for ( ;$i >= 0 && $j < $n;$j++, $i--) { echo $mat[$i][$j]." "; $k++; } // Set i and j according // to direction if ($i < 0 && $j <= $n - 1) $i = 0; if ($j == $n) { $i = $i + 2; $j--; } } // If isUp = 0 then // traverse up to down else { for ( ; $j >= 0 && $i<$n ; $i++, $j--) { echo $mat[$i][$j]." "; $k++; } // Set i and j according // to direction if ($j < 0 && $i <= $n - 1) $j = 0; if ($i == $n) { $j = $j + 2; $i--; } } // Revert the isUp to // change the direction $isUp = !$isUp; }} // Driver code $mat= array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); $n = 3; printMatrixDiagonal($mat, $n); // This code is contributed by Surbhi Tyagi ?> <script> // Javascript program to print// matrix in diagonal order function printMatrixDiagonal(arr, len) { // Initialize indices to traverse // through the array let i = 0, j = 0; // Direction is initially from // down to up let isUp = true; // Traverse the matrix till all // elements get traversed for (let k = 0; k < len * len;) { // If isUp = true traverse from // bottom to top if (isUp) { for (;i >= 0 && j < len; i--, j++) { document.write(arr[i][j] + ' '); k++; } // Set i and j according to direction if (i < 0 && j < len) i = 0; if (j === len) i = i + 2, j--; } // If isUp = false then traverse // from top to bottom else { for (;j >= 0 && i < len; i++, j--) { document.write(arr[i][j] + ' '); k++; } // Set i and j according to direction if (j < 0 && i < len) j = 0; if (i === len) j = j + 2, i--; } // Inverse the value of isUp to // change the direction isUp = !isUp } } // function calllet arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];let arrLength = arr.length; printMatrixDiagonal(arr, arrLength); // This code is contributed by karthiksrinivasprasad </script> 1 2 4 7 5 3 6 8 9 Complexity Analysis: Time Complexity: O(n*n). To traverse the matrix O(n*n) time complexity is needed. Space Complexity: O(1). As no extra space is required. Alternate Implementation: This is another simple and compact implementation of the same approach as mentioned above. C++ Java Python3 C# Javascript // C++ program to print matrix in diagonal order#include <bits/stdc++.h>using namespace std; int main(){ // Initialize matrix int mat[][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { cout << (mat[i][t1 + lower - i]) << endl; } else { cout << (mat[t1 + lower - i][i]) << endl; } } } return 0;} // This code is contributed by princiraj1992 // Java program to print matrix in diagonal orderpublic class MatrixDiag { public static void main(String[] args) { // Initialize matrix int[][] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { System.out.println(mat[i][t1 + lower - i]); } else { System.out.println(mat[t1 + lower - i][i]); } } } }} # Python3 program to print matrix in diagonal order # Driver code # Initialize matrixmat = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]; # n - size# mode - switch to derive up/down traversal# it - iterator count - increases until it# reaches n and then decreasesn = 4mode = 0it = 0lower = 0 # 2n will be the number of iterationsfor t in range(2 * n - 1): t1 = t if (t1 >= n): mode += 1 t1 = n - 1 it -= 1 lower += 1 else: lower = 0 it += 1 for i in range(t1, lower - 1, -1): if ((t1 + mode) % 2 == 0): print((mat[i][t1 + lower - i])) else: print(mat[t1 + lower - i][i]) # This code is contributed by princiraj1992 // C# program to print matrix in diagonal orderusing System; public class MatrixDiag { // Driver code public static void Main(String[] args) { // Initialize matrix int[, ] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { Console.WriteLine(mat[i, t1 + lower - i]); } else { Console.WriteLine(mat[t1 + lower - i, i]); } } } }} // This code contributed by Rajput-Ji <script>// Javascript program to print an n * n matrix in diagonal order function MatrixDiag(arr){ // n - size of the array // mode - to switch from top/bottom traversal // it - iterator count - increases until it // reaches n and then decreases // lower - to ensure we move to the // next row when columns go out of bounds let n = arr.length, mode = 0, it = 0, lower = 0; // A 4 * 4 matrix has 7 diagonals. // Hence (2 * n -1) iterations for(let t=0; t< (2 * n - 1); t++){ let t1 = t; if(t1 >= n){ mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for(let i = t1; i>= lower; i--){ if((t1 + mode) % 2 === 0){ console.log(arr[i][t1 + lower - i]) } else{ console.log(arr[t1 + lower - i][i]) } } } } // function call let arr = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]; MatrixDiag(arr) // This code is contributed by karthiksrinivasprasad </script> 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16 This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar ukasp SambaSivaKrishna Rajput-Ji princiraj1992 mohit kumar 29 Code_r andrew1234 surbhityagi15 karthiksrinivasprasad saurabh1990aror simmytarika5 surinderdawra388 Amazon pattern-printing Matrix School Programming Amazon pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26263, "s": 26235, "text": "\n07 Feb, 2022" }, { "code": null, "e": 26350, "s": 26263, "text": "Given a matrix of n*n size, the task is to print its elements in a diagonal pattern. " }, { "code": null, "e": 27201, "s": 26352, "text": "Input : mat[3][3] = {{1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}}\nOutput : 1 2 4 7 5 3 6 8 9.\nExplanation: Start from 1 \nThen from upward to downward diagonally i.e. 2 and 4\nThen from downward to upward diagonally i.e 7, 5, 3 \nThen from up to down diagonally i.e 6, 8 \nThen down to up i.e. end at 9.\n\nInput : mat[4][4] = {{1, 2, 3, 10},\n {4, 5, 6, 11},\n {7, 8, 9, 12},\n {13, 14, 15, 16}}\nOutput: 1 2 4 7 5 3 10 6 8 13 14 9 11 12 15 16 .\nExplanation: Start from 1 \nThen from upward to downward diagonally i.e. 2 and 4\nThen from downward to upward diagonally i.e 7, 5, 3 \nThen from upward to downward diagonally i.e. 10 6 8 13\nThen from downward to upward diagonally i.e 14 9 11\nThen from upward to downward diagonally i.e. 12 15\nthen end at 16" }, { "code": null, "e": 27537, "s": 27203, "text": "Approach: From the diagram it can be seen that every element is either printed diagonally upward or diagonally downward. Start from the index (0,0) and print the elements diagonally upward then change the direction, change the column and print diagonally downwards. This cycle continues until the last element is reached.Algorithm: " }, { "code": null, "e": 28083, "s": 27537, "text": "Create variables i=0, j=0 to store the current indices of row and columnRun a loop from 0 to n*n, where n is side of the matrix.Use a flag isUp to decide whether the direction is upwards or downwards. Set isUp = true initially the direction is going upward.If isUp = 1 then start printing elements by incrementing column index and decrementing the row index.Similarly if isUp = 0, then decrement the column index and increment the row index.Move to the next column or row (next starting row and columnDo this till all the elements get traversed." }, { "code": null, "e": 28156, "s": 28083, "text": "Create variables i=0, j=0 to store the current indices of row and column" }, { "code": null, "e": 28213, "s": 28156, "text": "Run a loop from 0 to n*n, where n is side of the matrix." }, { "code": null, "e": 28343, "s": 28213, "text": "Use a flag isUp to decide whether the direction is upwards or downwards. Set isUp = true initially the direction is going upward." }, { "code": null, "e": 28445, "s": 28343, "text": "If isUp = 1 then start printing elements by incrementing column index and decrementing the row index." }, { "code": null, "e": 28529, "s": 28445, "text": "Similarly if isUp = 0, then decrement the column index and increment the row index." }, { "code": null, "e": 28590, "s": 28529, "text": "Move to the next column or row (next starting row and column" }, { "code": null, "e": 28635, "s": 28590, "text": "Do this till all the elements get traversed." }, { "code": null, "e": 28653, "s": 28635, "text": "Implementation: " }, { "code": null, "e": 28657, "s": 28653, "text": "C++" }, { "code": null, "e": 28662, "s": 28657, "text": "Java" }, { "code": null, "e": 28671, "s": 28662, "text": "Python 3" }, { "code": null, "e": 28674, "s": 28671, "text": "C#" }, { "code": null, "e": 28678, "s": 28674, "text": "PHP" }, { "code": null, "e": 28689, "s": 28678, "text": "Javascript" }, { "code": "// C++ program to print matrix in diagonal order#include <bits/stdc++.h>using namespace std;const int MAX = 100; void printMatrixDiagonal(int mat[MAX][MAX], int n){ // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up bool isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { cout << mat[i][j] << \" \"; k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) i = i + 2, j--; } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { cout << mat[i][j] << \" \"; k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) j = j + 2, i--; } // Revert the isUp to change the direction isUp = !isUp; }} int main(){ int mat[MAX][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); return 0;}", "e": 30094, "s": 28689, "text": null }, { "code": "// Java program to print matrix in diagonal orderclass GFG { static final int MAX = 100; static void printMatrixDiagonal(int mat[][], int n) { // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up boolean isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { System.out.print(mat[i][j] + \" \"); k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) { i = i + 2; j--; } } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { System.out.print(mat[i][j] + \" \"); k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) { j = j + 2; i--; } } // Revert the isUp to change the direction isUp = !isUp; } } // Driver code public static void main(String[] args) { int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); }}// This code is contributed by Anant Agarwal.", "e": 31817, "s": 30094, "text": null }, { "code": "# Python 3 program to print matrix in diagonal orderMAX = 100 def printMatrixDiagonal(mat, n): # Initialize indexes of element to be printed next i = 0 j = 0 k = 0 # Direction is initially from down to up isUp = True # Traverse the matrix till all elements get traversed while k<n * n: # If isUp = True then traverse from downward # to upward if isUp: while i >= 0 and j<n : print(str(mat[i][j]), end = \" \") k += 1 j += 1 i -= 1 # Set i and j according to direction if i < 0 and j <= n - 1: i = 0 if j == n: i = i + 2 j -= 1 # If isUp = 0 then traverse up to down else: while j >= 0 and i<n : print(mat[i][j], end = \" \") k += 1 i += 1 j -= 1 # Set i and j according to direction if j < 0 and i <= n - 1: j = 0 if i == n: j = j + 2 i -= 1 # Revert the isUp to change the direction isUp = not isUp # Driver programif __name__ == \"__main__\": mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9] ] n = 3 printMatrixDiagonal(mat, n) # This code is contributed by Chitra Nayal", "e": 33181, "s": 31817, "text": null }, { "code": "// C# program to print matrix in diagonal orderusing System;class GFG { static int MAX = 100; static void printMatrixDiagonal(int[, ] mat, int n) { // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up bool isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { Console.Write(mat[i, j] + \" \"); k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) { i = i + 2; j--; } } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { Console.Write(mat[i, j] + \" \"); k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) { j = j + 2; i--; } } // Revert the isUp to change the direction isUp = !isUp; } } // Driver code public static void Main() { int[, ] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); }}// This code is contributed by vt_m.", "e": 34878, "s": 33181, "text": null }, { "code": "<?php// php program to print matrix// in diagonal order $MAX = 100; function printMatrixDiagonal($mat, $n){ // Initialize indexes of element // to be printed next $i = 0; $j = 0 ; // Direction is initially // from down to up $isUp = true; // Traverse the matrix till // all elements get traversed for ($k = 0;$k < $n * $n { // If isUp = true then traverse // from downward to upward if ($isUp) { for ( ;$i >= 0 && $j < $n;$j++, $i--) { echo $mat[$i][$j].\" \"; $k++; } // Set i and j according // to direction if ($i < 0 && $j <= $n - 1) $i = 0; if ($j == $n) { $i = $i + 2; $j--; } } // If isUp = 0 then // traverse up to down else { for ( ; $j >= 0 && $i<$n ; $i++, $j--) { echo $mat[$i][$j].\" \"; $k++; } // Set i and j according // to direction if ($j < 0 && $i <= $n - 1) $j = 0; if ($i == $n) { $j = $j + 2; $i--; } } // Revert the isUp to // change the direction $isUp = !$isUp; }} // Driver code $mat= array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); $n = 3; printMatrixDiagonal($mat, $n); // This code is contributed by Surbhi Tyagi ?>", "e": 36488, "s": 34878, "text": null }, { "code": "<script> // Javascript program to print// matrix in diagonal order function printMatrixDiagonal(arr, len) { // Initialize indices to traverse // through the array let i = 0, j = 0; // Direction is initially from // down to up let isUp = true; // Traverse the matrix till all // elements get traversed for (let k = 0; k < len * len;) { // If isUp = true traverse from // bottom to top if (isUp) { for (;i >= 0 && j < len; i--, j++) { document.write(arr[i][j] + ' '); k++; } // Set i and j according to direction if (i < 0 && j < len) i = 0; if (j === len) i = i + 2, j--; } // If isUp = false then traverse // from top to bottom else { for (;j >= 0 && i < len; i++, j--) { document.write(arr[i][j] + ' '); k++; } // Set i and j according to direction if (j < 0 && i < len) j = 0; if (i === len) j = j + 2, i--; } // Inverse the value of isUp to // change the direction isUp = !isUp } } // function calllet arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];let arrLength = arr.length; printMatrixDiagonal(arr, arrLength); // This code is contributed by karthiksrinivasprasad </script>", "e": 37780, "s": 36488, "text": null }, { "code": null, "e": 37798, "s": 37780, "text": "1 2 4 7 5 3 6 8 9" }, { "code": null, "e": 37823, "s": 37800, "text": "Complexity Analysis: " }, { "code": null, "e": 37905, "s": 37823, "text": "Time Complexity: O(n*n). To traverse the matrix O(n*n) time complexity is needed." }, { "code": null, "e": 37960, "s": 37905, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 38078, "s": 37960, "text": "Alternate Implementation: This is another simple and compact implementation of the same approach as mentioned above. " }, { "code": null, "e": 38082, "s": 38078, "text": "C++" }, { "code": null, "e": 38087, "s": 38082, "text": "Java" }, { "code": null, "e": 38095, "s": 38087, "text": "Python3" }, { "code": null, "e": 38098, "s": 38095, "text": "C#" }, { "code": null, "e": 38109, "s": 38098, "text": "Javascript" }, { "code": "// C++ program to print matrix in diagonal order#include <bits/stdc++.h>using namespace std; int main(){ // Initialize matrix int mat[][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { cout << (mat[i][t1 + lower - i]) << endl; } else { cout << (mat[t1 + lower - i][i]) << endl; } } } return 0;} // This code is contributed by princiraj1992", "e": 39169, "s": 38109, "text": null }, { "code": "// Java program to print matrix in diagonal orderpublic class MatrixDiag { public static void main(String[] args) { // Initialize matrix int[][] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { System.out.println(mat[i][t1 + lower - i]); } else { System.out.println(mat[t1 + lower - i][i]); } } } }}", "e": 40322, "s": 39169, "text": null }, { "code": "# Python3 program to print matrix in diagonal order # Driver code # Initialize matrixmat = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]; # n - size# mode - switch to derive up/down traversal# it - iterator count - increases until it# reaches n and then decreasesn = 4mode = 0it = 0lower = 0 # 2n will be the number of iterationsfor t in range(2 * n - 1): t1 = t if (t1 >= n): mode += 1 t1 = n - 1 it -= 1 lower += 1 else: lower = 0 it += 1 for i in range(t1, lower - 1, -1): if ((t1 + mode) % 2 == 0): print((mat[i][t1 + lower - i])) else: print(mat[t1 + lower - i][i]) # This code is contributed by princiraj1992", "e": 41079, "s": 40322, "text": null }, { "code": "// C# program to print matrix in diagonal orderusing System; public class MatrixDiag { // Driver code public static void Main(String[] args) { // Initialize matrix int[, ] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { Console.WriteLine(mat[i, t1 + lower - i]); } else { Console.WriteLine(mat[t1 + lower - i, i]); } } } }} // This code contributed by Rajput-Ji", "e": 42297, "s": 41079, "text": null }, { "code": "<script>// Javascript program to print an n * n matrix in diagonal order function MatrixDiag(arr){ // n - size of the array // mode - to switch from top/bottom traversal // it - iterator count - increases until it // reaches n and then decreases // lower - to ensure we move to the // next row when columns go out of bounds let n = arr.length, mode = 0, it = 0, lower = 0; // A 4 * 4 matrix has 7 diagonals. // Hence (2 * n -1) iterations for(let t=0; t< (2 * n - 1); t++){ let t1 = t; if(t1 >= n){ mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for(let i = t1; i>= lower; i--){ if((t1 + mode) % 2 === 0){ console.log(arr[i][t1 + lower - i]) } else{ console.log(arr[t1 + lower - i][i]) } } } } // function call let arr = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]; MatrixDiag(arr) // This code is contributed by karthiksrinivasprasad </script>", "e": 43418, "s": 42297, "text": null }, { "code": null, "e": 43457, "s": 43418, "text": "1\n2\n5\n9\n6\n3\n4\n7\n10\n13\n14\n11\n8\n12\n15\n16" }, { "code": null, "e": 43881, "s": 43459, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 43894, "s": 43881, "text": "Mithun Kumar" }, { "code": null, "e": 43900, "s": 43894, "text": "ukasp" }, { "code": null, "e": 43917, "s": 43900, "text": "SambaSivaKrishna" }, { "code": null, "e": 43927, "s": 43917, "text": "Rajput-Ji" }, { "code": null, "e": 43941, "s": 43927, "text": "princiraj1992" }, { "code": null, "e": 43956, "s": 43941, "text": "mohit kumar 29" }, { "code": null, "e": 43963, "s": 43956, "text": "Code_r" }, { "code": null, "e": 43974, "s": 43963, "text": "andrew1234" }, { "code": null, "e": 43988, "s": 43974, "text": "surbhityagi15" }, { "code": null, "e": 44010, "s": 43988, "text": "karthiksrinivasprasad" }, { "code": null, "e": 44026, "s": 44010, "text": "saurabh1990aror" }, { "code": null, "e": 44039, "s": 44026, "text": "simmytarika5" }, { "code": null, "e": 44056, "s": 44039, "text": "surinderdawra388" }, { "code": null, "e": 44063, "s": 44056, "text": "Amazon" }, { "code": null, "e": 44080, "s": 44063, "text": "pattern-printing" }, { "code": null, "e": 44087, "s": 44080, "text": "Matrix" }, { "code": null, "e": 44106, "s": 44087, "text": "School Programming" }, { "code": null, "e": 44113, "s": 44106, "text": "Amazon" }, { "code": null, "e": 44130, "s": 44113, "text": "pattern-printing" }, { "code": null, "e": 44137, "s": 44130, "text": "Matrix" }, { "code": null, "e": 44235, "s": 44137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44259, "s": 44235, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 44321, "s": 44259, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 44354, "s": 44321, "text": "Program to multiply two matrices" }, { "code": null, "e": 44405, "s": 44354, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 44426, "s": 44405, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 44444, "s": 44426, "text": "Python Dictionary" }, { "code": null, "e": 44460, "s": 44444, "text": "Arrays in C/C++" }, { "code": null, "e": 44479, "s": 44460, "text": "Inheritance in C++" }, { "code": null, "e": 44504, "s": 44479, "text": "Reverse a string in Java" } ]
How to divide a polynomial to another using NumPy in Python? - GeeksforGeeks
29 Aug, 2020 In this article, we will make a NumPy program to divide one polynomial to another. Two polynomials are given as input and the result is the quotient and remainder of the division. The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}. Let take two polynomials p(x) and g(x) then divide these to get quotient q(x) = p(x) // g(x) and remainder r(x) = p(x) % g(x) as a result. If p(x) = A3 x2 + A2 x + A1 and g(x) = B3 x2 + B2 x + B1 then result is q(x) = p(x) // g(x) and r(x) = p(x) % g(x) and the output is coefficientes of remainder and the coefficientes of quotient. This can be calculated using the polydiv() method. This method evaluates the division of two polynomials and returns the quotient and remainder of the polynomial division. Syntax: numpy.polydiv(p1, p2) Below is the implementation with some examples : Example 1 : Python3 # importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5, -2, 5) # g(x) = x +2gx = (2, 1, 0) # divide the polynomialsqx, rx = numpy.polynomial.polynomial.polydiv(px, gx) # print the result# quotiientprint(qx) # remainderprint(rx) Output : [-12. 5.] [ 29.] Example 2 : Python3 # importing packageimport numpy # define the polynomials# p(x) = (x**2) + 3x + 2px = (1,3,2) # g(x) = x + 1gx = (1,1,0) # divide the polynomialsqx,rx = numpy.polynomial.polynomial.polydiv(px,gx) # print the result# quotiientprint(qx) # remainderprint(rx) Output : [ 1. 2.] [ 0.] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Aug, 2020" }, { "code": null, "e": 25717, "s": 25537, "text": "In this article, we will make a NumPy program to divide one polynomial to another. Two polynomials are given as input and the result is the quotient and remainder of the division." }, { "code": null, "e": 25835, "s": 25717, "text": "The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}." }, { "code": null, "e": 25975, "s": 25835, "text": "Let take two polynomials p(x) and g(x) then divide these to get quotient q(x) = p(x) // g(x) and remainder r(x) = p(x) % g(x) as a result." }, { "code": null, "e": 26177, "s": 25975, "text": "If p(x) = A3 x2 + A2 x + A1\nand \ng(x) = B3 x2 + B2 x + B1 \n\nthen result is \nq(x) = p(x) // g(x) and r(x) = p(x) % g(x)\n\nand the output is coefficientes of remainder and\n the coefficientes of quotient.\n" }, { "code": null, "e": 26349, "s": 26177, "text": "This can be calculated using the polydiv() method. This method evaluates the division of two polynomials and returns the quotient and remainder of the polynomial division." }, { "code": null, "e": 26357, "s": 26349, "text": "Syntax:" }, { "code": null, "e": 26379, "s": 26357, "text": "numpy.polydiv(p1, p2)" }, { "code": null, "e": 26428, "s": 26379, "text": "Below is the implementation with some examples :" }, { "code": null, "e": 26442, "s": 26428, "text": "Example 1 : " }, { "code": null, "e": 26450, "s": 26442, "text": "Python3" }, { "code": "# importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5, -2, 5) # g(x) = x +2gx = (2, 1, 0) # divide the polynomialsqx, rx = numpy.polynomial.polynomial.polydiv(px, gx) # print the result# quotiientprint(qx) # remainderprint(rx)", "e": 26719, "s": 26450, "text": null }, { "code": null, "e": 26728, "s": 26719, "text": "Output :" }, { "code": null, "e": 26747, "s": 26728, "text": "[-12. 5.]\n[ 29.]" }, { "code": null, "e": 26760, "s": 26747, "text": "Example 2 : " }, { "code": null, "e": 26768, "s": 26760, "text": "Python3" }, { "code": "# importing packageimport numpy # define the polynomials# p(x) = (x**2) + 3x + 2px = (1,3,2) # g(x) = x + 1gx = (1,1,0) # divide the polynomialsqx,rx = numpy.polynomial.polynomial.polydiv(px,gx) # print the result# quotiientprint(qx) # remainderprint(rx)", "e": 27028, "s": 26768, "text": null }, { "code": null, "e": 27037, "s": 27028, "text": "Output :" }, { "code": null, "e": 27054, "s": 27037, "text": "[ 1. 2.]\n[ 0.]\n" }, { "code": null, "e": 27089, "s": 27054, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27102, "s": 27089, "text": "Python-numpy" }, { "code": null, "e": 27109, "s": 27102, "text": "Python" }, { "code": null, "e": 27207, "s": 27109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27239, "s": 27207, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27281, "s": 27239, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27323, "s": 27281, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27379, "s": 27323, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27406, "s": 27379, "text": "Python Classes and Objects" }, { "code": null, "e": 27437, "s": 27406, "text": "Python | os.path.join() method" }, { "code": null, "e": 27476, "s": 27437, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27505, "s": 27476, "text": "Create a directory in Python" }, { "code": null, "e": 27527, "s": 27505, "text": "Defaultdict in Python" } ]
Adjacent JSX elements must be wrapped in an enclosing tag - GeeksforGeeks
12 Oct, 2020 If anyone uses multiple HTML elements inside a render method in the React library, it shows an error specifying that Adjacent JSX elements must be wrapped in an enclosing tag. The reason for the error is that when we use the render method it can only take a single HTML element. That means if you have two or more HTML elements back to back in the render method, then it’s not going to work and show an error. So to fix this error one can embed this all HTML element inside a single div element. Anything that goes inside a div will count as a single HTML element. Syntax : ReactDOM.render( <div> // now one can use more than one html // element inside div element. </div>, document.getElementById("root) ); Example 1: When I use multiple HTML elements inside a render method : Javascript import React from 'react';import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Geeks For Geeks</h1> <p>Learn Programming </p> document.getElementById('root')); Output: I get an error specifying that Adjacent JSX elements must be wrapped in an enclosing tag . To fix this error <h1> and <p> tag must be wrapped in a single HTML element like <div> tag . Example 2: When I use a single HTML element inside a render method : Javascript import React from 'react';import ReactDOM from 'react-dom'; ReactDOM.render( <div> <h1>Geeks For Geeks</h1> <p>Learn Programming </p> </div>, document.getElementById('root')); Output: I get the expected output with no error, as in render method <h1> and <p> tag is wrapped inside a single div HTML element and anything that goes inside a div will count as a single HTML element. Picked react-js JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to filter object array based on attributes? How to remove duplicate elements from JavaScript Array ? Lodash _.debounce() Method Angular File Upload How to get selected value in dropdown list using JavaScript ?
[ { "code": null, "e": 26543, "s": 26515, "text": "\n12 Oct, 2020" }, { "code": null, "e": 27108, "s": 26543, "text": "If anyone uses multiple HTML elements inside a render method in the React library, it shows an error specifying that Adjacent JSX elements must be wrapped in an enclosing tag. The reason for the error is that when we use the render method it can only take a single HTML element. That means if you have two or more HTML elements back to back in the render method, then it’s not going to work and show an error. So to fix this error one can embed this all HTML element inside a single div element. Anything that goes inside a div will count as a single HTML element." }, { "code": null, "e": 27118, "s": 27108, "text": "Syntax : " }, { "code": null, "e": 27262, "s": 27118, "text": "ReactDOM.render(\n<div>\n // now one can use more than one html \n // element inside div element.\n</div>,\n document.getElementById(\"root)\n ); \n" }, { "code": null, "e": 27332, "s": 27262, "text": "Example 1: When I use multiple HTML elements inside a render method :" }, { "code": null, "e": 27343, "s": 27332, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Geeks For Geeks</h1> <p>Learn Programming </p> document.getElementById('root'));", "e": 27513, "s": 27343, "text": null }, { "code": null, "e": 27707, "s": 27513, "text": "Output: I get an error specifying that Adjacent JSX elements must be wrapped in an enclosing tag . To fix this error <h1> and <p> tag must be wrapped in a single HTML element like <div> tag . " }, { "code": null, "e": 27776, "s": 27707, "text": "Example 2: When I use a single HTML element inside a render method :" }, { "code": null, "e": 27787, "s": 27776, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; ReactDOM.render( <div> <h1>Geeks For Geeks</h1> <p>Learn Programming </p> </div>, document.getElementById('root'));", "e": 27973, "s": 27787, "text": null }, { "code": null, "e": 28176, "s": 27973, "text": "Output: I get the expected output with no error, as in render method <h1> and <p> tag is wrapped inside a single div HTML element and anything that goes inside a div will count as a single HTML element." }, { "code": null, "e": 28183, "s": 28176, "text": "Picked" }, { "code": null, "e": 28192, "s": 28183, "text": "react-js" }, { "code": null, "e": 28203, "s": 28192, "text": "JavaScript" }, { "code": null, "e": 28301, "s": 28203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28341, "s": 28301, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28402, "s": 28341, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28443, "s": 28402, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28465, "s": 28443, "text": "JavaScript | Promises" }, { "code": null, "e": 28519, "s": 28465, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28567, "s": 28519, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28624, "s": 28567, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 28651, "s": 28624, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 28671, "s": 28651, "text": "Angular File Upload" } ]
Find if there is a path of more than k length from a source - GeeksforGeeks
08 Apr, 2022 Given a graph, a source vertex in the graph and a number k, find if there is a simple path (without any cycle) starting from given source and ending at any other vertex such that the distance from source to that vertex is atleast ‘k’ length. Example: Input : Source s = 0, k = 58 Output : True There exists a simple path 0 -> 7 -> 1 -> 2 -> 8 -> 6 -> 5 -> 3 -> 4 Which has a total distance of 60 km which is more than 58. Input : Source s = 0, k = 62 Output : False In the above graph, the longest simple path has distance 61 (0 -> 7 -> 1-> 2 -> 3 -> 4 -> 5-> 6 -> 8, so output should be false for any input greater than 61. We strongly recommend you to minimize your browser and try this yourself first.One important thing to note is, simply doing BFS or DFS and picking the longest edge at every step would not work. The reason is, a shorter edge can produce longer path due to higher weight edges connected through it.The idea is to use Backtracking. We start from given source, explore all paths from current vertex. We keep track of current distance from source. If distance becomes more than k, we return true. If a path doesn’t produces more than k distance, we backtrack.How do we make sure that the path is simple and we don’t loop in a cycle? The idea is to keep track of current path vertices in an array. Whenever we add a vertex to path, we check if it already exists or not in current path. If it exists, we ignore the edge.Below is implementation of above idea. C++ Java Python3 // Program to find if there is a simple path with// weight more than k#include<bits/stdc++.h>using namespace std; // iPair ==> Integer Pairtypedef pair<int, int> iPair; // This class represents a dipathted graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; bool pathMoreThanKUtil(int src, int k, vector<bool> &path); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); bool pathMoreThanK(int src, int k);}; // Returns true if graph has path more than k lengthbool Graph::pathMoreThanK(int src, int k){ // Create a path array with nothing included // in path vector<bool> path(V, false); // Add source vertex to path path[src] = 1; return pathMoreThanKUtil(src, k, path);} // Prints shortest paths from src to all other verticesbool Graph::pathMoreThanKUtil(int src, int k, vector<bool> &path){ // If k is 0 or negative, return true; if (k <= 0) return true; // Get all adjacent vertices of source vertex src and // recursively explore all paths from src. list<iPair>::iterator i; for (i = adj[src].begin(); i != adj[src].end(); ++i) { // Get adjacent vertex and weight of edge int v = (*i).first; int w = (*i).second; // If vertex v is already there in path, then // there is a cycle (we ignore this edge) if (path[v] == true) continue; // If weight of is more than k, return true if (w >= k) return true; // Else add this vertex to path path[v] = true; // If this adjacent can provide a path longer // than k, return true. if (pathMoreThanKUtil(v, k-w, path)) return true; // Backtrack path[v] = false; } // If no adjacent could produce longer path, return // false return false;} // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list<iPair> [V];} // Utility function to an edge (u, v) of weight wvoid Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); int src = 0; int k = 62; g.pathMoreThanK(src, k)? cout << "Yes\n" : cout << "No\n"; k = 60; g.pathMoreThanK(src, k)? cout << "Yes\n" : cout << "No\n"; return 0;} // Java Program to find if there is a simple path with// weight more than kimport java.util.*;public class GFG{ static class AdjListNode { int v; int weight; AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; } } // This class represents a dipathted graph using // adjacency list representation static class Graph { int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge ArrayList<ArrayList<AdjListNode>> adj; // Allocates memory for adjacency list Graph(int V) { this.V = V; adj = new ArrayList<ArrayList<AdjListNode>>(V); for(int i = 0; i < V; i++) { adj.add(new ArrayList<AdjListNode>()); } } // Utility function to an edge (u, v) of weight w void addEdge(int u, int v, int weight) { AdjListNode node1 = new AdjListNode(v, weight); adj.get(u).add(node1); // Add v to u's list AdjListNode node2 = new AdjListNode(u, weight); adj.get(v).add(node2); // Add u to v's list } // Returns true if graph has path more than k length boolean pathMoreThanK(int src, int k) { // Create a path array with nothing included // in path boolean path[] = new boolean[V]; Arrays.fill(path, false); // Add source vertex to path path[src] = true; return pathMoreThanKUtil(src, k, path); } // Prints shortest paths from src to all other vertices boolean pathMoreThanKUtil(int src, int k, boolean[] path) { // If k is 0 or negative, return true; if (k <= 0) return true; // Get all adjacent vertices of source vertex src and // recursively explore all paths from src. ArrayList<AdjListNode> it = adj.get(src); int index = 0; for(int i = 0; i < adj.get(src).size(); i++) { AdjListNode vertex = adj.get(src).get(i); // Get adjacent vertex and weight of edge int v = vertex.v; int w = vertex.weight; // increase theindex index++; // If vertex v is already there in path, then // there is a cycle (we ignore this edge) if (path[v] == true) continue; // If weight of is more than k, return true if (w >= k) return true; // Else add this vertex to path path[v] = true; // If this adjacent can provide a path longer // than k, return true. if (pathMoreThanKUtil(v, k-w, path)) return true; // Backtrack path[v] = false; } // If no adjacent could produce longer path, return // false return false; } } // Driver program to test methods of graph class public static void main(String[] args) { // create the graph given in above figure int V = 9; Graph g = new Graph(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); int src = 0; int k = 62; if(g.pathMoreThanK(src, k)) System.out.println("YES"); else System.out.println("NO"); k = 60; if(g.pathMoreThanK(src, k)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by adityapande88. # Program to find if there is a simple path with# weight more than k # This class represents a dipathted graph using# adjacency list representationclass Graph: # Allocates memory for adjacency list def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] # Returns true if graph has path more than k length def pathMoreThanK(self,src, k): # Create a path array with nothing included # in path path = [False]*self.V # Add source vertex to path path[src] = 1 return self.pathMoreThanKUtil(src, k, path) # Prints shortest paths from src to all other vertices def pathMoreThanKUtil(self,src, k, path): # If k is 0 or negative, return true if (k <= 0): return True # Get all adjacent vertices of source vertex src and # recursively explore all paths from src. i = 0 while i != len(self.adj[src]): # Get adjacent vertex and weight of edge v = self.adj[src][i][0] w = self.adj[src][i][1] i += 1 # If vertex v is already there in path, then # there is a cycle (we ignore this edge) if (path[v] == True): continue # If weight of is more than k, return true if (w >= k): return True # Else add this vertex to path path[v] = True # If this adjacent can provide a path longer # than k, return true. if (self.pathMoreThanKUtil(v, k-w, path)): return True # Backtrack path[v] = False # If no adjacent could produce longer path, return # false return False # Utility function to an edge (u, v) of weight w def addEdge(self,u, v, w): self.adj[u].append([v, w]) self.adj[v].append([u, w]) # Driver program to test methods of graph classif __name__ == '__main__': # create the graph given in above figure V = 9 g = Graph(V) # making above shown graph g.addEdge(0, 1, 4) g.addEdge(0, 7, 8) g.addEdge(1, 2, 8) g.addEdge(1, 7, 11) g.addEdge(2, 3, 7) g.addEdge(2, 8, 2) g.addEdge(2, 5, 4) g.addEdge(3, 4, 9) g.addEdge(3, 5, 14) g.addEdge(4, 5, 10) g.addEdge(5, 6, 2) g.addEdge(6, 7, 1) g.addEdge(6, 8, 6) g.addEdge(7, 8, 7) src = 0 k = 62 if g.pathMoreThanK(src, k): print("Yes") else: print("No") k = 60 if g.pathMoreThanK(src, k): print("Yes") else: print("No") Output: No Yes Exercise: Modify the above solution to find weight of longest path from a given source.Time Complexity: O(n!) Explanation: From the source node, we one-by-one visit all the paths and check if the total weight is greater than k for each path. So, the worst case will be when the number of possible paths is maximum. This is the case when every node is connected to every other node. Beginning from the source node we have n-1 adjacent nodes. The time needed for a path to connect any two nodes is 2. One for joining the source and the next adjacent vertex. One for breaking the connection between the source and the old adjacent vertex. After selecting a node out of n-1 adjacent nodes, we are left with n-2 adjacent nodes (as the source node is already included in the path) and so on at every step of selecting a node our problem reduces by 1 node.We can write this in the form of a recurrence relation as: F(n) = n*(2+F(n-1)) This expands to: 2n + 2n*(n-1) + 2n*(n-1)*(n-2) + ....... + 2n(n-1)(n-2)(n-3).....1 As n times 2n(n-1)(n-2)(n-3)....1 is greater than the given expression so we can safely say time complexity is: n*2*n! Here in the question the first node is defined so time complexity becomes F(n-1) = 2(n-1)*(n-1)! = 2*n*(n-1)! – 2*1*(n-1)! = 2*n!-2*(n-1)! = O(n!)This article is contributed by Shivam Gupta. The explanation for time complexity is contributed by Pranav Nambiar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above PranchalKatiyar adityapande88 akshatsuwalka simmytarika5 Backtracking Graph Graph Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Subset Sum | Backtracking-4 Print all paths from a given source to a destination Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 26371, "s": 26343, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26614, "s": 26371, "text": "Given a graph, a source vertex in the graph and a number k, find if there is a simple path (without any cycle) starting from given source and ending at any other vertex such that the distance from source to that vertex is atleast ‘k’ length. " }, { "code": null, "e": 27004, "s": 26614, "text": "Example:\nInput : Source s = 0, k = 58\nOutput : True\nThere exists a simple path 0 -> 7 -> 1\n-> 2 -> 8 -> 6 -> 5 -> 3 -> 4\nWhich has a total distance of 60 km which\nis more than 58.\n\nInput : Source s = 0, k = 62\nOutput : False\n\nIn the above graph, the longest simple\npath has distance 61 (0 -> 7 -> 1-> 2\n -> 3 -> 4 -> 5-> 6 -> 8, so output \nshould be false for any input greater \nthan 61." }, { "code": null, "e": 27858, "s": 27004, "text": "We strongly recommend you to minimize your browser and try this yourself first.One important thing to note is, simply doing BFS or DFS and picking the longest edge at every step would not work. The reason is, a shorter edge can produce longer path due to higher weight edges connected through it.The idea is to use Backtracking. We start from given source, explore all paths from current vertex. We keep track of current distance from source. If distance becomes more than k, we return true. If a path doesn’t produces more than k distance, we backtrack.How do we make sure that the path is simple and we don’t loop in a cycle? The idea is to keep track of current path vertices in an array. Whenever we add a vertex to path, we check if it already exists or not in current path. If it exists, we ignore the edge.Below is implementation of above idea. " }, { "code": null, "e": 27862, "s": 27858, "text": "C++" }, { "code": null, "e": 27867, "s": 27862, "text": "Java" }, { "code": null, "e": 27875, "s": 27867, "text": "Python3" }, { "code": "// Program to find if there is a simple path with// weight more than k#include<bits/stdc++.h>using namespace std; // iPair ==> Integer Pairtypedef pair<int, int> iPair; // This class represents a dipathted graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; bool pathMoreThanKUtil(int src, int k, vector<bool> &path); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); bool pathMoreThanK(int src, int k);}; // Returns true if graph has path more than k lengthbool Graph::pathMoreThanK(int src, int k){ // Create a path array with nothing included // in path vector<bool> path(V, false); // Add source vertex to path path[src] = 1; return pathMoreThanKUtil(src, k, path);} // Prints shortest paths from src to all other verticesbool Graph::pathMoreThanKUtil(int src, int k, vector<bool> &path){ // If k is 0 or negative, return true; if (k <= 0) return true; // Get all adjacent vertices of source vertex src and // recursively explore all paths from src. list<iPair>::iterator i; for (i = adj[src].begin(); i != adj[src].end(); ++i) { // Get adjacent vertex and weight of edge int v = (*i).first; int w = (*i).second; // If vertex v is already there in path, then // there is a cycle (we ignore this edge) if (path[v] == true) continue; // If weight of is more than k, return true if (w >= k) return true; // Else add this vertex to path path[v] = true; // If this adjacent can provide a path longer // than k, return true. if (pathMoreThanKUtil(v, k-w, path)) return true; // Backtrack path[v] = false; } // If no adjacent could produce longer path, return // false return false;} // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list<iPair> [V];} // Utility function to an edge (u, v) of weight wvoid Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); int src = 0; int k = 62; g.pathMoreThanK(src, k)? cout << \"Yes\\n\" : cout << \"No\\n\"; k = 60; g.pathMoreThanK(src, k)? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 30899, "s": 27875, "text": null }, { "code": "// Java Program to find if there is a simple path with// weight more than kimport java.util.*;public class GFG{ static class AdjListNode { int v; int weight; AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; } } // This class represents a dipathted graph using // adjacency list representation static class Graph { int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge ArrayList<ArrayList<AdjListNode>> adj; // Allocates memory for adjacency list Graph(int V) { this.V = V; adj = new ArrayList<ArrayList<AdjListNode>>(V); for(int i = 0; i < V; i++) { adj.add(new ArrayList<AdjListNode>()); } } // Utility function to an edge (u, v) of weight w void addEdge(int u, int v, int weight) { AdjListNode node1 = new AdjListNode(v, weight); adj.get(u).add(node1); // Add v to u's list AdjListNode node2 = new AdjListNode(u, weight); adj.get(v).add(node2); // Add u to v's list } // Returns true if graph has path more than k length boolean pathMoreThanK(int src, int k) { // Create a path array with nothing included // in path boolean path[] = new boolean[V]; Arrays.fill(path, false); // Add source vertex to path path[src] = true; return pathMoreThanKUtil(src, k, path); } // Prints shortest paths from src to all other vertices boolean pathMoreThanKUtil(int src, int k, boolean[] path) { // If k is 0 or negative, return true; if (k <= 0) return true; // Get all adjacent vertices of source vertex src and // recursively explore all paths from src. ArrayList<AdjListNode> it = adj.get(src); int index = 0; for(int i = 0; i < adj.get(src).size(); i++) { AdjListNode vertex = adj.get(src).get(i); // Get adjacent vertex and weight of edge int v = vertex.v; int w = vertex.weight; // increase theindex index++; // If vertex v is already there in path, then // there is a cycle (we ignore this edge) if (path[v] == true) continue; // If weight of is more than k, return true if (w >= k) return true; // Else add this vertex to path path[v] = true; // If this adjacent can provide a path longer // than k, return true. if (pathMoreThanKUtil(v, k-w, path)) return true; // Backtrack path[v] = false; } // If no adjacent could produce longer path, return // false return false; } } // Driver program to test methods of graph class public static void main(String[] args) { // create the graph given in above figure int V = 9; Graph g = new Graph(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); int src = 0; int k = 62; if(g.pathMoreThanK(src, k)) System.out.println(\"YES\"); else System.out.println(\"NO\"); k = 60; if(g.pathMoreThanK(src, k)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by adityapande88.", "e": 34472, "s": 30899, "text": null }, { "code": "# Program to find if there is a simple path with# weight more than k # This class represents a dipathted graph using# adjacency list representationclass Graph: # Allocates memory for adjacency list def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] # Returns true if graph has path more than k length def pathMoreThanK(self,src, k): # Create a path array with nothing included # in path path = [False]*self.V # Add source vertex to path path[src] = 1 return self.pathMoreThanKUtil(src, k, path) # Prints shortest paths from src to all other vertices def pathMoreThanKUtil(self,src, k, path): # If k is 0 or negative, return true if (k <= 0): return True # Get all adjacent vertices of source vertex src and # recursively explore all paths from src. i = 0 while i != len(self.adj[src]): # Get adjacent vertex and weight of edge v = self.adj[src][i][0] w = self.adj[src][i][1] i += 1 # If vertex v is already there in path, then # there is a cycle (we ignore this edge) if (path[v] == True): continue # If weight of is more than k, return true if (w >= k): return True # Else add this vertex to path path[v] = True # If this adjacent can provide a path longer # than k, return true. if (self.pathMoreThanKUtil(v, k-w, path)): return True # Backtrack path[v] = False # If no adjacent could produce longer path, return # false return False # Utility function to an edge (u, v) of weight w def addEdge(self,u, v, w): self.adj[u].append([v, w]) self.adj[v].append([u, w]) # Driver program to test methods of graph classif __name__ == '__main__': # create the graph given in above figure V = 9 g = Graph(V) # making above shown graph g.addEdge(0, 1, 4) g.addEdge(0, 7, 8) g.addEdge(1, 2, 8) g.addEdge(1, 7, 11) g.addEdge(2, 3, 7) g.addEdge(2, 8, 2) g.addEdge(2, 5, 4) g.addEdge(3, 4, 9) g.addEdge(3, 5, 14) g.addEdge(4, 5, 10) g.addEdge(5, 6, 2) g.addEdge(6, 7, 1) g.addEdge(6, 8, 6) g.addEdge(7, 8, 7) src = 0 k = 62 if g.pathMoreThanK(src, k): print(\"Yes\") else: print(\"No\") k = 60 if g.pathMoreThanK(src, k): print(\"Yes\") else: print(\"No\")", "e": 37112, "s": 34472, "text": null }, { "code": null, "e": 37122, "s": 37112, "text": "Output: " }, { "code": null, "e": 37129, "s": 37122, "text": "No\nYes" }, { "code": null, "e": 38646, "s": 37129, "text": "Exercise: Modify the above solution to find weight of longest path from a given source.Time Complexity: O(n!) Explanation: From the source node, we one-by-one visit all the paths and check if the total weight is greater than k for each path. So, the worst case will be when the number of possible paths is maximum. This is the case when every node is connected to every other node. Beginning from the source node we have n-1 adjacent nodes. The time needed for a path to connect any two nodes is 2. One for joining the source and the next adjacent vertex. One for breaking the connection between the source and the old adjacent vertex. After selecting a node out of n-1 adjacent nodes, we are left with n-2 adjacent nodes (as the source node is already included in the path) and so on at every step of selecting a node our problem reduces by 1 node.We can write this in the form of a recurrence relation as: F(n) = n*(2+F(n-1)) This expands to: 2n + 2n*(n-1) + 2n*(n-1)*(n-2) + ....... + 2n(n-1)(n-2)(n-3).....1 As n times 2n(n-1)(n-2)(n-3)....1 is greater than the given expression so we can safely say time complexity is: n*2*n! Here in the question the first node is defined so time complexity becomes F(n-1) = 2(n-1)*(n-1)! = 2*n*(n-1)! – 2*1*(n-1)! = 2*n!-2*(n-1)! = O(n!)This article is contributed by Shivam Gupta. The explanation for time complexity is contributed by Pranav Nambiar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 38662, "s": 38646, "text": "PranchalKatiyar" }, { "code": null, "e": 38676, "s": 38662, "text": "adityapande88" }, { "code": null, "e": 38690, "s": 38676, "text": "akshatsuwalka" }, { "code": null, "e": 38703, "s": 38690, "text": "simmytarika5" }, { "code": null, "e": 38716, "s": 38703, "text": "Backtracking" }, { "code": null, "e": 38722, "s": 38716, "text": "Graph" }, { "code": null, "e": 38728, "s": 38722, "text": "Graph" }, { "code": null, "e": 38741, "s": 38728, "text": "Backtracking" }, { "code": null, "e": 38839, "s": 38741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38867, "s": 38839, "text": "Backtracking | Introduction" }, { "code": null, "e": 38902, "s": 38867, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 38938, "s": 38902, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 38966, "s": 38938, "text": "Subset Sum | Backtracking-4" }, { "code": null, "e": 39019, "s": 38966, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 39070, "s": 39019, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 39128, "s": 39070, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 39179, "s": 39128, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
Number of ways to partition a string into two balanced subsequences - GeeksforGeeks
21 Oct, 2021 Given a string ‘S’ consisting of open and closed brackets, the task is find the number of ways in which each character of ‘S’ can be assigned to either a string ‘X’ or string ‘Y’ (both initially empty) such that the strings formed by X and Y are balanced. It can be assumed that ‘S’ is itself balanced.Examples: Input: S = "(())" Output: 6 Valid assignments are : X = "(())" and Y = "" [All characters in X] X = "" and Y = "(())" [Nothing in X] X = "()" and Y = "()" [1st and 3rd characters in X] X = "()" and Y = "()" [2nd and 3rd characters in X] X = "()" and Y = "()" [2nd and 4th characters in X] X = "()" and Y = "()" [1st and 4th characters in X] Input: S = "()()" Output: 4 X = "()()", Y = "" X = "()", Y = "()" [1st and 2nd in X] X = "()", Y = "" [1st and 4th in X] X = "", Y = "()()" A simple approach: We can generate every possible way of assigning the characters, and check if the strings formed are balanced or not. There are 2n assignments, valid or invalid, and it takes O(n) time to check if the strings formed are balanced or not. Therefore the time complexity of this approach is O(n * 2n).An efficient approach (Dynamic programming): We can solve this problem in a more efficient manner using Dynamic Programming. We can describe the current state of assignment using three variables: the index i of the character to be assigned, and the strings formed by X and Y up to that state. Passing the whole strings to function calls will result in high memory requirements, so we can replace them with count variables cx and cy. We will increment the count variable for every opening bracket and decrement it for every closing bracket. The time and space complexity of this approach is O(n3).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // For maximum length of input stringconst int MAX = 10; // Declaring the DP tableint F[MAX][MAX][MAX]; // Function to calculate the// number of valid assignmentsint noOfAssignments(string& S, int& n, int i, int c_x, int c_y){ if (F[i][c_x][c_y] != -1) return F[i][c_x][c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i][c_x][c_y] = !c_x && !c_y; return F[i][c_x][c_y]; } // Increment the count // if it an opening bracket if (S[i] == '(') { F[i][c_x][c_y] = noOfAssignments(S, n, i + 1, c_x + 1, c_y) + noOfAssignments(S, n, i + 1, c_x, c_y + 1); return F[i][c_x][c_y]; } F[i][c_x][c_y] = 0; // Decrement the count // if it a closing bracket if (c_x) F[i][c_x][c_y] += noOfAssignments(S, n, i + 1, c_x - 1, c_y); if (c_y) F[i][c_x][c_y] += noOfAssignments(S, n, i + 1, c_x, c_y - 1); return F[i][c_x][c_y];} // Driver codeint main(){ string S = "(())"; int n = S.length(); // Initializing the DP table memset(F, -1, sizeof(F)); // Initial value for c_x // and c_y is zero cout << noOfAssignments(S, n, 0, 0, 0); return 0;} // Java implementation of the above approachclass GFG{ // For maximum length of input string static int MAX = 10; // Declaring the DP table static int[][][] F = new int[MAX][MAX][MAX]; // Function to calculate the // number of valid assignments static int noOfAssignments(String s, int n, int i, int c_x, int c_y) { if (F[i][c_x][c_y] != -1) return F[i][c_x][c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i][c_x][c_y] = (c_x == 0 && c_y == 0) ? 1 : 0; return F[i][c_x][c_y]; } // Increment the count // if it an opening bracket if (s.charAt(i) == '(') { F[i][c_x][c_y] = noOfAssignments(s, n, i + 1, c_x + 1, c_y) + noOfAssignments(s, n, i + 1, c_x, c_y + 1); return F[i][c_x][c_y]; } F[i][c_x][c_y] = 0; // Decrement the count // if it a closing bracket if (c_x != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x - 1, c_y); if (c_y != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x, c_y - 1); return F[i][c_x][c_y]; } // Driver Code public static void main(String[] args) { String s = "(())"; int n = s.length(); // Initializing the DP table for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) F[i][j][k] = -1; // Initial value for c_x // and c_y is zero System.out.println(noOfAssignments(s, n, 0, 0, 0)); }} // This code is contributed by// sanjeev2552 # Python3 implementation of above approach # For maximum length of input stringMAX = 10 # Declaring the DP tableF = [[[-1 for i in range(MAX)] for j in range(MAX)] for k in range(MAX)] # Function to calculate the number# of valid assignmentsdef noOfAssignments(S, n, i, c_x, c_y): if F[i][c_x][c_y] != -1: return F[i][c_x][c_y] if i == n: # Return 1 if both subsequences are balanced F[i][c_x][c_y] = not c_x and not c_y return F[i][c_x][c_y] # Increment the count if # it is an opening bracket if S[i] == '(': F[i][c_x][c_y] = \ noOfAssignments(S, n, i + 1, c_x + 1, c_y) + \ noOfAssignments(S, n, i + 1, c_x, c_y + 1) return F[i][c_x][c_y] F[i][c_x][c_y] = 0 # Decrement the count # if it a closing bracket if c_x: F[i][c_x][c_y] += \ noOfAssignments(S, n, i + 1, c_x - 1, c_y) if c_y: F[i][c_x][c_y] += \ noOfAssignments(S, n, i + 1, c_x, c_y - 1) return F[i][c_x][c_y] # Driver codeif __name__ == "__main__": S = "(())" n = len(S) # Initial value for c_x and c_y is zero print(noOfAssignments(S, n, 0, 0, 0)) # This code is contributed by Rituraj Jain // C# implementation of the above approachusing System; class GFG{ // For maximum length of input string static int MAX = 10; // Declaring the DP table static int[,,] F = new int[MAX, MAX, MAX]; // Function to calculate the // number of valid assignments static int noOfAssignments(String s, int n, int i, int c_x, int c_y) { if (F[i, c_x, c_y] != -1) return F[i, c_x, c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i, c_x, c_y] = (c_x == 0 && c_y == 0) ? 1 : 0; return F[i, c_x, c_y]; } // Increment the count // if it an opening bracket if (s[i] == '(') { F[i, c_x, c_y] = noOfAssignments(s, n, i + 1, c_x + 1, c_y) + noOfAssignments(s, n, i + 1, c_x, c_y + 1); return F[i, c_x, c_y]; } F[i, c_x, c_y] = 0; // Decrement the count // if it a closing bracket if (c_x != 0) F[i, c_x, c_y] += noOfAssignments(s, n, i + 1, c_x - 1, c_y); if (c_y != 0) F[i, c_x, c_y] += noOfAssignments(s, n, i + 1, c_x, c_y - 1); return F[i, c_x, c_y]; } // Driver Code public static void Main(String[] args) { String s = "(())"; int n = s.Length; // Initializing the DP table for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) F[i, j, k] = -1; // Initial value for c_x // and c_y is zero Console.WriteLine(noOfAssignments(s, n, 0, 0, 0)); }} // This code is contributed by PrinciRaj1992 <script>// Javascript implementation of the above approach // For maximum length of input string let MAX = 10; // Declaring the DP table let F = new Array(MAX); for(let i = 0; i < MAX; i++) { F[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { F[i][j] = new Array(MAX); for(let k = 0; k < MAX; k++) { F[i][j][k] = -1; } } } // Function to calculate the // number of valid assignments function noOfAssignments(s,n,i,c_x,c_y) { if (F[i][c_x][c_y] != -1) return F[i][c_x][c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i][c_x][c_y] = (c_x == 0 && c_y == 0) ? 1 : 0; return F[i][c_x][c_y]; } // Increment the count // if it an opening bracket if (s.charAt(i) == '(') { F[i][c_x][c_y] = noOfAssignments(s, n, i + 1, c_x + 1, c_y) + noOfAssignments(s, n, i + 1, c_x, c_y + 1); return F[i][c_x][c_y]; } F[i][c_x][c_y] = 0; // Decrement the count // if it a closing bracket if (c_x != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x - 1, c_y); if (c_y != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x, c_y - 1); return F[i][c_x][c_y]; } // Driver Code let s = "(())"; let n = s.length; // Initial value for c_x // and c_y is zero document.write(noOfAssignments(s, n, 0, 0, 0)); // This code is contributed by rag2127</script> 6 Optimized Dynamic Programming approach: We can create a prefix array to store the count variable ci for the substring S[0 : i + 1]. We can observe that the sum of c_x and c_y will always be equal to the count variable for the whole string. By exploiting this property, we can reduce our dynamic programming approach to two states. A prefix array can be created in linear complexity, so the time and space complexity of this approach is O(n2). C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // For maximum length of input stringconst int MAX = 10; // Declaring the DP tableint F[MAX][MAX]; // Declaring the prefix arrayint C[MAX]; // Function to calculate the// number of valid assignmentsint noOfAssignments(string& S, int& n, int i, int c_x){ if (F[i][c_x] != -1) return F[i][c_x]; if (i == n) { // Return 1 if X is // balanced. F[i][c_x] = !c_x; return F[i][c_x]; } int c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S[i] == '(') { F[i][c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i][c_x]; } F[i][c_x] = 0; // Decrement the count // if it a closing bracket if (c_x) F[i][c_x] += noOfAssignments(S, n, i + 1, c_x - 1); if (c_y) F[i][c_x] += noOfAssignments(S, n, i + 1, c_x); return F[i][c_x];} // Driver codeint main(){ string S = "()"; int n = S.length(); // Initializing the DP table memset(F, -1, sizeof(F)); C[0] = 0; // Creating the prefix array for (int i = 0; i < n; ++i) if (S[i] == '(') C[i + 1] = C[i] + 1; else C[i + 1] = C[i] - 1; // Initial value for c_x // and c_y is zero cout << noOfAssignments(S, n, 0, 0); return 0;} // Java implementation of the approach public class GFG { // For maximum length of input string static int MAX = 10; // Declaring the DP table static int F[][] = new int[MAX][MAX]; // Declaring the prefix array static int C[] = new int[MAX]; // Function to calculate the// number of valid assignments static int noOfAssignments(String S, int n, int i, int c_x) { if (F[i][c_x] != -1) { return F[i][c_x]; } if (i == n) { // Return 1 if X is // balanced. if (c_x == 1) { F[i][c_x] = 0; } else { F[i][c_x] = 1; } return F[i][c_x]; } int c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S.charAt(i) == '(') { F[i][c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i][c_x]; } F[i][c_x] = 0; // Decrement the count // if it a closing bracket if (c_x == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x - 1); } if (c_y == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x); } return F[i][c_x]; } // Driver code public static void main(String[] args) { String S = "()"; int n = S.length(); // Initializing the DP table for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { F[i][j] = -1; } } C[0] = 0; // Creating the prefix array for (int i = 0; i < n; ++i) { if (S.charAt(i) == '(') { C[i + 1] = C[i] + 1; } else { C[i + 1] = C[i] - 1; } } // Initial value for c_x // and c_y is zero System.out.println(noOfAssignments(S, n, 0, 0)); }}// This code is contributed by 29AjayKumar # Python3 implementation of above approach # For maximum length of input stringMAX = 10 # Declaring the DP tableF = [[-1 for i in range(MAX)] for j in range(MAX)] # Declaring the prefix arrayC = [None] * MAX # Function to calculate the# number of valid assignmentsdef noOfAssignments(S, n, i, c_x): if F[i][c_x] != -1: return F[i][c_x] if i == n: # Return 1 if X is balanced. F[i][c_x] = not c_x return F[i][c_x] c_y = C[i] - c_x # Increment the count # if it is an opening bracket if S[i] == '(': F[i][c_x] = \ noOfAssignments(S, n, i + 1, c_x + 1) + \ noOfAssignments(S, n, i + 1, c_x) return F[i][c_x] F[i][c_x] = 0 # Decrement the count if it is a closing bracket if c_x: F[i][c_x] += \ noOfAssignments(S, n, i + 1, c_x - 1) if c_y: F[i][c_x] += \ noOfAssignments(S, n, i + 1, c_x) return F[i][c_x] # Driver codeif __name__ == "__main__": S = "()" n = len(S) C[0] = 0 # Creating the prefix array for i in range(0, n): if S[i] == '(': C[i + 1] = C[i] + 1 else: C[i + 1] = C[i] - 1 # Initial value for c_x and c_y is zero print(noOfAssignments(S, n, 0, 0)) # This code is contributed by Rituraj Jain // C# implementation of the approach using System;public class GFG { // For maximum length of input string static int MAX = 10; // Declaring the DP table static int[,] F = new int[MAX,MAX]; // Declaring the prefix array static int[] C = new int[MAX]; // Function to calculate the// number of valid assignments static int noOfAssignments(string S, int n, int i, int c_x) { if (F[i,c_x] != -1) { return F[i,c_x]; } if (i == n) { // Return 1 if X is // balanced. if (c_x == 1) { F[i,c_x] = 0; } else { F[i,c_x] = 1; } return F[i,c_x]; } int c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S[i] == '(') { F[i,c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i,c_x]; } F[i,c_x] = 0; // Decrement the count // if it a closing bracket if (c_x == 1) { F[i,c_x] += noOfAssignments(S, n, i + 1, c_x - 1); } if (c_y == 1) { F[i,c_x] += noOfAssignments(S, n, i + 1, c_x); } return F[i,c_x]; } // Driver code public static void Main() { string S = "()"; int n = S.Length; // Initializing the DP table for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { F[i,j] = -1; } } C[0] = 0; // Creating the prefix array for (int i = 0; i < n; ++i) { if (S[i] == '(') { C[i + 1] = C[i] + 1; } else { C[i + 1] = C[i] - 1; } } // Initial value for c_x // and c_y is zero Console.WriteLine(noOfAssignments(S, n, 0, 0)); }}// This code is contributed by Ita_c. <script>// Javascript implementation of the approach // For maximum length of input stringvar MAX = 10; // Declaring the DP tablevar F = Array.from(Array(MAX), ()=>Array(MAX).fill(0)); // Declaring the prefix arrayvar C = Array(MAX).fill(0); // Function to calculate the// number of valid assignmentsfunction noOfAssignments(S, n, i, c_x) { if (F[i][c_x] != -1) { return F[i][c_x]; } if (i == n) { // Return 1 if X is // balanced. if (c_x == 1) { F[i][c_x] = 0; } else { F[i][c_x] = 1; } return F[i][c_x]; } var c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S[i] == '(') { F[i][c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i][c_x]; } F[i][c_x] = 0; // Decrement the count // if it a closing bracket if (c_x == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x - 1); } if (c_y == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x); } return F[i][c_x]; } // Driver codevar S = "()";var n = S.length; // Initializing the DP tablefor(var i = 0; i < MAX; i++) { for(var j = 0; j < MAX; j++) { F[i][j] = -1; }} C[0] = 0; // Creating the prefix arrayfor (var i = 0; i < n; ++i) { if (S[i] == '(') { C[i + 1] = C[i] + 1; } else { C[i + 1] = C[i] - 1; }} // Initial value for c_x// and c_y is zerodocument.write(noOfAssignments(S, n, 0, 0) + "<br>"); // This code is contributed by rrrtnx.</script> 2 29AjayKumar ukasp rituraj_jain sanjeev2552 princiraj1992 rag2127 rrrtnx saurabh1990aror Directi media.net Parentheses-Problems subsequence Technical Scripter 2018 Dynamic Programming Strings Technical Scripter Directi Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26257, "s": 26229, "text": "\n21 Oct, 2021" }, { "code": null, "e": 26571, "s": 26257, "text": "Given a string ‘S’ consisting of open and closed brackets, the task is find the number of ways in which each character of ‘S’ can be assigned to either a string ‘X’ or string ‘Y’ (both initially empty) such that the strings formed by X and Y are balanced. It can be assumed that ‘S’ is itself balanced.Examples: " }, { "code": null, "e": 27055, "s": 26571, "text": "Input: S = \"(())\"\nOutput: 6\nValid assignments are :\nX = \"(())\" and Y = \"\" [All characters in X]\nX = \"\" and Y = \"(())\" [Nothing in X]\nX = \"()\" and Y = \"()\" [1st and 3rd characters in X]\nX = \"()\" and Y = \"()\" [2nd and 3rd characters in X]\nX = \"()\" and Y = \"()\" [2nd and 4th characters in X]\nX = \"()\" and Y = \"()\" [1st and 4th characters in X]\n\nInput: S = \"()()\"\nOutput: 4\nX = \"()()\", Y = \"\"\nX = \"()\", Y = \"()\" [1st and 2nd in X]\nX = \"()\", Y = \"\" [1st and 4th in X]\nX = \"\", Y = \"()()\"" }, { "code": null, "e": 28020, "s": 27057, "text": "A simple approach: We can generate every possible way of assigning the characters, and check if the strings formed are balanced or not. There are 2n assignments, valid or invalid, and it takes O(n) time to check if the strings formed are balanced or not. Therefore the time complexity of this approach is O(n * 2n).An efficient approach (Dynamic programming): We can solve this problem in a more efficient manner using Dynamic Programming. We can describe the current state of assignment using three variables: the index i of the character to be assigned, and the strings formed by X and Y up to that state. Passing the whole strings to function calls will result in high memory requirements, so we can replace them with count variables cx and cy. We will increment the count variable for every opening bracket and decrement it for every closing bracket. The time and space complexity of this approach is O(n3).Below is the implementation of the above approach: " }, { "code": null, "e": 28024, "s": 28020, "text": "C++" }, { "code": null, "e": 28029, "s": 28024, "text": "Java" }, { "code": null, "e": 28037, "s": 28029, "text": "Python3" }, { "code": null, "e": 28040, "s": 28037, "text": "C#" }, { "code": null, "e": 28051, "s": 28040, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // For maximum length of input stringconst int MAX = 10; // Declaring the DP tableint F[MAX][MAX][MAX]; // Function to calculate the// number of valid assignmentsint noOfAssignments(string& S, int& n, int i, int c_x, int c_y){ if (F[i][c_x][c_y] != -1) return F[i][c_x][c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i][c_x][c_y] = !c_x && !c_y; return F[i][c_x][c_y]; } // Increment the count // if it an opening bracket if (S[i] == '(') { F[i][c_x][c_y] = noOfAssignments(S, n, i + 1, c_x + 1, c_y) + noOfAssignments(S, n, i + 1, c_x, c_y + 1); return F[i][c_x][c_y]; } F[i][c_x][c_y] = 0; // Decrement the count // if it a closing bracket if (c_x) F[i][c_x][c_y] += noOfAssignments(S, n, i + 1, c_x - 1, c_y); if (c_y) F[i][c_x][c_y] += noOfAssignments(S, n, i + 1, c_x, c_y - 1); return F[i][c_x][c_y];} // Driver codeint main(){ string S = \"(())\"; int n = S.length(); // Initializing the DP table memset(F, -1, sizeof(F)); // Initial value for c_x // and c_y is zero cout << noOfAssignments(S, n, 0, 0, 0); return 0;}", "e": 29509, "s": 28051, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // For maximum length of input string static int MAX = 10; // Declaring the DP table static int[][][] F = new int[MAX][MAX][MAX]; // Function to calculate the // number of valid assignments static int noOfAssignments(String s, int n, int i, int c_x, int c_y) { if (F[i][c_x][c_y] != -1) return F[i][c_x][c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i][c_x][c_y] = (c_x == 0 && c_y == 0) ? 1 : 0; return F[i][c_x][c_y]; } // Increment the count // if it an opening bracket if (s.charAt(i) == '(') { F[i][c_x][c_y] = noOfAssignments(s, n, i + 1, c_x + 1, c_y) + noOfAssignments(s, n, i + 1, c_x, c_y + 1); return F[i][c_x][c_y]; } F[i][c_x][c_y] = 0; // Decrement the count // if it a closing bracket if (c_x != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x - 1, c_y); if (c_y != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x, c_y - 1); return F[i][c_x][c_y]; } // Driver Code public static void main(String[] args) { String s = \"(())\"; int n = s.length(); // Initializing the DP table for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) F[i][j][k] = -1; // Initial value for c_x // and c_y is zero System.out.println(noOfAssignments(s, n, 0, 0, 0)); }} // This code is contributed by// sanjeev2552", "e": 31455, "s": 29509, "text": null }, { "code": "# Python3 implementation of above approach # For maximum length of input stringMAX = 10 # Declaring the DP tableF = [[[-1 for i in range(MAX)] for j in range(MAX)] for k in range(MAX)] # Function to calculate the number# of valid assignmentsdef noOfAssignments(S, n, i, c_x, c_y): if F[i][c_x][c_y] != -1: return F[i][c_x][c_y] if i == n: # Return 1 if both subsequences are balanced F[i][c_x][c_y] = not c_x and not c_y return F[i][c_x][c_y] # Increment the count if # it is an opening bracket if S[i] == '(': F[i][c_x][c_y] = \\ noOfAssignments(S, n, i + 1, c_x + 1, c_y) + \\ noOfAssignments(S, n, i + 1, c_x, c_y + 1) return F[i][c_x][c_y] F[i][c_x][c_y] = 0 # Decrement the count # if it a closing bracket if c_x: F[i][c_x][c_y] += \\ noOfAssignments(S, n, i + 1, c_x - 1, c_y) if c_y: F[i][c_x][c_y] += \\ noOfAssignments(S, n, i + 1, c_x, c_y - 1) return F[i][c_x][c_y] # Driver codeif __name__ == \"__main__\": S = \"(())\" n = len(S) # Initial value for c_x and c_y is zero print(noOfAssignments(S, n, 0, 0, 0)) # This code is contributed by Rituraj Jain", "e": 32693, "s": 31455, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // For maximum length of input string static int MAX = 10; // Declaring the DP table static int[,,] F = new int[MAX, MAX, MAX]; // Function to calculate the // number of valid assignments static int noOfAssignments(String s, int n, int i, int c_x, int c_y) { if (F[i, c_x, c_y] != -1) return F[i, c_x, c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i, c_x, c_y] = (c_x == 0 && c_y == 0) ? 1 : 0; return F[i, c_x, c_y]; } // Increment the count // if it an opening bracket if (s[i] == '(') { F[i, c_x, c_y] = noOfAssignments(s, n, i + 1, c_x + 1, c_y) + noOfAssignments(s, n, i + 1, c_x, c_y + 1); return F[i, c_x, c_y]; } F[i, c_x, c_y] = 0; // Decrement the count // if it a closing bracket if (c_x != 0) F[i, c_x, c_y] += noOfAssignments(s, n, i + 1, c_x - 1, c_y); if (c_y != 0) F[i, c_x, c_y] += noOfAssignments(s, n, i + 1, c_x, c_y - 1); return F[i, c_x, c_y]; } // Driver Code public static void Main(String[] args) { String s = \"(())\"; int n = s.Length; // Initializing the DP table for (int i = 0; i < MAX; i++) for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) F[i, j, k] = -1; // Initial value for c_x // and c_y is zero Console.WriteLine(noOfAssignments(s, n, 0, 0, 0)); }} // This code is contributed by PrinciRaj1992", "e": 34650, "s": 32693, "text": null }, { "code": "<script>// Javascript implementation of the above approach // For maximum length of input string let MAX = 10; // Declaring the DP table let F = new Array(MAX); for(let i = 0; i < MAX; i++) { F[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { F[i][j] = new Array(MAX); for(let k = 0; k < MAX; k++) { F[i][j][k] = -1; } } } // Function to calculate the // number of valid assignments function noOfAssignments(s,n,i,c_x,c_y) { if (F[i][c_x][c_y] != -1) return F[i][c_x][c_y]; if (i == n) { // Return 1 if both // subsequences are balanced F[i][c_x][c_y] = (c_x == 0 && c_y == 0) ? 1 : 0; return F[i][c_x][c_y]; } // Increment the count // if it an opening bracket if (s.charAt(i) == '(') { F[i][c_x][c_y] = noOfAssignments(s, n, i + 1, c_x + 1, c_y) + noOfAssignments(s, n, i + 1, c_x, c_y + 1); return F[i][c_x][c_y]; } F[i][c_x][c_y] = 0; // Decrement the count // if it a closing bracket if (c_x != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x - 1, c_y); if (c_y != 0) F[i][c_x][c_y] += noOfAssignments(s, n, i + 1, c_x, c_y - 1); return F[i][c_x][c_y]; } // Driver Code let s = \"(())\"; let n = s.length; // Initial value for c_x // and c_y is zero document.write(noOfAssignments(s, n, 0, 0, 0)); // This code is contributed by rag2127</script>", "e": 36532, "s": 34650, "text": null }, { "code": null, "e": 36534, "s": 36532, "text": "6" }, { "code": null, "e": 36981, "s": 36536, "text": "Optimized Dynamic Programming approach: We can create a prefix array to store the count variable ci for the substring S[0 : i + 1]. We can observe that the sum of c_x and c_y will always be equal to the count variable for the whole string. By exploiting this property, we can reduce our dynamic programming approach to two states. A prefix array can be created in linear complexity, so the time and space complexity of this approach is O(n2). " }, { "code": null, "e": 36985, "s": 36981, "text": "C++" }, { "code": null, "e": 36990, "s": 36985, "text": "Java" }, { "code": null, "e": 36998, "s": 36990, "text": "Python3" }, { "code": null, "e": 37001, "s": 36998, "text": "C#" }, { "code": null, "e": 37012, "s": 37001, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // For maximum length of input stringconst int MAX = 10; // Declaring the DP tableint F[MAX][MAX]; // Declaring the prefix arrayint C[MAX]; // Function to calculate the// number of valid assignmentsint noOfAssignments(string& S, int& n, int i, int c_x){ if (F[i][c_x] != -1) return F[i][c_x]; if (i == n) { // Return 1 if X is // balanced. F[i][c_x] = !c_x; return F[i][c_x]; } int c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S[i] == '(') { F[i][c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i][c_x]; } F[i][c_x] = 0; // Decrement the count // if it a closing bracket if (c_x) F[i][c_x] += noOfAssignments(S, n, i + 1, c_x - 1); if (c_y) F[i][c_x] += noOfAssignments(S, n, i + 1, c_x); return F[i][c_x];} // Driver codeint main(){ string S = \"()\"; int n = S.length(); // Initializing the DP table memset(F, -1, sizeof(F)); C[0] = 0; // Creating the prefix array for (int i = 0; i < n; ++i) if (S[i] == '(') C[i + 1] = C[i] + 1; else C[i + 1] = C[i] - 1; // Initial value for c_x // and c_y is zero cout << noOfAssignments(S, n, 0, 0); return 0;}", "e": 38594, "s": 37012, "text": null }, { "code": "// Java implementation of the approach public class GFG { // For maximum length of input string static int MAX = 10; // Declaring the DP table static int F[][] = new int[MAX][MAX]; // Declaring the prefix array static int C[] = new int[MAX]; // Function to calculate the// number of valid assignments static int noOfAssignments(String S, int n, int i, int c_x) { if (F[i][c_x] != -1) { return F[i][c_x]; } if (i == n) { // Return 1 if X is // balanced. if (c_x == 1) { F[i][c_x] = 0; } else { F[i][c_x] = 1; } return F[i][c_x]; } int c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S.charAt(i) == '(') { F[i][c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i][c_x]; } F[i][c_x] = 0; // Decrement the count // if it a closing bracket if (c_x == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x - 1); } if (c_y == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x); } return F[i][c_x]; } // Driver code public static void main(String[] args) { String S = \"()\"; int n = S.length(); // Initializing the DP table for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { F[i][j] = -1; } } C[0] = 0; // Creating the prefix array for (int i = 0; i < n; ++i) { if (S.charAt(i) == '(') { C[i + 1] = C[i] + 1; } else { C[i + 1] = C[i] - 1; } } // Initial value for c_x // and c_y is zero System.out.println(noOfAssignments(S, n, 0, 0)); }}// This code is contributed by 29AjayKumar", "e": 40716, "s": 38594, "text": null }, { "code": "# Python3 implementation of above approach # For maximum length of input stringMAX = 10 # Declaring the DP tableF = [[-1 for i in range(MAX)] for j in range(MAX)] # Declaring the prefix arrayC = [None] * MAX # Function to calculate the# number of valid assignmentsdef noOfAssignments(S, n, i, c_x): if F[i][c_x] != -1: return F[i][c_x] if i == n: # Return 1 if X is balanced. F[i][c_x] = not c_x return F[i][c_x] c_y = C[i] - c_x # Increment the count # if it is an opening bracket if S[i] == '(': F[i][c_x] = \\ noOfAssignments(S, n, i + 1, c_x + 1) + \\ noOfAssignments(S, n, i + 1, c_x) return F[i][c_x] F[i][c_x] = 0 # Decrement the count if it is a closing bracket if c_x: F[i][c_x] += \\ noOfAssignments(S, n, i + 1, c_x - 1) if c_y: F[i][c_x] += \\ noOfAssignments(S, n, i + 1, c_x) return F[i][c_x] # Driver codeif __name__ == \"__main__\": S = \"()\" n = len(S) C[0] = 0 # Creating the prefix array for i in range(0, n): if S[i] == '(': C[i + 1] = C[i] + 1 else: C[i + 1] = C[i] - 1 # Initial value for c_x and c_y is zero print(noOfAssignments(S, n, 0, 0)) # This code is contributed by Rituraj Jain", "e": 42038, "s": 40716, "text": null }, { "code": "// C# implementation of the approach using System;public class GFG { // For maximum length of input string static int MAX = 10; // Declaring the DP table static int[,] F = new int[MAX,MAX]; // Declaring the prefix array static int[] C = new int[MAX]; // Function to calculate the// number of valid assignments static int noOfAssignments(string S, int n, int i, int c_x) { if (F[i,c_x] != -1) { return F[i,c_x]; } if (i == n) { // Return 1 if X is // balanced. if (c_x == 1) { F[i,c_x] = 0; } else { F[i,c_x] = 1; } return F[i,c_x]; } int c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S[i] == '(') { F[i,c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i,c_x]; } F[i,c_x] = 0; // Decrement the count // if it a closing bracket if (c_x == 1) { F[i,c_x] += noOfAssignments(S, n, i + 1, c_x - 1); } if (c_y == 1) { F[i,c_x] += noOfAssignments(S, n, i + 1, c_x); } return F[i,c_x]; } // Driver code public static void Main() { string S = \"()\"; int n = S.Length; // Initializing the DP table for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { F[i,j] = -1; } } C[0] = 0; // Creating the prefix array for (int i = 0; i < n; ++i) { if (S[i] == '(') { C[i + 1] = C[i] + 1; } else { C[i + 1] = C[i] - 1; } } // Initial value for c_x // and c_y is zero Console.WriteLine(noOfAssignments(S, n, 0, 0)); }}// This code is contributed by Ita_c.", "e": 44142, "s": 42038, "text": null }, { "code": "<script>// Javascript implementation of the approach // For maximum length of input stringvar MAX = 10; // Declaring the DP tablevar F = Array.from(Array(MAX), ()=>Array(MAX).fill(0)); // Declaring the prefix arrayvar C = Array(MAX).fill(0); // Function to calculate the// number of valid assignmentsfunction noOfAssignments(S, n, i, c_x) { if (F[i][c_x] != -1) { return F[i][c_x]; } if (i == n) { // Return 1 if X is // balanced. if (c_x == 1) { F[i][c_x] = 0; } else { F[i][c_x] = 1; } return F[i][c_x]; } var c_y = C[i] - c_x; // Increment the count // if it an opening bracket if (S[i] == '(') { F[i][c_x] = noOfAssignments(S, n, i + 1, c_x + 1) + noOfAssignments(S, n, i + 1, c_x); return F[i][c_x]; } F[i][c_x] = 0; // Decrement the count // if it a closing bracket if (c_x == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x - 1); } if (c_y == 1) { F[i][c_x] += noOfAssignments(S, n, i + 1, c_x); } return F[i][c_x]; } // Driver codevar S = \"()\";var n = S.length; // Initializing the DP tablefor(var i = 0; i < MAX; i++) { for(var j = 0; j < MAX; j++) { F[i][j] = -1; }} C[0] = 0; // Creating the prefix arrayfor (var i = 0; i < n; ++i) { if (S[i] == '(') { C[i + 1] = C[i] + 1; } else { C[i + 1] = C[i] - 1; }} // Initial value for c_x// and c_y is zerodocument.write(noOfAssignments(S, n, 0, 0) + \"<br>\"); // This code is contributed by rrrtnx.</script>", "e": 46023, "s": 44142, "text": null }, { "code": null, "e": 46025, "s": 46023, "text": "2" }, { "code": null, "e": 46039, "s": 46027, "text": "29AjayKumar" }, { "code": null, "e": 46045, "s": 46039, "text": "ukasp" }, { "code": null, "e": 46058, "s": 46045, "text": "rituraj_jain" }, { "code": null, "e": 46070, "s": 46058, "text": "sanjeev2552" }, { "code": null, "e": 46084, "s": 46070, "text": "princiraj1992" }, { "code": null, "e": 46092, "s": 46084, "text": "rag2127" }, { "code": null, "e": 46099, "s": 46092, "text": "rrrtnx" }, { "code": null, "e": 46115, "s": 46099, "text": "saurabh1990aror" }, { "code": null, "e": 46123, "s": 46115, "text": "Directi" }, { "code": null, "e": 46133, "s": 46123, "text": "media.net" }, { "code": null, "e": 46154, "s": 46133, "text": "Parentheses-Problems" }, { "code": null, "e": 46166, "s": 46154, "text": "subsequence" }, { "code": null, "e": 46190, "s": 46166, "text": "Technical Scripter 2018" }, { "code": null, "e": 46210, "s": 46190, "text": "Dynamic Programming" }, { "code": null, "e": 46218, "s": 46210, "text": "Strings" }, { "code": null, "e": 46237, "s": 46218, "text": "Technical Scripter" }, { "code": null, "e": 46245, "s": 46237, "text": "Directi" }, { "code": null, "e": 46253, "s": 46245, "text": "Strings" }, { "code": null, "e": 46273, "s": 46253, "text": "Dynamic Programming" }, { "code": null, "e": 46371, "s": 46273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46402, "s": 46371, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 46435, "s": 46402, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 46462, "s": 46435, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 46481, "s": 46462, "text": "Coin Change | DP-7" }, { "code": null, "e": 46516, "s": 46481, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 46562, "s": 46516, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 46587, "s": 46562, "text": "Reverse a string in Java" }, { "code": null, "e": 46647, "s": 46587, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 46662, "s": 46647, "text": "C++ Data Types" } ]
length vs length() in Java - GeeksforGeeks
04 Aug, 2021 array.length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array. string.length() : length() method is a final variable which is applicable for string objects. The length() method returns the number of characters present in the string. length vs length() 1. The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays. 2. Examples: // length can be used for int[], double[], String[] // to know the length of the arrays. // length() can be used for String, StringBuilder, etc // String class related Objects to know the length of the String 3. To directly access a field member of an array we can use .length; whereas .length() invokes a method to access a field member. Example: JAVA // Java program to illustrate the// concept of length// and length()public class Test { public static void main(String[] args) { // Here array is the array name of int type int[] array = new int[4]; System.out.println("The size of the array is " + array.length); // Here str is a string object String str = "GeeksforGeeks"; System.out.println("The size of the String is " + str.length()); }} The size of the array is 4 The size of the String is 13 Practice Questions based on the concept of length vs length() Let’s have a look at the output of the following programs: What will be the output of the following program? JAVA public class Test { public static void main(String[] args) { // Here str is the array name of String type. String[] str = { "GEEKS", "FOR", "GEEKS" }; System.out.println(str.length); }} 3 Explanation: Here the str is an array of type string and that’s why str.length is used to find its length. What will be the output of the following program? JAVA public class Test { public static void main(String[] args) { // Here str[0] pointing to a string i.e. GEEKS String[] str = { "GEEKS", "FOR", "GEEKS" }; System.out.println(str.length()); }} Output: error: cannot find symbol symbol: method length() location: variable str of type String[] Explanation: Here the str is an array of type string and that’s why str.length() CANNOT be used to find its length. What will be the output of the following program? JAVA public class Test { public static void main(String[] args) { // Here str[0] pointing to String i.e. GEEKS String[] str = { "GEEKS", "FOR", "GEEKS" }; System.out.println(str[0].length()); }} 5 Explanation: Here str[0] pointing to String i.e. GEEKS and thus can be accessed using .length() This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. usaraswat82 agiledanish musamaali45 Java-Arrays Java-String-Programs Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26291, "s": 26263, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26431, "s": 26291, "text": "array.length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array. " }, { "code": null, "e": 26602, "s": 26431, "text": "string.length() : length() method is a final variable which is applicable for string objects. The length() method returns the number of characters present in the string. " }, { "code": null, "e": 26621, "s": 26602, "text": "length vs length()" }, { "code": null, "e": 26778, "s": 26621, "text": "1. The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays." }, { "code": null, "e": 26791, "s": 26778, "text": "2. Examples:" }, { "code": null, "e": 27003, "s": 26791, "text": "// length can be used for int[], double[], String[] \n// to know the length of the arrays.\n\n// length() can be used for String, StringBuilder, etc \n// String class related Objects to know the length of the String" }, { "code": null, "e": 27133, "s": 27003, "text": "3. To directly access a field member of an array we can use .length; whereas .length() invokes a method to access a field member." }, { "code": null, "e": 27144, "s": 27133, "text": "Example: " }, { "code": null, "e": 27149, "s": 27144, "text": "JAVA" }, { "code": "// Java program to illustrate the// concept of length// and length()public class Test { public static void main(String[] args) { // Here array is the array name of int type int[] array = new int[4]; System.out.println(\"The size of the array is \" + array.length); // Here str is a string object String str = \"GeeksforGeeks\"; System.out.println(\"The size of the String is \" + str.length()); }}", "e": 27645, "s": 27149, "text": null }, { "code": null, "e": 27701, "s": 27645, "text": "The size of the array is 4\nThe size of the String is 13" }, { "code": null, "e": 27763, "s": 27701, "text": "Practice Questions based on the concept of length vs length()" }, { "code": null, "e": 27822, "s": 27763, "text": "Let’s have a look at the output of the following programs:" }, { "code": null, "e": 27872, "s": 27822, "text": "What will be the output of the following program?" }, { "code": null, "e": 27877, "s": 27872, "text": "JAVA" }, { "code": "public class Test { public static void main(String[] args) { // Here str is the array name of String type. String[] str = { \"GEEKS\", \"FOR\", \"GEEKS\" }; System.out.println(str.length); }}", "e": 28093, "s": 27877, "text": null }, { "code": null, "e": 28095, "s": 28093, "text": "3" }, { "code": null, "e": 28204, "s": 28095, "text": "Explanation: Here the str is an array of type string and that’s why str.length is used to find its length. " }, { "code": null, "e": 28256, "s": 28204, "text": "What will be the output of the following program? " }, { "code": null, "e": 28261, "s": 28256, "text": "JAVA" }, { "code": "public class Test { public static void main(String[] args) { // Here str[0] pointing to a string i.e. GEEKS String[] str = { \"GEEKS\", \"FOR\", \"GEEKS\" }; System.out.println(str.length()); }}", "e": 28480, "s": 28261, "text": null }, { "code": null, "e": 28489, "s": 28480, "text": "Output: " }, { "code": null, "e": 28579, "s": 28489, "text": "error: cannot find symbol\nsymbol: method length()\nlocation: variable str of type String[]" }, { "code": null, "e": 28697, "s": 28579, "text": "Explanation: Here the str is an array of type string and that’s why str.length() CANNOT be used to find its length. " }, { "code": null, "e": 28747, "s": 28697, "text": "What will be the output of the following program?" }, { "code": null, "e": 28752, "s": 28747, "text": "JAVA" }, { "code": "public class Test { public static void main(String[] args) { // Here str[0] pointing to String i.e. GEEKS String[] str = { \"GEEKS\", \"FOR\", \"GEEKS\" }; System.out.println(str[0].length()); }}", "e": 28972, "s": 28752, "text": null }, { "code": null, "e": 28974, "s": 28972, "text": "5" }, { "code": null, "e": 29372, "s": 28974, "text": "Explanation: Here str[0] pointing to String i.e. GEEKS and thus can be accessed using .length() This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29498, "s": 29372, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29510, "s": 29498, "text": "usaraswat82" }, { "code": null, "e": 29522, "s": 29510, "text": "agiledanish" }, { "code": null, "e": 29534, "s": 29522, "text": "musamaali45" }, { "code": null, "e": 29546, "s": 29534, "text": "Java-Arrays" }, { "code": null, "e": 29567, "s": 29546, "text": "Java-String-Programs" }, { "code": null, "e": 29580, "s": 29567, "text": "Java-Strings" }, { "code": null, "e": 29585, "s": 29580, "text": "Java" }, { "code": null, "e": 29598, "s": 29585, "text": "Java-Strings" }, { "code": null, "e": 29603, "s": 29598, "text": "Java" }, { "code": null, "e": 29701, "s": 29603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29752, "s": 29701, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29782, "s": 29752, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29797, "s": 29782, "text": "Stream In Java" }, { "code": null, "e": 29816, "s": 29797, "text": "Interfaces in Java" }, { "code": null, "e": 29847, "s": 29816, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29865, "s": 29847, "text": "ArrayList in Java" }, { "code": null, "e": 29897, "s": 29865, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29917, "s": 29897, "text": "Stack Class in Java" }, { "code": null, "e": 29949, "s": 29917, "text": "Multidimensional Arrays in Java" } ]
Java Program to Print Summation of Numbers - GeeksforGeeks
21 Oct, 2020 Given an array of integers, print the sum of all the elements in an array. Input: arr[] = {1,2,3,4,5} Output: 15 Input: arr[] = {2, 9, -10, -1, 5, -12} Output: -7 Create a variable named sum and initialize it to 0.Traverse the array through a loop and add the value of each element into sum.Print sum as the answer. Create a variable named sum and initialize it to 0. Traverse the array through a loop and add the value of each element into sum. Print sum as the answer. Below is the implementation of the above approach. Java // Java Program to print the sum // of all the elements in an arrayclass GFG { static int sumOfArray(int arr[]) { // initialise sum to 0 int sum = 0; // iterate through the array using loop for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } // return sum as the answer return sum; } // Driver code public static void main(String[] args) { // print the sum int arr[] = { 1, 2, 3, 4, -2, 5 }; System.out.println( "The sum of elements of given array is: " + sumOfArray(arr)); }} The sum of elements of given array is: 13 Time Complexity: O(N), where N is the size of array Inbuilt function IntStream.of(arrayName).sum() is used to sum all the elements in an integer array. Syntax: IntStream.of(arrayName).sum(); Below is the implementation of the above approach. Java // Java Program to print the sum // of all the elements in an array // import IntStreamimport java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // print the sum int arr[] = { 1, 2, 3, 4, -2, 5 }; System.out.println( "The sum of elements of given array is: " + IntStream.of(arr).sum()); }} The sum of elements of given array is: 13 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n21 Oct, 2020" }, { "code": null, "e": 25300, "s": 25225, "text": "Given an array of integers, print the sum of all the elements in an array." }, { "code": null, "e": 25327, "s": 25300, "text": "Input: arr[] = {1,2,3,4,5}" }, { "code": null, "e": 25338, "s": 25327, "text": "Output: 15" }, { "code": null, "e": 25377, "s": 25338, "text": "Input: arr[] = {2, 9, -10, -1, 5, -12}" }, { "code": null, "e": 25388, "s": 25377, "text": "Output: -7" }, { "code": null, "e": 25541, "s": 25388, "text": "Create a variable named sum and initialize it to 0.Traverse the array through a loop and add the value of each element into sum.Print sum as the answer." }, { "code": null, "e": 25593, "s": 25541, "text": "Create a variable named sum and initialize it to 0." }, { "code": null, "e": 25671, "s": 25593, "text": "Traverse the array through a loop and add the value of each element into sum." }, { "code": null, "e": 25696, "s": 25671, "text": "Print sum as the answer." }, { "code": null, "e": 25747, "s": 25696, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 25752, "s": 25747, "text": "Java" }, { "code": "// Java Program to print the sum // of all the elements in an arrayclass GFG { static int sumOfArray(int arr[]) { // initialise sum to 0 int sum = 0; // iterate through the array using loop for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } // return sum as the answer return sum; } // Driver code public static void main(String[] args) { // print the sum int arr[] = { 1, 2, 3, 4, -2, 5 }; System.out.println( \"The sum of elements of given array is: \" + sumOfArray(arr)); }}", "e": 26376, "s": 25752, "text": null }, { "code": null, "e": 26418, "s": 26376, "text": "The sum of elements of given array is: 13" }, { "code": null, "e": 26470, "s": 26418, "text": "Time Complexity: O(N), where N is the size of array" }, { "code": null, "e": 26570, "s": 26470, "text": "Inbuilt function IntStream.of(arrayName).sum() is used to sum all the elements in an integer array." }, { "code": null, "e": 26578, "s": 26570, "text": "Syntax:" }, { "code": null, "e": 26609, "s": 26578, "text": "IntStream.of(arrayName).sum();" }, { "code": null, "e": 26660, "s": 26609, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26665, "s": 26660, "text": "Java" }, { "code": "// Java Program to print the sum // of all the elements in an array // import IntStreamimport java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // print the sum int arr[] = { 1, 2, 3, 4, -2, 5 }; System.out.println( \"The sum of elements of given array is: \" + IntStream.of(arr).sum()); }}", "e": 27059, "s": 26665, "text": null }, { "code": null, "e": 27101, "s": 27059, "text": "The sum of elements of given array is: 13" }, { "code": null, "e": 27106, "s": 27101, "text": "Java" }, { "code": null, "e": 27120, "s": 27106, "text": "Java Programs" }, { "code": null, "e": 27125, "s": 27120, "text": "Java" }, { "code": null, "e": 27223, "s": 27125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27238, "s": 27223, "text": "Stream In Java" }, { "code": null, "e": 27259, "s": 27238, "text": "Constructors in Java" }, { "code": null, "e": 27278, "s": 27259, "text": "Exceptions in Java" }, { "code": null, "e": 27308, "s": 27278, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27354, "s": 27308, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27380, "s": 27354, "text": "Java Programming Examples" }, { "code": null, "e": 27414, "s": 27380, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27461, "s": 27414, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 27493, "s": 27461, "text": "How to Iterate HashMap in Java?" } ]
How to Select a Range of Elements using jQuery ? - GeeksforGeeks
02 Mar, 2020 Given an HTML document with a range of similar elements and the task is to select a range of those elements with the help of JavaScript. There are two approaches that are discussed below with an example. Approach 1: First, select all elements of class = ‘child’ by jQuery selector then use slice() method to select a range of elements continuously. The background color of the elements has been changed to see the effect. Example:<!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class="outer"> <div class="child"> Child 1</div> <div class="child"> Child 2</div> <div class="child"> Child 3</div> <div class="child"> Child 4</div> </div> <br> <button onClick="gfg()"> click here </button> <p id="geeks"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(".outer .child"); for (var i = 0; i < arr.length; i++) { $el.slice(arr[i], arr[i] + 1) .css("color", "red"); } down.innerHTML = "Range of elements selected"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class="outer"> <div class="child"> Child 1</div> <div class="child"> Child 2</div> <div class="child"> Child 3</div> <div class="child"> Child 4</div> </div> <br> <button onClick="gfg()"> click here </button> <p id="geeks"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(".outer .child"); for (var i = 0; i < arr.length; i++) { $el.slice(arr[i], arr[i] + 1) .css("color", "red"); } down.innerHTML = "Range of elements selected"; } </script></body> </html> Output: Approach 2: First select all elements of class = ‘child’ by jQuery selector. There is an array which contains the indexes of the elements to be selected. We are traversing the array and using slice() method to select the particular element of that index. The background color of the elements has been changed to see the effect. Example:<!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class="outer"> <div class="child"> Child 1</div> <div class="child"> Child 2</div> <div class="child"> Child 3</div> <div class="child"> Child 4</div> </div> <br> <button onClick="gfg()"> click here </button> <p id="geeks"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(".outer .child"); for(var i=0; i<arr.length; i++) { $el.slice(arr[i], arr[i]+1) .css("color", "red"); } down.innerHTML = "Range of elements selected"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class="outer"> <div class="child"> Child 1</div> <div class="child"> Child 2</div> <div class="child"> Child 3</div> <div class="child"> Child 4</div> </div> <br> <button onClick="gfg()"> click here </button> <p id="geeks"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(".outer .child"); for(var i=0; i<arr.length; i++) { $el.slice(arr[i], arr[i]+1) .css("color", "red"); } down.innerHTML = "Range of elements selected"; } </script></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 26206, "s": 26178, "text": "\n02 Mar, 2020" }, { "code": null, "e": 26410, "s": 26206, "text": "Given an HTML document with a range of similar elements and the task is to select a range of those elements with the help of JavaScript. There are two approaches that are discussed below with an example." }, { "code": null, "e": 26628, "s": 26410, "text": "Approach 1: First, select all elements of class = ‘child’ by jQuery selector then use slice() method to select a range of elements continuously. The background color of the elements has been changed to see the effect." }, { "code": null, "e": 28028, "s": 26628, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class=\"outer\"> <div class=\"child\"> Child 1</div> <div class=\"child\"> Child 2</div> <div class=\"child\"> Child 3</div> <div class=\"child\"> Child 4</div> </div> <br> <button onClick=\"gfg()\"> click here </button> <p id=\"geeks\"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(\".outer .child\"); for (var i = 0; i < arr.length; i++) { $el.slice(arr[i], arr[i] + 1) .css(\"color\", \"red\"); } down.innerHTML = \"Range of elements selected\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class=\"outer\"> <div class=\"child\"> Child 1</div> <div class=\"child\"> Child 2</div> <div class=\"child\"> Child 3</div> <div class=\"child\"> Child 4</div> </div> <br> <button onClick=\"gfg()\"> click here </button> <p id=\"geeks\"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(\".outer .child\"); for (var i = 0; i < arr.length; i++) { $el.slice(arr[i], arr[i] + 1) .css(\"color\", \"red\"); } down.innerHTML = \"Range of elements selected\"; } </script></body> </html>", "e": 29420, "s": 28028, "text": null }, { "code": null, "e": 29428, "s": 29420, "text": "Output:" }, { "code": null, "e": 29756, "s": 29428, "text": "Approach 2: First select all elements of class = ‘child’ by jQuery selector. There is an array which contains the indexes of the elements to be selected. We are traversing the array and using slice() method to select the particular element of that index. The background color of the elements has been changed to see the effect." }, { "code": null, "e": 31157, "s": 29756, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class=\"outer\"> <div class=\"child\"> Child 1</div> <div class=\"child\"> Child 2</div> <div class=\"child\"> Child 3</div> <div class=\"child\"> Child 4</div> </div> <br> <button onClick=\"gfg()\"> click here </button> <p id=\"geeks\"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(\".outer .child\"); for(var i=0; i<arr.length; i++) { $el.slice(arr[i], arr[i]+1) .css(\"color\", \"red\"); } down.innerHTML = \"Range of elements selected\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to select a range of elements in JQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Click on button to select a range of elements </b> <div class=\"outer\"> <div class=\"child\"> Child 1</div> <div class=\"child\"> Child 2</div> <div class=\"child\"> Child 3</div> <div class=\"child\"> Child 4</div> </div> <br> <button onClick=\"gfg()\"> click here </button> <p id=\"geeks\"> </p> </center> <script> var down = document.getElementById('geeks'); // Defining childs var arr = [0, 2, 3]; function gfg() { var $el = $(\".outer .child\"); for(var i=0; i<arr.length; i++) { $el.slice(arr[i], arr[i]+1) .css(\"color\", \"red\"); } down.innerHTML = \"Range of elements selected\"; } </script></body> </html>", "e": 32550, "s": 31157, "text": null }, { "code": null, "e": 32558, "s": 32550, "text": "Output:" }, { "code": null, "e": 32695, "s": 32558, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 32704, "s": 32695, "text": "CSS-Misc" }, { "code": null, "e": 32714, "s": 32704, "text": "HTML-Misc" }, { "code": null, "e": 32726, "s": 32714, "text": "jQuery-Misc" }, { "code": null, "e": 32730, "s": 32726, "text": "CSS" }, { "code": null, "e": 32735, "s": 32730, "text": "HTML" }, { "code": null, "e": 32742, "s": 32735, "text": "JQuery" }, { "code": null, "e": 32759, "s": 32742, "text": "Web Technologies" }, { "code": null, "e": 32786, "s": 32759, "text": "Web technologies Questions" }, { "code": null, "e": 32791, "s": 32786, "text": "HTML" }, { "code": null, "e": 32889, "s": 32791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32944, "s": 32889, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32981, "s": 32944, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 33045, "s": 32981, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 33082, "s": 33045, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33143, "s": 33082, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 33203, "s": 33143, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33256, "s": 33203, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33306, "s": 33256, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 33330, "s": 33306, "text": "REST API (Introduction)" } ]
Longest subsequence with consecutive English alphabets - GeeksforGeeks
13 Aug, 2021 Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets. Examples: Input: S = “acbdcfhg”Output: 3Explanation: String “abc” is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence “abc”. Input: S = “gabbsdcdggbe”Output: 5 Naive Approach: The simplest approach is to generate all possible subsequences of the given string and if there exists any subsequence of the given string that has consecutive characters and is of maximum length then print that length. Time Complexity: O(2N)Auxiliary Space: O(1) Efficient Approach: The above approach can also be optimized by generating all possible consecutive subsequences of the given string starting from each lowercase alphabets and print the maximum among all the subsequence found. Follow the steps below to solve the problem: Initialize a variable, say ans, as 0 that stores the maximum length of the consecutive subsequence. For each character ch over the range [a, z] perform the following:Initialize a variable cnt as 0 that stores the length of a subsequence of consecutive characters starting from ch.Traverse the given string S and if the current character is ch then increment the cnt by 1 and update the current character ch to the next character by (ch + 1).Update ans = max(ans, cnt) Initialize a variable cnt as 0 that stores the length of a subsequence of consecutive characters starting from ch. Traverse the given string S and if the current character is ch then increment the cnt by 1 and update the current character ch to the next character by (ch + 1). Update ans = max(ans, cnt) After the above steps, print the value of ans as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of subsequence// starting with character chint findSubsequence(string S, char ch){ // Length of the string int N = S.length(); // Stores the maximum length int ans = 0; // Traverse the given string for (int i = 0; i < N; i++) { // If s[i] is required // character ch if (S[i] == ch) { // Increment ans by 1 ans++; // Increment character ch ch++; } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersint findMaxSubsequence(string S){ // Stores the maximum length of // consecutive characters int ans = 0; for (char ch = 'a'; ch <= 'z'; ch++) { // Update ans ans = max(ans, findSubsequence(S, ch)); } // Return the maximum length of // subsequence return ans;} // Driver Codeint main(){ // Input string S = "abcabefghijk"; // Function Call cout << findMaxSubsequence(S); return 0;} // C# program for the above approachimport java.io.*;import java.util.*;import java.util.Arrays; class GFG{ // Function to find the length of subsequence// starting with character chstatic int findSubsequence(String S, char ch){ // Length of the string int N = S.length(); // Stores the maximum length int ans = 0; // Traverse the given string for(int i = 0; i < N; i++) { // If s[i] is required // character ch if(S.charAt(i) == ch) { // Increment ans by 1 ans++; // Increment character ch ch++; } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersstatic int findMaxSubsequence(String S){ // Stores the maximum length of // consecutive characters int ans = 0; for(char ch = 'a'; ch <= 'z'; ch++) { // Update ans ans = Math.max(ans, findSubsequence(S, ch)); } // Return the maximum length of // subsequence return ans;} // Driver Codepublic static void main(String[] args){ // Input String S = "abcabefghijk"; // Function Call System.out.print(findMaxSubsequence(S));}} // This code is contributed by shivanisinghss2110 # Python3 program for the above approach # Function to find the length of subsequence# starting with character chdef findSubsequence(S, ch): # Length of the string N = len(S) # Stores the maximum length ans = 0 # Traverse the given string for i in range(N): # If s[i] is required # character ch if (S[i] == ch): # Increment ans by 1 ans += 1 # Increment character ch ch=chr(ord(ch) + 1) # Return the current maximum # length with character ch return ans # Function to find the maximum length# of subsequence of consecutive# charactersdef findMaxSubsequence(S): #Stores the maximum length of # consecutive characters ans = 0 for ch in range(ord('a'),ord('z') + 1): # Update ans ans = max(ans, findSubsequence(S, chr(ch))) # Return the maximum length of # subsequence return ans # Driver Codeif __name__ == '__main__': # Input S = "abcabefghijk" # Function Call print (findMaxSubsequence(S)) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the length of subsequence// starting with character chstatic int findSubsequence(string S, char ch){ // Length of the string int N = S.Length; // Stores the maximum length int ans = 0; // Traverse the given string for(int i = 0; i < N; i++) { // If s[i] is required // character ch if (S[i] == ch) { // Increment ans by 1 ans++; // Increment character ch ch++; } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersstatic int findMaxSubsequence(string S){ // Stores the maximum length of // consecutive characters int ans = 0; for(char ch = 'a'; ch <= 'z'; ch++) { // Update ans ans = Math.Max(ans, findSubsequence(S, ch)); } // Return the maximum length of // subsequence return ans;} // Driver Codepublic static void Main(){ // Input string S = "abcabefghijk"; // Function Call Console.Write(findMaxSubsequence(S));}} // This code is contributed by SURENDRA_GANGWAR <script>// Javascript program for the above approach // Function to find the length of subsequence// starting with character chfunction findSubsequence(S,ch){ // Length of the string let N = S.length; // Stores the maximum length let ans = 0; // Traverse the given string for(let i = 0; i < N; i++) { // If s[i] is required // character ch if (S[i] == ch) { // Increment ans by 1 ans++; // Increment character ch ch=String.fromCharCode(ch.charCodeAt(0)+1); } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersfunction findMaxSubsequence(S){ // Stores the maximum length of // consecutive characters let ans = 0; for(let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) { // Update ans ans = Math.max(ans, findSubsequence(S, String.fromCharCode(ch))); } // Return the maximum length of // subsequence return ans;} // Driver Codelet S = "abcabefghijk"; // Function Calldocument.write(findMaxSubsequence(S)); // This code is contributed by patel2127</script> 7 Time Complexity: O(26*N)Auxiliary Space: O(1) mohit kumar 29 SURENDRA_GANGWAR unknown2108 shivanisinghss2110 gulshankumarar231 sagartomar9927 subsequence Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher String class in Java | Set 1 Print all subsequences of a string sprintf() in C Convert character array to string in C++ How to Append a Character to a String in C Program to count occurrence of a given character in a string Naive algorithm for Pattern Searching
[ { "code": null, "e": 26073, "s": 26045, "text": "\n13 Aug, 2021" }, { "code": null, "e": 26187, "s": 26073, "text": "Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets." }, { "code": null, "e": 26197, "s": 26187, "text": "Examples:" }, { "code": null, "e": 26380, "s": 26197, "text": "Input: S = “acbdcfhg”Output: 3Explanation: String “abc” is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence “abc”." }, { "code": null, "e": 26415, "s": 26380, "text": "Input: S = “gabbsdcdggbe”Output: 5" }, { "code": null, "e": 26651, "s": 26415, "text": "Naive Approach: The simplest approach is to generate all possible subsequences of the given string and if there exists any subsequence of the given string that has consecutive characters and is of maximum length then print that length." }, { "code": null, "e": 26695, "s": 26651, "text": "Time Complexity: O(2N)Auxiliary Space: O(1)" }, { "code": null, "e": 26967, "s": 26695, "text": "Efficient Approach: The above approach can also be optimized by generating all possible consecutive subsequences of the given string starting from each lowercase alphabets and print the maximum among all the subsequence found. Follow the steps below to solve the problem:" }, { "code": null, "e": 27067, "s": 26967, "text": "Initialize a variable, say ans, as 0 that stores the maximum length of the consecutive subsequence." }, { "code": null, "e": 27435, "s": 27067, "text": "For each character ch over the range [a, z] perform the following:Initialize a variable cnt as 0 that stores the length of a subsequence of consecutive characters starting from ch.Traverse the given string S and if the current character is ch then increment the cnt by 1 and update the current character ch to the next character by (ch + 1).Update ans = max(ans, cnt)" }, { "code": null, "e": 27550, "s": 27435, "text": "Initialize a variable cnt as 0 that stores the length of a subsequence of consecutive characters starting from ch." }, { "code": null, "e": 27712, "s": 27550, "text": "Traverse the given string S and if the current character is ch then increment the cnt by 1 and update the current character ch to the next character by (ch + 1)." }, { "code": null, "e": 27739, "s": 27712, "text": "Update ans = max(ans, cnt)" }, { "code": null, "e": 27800, "s": 27739, "text": "After the above steps, print the value of ans as the result." }, { "code": null, "e": 27851, "s": 27800, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27855, "s": 27851, "text": "C++" }, { "code": null, "e": 27860, "s": 27855, "text": "Java" }, { "code": null, "e": 27868, "s": 27860, "text": "Python3" }, { "code": null, "e": 27871, "s": 27868, "text": "C#" }, { "code": null, "e": 27882, "s": 27871, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of subsequence// starting with character chint findSubsequence(string S, char ch){ // Length of the string int N = S.length(); // Stores the maximum length int ans = 0; // Traverse the given string for (int i = 0; i < N; i++) { // If s[i] is required // character ch if (S[i] == ch) { // Increment ans by 1 ans++; // Increment character ch ch++; } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersint findMaxSubsequence(string S){ // Stores the maximum length of // consecutive characters int ans = 0; for (char ch = 'a'; ch <= 'z'; ch++) { // Update ans ans = max(ans, findSubsequence(S, ch)); } // Return the maximum length of // subsequence return ans;} // Driver Codeint main(){ // Input string S = \"abcabefghijk\"; // Function Call cout << findMaxSubsequence(S); return 0;}", "e": 29048, "s": 27882, "text": null }, { "code": "// C# program for the above approachimport java.io.*;import java.util.*;import java.util.Arrays; class GFG{ // Function to find the length of subsequence// starting with character chstatic int findSubsequence(String S, char ch){ // Length of the string int N = S.length(); // Stores the maximum length int ans = 0; // Traverse the given string for(int i = 0; i < N; i++) { // If s[i] is required // character ch if(S.charAt(i) == ch) { // Increment ans by 1 ans++; // Increment character ch ch++; } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersstatic int findMaxSubsequence(String S){ // Stores the maximum length of // consecutive characters int ans = 0; for(char ch = 'a'; ch <= 'z'; ch++) { // Update ans ans = Math.max(ans, findSubsequence(S, ch)); } // Return the maximum length of // subsequence return ans;} // Driver Codepublic static void main(String[] args){ // Input String S = \"abcabefghijk\"; // Function Call System.out.print(findMaxSubsequence(S));}} // This code is contributed by shivanisinghss2110", "e": 30395, "s": 29048, "text": null }, { "code": "# Python3 program for the above approach # Function to find the length of subsequence# starting with character chdef findSubsequence(S, ch): # Length of the string N = len(S) # Stores the maximum length ans = 0 # Traverse the given string for i in range(N): # If s[i] is required # character ch if (S[i] == ch): # Increment ans by 1 ans += 1 # Increment character ch ch=chr(ord(ch) + 1) # Return the current maximum # length with character ch return ans # Function to find the maximum length# of subsequence of consecutive# charactersdef findMaxSubsequence(S): #Stores the maximum length of # consecutive characters ans = 0 for ch in range(ord('a'),ord('z') + 1): # Update ans ans = max(ans, findSubsequence(S, chr(ch))) # Return the maximum length of # subsequence return ans # Driver Codeif __name__ == '__main__': # Input S = \"abcabefghijk\" # Function Call print (findMaxSubsequence(S)) # This code is contributed by mohit kumar 29.", "e": 31487, "s": 30395, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the length of subsequence// starting with character chstatic int findSubsequence(string S, char ch){ // Length of the string int N = S.Length; // Stores the maximum length int ans = 0; // Traverse the given string for(int i = 0; i < N; i++) { // If s[i] is required // character ch if (S[i] == ch) { // Increment ans by 1 ans++; // Increment character ch ch++; } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersstatic int findMaxSubsequence(string S){ // Stores the maximum length of // consecutive characters int ans = 0; for(char ch = 'a'; ch <= 'z'; ch++) { // Update ans ans = Math.Max(ans, findSubsequence(S, ch)); } // Return the maximum length of // subsequence return ans;} // Driver Codepublic static void Main(){ // Input string S = \"abcabefghijk\"; // Function Call Console.Write(findMaxSubsequence(S));}} // This code is contributed by SURENDRA_GANGWAR", "e": 32793, "s": 31487, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the length of subsequence// starting with character chfunction findSubsequence(S,ch){ // Length of the string let N = S.length; // Stores the maximum length let ans = 0; // Traverse the given string for(let i = 0; i < N; i++) { // If s[i] is required // character ch if (S[i] == ch) { // Increment ans by 1 ans++; // Increment character ch ch=String.fromCharCode(ch.charCodeAt(0)+1); } } // Return the current maximum // length with character ch return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersfunction findMaxSubsequence(S){ // Stores the maximum length of // consecutive characters let ans = 0; for(let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) { // Update ans ans = Math.max(ans, findSubsequence(S, String.fromCharCode(ch))); } // Return the maximum length of // subsequence return ans;} // Driver Codelet S = \"abcabefghijk\"; // Function Calldocument.write(findMaxSubsequence(S)); // This code is contributed by patel2127</script>", "e": 34068, "s": 32793, "text": null }, { "code": null, "e": 34070, "s": 34068, "text": "7" }, { "code": null, "e": 34116, "s": 34070, "text": "Time Complexity: O(26*N)Auxiliary Space: O(1)" }, { "code": null, "e": 34133, "s": 34118, "text": "mohit kumar 29" }, { "code": null, "e": 34150, "s": 34133, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34162, "s": 34150, "text": "unknown2108" }, { "code": null, "e": 34181, "s": 34162, "text": "shivanisinghss2110" }, { "code": null, "e": 34199, "s": 34181, "text": "gulshankumarar231" }, { "code": null, "e": 34214, "s": 34199, "text": "sagartomar9927" }, { "code": null, "e": 34226, "s": 34214, "text": "subsequence" }, { "code": null, "e": 34234, "s": 34226, "text": "Strings" }, { "code": null, "e": 34242, "s": 34234, "text": "Strings" }, { "code": null, "e": 34340, "s": 34242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34385, "s": 34340, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 34430, "s": 34385, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 34447, "s": 34430, "text": "Vigenère Cipher" }, { "code": null, "e": 34476, "s": 34447, "text": "String class in Java | Set 1" }, { "code": null, "e": 34511, "s": 34476, "text": "Print all subsequences of a string" }, { "code": null, "e": 34526, "s": 34511, "text": "sprintf() in C" }, { "code": null, "e": 34567, "s": 34526, "text": "Convert character array to string in C++" }, { "code": null, "e": 34610, "s": 34567, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 34671, "s": 34610, "text": "Program to count occurrence of a given character in a string" } ]
Sprinklr Interview Experience | On-Campus - GeeksforGeeks
30 Jul, 2021 Round One Coding test of 1.5 Hours: It was an online coding test conducted on HackerRank. A test consisting of 3 coding questions. A medical team wants to send a minimum number of workers for vaccinating people in the city, each worker can vaccinate people in an area whose radius is D, and can start from anywhere, an array is given which tells the location of people on X-axis, there is no one on Y-axis, help the medical team to know the minimum number of people needed to vaccinate the whole town.Example : D - 2 , arr = {1,2,4,7,8,9,10,12,14,16,18,20} Output : 4 Explaination :- (1,2,4) , (7,8,9,10) , (12,14,16) , (18,20) , workers will be divided like this(50 Marks) – O(N) solution accepted(HINT: sort the array and take the group of people in a 2D distance at once)Sprinklr users are seeing some duplicate documents on the platform and we need you to help to detect those documents and remove them. We already have a framework to detect if 2 documents are duplicates or not, what we need from you is how many unique documents are present given pairs of duplicate documents. We also want to query if 2 documents are similar or not(75 Marks)Input Format :- N : total documents OPS - total operations next ops line will contain 3 space separate integers say(op , doc1 , doc2) where the first integer (op) denotes operation type and remaining two are documents numbers op = 0 , means next 2 documents are similar OUTPUT :- Single integer in new line for every query , 0 if documents are not duplicate , 1 if documents are duplicateSingle integer in new line for every query , 0 if documents are not duplicate , 1 if documents are duplicateEXAMPLE :- 10 5 0 1 2 0 5 7 1 1 3 0 2 3 1 1 3OUTPUT :- 0 1 7EXPLAINATION :- There are total of 10 documents Given 5 operations are :- 1) Mark the document 1 & 2 duplicate 2) Mark the document 5 & 7 duplicate 3) Query if document 1 & 3 are duplicate , hence the first line in output 0 4) Mark the document 2 & 3 duplicate 5) Query if document 1 & 3 are duplicate , hence the second line in output 1 Print total unique documents now (1,2,3) , (5,7) , (4) , (6) , (8) , (9) , (10) = total 7 unique documentsHint :- two ways through which this problem can be solved 1) using dfs traversal in each query , similar to count total number of connected components 2) using disjoint set union methodMaximise the sumyou will be given N intervals, where i’th interval will start at time Li and will be finished at Ri and contains the special value Ki, You have to select P intervals such that no intervals overlap each other and maximize the sum of special values of the selected P intervals. (100 Marks)Constraints 1<= N <= 10^5 1<= P <= 10^2 1<= N*P <= 10^6 1<= Li , Ri <= 10^9 1<=Ki <= 10^6Example :- consider N=3 and P=2 and the intervals are 1 3 10 2 5 15 5 7 6 Here the answer is 16 , as taking 1st and 3rd intervals will be optimalInput Format :- first line contains N and P N lines follow 3 space separated integers Li , Ri , KiSample Input 3 2 1 3 10 2 5 15 5 7 6 Sample Output 16HINT:Try to think DP with Binary Search in every recursive stack A medical team wants to send a minimum number of workers for vaccinating people in the city, each worker can vaccinate people in an area whose radius is D, and can start from anywhere, an array is given which tells the location of people on X-axis, there is no one on Y-axis, help the medical team to know the minimum number of people needed to vaccinate the whole town.Example : D - 2 , arr = {1,2,4,7,8,9,10,12,14,16,18,20} Output : 4 Explaination :- (1,2,4) , (7,8,9,10) , (12,14,16) , (18,20) , workers will be divided like this(50 Marks) – O(N) solution accepted(HINT: sort the array and take the group of people in a 2D distance at once) Example : D - 2 , arr = {1,2,4,7,8,9,10,12,14,16,18,20} Output : 4 Explaination :- (1,2,4) , (7,8,9,10) , (12,14,16) , (18,20) , workers will be divided like this (50 Marks) – O(N) solution accepted (HINT: sort the array and take the group of people in a 2D distance at once) Sprinklr users are seeing some duplicate documents on the platform and we need you to help to detect those documents and remove them. We already have a framework to detect if 2 documents are duplicates or not, what we need from you is how many unique documents are present given pairs of duplicate documents. We also want to query if 2 documents are similar or not(75 Marks)Input Format :- N : total documents OPS - total operations next ops line will contain 3 space separate integers say(op , doc1 , doc2) where the first integer (op) denotes operation type and remaining two are documents numbers op = 0 , means next 2 documents are similar OUTPUT :- Single integer in new line for every query , 0 if documents are not duplicate , 1 if documents are duplicateSingle integer in new line for every query , 0 if documents are not duplicate , 1 if documents are duplicateEXAMPLE :- 10 5 0 1 2 0 5 7 1 1 3 0 2 3 1 1 3OUTPUT :- 0 1 7EXPLAINATION :- There are total of 10 documents Given 5 operations are :- 1) Mark the document 1 & 2 duplicate 2) Mark the document 5 & 7 duplicate 3) Query if document 1 & 3 are duplicate , hence the first line in output 0 4) Mark the document 2 & 3 duplicate 5) Query if document 1 & 3 are duplicate , hence the second line in output 1 Print total unique documents now (1,2,3) , (5,7) , (4) , (6) , (8) , (9) , (10) = total 7 unique documentsHint :- two ways through which this problem can be solved 1) using dfs traversal in each query , similar to count total number of connected components 2) using disjoint set union method (75 Marks) Input Format :- N : total documents OPS - total operations next ops line will contain 3 space separate integers say(op , doc1 , doc2) where the first integer (op) denotes operation type and remaining two are documents numbers op = 0 , means next 2 documents are similar OUTPUT :- Single integer in new line for every query , 0 if documents are not duplicate , 1 if documents are duplicateSingle integer in new line for every query , 0 if documents are not duplicate , 1 if documents are duplicate EXAMPLE :- 10 5 0 1 2 0 5 7 1 1 3 0 2 3 1 1 3 OUTPUT :- 0 1 7 EXPLAINATION :- There are total of 10 documents Given 5 operations are :- 1) Mark the document 1 & 2 duplicate 2) Mark the document 5 & 7 duplicate 3) Query if document 1 & 3 are duplicate , hence the first line in output 0 4) Mark the document 2 & 3 duplicate 5) Query if document 1 & 3 are duplicate , hence the second line in output 1 Print total unique documents now (1,2,3) , (5,7) , (4) , (6) , (8) , (9) , (10) = total 7 unique documents Hint :- two ways through which this problem can be solved 1) using dfs traversal in each query , similar to count total number of connected components 2) using disjoint set union method Maximise the sumyou will be given N intervals, where i’th interval will start at time Li and will be finished at Ri and contains the special value Ki, You have to select P intervals such that no intervals overlap each other and maximize the sum of special values of the selected P intervals. (100 Marks)Constraints 1<= N <= 10^5 1<= P <= 10^2 1<= N*P <= 10^6 1<= Li , Ri <= 10^9 1<=Ki <= 10^6Example :- consider N=3 and P=2 and the intervals are 1 3 10 2 5 15 5 7 6 Here the answer is 16 , as taking 1st and 3rd intervals will be optimalInput Format :- first line contains N and P N lines follow 3 space separated integers Li , Ri , KiSample Input 3 2 1 3 10 2 5 15 5 7 6 Sample Output 16HINT:Try to think DP with Binary Search in every recursive stack you will be given N intervals, where i’th interval will start at time Li and will be finished at Ri and contains the special value Ki, You have to select P intervals such that no intervals overlap each other and maximize the sum of special values of the selected P intervals. (100 Marks) Constraints 1<= N <= 10^5 1<= P <= 10^2 1<= N*P <= 10^6 1<= Li , Ri <= 10^9 1<=Ki <= 10^6 Example :- consider N=3 and P=2 and the intervals are 1 3 10 2 5 15 5 7 6 Here the answer is 16 , as taking 1st and 3rd intervals will be optimal Input Format :- first line contains N and P N lines follow 3 space separated integers Li , Ri , Ki Sample Input 3 2 1 3 10 2 5 15 5 7 6 Sample Output 16 HINT: Try to think DP with Binary Search in every recursive stack Students who scored more than 125 marks were selected for interviews in Sprinklr. Marketing On-Campus Sprinklr Internship Interview Experiences Sprinklr Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus) JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Zoho Interview Experience (Off-Campus ) 2022 Resume Writing For Internship Difference Between ON Page and OFF Page SEO Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 26421, "s": 26393, "text": "\n30 Jul, 2021" }, { "code": null, "e": 26553, "s": 26421, "text": "Round One Coding test of 1.5 Hours: It was an online coding test conducted on HackerRank. A test consisting of 3 coding questions. " }, { "code": null, "e": 29617, "s": 26553, "text": "A medical team wants to send a minimum number of workers for vaccinating people in the city, each worker can vaccinate people in an area whose radius is D, and can start from anywhere, an array is given which tells the location of people on X-axis, there is no one on Y-axis, help the medical team to know the minimum number of people needed to vaccinate the whole town.Example : D - 2 , \narr = {1,2,4,7,8,9,10,12,14,16,18,20}\nOutput : 4 \nExplaination :- (1,2,4) , (7,8,9,10) , \n(12,14,16) , (18,20) , \nworkers will be divided like this(50 Marks) – O(N) solution accepted(HINT: sort the array and take the group of people in a 2D distance at once)Sprinklr users are seeing some duplicate documents on the platform and we need you to help to detect those documents and remove them. We already have a framework to detect if 2 documents are duplicates or not, what we need from you is how many unique documents are present given pairs of duplicate documents. We also want to query if 2 documents are similar or not(75 Marks)Input Format :-\nN : total documents \nOPS - total operations\n\nnext ops line will contain 3 space \nseparate integers say(op , doc1 , doc2) \nwhere the first integer (op) denotes \noperation type and remaining \ntwo are documents numbers\n\nop = 0 , means next 2 documents are similar\n\nOUTPUT :-\nSingle integer in new line for every query , \n0 if documents are not duplicate , \n1 if documents are duplicateSingle \ninteger in new line for every query , \n0 if documents are not duplicate , \n1 if documents are duplicateEXAMPLE :-\n10 \n5 \n0 1 2 \n0 5 7\n1 1 3\n0 2 3\n1 1 3OUTPUT :-\n0\n1\n7EXPLAINATION :-\nThere are total of 10 documents\nGiven 5 operations are :-\n1) Mark the document 1 & 2 duplicate\n2) Mark the document 5 & 7 duplicate\n3) Query if document 1 & 3 are duplicate , \nhence the first line in output 0\n4) Mark the document 2 & 3 duplicate\n5) Query if document 1 & 3 are duplicate , \nhence the second line in output 1\nPrint total unique documents now\n(1,2,3) , (5,7) , (4) , (6) , (8) , \n(9) , (10) = total 7 unique documentsHint :- \ntwo ways through which this \nproblem can be solved\n1) using dfs traversal in each query , \nsimilar to count total number \nof connected components\n2) using disjoint set union methodMaximise the sumyou will be given N intervals, where i’th interval will start at time Li and will be finished at Ri and contains the special value Ki, You have to select P intervals such that no intervals overlap each other and maximize the sum of special values of the selected P intervals. (100 Marks)Constraints\n1<= N <= 10^5\n1<= P <= 10^2\n1<= N*P <= 10^6\n1<= Li , Ri <= 10^9\n1<=Ki <= 10^6Example :-\nconsider N=3 and \nP=2 and the intervals are \n1 3 10\n2 5 15\n5 7 6\nHere the answer is 16 , \nas taking 1st and 3rd intervals\nwill be optimalInput Format :-\nfirst line contains N and P\nN lines follow 3 space separated \nintegers Li , Ri , KiSample Input \n3 2\n1 3 10\n2 5 15\n5 7 6\nSample Output\n16HINT:Try to think DP with Binary Search in every recursive stack" }, { "code": null, "e": 30265, "s": 29617, "text": "A medical team wants to send a minimum number of workers for vaccinating people in the city, each worker can vaccinate people in an area whose radius is D, and can start from anywhere, an array is given which tells the location of people on X-axis, there is no one on Y-axis, help the medical team to know the minimum number of people needed to vaccinate the whole town.Example : D - 2 , \narr = {1,2,4,7,8,9,10,12,14,16,18,20}\nOutput : 4 \nExplaination :- (1,2,4) , (7,8,9,10) , \n(12,14,16) , (18,20) , \nworkers will be divided like this(50 Marks) – O(N) solution accepted(HINT: sort the array and take the group of people in a 2D distance at once)" }, { "code": null, "e": 30432, "s": 30265, "text": "Example : D - 2 , \narr = {1,2,4,7,8,9,10,12,14,16,18,20}\nOutput : 4 \nExplaination :- (1,2,4) , (7,8,9,10) , \n(12,14,16) , (18,20) , \nworkers will be divided like this" }, { "code": null, "e": 30468, "s": 30432, "text": "(50 Marks) – O(N) solution accepted" }, { "code": null, "e": 30545, "s": 30468, "text": "(HINT: sort the array and take the group of people in a 2D distance at once)" }, { "code": null, "e": 32205, "s": 30545, "text": "Sprinklr users are seeing some duplicate documents on the platform and we need you to help to detect those documents and remove them. We already have a framework to detect if 2 documents are duplicates or not, what we need from you is how many unique documents are present given pairs of duplicate documents. We also want to query if 2 documents are similar or not(75 Marks)Input Format :-\nN : total documents \nOPS - total operations\n\nnext ops line will contain 3 space \nseparate integers say(op , doc1 , doc2) \nwhere the first integer (op) denotes \noperation type and remaining \ntwo are documents numbers\n\nop = 0 , means next 2 documents are similar\n\nOUTPUT :-\nSingle integer in new line for every query , \n0 if documents are not duplicate , \n1 if documents are duplicateSingle \ninteger in new line for every query , \n0 if documents are not duplicate , \n1 if documents are duplicateEXAMPLE :-\n10 \n5 \n0 1 2 \n0 5 7\n1 1 3\n0 2 3\n1 1 3OUTPUT :-\n0\n1\n7EXPLAINATION :-\nThere are total of 10 documents\nGiven 5 operations are :-\n1) Mark the document 1 & 2 duplicate\n2) Mark the document 5 & 7 duplicate\n3) Query if document 1 & 3 are duplicate , \nhence the first line in output 0\n4) Mark the document 2 & 3 duplicate\n5) Query if document 1 & 3 are duplicate , \nhence the second line in output 1\nPrint total unique documents now\n(1,2,3) , (5,7) , (4) , (6) , (8) , \n(9) , (10) = total 7 unique documentsHint :- \ntwo ways through which this \nproblem can be solved\n1) using dfs traversal in each query , \nsimilar to count total number \nof connected components\n2) using disjoint set union method" }, { "code": null, "e": 32216, "s": 32205, "text": "(75 Marks)" }, { "code": null, "e": 32726, "s": 32216, "text": "Input Format :-\nN : total documents \nOPS - total operations\n\nnext ops line will contain 3 space \nseparate integers say(op , doc1 , doc2) \nwhere the first integer (op) denotes \noperation type and remaining \ntwo are documents numbers\n\nop = 0 , means next 2 documents are similar\n\nOUTPUT :-\nSingle integer in new line for every query , \n0 if documents are not duplicate , \n1 if documents are duplicateSingle \ninteger in new line for every query , \n0 if documents are not duplicate , \n1 if documents are duplicate" }, { "code": null, "e": 32852, "s": 32726, "text": "EXAMPLE :-\n10 \n5 \n0 1 2 \n0 5 7\n1 1 3\n0 2 3\n1 1 3" }, { "code": null, "e": 32868, "s": 32852, "text": "OUTPUT :-\n0\n1\n7" }, { "code": null, "e": 33316, "s": 32868, "text": "EXPLAINATION :-\nThere are total of 10 documents\nGiven 5 operations are :-\n1) Mark the document 1 & 2 duplicate\n2) Mark the document 5 & 7 duplicate\n3) Query if document 1 & 3 are duplicate , \nhence the first line in output 0\n4) Mark the document 2 & 3 duplicate\n5) Query if document 1 & 3 are duplicate , \nhence the second line in output 1\nPrint total unique documents now\n(1,2,3) , (5,7) , (4) , (6) , (8) , \n(9) , (10) = total 7 unique documents" }, { "code": null, "e": 33506, "s": 33316, "text": "Hint :- \ntwo ways through which this \nproblem can be solved\n1) using dfs traversal in each query , \nsimilar to count total number \nof connected components\n2) using disjoint set union method" }, { "code": null, "e": 34264, "s": 33506, "text": "Maximise the sumyou will be given N intervals, where i’th interval will start at time Li and will be finished at Ri and contains the special value Ki, You have to select P intervals such that no intervals overlap each other and maximize the sum of special values of the selected P intervals. (100 Marks)Constraints\n1<= N <= 10^5\n1<= P <= 10^2\n1<= N*P <= 10^6\n1<= Li , Ri <= 10^9\n1<=Ki <= 10^6Example :-\nconsider N=3 and \nP=2 and the intervals are \n1 3 10\n2 5 15\n5 7 6\nHere the answer is 16 , \nas taking 1st and 3rd intervals\nwill be optimalInput Format :-\nfirst line contains N and P\nN lines follow 3 space separated \nintegers Li , Ri , KiSample Input \n3 2\n1 3 10\n2 5 15\n5 7 6\nSample Output\n16HINT:Try to think DP with Binary Search in every recursive stack" }, { "code": null, "e": 34552, "s": 34264, "text": "you will be given N intervals, where i’th interval will start at time Li and will be finished at Ri and contains the special value Ki, You have to select P intervals such that no intervals overlap each other and maximize the sum of special values of the selected P intervals. (100 Marks)" }, { "code": null, "e": 34642, "s": 34552, "text": "Constraints\n1<= N <= 10^5\n1<= P <= 10^2\n1<= N*P <= 10^6\n1<= Li , Ri <= 10^9\n1<=Ki <= 10^6" }, { "code": null, "e": 34791, "s": 34642, "text": "Example :-\nconsider N=3 and \nP=2 and the intervals are \n1 3 10\n2 5 15\n5 7 6\nHere the answer is 16 , \nas taking 1st and 3rd intervals\nwill be optimal" }, { "code": null, "e": 34891, "s": 34791, "text": "Input Format :-\nfirst line contains N and P\nN lines follow 3 space separated \nintegers Li , Ri , Ki" }, { "code": null, "e": 34946, "s": 34891, "text": "Sample Input \n3 2\n1 3 10\n2 5 15\n5 7 6\nSample Output\n16" }, { "code": null, "e": 34952, "s": 34946, "text": "HINT:" }, { "code": null, "e": 35012, "s": 34952, "text": "Try to think DP with Binary Search in every recursive stack" }, { "code": null, "e": 35094, "s": 35012, "text": "Students who scored more than 125 marks were selected for interviews in Sprinklr." }, { "code": null, "e": 35104, "s": 35094, "text": "Marketing" }, { "code": null, "e": 35114, "s": 35104, "text": "On-Campus" }, { "code": null, "e": 35123, "s": 35114, "text": "Sprinklr" }, { "code": null, "e": 35134, "s": 35123, "text": "Internship" }, { "code": null, "e": 35156, "s": 35134, "text": "Interview Experiences" }, { "code": null, "e": 35165, "s": 35156, "text": "Sprinklr" }, { "code": null, "e": 35263, "s": 35165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35340, "s": 35263, "text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)" }, { "code": null, "e": 35412, "s": 35340, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 35457, "s": 35412, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 35487, "s": 35457, "text": "Resume Writing For Internship" }, { "code": null, "e": 35531, "s": 35487, "text": "Difference Between ON Page and OFF Page SEO" }, { "code": null, "e": 35558, "s": 35531, "text": "Amazon Interview Questions" }, { "code": null, "e": 35618, "s": 35558, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 35669, "s": 35618, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 35711, "s": 35669, "text": "Amazon AWS Interview Experience for SDE-1" } ]
Introduction to Object Detection Model Evaluation | by Déborah Mesquita | Towards Data Science
Evaluating object detection models is not straightforward because each image can have many objects and each object can belong to different classes. This means that we need to measure if the model found all the objects and also a way to verify if the found objects belong to the correct class. This means that an object detection model needs to accomplish two things: Find all the objects in an image Check if the found objects belong to the correct class In this article you’ll see how the object detection researchers created ways to combine these two things in a single metric, the mean Average Precision (mAP). Two recent open-source tools were released recently and they help us a lot on these evaluation tasks. This means that right now is a great time to start working on object detection models. Let’s get started! When you’re annotating objected, the bounding box are the boxes you draw to indicate the location. A object detection model produces the output in three components: The bounding boxes — x1, y1, width, height if using the COCO file format The class of the bounding box The probability score for that prediction— how certain the model is that the class is actually the predicted class We need to take a closer look at the probability score component. Mostly because modern neural networks are poorly calibrated [1]: Recent advances in neural network architecture and training — model capacity, normalization, and regularization– have strong effects on network calibration — Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger, On Calibration of Modern Neural Networks Now imagine you need to compare the performance of two different object detection models. Since we know that the probability scores are poorly calibrated, there is a good chance that a bounding box with a probability score of say 80% having the same location coordinates as a bounding box with a probability score of 50% on the other model. How would we go about comparing the performance of these models? We’ll figure this out in the next sections. As you can see, the object detection task introduces some new challenges that we don’t see in regular classification tasks. Let’s talk about three of them in the next sections. In a multiclass classification task, you know the distribution of your dataset per image because each image can only have one class. This means you can easily split your training/test datates. But in object detection, each image can have many objects from different classes. Imagine that you have a dataset with images from supermarket shelves. Given that you don’t have access to new data and you need to split this dataset to create a test set, how would you split the images into the training/test groups? In a project I was working on we did some experiments with clustering using the brands and the quantity of products to get a sample from the images. We still need to do more research to present the findings but it seems to provide us with a good proxy to create the training/test groups in object detection dataset. To evaluate if an object was located we use the Intersection over Union (IoU) as a similarity measure. It’s given by the area of the overlap divided by the size of the union of the two bounding boxes. The IoU is needed to calculate the Average Precision because the first step is to define if two bounding boxes are pointing to the same object. To answer this question the default IoU value we use is 0.5. The model outputs the coordinates of the bounding boxes and the probability score for the predicted class. The problem is that the neural networks are poorly calibrated, meaning that we don’t have a direct way of comparting the probability scores of two different models. The solution for this problem is using the ranking of the bounding boxes each model outputs. This is the way the Average Precision (AP) metric is calculated. You start sorting the probability scores and then check if the bounding box is a True Positive or a False Positive using an IoU threshold to compare them. As Harshit Kumar [2] points out in this great explanation, if there is more than one detection for a single object, the detection having the highest IoU is considered as TP, rest as FP. You count the accumulated TP and the accumulated FP and compute the precision/recall at each line. Usually, the Average Precision is computed as the average precision at 11 equally spaced recall levels. The Mean Average Precision (mAP) is the averaged AP over all the object categories, and it’s the metric more used to evaluate an object detection model. Since we first rank the predictions, now the absolute probability scores don’t matter much and we can use the same metric for different models. One peculiarity of object annotation tasks is that there is a lack of consensus on the representation of the location and size of objects and performance assessment tools implement different metrics [3]. If you need to evaluate an object detection model and don’t want to compute the metrics from scratch (why would you like to do that? haha) the authors of [3] developed and released a tool named Open-Source Toolbox for Object Detection Metrics. The toolkit fills the gap of a reliable source of object detection metrics. The mAP is good if we need to compare models, but what if our goal is to have a qualitative view of how it’s performing? We’ll talk about this in the next section. The mAP is good for a competition settings or to get a quick assessment of how a model is performing, but if you care about understanding what the model is doing you’ll need different metrics. The source of errors in object detection tasks can be various: the model could find the correct location of the bounding box but output it with an incorrect class the model could find an object with a correct class but be totally wrong about the location of the bounding box the model could miss an object entirely and so on To solve this problem the authors of [4] developed TIDE. TIDE is a general toolbox to compute and evaluate the effect of object detection and instance segmentation on overall performance. The toolbox determines the importance of a given error to overall to the mAP by fixing the error and observing the resulting change in mAP. Let’s see what kind of errors are analyzed and how they do it. The authors define 6 error types: Classification Error: localized correctly but classified incorrectlyLocalization Error: classified correctly but localized incorrectlyBoth Cls and Loc Error: classified incorrectly and localized incorrectlyDuplicate Detection Error: would be correct if not for a higher scoring detectionBackground Error: detected background as fore-groundMissed GT Error: All undetected ground truth (false negatives) not already covered by classification or localization error Classification Error: localized correctly but classified incorrectly Localization Error: classified correctly but localized incorrectly Both Cls and Loc Error: classified incorrectly and localized incorrectly Duplicate Detection Error: would be correct if not for a higher scoring detection Background Error: detected background as fore-ground Missed GT Error: All undetected ground truth (false negatives) not already covered by classification or localization error To measure each type of error an oracle is implemented to correct them and the tool computes how the mAP would increase if this type of error didn’t exist. This information is gold because it can guide us on how to improve the model. Here is an example of TIDE results: -- mask_rcnn_bbox --bbox AP @ 50: 61.80 Main Errors============================================================= Type Cls Loc Both Dupe Bkg Miss------------------------------------------------------------- dAP 3.40 6.65 1.18 0.19 3.96 7.53============================================================= Special Error============================= Type FalsePos FalseNeg----------------------------- dAP 16.28 15.57============================= We can see that you could increase the mAP by 7.53 points if you correct the Missed GT Error. Now you can investigate the training images and the validation images to figure out how to fix these errors. This is something we’ll probably need a lot of time to find out if we were working only with the mAP result, 61.80. Object Detection tasks come with challenges we don’t see in multiclass classification tasks. With object detection, you need to find the objects and predict the correct class. Also, each image usually have a variable number of annotated objects. Fortunately, a lot of good researchers have been working on these problems and noew we have ways to work with them. To compare two bounding boxes are similar we use the Intersection over Union (IoU) and to measure the model performance we use the mean Average Precision (mAP). The Open-Source Toolbox for Object Detection Metrics provides an open-source tool that supports many bounding box formats and evaluates detections with different metrics. Having just the mAP is not enough to figure out what you need to do to increase the performance of a model. To solve that problem the authors of [4] created TIDE, a toolbox to compute and evaluate the effect of object detection on overall model performance. [1] Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger, “On Calibration of Modern Neural Networks” arXiv:1706.04599 [cs.LG], Aug. 2016. [2] Kumar, Harshit. “Evaluation metrics for object detection and segmentation: mAP”. https://kharshit.github.io/blog/2019/09/20/evaluation-metrics-for-object-detection-and-segmentation [3] Padilla, Rafael, et al. “A Comparative Analysis of Object Detection Metrics with a Companion Open-Source Toolkit.” Electronics 10.3 (2021): 279. [4] Bolya, Daniel, et al. “Tide: A general toolbox for identifying object detection errors.” arXiv preprint arXiv:2008.08115 (2020).
[ { "code": null, "e": 465, "s": 172, "text": "Evaluating object detection models is not straightforward because each image can have many objects and each object can belong to different classes. This means that we need to measure if the model found all the objects and also a way to verify if the found objects belong to the correct class." }, { "code": null, "e": 539, "s": 465, "text": "This means that an object detection model needs to accomplish two things:" }, { "code": null, "e": 572, "s": 539, "text": "Find all the objects in an image" }, { "code": null, "e": 627, "s": 572, "text": "Check if the found objects belong to the correct class" }, { "code": null, "e": 786, "s": 627, "text": "In this article you’ll see how the object detection researchers created ways to combine these two things in a single metric, the mean Average Precision (mAP)." }, { "code": null, "e": 994, "s": 786, "text": "Two recent open-source tools were released recently and they help us a lot on these evaluation tasks. This means that right now is a great time to start working on object detection models. Let’s get started!" }, { "code": null, "e": 1093, "s": 994, "text": "When you’re annotating objected, the bounding box are the boxes you draw to indicate the location." }, { "code": null, "e": 1159, "s": 1093, "text": "A object detection model produces the output in three components:" }, { "code": null, "e": 1232, "s": 1159, "text": "The bounding boxes — x1, y1, width, height if using the COCO file format" }, { "code": null, "e": 1262, "s": 1232, "text": "The class of the bounding box" }, { "code": null, "e": 1377, "s": 1262, "text": "The probability score for that prediction— how certain the model is that the class is actually the predicted class" }, { "code": null, "e": 1508, "s": 1377, "text": "We need to take a closer look at the probability score component. Mostly because modern neural networks are poorly calibrated [1]:" }, { "code": null, "e": 1762, "s": 1508, "text": "Recent advances in neural network architecture and training — model capacity, normalization, and regularization– have strong effects on network calibration — Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger, On Calibration of Modern Neural Networks" }, { "code": null, "e": 2212, "s": 1762, "text": "Now imagine you need to compare the performance of two different object detection models. Since we know that the probability scores are poorly calibrated, there is a good chance that a bounding box with a probability score of say 80% having the same location coordinates as a bounding box with a probability score of 50% on the other model. How would we go about comparing the performance of these models? We’ll figure this out in the next sections." }, { "code": null, "e": 2389, "s": 2212, "text": "As you can see, the object detection task introduces some new challenges that we don’t see in regular classification tasks. Let’s talk about three of them in the next sections." }, { "code": null, "e": 2664, "s": 2389, "text": "In a multiclass classification task, you know the distribution of your dataset per image because each image can only have one class. This means you can easily split your training/test datates. But in object detection, each image can have many objects from different classes." }, { "code": null, "e": 2898, "s": 2664, "text": "Imagine that you have a dataset with images from supermarket shelves. Given that you don’t have access to new data and you need to split this dataset to create a test set, how would you split the images into the training/test groups?" }, { "code": null, "e": 3214, "s": 2898, "text": "In a project I was working on we did some experiments with clustering using the brands and the quantity of products to get a sample from the images. We still need to do more research to present the findings but it seems to provide us with a good proxy to create the training/test groups in object detection dataset." }, { "code": null, "e": 3415, "s": 3214, "text": "To evaluate if an object was located we use the Intersection over Union (IoU) as a similarity measure. It’s given by the area of the overlap divided by the size of the union of the two bounding boxes." }, { "code": null, "e": 3620, "s": 3415, "text": "The IoU is needed to calculate the Average Precision because the first step is to define if two bounding boxes are pointing to the same object. To answer this question the default IoU value we use is 0.5." }, { "code": null, "e": 3892, "s": 3620, "text": "The model outputs the coordinates of the bounding boxes and the probability score for the predicted class. The problem is that the neural networks are poorly calibrated, meaning that we don’t have a direct way of comparting the probability scores of two different models." }, { "code": null, "e": 4205, "s": 3892, "text": "The solution for this problem is using the ranking of the bounding boxes each model outputs. This is the way the Average Precision (AP) metric is calculated. You start sorting the probability scores and then check if the bounding box is a True Positive or a False Positive using an IoU threshold to compare them." }, { "code": null, "e": 4391, "s": 4205, "text": "As Harshit Kumar [2] points out in this great explanation, if there is more than one detection for a single object, the detection having the highest IoU is considered as TP, rest as FP." }, { "code": null, "e": 4747, "s": 4391, "text": "You count the accumulated TP and the accumulated FP and compute the precision/recall at each line. Usually, the Average Precision is computed as the average precision at 11 equally spaced recall levels. The Mean Average Precision (mAP) is the averaged AP over all the object categories, and it’s the metric more used to evaluate an object detection model." }, { "code": null, "e": 4891, "s": 4747, "text": "Since we first rank the predictions, now the absolute probability scores don’t matter much and we can use the same metric for different models." }, { "code": null, "e": 5095, "s": 4891, "text": "One peculiarity of object annotation tasks is that there is a lack of consensus on the representation of the location and size of objects and performance assessment tools implement different metrics [3]." }, { "code": null, "e": 5415, "s": 5095, "text": "If you need to evaluate an object detection model and don’t want to compute the metrics from scratch (why would you like to do that? haha) the authors of [3] developed and released a tool named Open-Source Toolbox for Object Detection Metrics. The toolkit fills the gap of a reliable source of object detection metrics." }, { "code": null, "e": 5579, "s": 5415, "text": "The mAP is good if we need to compare models, but what if our goal is to have a qualitative view of how it’s performing? We’ll talk about this in the next section." }, { "code": null, "e": 5772, "s": 5579, "text": "The mAP is good for a competition settings or to get a quick assessment of how a model is performing, but if you care about understanding what the model is doing you’ll need different metrics." }, { "code": null, "e": 5835, "s": 5772, "text": "The source of errors in object detection tasks can be various:" }, { "code": null, "e": 5935, "s": 5835, "text": "the model could find the correct location of the bounding box but output it with an incorrect class" }, { "code": null, "e": 6047, "s": 5935, "text": "the model could find an object with a correct class but be totally wrong about the location of the bounding box" }, { "code": null, "e": 6087, "s": 6047, "text": "the model could miss an object entirely" }, { "code": null, "e": 6097, "s": 6087, "text": "and so on" }, { "code": null, "e": 6285, "s": 6097, "text": "To solve this problem the authors of [4] developed TIDE. TIDE is a general toolbox to compute and evaluate the effect of object detection and instance segmentation on overall performance." }, { "code": null, "e": 6488, "s": 6285, "text": "The toolbox determines the importance of a given error to overall to the mAP by fixing the error and observing the resulting change in mAP. Let’s see what kind of errors are analyzed and how they do it." }, { "code": null, "e": 6522, "s": 6488, "text": "The authors define 6 error types:" }, { "code": null, "e": 6984, "s": 6522, "text": "Classification Error: localized correctly but classified incorrectlyLocalization Error: classified correctly but localized incorrectlyBoth Cls and Loc Error: classified incorrectly and localized incorrectlyDuplicate Detection Error: would be correct if not for a higher scoring detectionBackground Error: detected background as fore-groundMissed GT Error: All undetected ground truth (false negatives) not already covered by classification or localization error" }, { "code": null, "e": 7053, "s": 6984, "text": "Classification Error: localized correctly but classified incorrectly" }, { "code": null, "e": 7120, "s": 7053, "text": "Localization Error: classified correctly but localized incorrectly" }, { "code": null, "e": 7193, "s": 7120, "text": "Both Cls and Loc Error: classified incorrectly and localized incorrectly" }, { "code": null, "e": 7275, "s": 7193, "text": "Duplicate Detection Error: would be correct if not for a higher scoring detection" }, { "code": null, "e": 7328, "s": 7275, "text": "Background Error: detected background as fore-ground" }, { "code": null, "e": 7451, "s": 7328, "text": "Missed GT Error: All undetected ground truth (false negatives) not already covered by classification or localization error" }, { "code": null, "e": 7685, "s": 7451, "text": "To measure each type of error an oracle is implemented to correct them and the tool computes how the mAP would increase if this type of error didn’t exist. This information is gold because it can guide us on how to improve the model." }, { "code": null, "e": 7721, "s": 7685, "text": "Here is an example of TIDE results:" }, { "code": null, "e": 8264, "s": 7721, "text": "-- mask_rcnn_bbox --bbox AP @ 50: 61.80 Main Errors============================================================= Type Cls Loc Both Dupe Bkg Miss------------------------------------------------------------- dAP 3.40 6.65 1.18 0.19 3.96 7.53============================================================= Special Error============================= Type FalsePos FalseNeg----------------------------- dAP 16.28 15.57=============================" }, { "code": null, "e": 8583, "s": 8264, "text": "We can see that you could increase the mAP by 7.53 points if you correct the Missed GT Error. Now you can investigate the training images and the validation images to figure out how to fix these errors. This is something we’ll probably need a lot of time to find out if we were working only with the mAP result, 61.80." }, { "code": null, "e": 8829, "s": 8583, "text": "Object Detection tasks come with challenges we don’t see in multiclass classification tasks. With object detection, you need to find the objects and predict the correct class. Also, each image usually have a variable number of annotated objects." }, { "code": null, "e": 9277, "s": 8829, "text": "Fortunately, a lot of good researchers have been working on these problems and noew we have ways to work with them. To compare two bounding boxes are similar we use the Intersection over Union (IoU) and to measure the model performance we use the mean Average Precision (mAP). The Open-Source Toolbox for Object Detection Metrics provides an open-source tool that supports many bounding box formats and evaluates detections with different metrics." }, { "code": null, "e": 9535, "s": 9277, "text": "Having just the mAP is not enough to figure out what you need to do to increase the performance of a model. To solve that problem the authors of [4] created TIDE, a toolbox to compute and evaluate the effect of object detection on overall model performance." }, { "code": null, "e": 9674, "s": 9535, "text": "[1] Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger, “On Calibration of Modern Neural Networks” arXiv:1706.04599 [cs.LG], Aug. 2016." }, { "code": null, "e": 9859, "s": 9674, "text": "[2] Kumar, Harshit. “Evaluation metrics for object detection and segmentation: mAP”. https://kharshit.github.io/blog/2019/09/20/evaluation-metrics-for-object-detection-and-segmentation" }, { "code": null, "e": 10008, "s": 9859, "text": "[3] Padilla, Rafael, et al. “A Comparative Analysis of Object Detection Metrics with a Companion Open-Source Toolkit.” Electronics 10.3 (2021): 279." } ]
User-defined Custom Exception with class in C++ - GeeksforGeeks
16 Apr, 2021 We can use Exception handling with class too. Even we can throw an exception of user defined class types. For throwing an exception of say demo class type within try block we may write throw demo(); Example 1: Program to implement exception handling with single class CPP14 #include <iostream>using namespace std; class demo {}; int main(){ try { throw demo(); } catch (demo d) { cout << "Caught exception of demo class \n"; }} Output: Caught exception of demo class Explanation: In the program we have declared an empty class.In the try block we are throwing an object of demo class type. The try block catches the object and displays.Example 2: Program to implement exception handling with two class CPP14 #include <iostream>using namespace std; class demo1 {}; class demo2 {}; int main(){ for (int i = 1; i <= 2; i++) { try { if (i == 1) throw demo1(); else if (i == 2) throw demo2(); } catch (demo1 d1) { cout << "Caught exception of demo1 class \n"; } catch (demo2 d2) { cout << "Caught exception of demo2 class \n"; } }} Output: Caught exception of demo1 class Caught exception of demo2 class Exception handling with inheritance: Exception handling can also be implemented with the help of inheritance. In case of inheritance object thrown by derived class is caught by the first catch block. Example: CPP14 #include <iostream>using namespace std; class demo1 {}; class demo2 : public demo1 {}; int main(){ for (int i = 1; i <= 2; i++) { try { if (i == 1) throw demo1(); else if (i == 2) throw demo2(); } catch (demo1 d1) { cout << "Caught exception of demo1 class \n"; } catch (demo2 d2) { cout << "Caught exception of demo2 class \n"; } }} Output: Caught exception of demo1 class Caught exception of demo1 class Explanation: The program is similar to previous one but here we have made demo2 as derived class for demo1.Note the catch block for demo1 is written first.As demo1 is base class for demo2 an object thrown of demo2 class will be handled by first catch block.That is why output as shown. Exception handling with constructor: Exception handling can also be implemented by using constructor. Though we cannot return any value from the constructor but with the help of try and catch block we can.Example: CPP14 #include <iostream>using namespace std; class demo { int num; public: demo(int x) { try { if (x == 0) // catch block would be called throw "Zero not allowed "; num = x; show(); } catch (const char* exp) { cout << "Exception caught \n "; cout << exp << endl; } } void show() { cout << "Num = " << num << endl; }}; int main(){ // constructor will be called demo(0); cout << "Again creating object \n"; demo(1);} Output: Exception caught Zero not allowed Again creating object Num = 1 Explanation: when x = 0 exception is thrown and catch block is called. And when x = 1 no exception is created . simmytarika5 C++-Exception Handling C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments cin in C++ Shallow Copy and Deep Copy in C++ Check if given number is perfect square C++ Program to check if a given String is Palindrome or not Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class C Program to Swap two Numbers CSV file management using C++ cout in C++ Pi(π) in C++ with Examples
[ { "code": null, "e": 24407, "s": 24379, "text": "\n16 Apr, 2021" }, { "code": null, "e": 24594, "s": 24407, "text": "We can use Exception handling with class too. Even we can throw an exception of user defined class types. For throwing an exception of say demo class type within try block we may write " }, { "code": null, "e": 24608, "s": 24594, "text": "throw demo();" }, { "code": null, "e": 24679, "s": 24608, "text": "Example 1: Program to implement exception handling with single class " }, { "code": null, "e": 24685, "s": 24679, "text": "CPP14" }, { "code": "#include <iostream>using namespace std; class demo {}; int main(){ try { throw demo(); } catch (demo d) { cout << \"Caught exception of demo class \\n\"; }}", "e": 24866, "s": 24685, "text": null }, { "code": null, "e": 24876, "s": 24866, "text": "Output: " }, { "code": null, "e": 24907, "s": 24876, "text": "Caught exception of demo class" }, { "code": null, "e": 25144, "s": 24907, "text": "Explanation: In the program we have declared an empty class.In the try block we are throwing an object of demo class type. The try block catches the object and displays.Example 2: Program to implement exception handling with two class " }, { "code": null, "e": 25150, "s": 25144, "text": "CPP14" }, { "code": "#include <iostream>using namespace std; class demo1 {}; class demo2 {}; int main(){ for (int i = 1; i <= 2; i++) { try { if (i == 1) throw demo1(); else if (i == 2) throw demo2(); } catch (demo1 d1) { cout << \"Caught exception of demo1 class \\n\"; } catch (demo2 d2) { cout << \"Caught exception of demo2 class \\n\"; } }}", "e": 25594, "s": 25150, "text": null }, { "code": null, "e": 25604, "s": 25594, "text": "Output: " }, { "code": null, "e": 25668, "s": 25604, "text": "Caught exception of demo1 class\nCaught exception of demo2 class" }, { "code": null, "e": 25707, "s": 25670, "text": "Exception handling with inheritance:" }, { "code": null, "e": 25881, "s": 25707, "text": "Exception handling can also be implemented with the help of inheritance. In case of inheritance object thrown by derived class is caught by the first catch block. Example: " }, { "code": null, "e": 25887, "s": 25881, "text": "CPP14" }, { "code": "#include <iostream>using namespace std; class demo1 {}; class demo2 : public demo1 {}; int main(){ for (int i = 1; i <= 2; i++) { try { if (i == 1) throw demo1(); else if (i == 2) throw demo2(); } catch (demo1 d1) { cout << \"Caught exception of demo1 class \\n\"; } catch (demo2 d2) { cout << \"Caught exception of demo2 class \\n\"; } }}", "e": 26345, "s": 25887, "text": null }, { "code": null, "e": 26355, "s": 26345, "text": "Output: " }, { "code": null, "e": 26419, "s": 26355, "text": "Caught exception of demo1 class\nCaught exception of demo1 class" }, { "code": null, "e": 26706, "s": 26419, "text": "Explanation: The program is similar to previous one but here we have made demo2 as derived class for demo1.Note the catch block for demo1 is written first.As demo1 is base class for demo2 an object thrown of demo2 class will be handled by first catch block.That is why output as shown. " }, { "code": null, "e": 26743, "s": 26706, "text": "Exception handling with constructor:" }, { "code": null, "e": 26922, "s": 26743, "text": "Exception handling can also be implemented by using constructor. Though we cannot return any value from the constructor but with the help of try and catch block we can.Example: " }, { "code": null, "e": 26928, "s": 26922, "text": "CPP14" }, { "code": "#include <iostream>using namespace std; class demo { int num; public: demo(int x) { try { if (x == 0) // catch block would be called throw \"Zero not allowed \"; num = x; show(); } catch (const char* exp) { cout << \"Exception caught \\n \"; cout << exp << endl; } } void show() { cout << \"Num = \" << num << endl; }}; int main(){ // constructor will be called demo(0); cout << \"Again creating object \\n\"; demo(1);}", "e": 27496, "s": 26928, "text": null }, { "code": null, "e": 27506, "s": 27496, "text": "Output: " }, { "code": null, "e": 27571, "s": 27506, "text": "Exception caught\n Zero not allowed\nAgain creating object\nNum = 1" }, { "code": null, "e": 27684, "s": 27571, "text": "Explanation: when x = 0 exception is thrown and catch block is called. And when x = 1 no exception is created . " }, { "code": null, "e": 27697, "s": 27684, "text": "simmytarika5" }, { "code": null, "e": 27720, "s": 27697, "text": "C++-Exception Handling" }, { "code": null, "e": 27733, "s": 27720, "text": "C++ Programs" }, { "code": null, "e": 27831, "s": 27733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27840, "s": 27831, "text": "Comments" }, { "code": null, "e": 27853, "s": 27840, "text": "Old Comments" }, { "code": null, "e": 27864, "s": 27853, "text": "cin in C++" }, { "code": null, "e": 27898, "s": 27864, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 27938, "s": 27898, "text": "Check if given number is perfect square" }, { "code": null, "e": 27998, "s": 27938, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 28039, "s": 27998, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 28098, "s": 28039, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 28128, "s": 28098, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 28158, "s": 28128, "text": "CSV file management using C++" }, { "code": null, "e": 28170, "s": 28158, "text": "cout in C++" } ]
Convert files from jpg to gif and vice versa using Python - GeeksforGeeks
26 Jul, 2021 Sometimes it is required to attach the Image where we required image file with the specified extension. And we have the image with the different extension which needs to be converted with a specified extension like in this we will convert the image having Extension of .jpg to .gif and Vice-Versa And Also we will be creating the GUI interface to the code, so we will require the Library tkinter. Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit which provide the interface to the GUI apps Follow the below steps: Step 1: Import the library. from PIL import Image Step 2: JPG to GIF To convert the image From JPG to GIF : {Syntax} img = Image.open("Image.jpg") img.save("Image.gif") Step 3: GIF to JPG To convert the Image From PNG to JPG img = Image.open("Image.gif") img.save("Image.jpg") Adding the GUI interface from tkinter import * Approach: In function jpg_to_gif() we first check whether The Selecting the image is in the same format (.jpg) which to convert to .gif if not then return error. Else Convert the image the to .gif. To open the Image we use the Function in tkinter called the FileDialog which helps to open the image from the folder. From tkinter import filedialog as fd. Same Approach for the GIF to JPG. Below is the Implementation: Python3 # import required modulesfrom tkinter import *from tkinter import filedialog as fdimport osfrom PIL import Imagefrom tkinter import messagebox # create TK object root = Tk() # naming the GUI interface to image_conversion_APProot.title("Image_Conversion_App") # function to convert jpg to gifdef jpg_to_gif(): global im1 # import the image from the folder import_filename = fd.askopenfilename() if import_filename.endswith(".jpg"): im1 = Image.open(import_filename) # after converting the image save to desired # location with the Extersion .png export_filename = fd.asksaveasfilename(defaultextension=".gif") im1.save(export_filename) # displaying the Messaging box with the Success messagebox.showinfo("success ", "your Image converted to GIF Format") else: # if Image select is not with the Format of .jpg # then display the Error Label_2 = Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) messagebox.showerror("Fail!!", "Something Went Wrong...") # function to convert gif to jpg def gif_to_jpg(): global im1 import_filename = fd.askopenfilename() if import_filename.endswith(".gif"): im1=Image.open(import_filename).convert('RGB') export_filename=fd.asksaveasfilename(defaultextension=".jpg") im1.save(export_filename) messagebox.showinfo("Success","File converted to .jpg") else: messagebox.showerror("Fail!!","Error Interrupted!!!! Check Again") # Driver Code # add buttonsbutton1 = Button(root, text="JPG_to_GIF", width=20, height=2, bg="green", fg="white", font=("helvetica", 12, "bold"), command=jpg_to_gif) button1.place(x=120, y=120) button2 = Button(root, text="GIF_to_JPG", width=20, height=2, bg="green", fg="white", font=("helvetica", 12, "bold"), command=gif_to_jpg) button2.place(x=120, y=220) # adjust window sizeroot.geometry("500x500+400+200")root.mainloop() ruhelaa48 saurabh1990aror Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n26 Jul, 2021" }, { "code": null, "e": 24589, "s": 24292, "text": "Sometimes it is required to attach the Image where we required image file with the specified extension. And we have the image with the different extension which needs to be converted with a specified extension like in this we will convert the image having Extension of .jpg to .gif and Vice-Versa" }, { "code": null, "e": 24842, "s": 24589, "text": "And Also we will be creating the GUI interface to the code, so we will require the Library tkinter. Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit which provide the interface to the GUI apps" }, { "code": null, "e": 24866, "s": 24842, "text": "Follow the below steps:" }, { "code": null, "e": 24894, "s": 24866, "text": "Step 1: Import the library." }, { "code": null, "e": 24916, "s": 24894, "text": "from PIL import Image" }, { "code": null, "e": 24935, "s": 24916, "text": "Step 2: JPG to GIF" }, { "code": null, "e": 25036, "s": 24935, "text": "To convert the image From JPG to GIF : {Syntax}\n\nimg = Image.open(\"Image.jpg\")\nimg.save(\"Image.gif\")" }, { "code": null, "e": 25055, "s": 25036, "text": "Step 3: GIF to JPG" }, { "code": null, "e": 25144, "s": 25055, "text": "To convert the Image From PNG to JPG\nimg = Image.open(\"Image.gif\")\nimg.save(\"Image.jpg\")" }, { "code": null, "e": 25169, "s": 25144, "text": "Adding the GUI interface" }, { "code": null, "e": 25191, "s": 25169, "text": "from tkinter import *" }, { "code": null, "e": 25201, "s": 25191, "text": "Approach:" }, { "code": null, "e": 25353, "s": 25201, "text": "In function jpg_to_gif() we first check whether The Selecting the image is in the same format (.jpg) which to convert to .gif if not then return error." }, { "code": null, "e": 25389, "s": 25353, "text": "Else Convert the image the to .gif." }, { "code": null, "e": 25507, "s": 25389, "text": "To open the Image we use the Function in tkinter called the FileDialog which helps to open the image from the folder." }, { "code": null, "e": 25545, "s": 25507, "text": "From tkinter import filedialog as fd." }, { "code": null, "e": 25579, "s": 25545, "text": "Same Approach for the GIF to JPG." }, { "code": null, "e": 25608, "s": 25579, "text": "Below is the Implementation:" }, { "code": null, "e": 25616, "s": 25608, "text": "Python3" }, { "code": "# import required modulesfrom tkinter import *from tkinter import filedialog as fdimport osfrom PIL import Imagefrom tkinter import messagebox # create TK object root = Tk() # naming the GUI interface to image_conversion_APProot.title(\"Image_Conversion_App\") # function to convert jpg to gifdef jpg_to_gif(): global im1 # import the image from the folder import_filename = fd.askopenfilename() if import_filename.endswith(\".jpg\"): im1 = Image.open(import_filename) # after converting the image save to desired # location with the Extersion .png export_filename = fd.asksaveasfilename(defaultextension=\".gif\") im1.save(export_filename) # displaying the Messaging box with the Success messagebox.showinfo(\"success \", \"your Image converted to GIF Format\") else: # if Image select is not with the Format of .jpg # then display the Error Label_2 = Label(root, text=\"Error!\", width=20, fg=\"red\", font=(\"bold\", 15)) Label_2.place(x=80, y=280) messagebox.showerror(\"Fail!!\", \"Something Went Wrong...\") # function to convert gif to jpg def gif_to_jpg(): global im1 import_filename = fd.askopenfilename() if import_filename.endswith(\".gif\"): im1=Image.open(import_filename).convert('RGB') export_filename=fd.asksaveasfilename(defaultextension=\".jpg\") im1.save(export_filename) messagebox.showinfo(\"Success\",\"File converted to .jpg\") else: messagebox.showerror(\"Fail!!\",\"Error Interrupted!!!! Check Again\") # Driver Code # add buttonsbutton1 = Button(root, text=\"JPG_to_GIF\", width=20, height=2, bg=\"green\", fg=\"white\", font=(\"helvetica\", 12, \"bold\"), command=jpg_to_gif) button1.place(x=120, y=120) button2 = Button(root, text=\"GIF_to_JPG\", width=20, height=2, bg=\"green\", fg=\"white\", font=(\"helvetica\", 12, \"bold\"), command=gif_to_jpg) button2.place(x=120, y=220) # adjust window sizeroot.geometry(\"500x500+400+200\")root.mainloop()", "e": 27772, "s": 25616, "text": null }, { "code": null, "e": 27782, "s": 27772, "text": "ruhelaa48" }, { "code": null, "e": 27798, "s": 27782, "text": "saurabh1990aror" }, { "code": null, "e": 27809, "s": 27798, "text": "Python-pil" }, { "code": null, "e": 27816, "s": 27809, "text": "Python" }, { "code": null, "e": 27914, "s": 27816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27946, "s": 27914, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27988, "s": 27946, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28044, "s": 27988, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28086, "s": 28044, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28117, "s": 28086, "text": "Python | os.path.join() method" }, { "code": null, "e": 28139, "s": 28117, "text": "Defaultdict in Python" }, { "code": null, "e": 28194, "s": 28139, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28233, "s": 28194, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28262, "s": 28233, "text": "Create a directory in Python" } ]
How do I create child windows with Python tkinter?
The child window can be referred to as the independent window which is separated from the root or main window. In order to create a child window, we have to define a toplevel window which can be created manually using the Toplevel(win) method. In the method toplevel(root), we have to pass the main window as the parameter and further define the widgets if needed. Let us create a child window which contains some widgets in it. #Import tkinter library from tkinter import * from tkinter import ttk #Create an instance of tkinter frame win = Tk() #Set the geometry and title of tkinter Main window win.geometry("750x250") win.title("Main Window") #Create a child window using Toplevel method child_w= Toplevel(win) child_w.geometry("750x250") child_w.title("New Child Window") #Create Label in Mainwindow and Childwindow label_main= Label(win, text="Hi, this is Main window", font=('Helvetica 15')) label_main.pack(pady=20) label_child= Label(child_w, text= "Hi, this is Child Window", font=('Helvetica 15')) label_child.pack() win.mainloop() When we run the above code, it will display two windows: a Main window and a Child Window
[ { "code": null, "e": 1427, "s": 1062, "text": "The child window can be referred to as the independent window which is separated from the root or main window. In order to create a child window, we have to define a toplevel window which can be created manually using the Toplevel(win) method. In the method toplevel(root), we have to pass the main window as the parameter and further define the widgets if needed." }, { "code": null, "e": 1491, "s": 1427, "text": "Let us create a child window which contains some widgets in it." }, { "code": null, "e": 2105, "s": 1491, "text": "#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry and title of tkinter Main window\nwin.geometry(\"750x250\")\nwin.title(\"Main Window\")\n#Create a child window using Toplevel method\nchild_w= Toplevel(win)\nchild_w.geometry(\"750x250\")\nchild_w.title(\"New Child Window\")\n#Create Label in Mainwindow and Childwindow\nlabel_main= Label(win, text=\"Hi, this is Main window\", font=('Helvetica 15'))\nlabel_main.pack(pady=20)\nlabel_child= Label(child_w, text= \"Hi, this is Child Window\", font=('Helvetica 15'))\nlabel_child.pack()\nwin.mainloop()" }, { "code": null, "e": 2195, "s": 2105, "text": "When we run the above code, it will display two windows: a Main window and a Child Window" } ]
How to install gnome desktop on centos rhel 7 using yum command
GNOME is a totally intuitive and user friendly desktop environment for CentOS and RHEL 7.x based system. The latest version of GNOME Desktops are GNOME 2 to GNOME 3 and the GNOME Shell desktop. Most of the users who prefer traditional desktop environments can get it via GNOME’s classic mode. It is also fully configurable with extensions. If you have done basic installation, this article will give insights on – how to install Gnome GUI on a CentOS 7 or RHEL 7 using a command line options. To install Gnome GUI, use the following commands- $ yum grouplist The sample output should be like this – Loaded plugins: fastestmirror, langpacks Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Determining fastest mirrors * base: mirror.nbrc.ac.in * elrepo: elrepo.reloumirrors.net * extras: mirror.nbrc.ac.in * updates: mirror.nbrc.ac.in google-chrome 3/3 Available Environment Groups: Minimal Install Compute Node Infrastructure Server File and Print Server Basic Web Server Virtualization Host Server with GUI GNOME Desktop KDE Plasma Workspaces Development and Creative Workstation Available Groups: Compatibility Libraries Console Internet Tools Development Tools Graphical Administration Tools Legacy UNIX Compatibility Scientific Support Security Tools Smart Card Support System Administration Tools System Management Done To install GNOME desktop group, enter the following command (it requires a root permission) – # sudo yum groups install "GNOME Desktop" The sample output should be like this – Loaded plugins: fastestmirror, langpacks Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast There is no installed groups file. Maybe run: yum groups mark convert (see man yum) base | 3.6 kB 00:00 elrepo | 2.9 kB 00:00 extras | 3.4 kB 00:00 google-chrome | 951 B 00:00 updates | 3.4 kB 00:00 (1/3): extras/7/x86_64/primary_db | 101 kB 00:00 (2/3): updates/7/x86_64/primary_db | 3.1 MB 00:00 (3/3): elrepo/primary_db | 348 kB 00:02 google-chrome/primary | 1.8 kB 00:00 Loading mirror speeds from cached hostfile * base: ftp.iitm.ac.in * elrepo: mirrors.ircam.fr * extras: ftp.iitm.ac.in * updates: ftp.iitm.ac.in google-chrome 3/3 Warning: Group core does not have any packages to install. Warning: Group guest-agents does not have any packages to install. Package gtk2-immodule-xim-2.24.28-8.el7.x86_64 already installed and latest version ......... To install Gnome on a RHEL 7 or CentOS Linux 7 server for operating network infrastructure services with a GUI, enter the following command – # sudo yum groups install "Server with GUI" It allows the user to GNOME GUI while entering the user name and password to login – # sudo systemctl set-default graphical.target The sample output should be like this – Removed symlink /etc/systemd/system/default.target. Created symlink from /etc/systemd/system/default.target to /usr/lib/systemd/system/graphical.target. Starting GUI login From Command Line To start GUI login from Command line interface, use the following command – # sudo systemctl start graphical.target The sample of login screen should be like this- In the above result shows, Operating system allows to user with GNOME GUI.Congratulations! Now, you know “ How to install gnome desktop on CentOS / RHEL 7 using yum command”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1555, "s": 1062, "text": "GNOME is a totally intuitive and user friendly desktop environment for CentOS and RHEL 7.x based system. The latest version of GNOME Desktops are GNOME 2 to GNOME 3 and the GNOME Shell desktop. Most of the users who prefer traditional desktop environments can get it via GNOME’s classic mode. It is also fully configurable with extensions. If you have done basic installation, this article will give insights on – how to install Gnome GUI on a CentOS 7 or RHEL 7 using a command line options." }, { "code": null, "e": 1605, "s": 1555, "text": "To install Gnome GUI, use the following commands-" }, { "code": null, "e": 1621, "s": 1605, "text": "$ yum grouplist" }, { "code": null, "e": 1661, "s": 1621, "text": "The sample output should be like this –" }, { "code": null, "e": 2497, "s": 1661, "text": "Loaded plugins: fastestmirror, langpacks\nRepodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast\nThere is no installed groups file.\nMaybe run: yum groups mark convert (see man yum)\nDetermining fastest mirrors\n* base: mirror.nbrc.ac.in\n* elrepo: elrepo.reloumirrors.net\n* extras: mirror.nbrc.ac.in\n* updates: mirror.nbrc.ac.in\ngoogle-chrome 3/3\nAvailable Environment Groups:\nMinimal Install\nCompute Node\nInfrastructure Server\nFile and Print Server\nBasic Web Server\nVirtualization Host\nServer with GUI\nGNOME Desktop\nKDE Plasma Workspaces\nDevelopment and Creative Workstation\nAvailable Groups:\nCompatibility Libraries\nConsole Internet Tools\nDevelopment Tools\nGraphical Administration Tools\nLegacy UNIX Compatibility\nScientific Support\nSecurity Tools\nSmart Card Support\nSystem Administration Tools\nSystem Management\nDone" }, { "code": null, "e": 2591, "s": 2497, "text": "To install GNOME desktop group, enter the following command (it requires a root permission) –" }, { "code": null, "e": 2633, "s": 2591, "text": "# sudo yum groups install \"GNOME Desktop\"" }, { "code": null, "e": 2673, "s": 2633, "text": "The sample output should be like this –" }, { "code": null, "e": 3731, "s": 2673, "text": "Loaded plugins: fastestmirror, langpacks\nRepodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast\nThere is no installed groups file.\nMaybe run: yum groups mark convert (see man yum)\nbase | 3.6 kB 00:00\nelrepo | 2.9 kB 00:00\nextras | 3.4 kB 00:00\ngoogle-chrome | 951 B 00:00\nupdates | 3.4 kB 00:00\n(1/3): extras/7/x86_64/primary_db | 101 kB 00:00\n(2/3): updates/7/x86_64/primary_db | 3.1 MB 00:00\n(3/3): elrepo/primary_db | 348 kB 00:02\ngoogle-chrome/primary | 1.8 kB 00:00\nLoading mirror speeds from cached hostfile\n* base: ftp.iitm.ac.in\n* elrepo: mirrors.ircam.fr\n* extras: ftp.iitm.ac.in\n* updates: ftp.iitm.ac.in\ngoogle-chrome 3/3\nWarning: Group core does not have any packages to install.\nWarning: Group guest-agents does not have any packages to install.\nPackage gtk2-immodule-xim-2.24.28-8.el7.x86_64 already installed and latest version\n........." }, { "code": null, "e": 3873, "s": 3731, "text": "To install Gnome on a RHEL 7 or CentOS Linux 7 server for operating network infrastructure services with a GUI, enter the following command –" }, { "code": null, "e": 3917, "s": 3873, "text": "# sudo yum groups install \"Server with GUI\"" }, { "code": null, "e": 4002, "s": 3917, "text": "It allows the user to GNOME GUI while entering the user name and password to login –" }, { "code": null, "e": 4048, "s": 4002, "text": "# sudo systemctl set-default graphical.target" }, { "code": null, "e": 4088, "s": 4048, "text": "The sample output should be like this –" }, { "code": null, "e": 4241, "s": 4088, "text": "Removed symlink /etc/systemd/system/default.target.\nCreated symlink from /etc/systemd/system/default.target to /usr/lib/systemd/system/graphical.target." }, { "code": null, "e": 4278, "s": 4241, "text": "Starting GUI login From Command Line" }, { "code": null, "e": 4354, "s": 4278, "text": "To start GUI login from Command line interface, use the following command –" }, { "code": null, "e": 4394, "s": 4354, "text": "# sudo systemctl start graphical.target" }, { "code": null, "e": 4442, "s": 4394, "text": "The sample of login screen should be like this-" }, { "code": null, "e": 4702, "s": 4442, "text": "In the above result shows, Operating system allows to user with GNOME GUI.Congratulations! Now, you know “ How to install gnome desktop on CentOS / RHEL 7 using yum command”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
Exploring Exploratory Data Analysis | by Aamodini Gupta | Towards Data Science
The whole point of Exploratory Data Analysis (EDA) is to just take a step back and look at the dataset before doing anything with it. EDA is just as important as any part of a data project because real datasets are really messy and lots of things can go wrong. If you don’t know your data well enough, how are you going to know where to look for those sources of error or confusion? Take some time to understand the dataset you are going to be working with. Here are a few things I routinely ask myself/check for whenever I work with a new dataset: I used to struggle a lot with finding the right way to import my data. The read.csv() function can be found in R’s base library and was consequently the very first function I used to import my dataset. # the two assignment statements below render the same output> df <- read.csv("mydataset.csv")> df <- read.csv("mydataset.csv", header = TRUE) The default header option for read.csv() is set as TRUE, which means that the function assigns the first row of observation in the dataset to column names. Suppose that mydataset.csv contains only observation values with no defined column names. If header = FALSE is not specified within the function, then the column names of the data frame that is imported will attain the values of the first observation in the dataset. The best way to check this is by simply looking at the first few rows of the imported data. Using colnames() can be helpful as well in this case. # returns the first few rows of df> head(df)# returns a vector of characters that correspond to the column names > colnames(df) One way to avoid this is by using fread() which can be found in the data.table library in R. The header option in this case is set to auto so the function checks automatically if the first row of observations could be column names and assigns a TRUE or FALSE value accordingly. I would suggest to look at the first few rows regardless, but it is faster and a more convenient alternative to read.csv() Note: read.csv() returns a data frame and fread() returns a data table. After successfully importing the data file, I always check for any missing values in my dataset. I find that the best way to inspect this is by summing all the TRUE values from is.na() by column like this: > colSums(is.na(df)) There are many ways to treat missing values. The handling of missing values is a separate topic in itself, but it is the awareness of these values that I am trying to emphasize here. Once I know there are missing values in my dataset, I can then take appropriate steps to deal with these values. It is also worth asking yourself “Why are these values missing?”. Understanding why certain values in your dataset are missing can help you understand your data better. Remember that the whole point of this exercise is to help you get the full measure of your dataset so you know what you are dealing with. Some datasets can also have very unusual values. It is easier to talk about this with an example so let’s look at the pima dataset from the faraway package. A description of the dataset can be found here. Looking at some of the basic summary statistics of the dataset per column is a good place to start in making sure that the values in your dataset make sense. Take a look at the summary for the pima dataset below. Look specifically at the minimum values for glucose , diastolic , triceps , insulin , and bmi . Does it make sense for these variables to take on a value of 0? No. It is not possible for a person to have no blood pressure or no body mass index. The only possible explanation for these values to be 0 is that those entries are instances in which no data was collected (i.e. they are missing values). Set these values to NA values so you can deal with them with any other missing values you have in the dataset. Here is an example of how you can replace those 0 values for the variable bmi: # pima loaded as a dataframe> pima$bmi[pima$bmi==0] <- NA Notice the change in the summary of bmi. These values make more sense this way. Now take a look at test . This variable is supposed to be a binary indication for signs diabetes. Why is there a mean value? This clearly indicates that R recognizes the 1’s and 0’s as quantitative variables instead of categorical variables. Run class() to see how these values are treated in R: > class(pima$test)[1] "integer" To get R to handle this column as a categorical variable, you can use factor() : > pima$test <- factor(pima$test)> class(pima$test)[1] "factor" Detecting these instances are important — these unusual values can heavily bias prediction models and any conclusions that may be drawn from them. Visualizing your data in various ways can help you see things you may have missed out on in your early stages of exploration. Here are some of my go-to visualizations: Continuing with the example earlier with the pima dataset, below is a histogram I plotted using ggplot2 and tidyr libraries. This method of visualization helps me to look at the frequency/count of points for each variable in the dataset: > pima %>%+ gather() %>% + ggplot(aes(value)) ++ facet_wrap(~ key, scales = "free") ++ geom_histogram(stat="count") Just by visualizing your data, you can see that there are clearly a dominant number of missing values for the variables triceps and insulin. This goes to show that in this case, handling of missing data must be conducted carefully. Understanding why exactly so many values are missing might be an important feature to note. Note: You would see a similar visualization if you did not correct for the unusual 0 values previously. For details on the code for visualization using ggplot2 and tidyr, take a look at this website. A scatterplot matrix can help you see if some kind of a relationship exists between any two variables in your dataset. Take a look at this symmetric matrix of pairwise scatterplots using the iris dataset. > pairs(iris) You can see, just by looking at the plots above, that there is some linearity between Petal.Length and Petal.Width . You have not even gotten to the modeling stage and you already have an insight about the variables you want to keep your eyes on! This correlation matrix plot provides visual aid for understanding how two numeric type variables change in relation to each other. In other words, it is just literally just a visual representation of a correlation matrix. The function cor() is used to evaluate the correlation matrix, and the function corrplot() from the library corrplot is used to create a heat map based on the correlation matrix. Take a look at an example below using the same iris dataset. # use only numeric type variables> correlations <- cor(iris[,1:4])# correlation plot> corrplot(correlations) You can see from the scale that a large positive correlation value is more blue, and a large negative correlation values is more red. So from this graph, it looks like Petal.Length and Petal.Width are strongly correlated and it also looks like there is a high correlation between Petal.Length and Sepal.Length . Note that the diagonal is perfectly positively correlated because it represents the correlation of the variable with itself. Although these conclusions are similar to those that were made earlier with the scatterplots, this method just provides a more concrete reason to believe that two attributes are related. Going through this process of understanding your data is vital for more than just the reasons I have mentioned. It might also eventually help you make informed decisions when it comes to selecting your model.The methods and processes I have outlined in this article are some of the ones I use most frequently whenever I get a new dataset. There are so many more visualizations that you can explore and experiment with using your dataset. Don’t hold yourself back. You’re just trying to look at your data and understand it here. I hope this article helps provide some insight on what exploratory data analysis is and why it is important to go through this process.
[ { "code": null, "e": 555, "s": 172, "text": "The whole point of Exploratory Data Analysis (EDA) is to just take a step back and look at the dataset before doing anything with it. EDA is just as important as any part of a data project because real datasets are really messy and lots of things can go wrong. If you don’t know your data well enough, how are you going to know where to look for those sources of error or confusion?" }, { "code": null, "e": 721, "s": 555, "text": "Take some time to understand the dataset you are going to be working with. Here are a few things I routinely ask myself/check for whenever I work with a new dataset:" }, { "code": null, "e": 923, "s": 721, "text": "I used to struggle a lot with finding the right way to import my data. The read.csv() function can be found in R’s base library and was consequently the very first function I used to import my dataset." }, { "code": null, "e": 1065, "s": 923, "text": "# the two assignment statements below render the same output> df <- read.csv(\"mydataset.csv\")> df <- read.csv(\"mydataset.csv\", header = TRUE)" }, { "code": null, "e": 1221, "s": 1065, "text": "The default header option for read.csv() is set as TRUE, which means that the function assigns the first row of observation in the dataset to column names." }, { "code": null, "e": 1634, "s": 1221, "text": "Suppose that mydataset.csv contains only observation values with no defined column names. If header = FALSE is not specified within the function, then the column names of the data frame that is imported will attain the values of the first observation in the dataset. The best way to check this is by simply looking at the first few rows of the imported data. Using colnames() can be helpful as well in this case." }, { "code": null, "e": 1762, "s": 1634, "text": "# returns the first few rows of df> head(df)# returns a vector of characters that correspond to the column names > colnames(df)" }, { "code": null, "e": 2163, "s": 1762, "text": "One way to avoid this is by using fread() which can be found in the data.table library in R. The header option in this case is set to auto so the function checks automatically if the first row of observations could be column names and assigns a TRUE or FALSE value accordingly. I would suggest to look at the first few rows regardless, but it is faster and a more convenient alternative to read.csv()" }, { "code": null, "e": 2235, "s": 2163, "text": "Note: read.csv() returns a data frame and fread() returns a data table." }, { "code": null, "e": 2441, "s": 2235, "text": "After successfully importing the data file, I always check for any missing values in my dataset. I find that the best way to inspect this is by summing all the TRUE values from is.na() by column like this:" }, { "code": null, "e": 2462, "s": 2441, "text": "> colSums(is.na(df))" }, { "code": null, "e": 2758, "s": 2462, "text": "There are many ways to treat missing values. The handling of missing values is a separate topic in itself, but it is the awareness of these values that I am trying to emphasize here. Once I know there are missing values in my dataset, I can then take appropriate steps to deal with these values." }, { "code": null, "e": 3065, "s": 2758, "text": "It is also worth asking yourself “Why are these values missing?”. Understanding why certain values in your dataset are missing can help you understand your data better. Remember that the whole point of this exercise is to help you get the full measure of your dataset so you know what you are dealing with." }, { "code": null, "e": 3270, "s": 3065, "text": "Some datasets can also have very unusual values. It is easier to talk about this with an example so let’s look at the pima dataset from the faraway package. A description of the dataset can be found here." }, { "code": null, "e": 3483, "s": 3270, "text": "Looking at some of the basic summary statistics of the dataset per column is a good place to start in making sure that the values in your dataset make sense. Take a look at the summary for the pima dataset below." }, { "code": null, "e": 4072, "s": 3483, "text": "Look specifically at the minimum values for glucose , diastolic , triceps , insulin , and bmi . Does it make sense for these variables to take on a value of 0? No. It is not possible for a person to have no blood pressure or no body mass index. The only possible explanation for these values to be 0 is that those entries are instances in which no data was collected (i.e. they are missing values). Set these values to NA values so you can deal with them with any other missing values you have in the dataset. Here is an example of how you can replace those 0 values for the variable bmi:" }, { "code": null, "e": 4130, "s": 4072, "text": "# pima loaded as a dataframe> pima$bmi[pima$bmi==0] <- NA" }, { "code": null, "e": 4210, "s": 4130, "text": "Notice the change in the summary of bmi. These values make more sense this way." }, { "code": null, "e": 4506, "s": 4210, "text": "Now take a look at test . This variable is supposed to be a binary indication for signs diabetes. Why is there a mean value? This clearly indicates that R recognizes the 1’s and 0’s as quantitative variables instead of categorical variables. Run class() to see how these values are treated in R:" }, { "code": null, "e": 4538, "s": 4506, "text": "> class(pima$test)[1] \"integer\"" }, { "code": null, "e": 4619, "s": 4538, "text": "To get R to handle this column as a categorical variable, you can use factor() :" }, { "code": null, "e": 4682, "s": 4619, "text": "> pima$test <- factor(pima$test)> class(pima$test)[1] \"factor\"" }, { "code": null, "e": 4829, "s": 4682, "text": "Detecting these instances are important — these unusual values can heavily bias prediction models and any conclusions that may be drawn from them." }, { "code": null, "e": 4997, "s": 4829, "text": "Visualizing your data in various ways can help you see things you may have missed out on in your early stages of exploration. Here are some of my go-to visualizations:" }, { "code": null, "e": 5235, "s": 4997, "text": "Continuing with the example earlier with the pima dataset, below is a histogram I plotted using ggplot2 and tidyr libraries. This method of visualization helps me to look at the frequency/count of points for each variable in the dataset:" }, { "code": null, "e": 5359, "s": 5235, "text": "> pima %>%+ gather() %>% + ggplot(aes(value)) ++ facet_wrap(~ key, scales = \"free\") ++ geom_histogram(stat=\"count\")" }, { "code": null, "e": 5683, "s": 5359, "text": "Just by visualizing your data, you can see that there are clearly a dominant number of missing values for the variables triceps and insulin. This goes to show that in this case, handling of missing data must be conducted carefully. Understanding why exactly so many values are missing might be an important feature to note." }, { "code": null, "e": 5787, "s": 5683, "text": "Note: You would see a similar visualization if you did not correct for the unusual 0 values previously." }, { "code": null, "e": 5883, "s": 5787, "text": "For details on the code for visualization using ggplot2 and tidyr, take a look at this website." }, { "code": null, "e": 6088, "s": 5883, "text": "A scatterplot matrix can help you see if some kind of a relationship exists between any two variables in your dataset. Take a look at this symmetric matrix of pairwise scatterplots using the iris dataset." }, { "code": null, "e": 6102, "s": 6088, "text": "> pairs(iris)" }, { "code": null, "e": 6349, "s": 6102, "text": "You can see, just by looking at the plots above, that there is some linearity between Petal.Length and Petal.Width . You have not even gotten to the modeling stage and you already have an insight about the variables you want to keep your eyes on!" }, { "code": null, "e": 6572, "s": 6349, "text": "This correlation matrix plot provides visual aid for understanding how two numeric type variables change in relation to each other. In other words, it is just literally just a visual representation of a correlation matrix." }, { "code": null, "e": 6812, "s": 6572, "text": "The function cor() is used to evaluate the correlation matrix, and the function corrplot() from the library corrplot is used to create a heat map based on the correlation matrix. Take a look at an example below using the same iris dataset." }, { "code": null, "e": 6921, "s": 6812, "text": "# use only numeric type variables> correlations <- cor(iris[,1:4])# correlation plot> corrplot(correlations)" }, { "code": null, "e": 7358, "s": 6921, "text": "You can see from the scale that a large positive correlation value is more blue, and a large negative correlation values is more red. So from this graph, it looks like Petal.Length and Petal.Width are strongly correlated and it also looks like there is a high correlation between Petal.Length and Sepal.Length . Note that the diagonal is perfectly positively correlated because it represents the correlation of the variable with itself." }, { "code": null, "e": 7545, "s": 7358, "text": "Although these conclusions are similar to those that were made earlier with the scatterplots, this method just provides a more concrete reason to believe that two attributes are related." }, { "code": null, "e": 8073, "s": 7545, "text": "Going through this process of understanding your data is vital for more than just the reasons I have mentioned. It might also eventually help you make informed decisions when it comes to selecting your model.The methods and processes I have outlined in this article are some of the ones I use most frequently whenever I get a new dataset. There are so many more visualizations that you can explore and experiment with using your dataset. Don’t hold yourself back. You’re just trying to look at your data and understand it here." } ]
Q Programming Language
Kdb+ comes with its built-in programming language that is known as q. It incorporates a superset of standard SQL which is extended for time-series analysis and offers many advantages over the standard version. Anyone familiar with SQL can learn q in a matter of days and be able to quickly write her own ad-hoc queries. To start using kdb+, you need to start the q session. There are three ways to start a q session − Simply type “c:/q/w32/q.exe” on your run terminal. Simply type “c:/q/w32/q.exe” on your run terminal. Start the MS-DOS command terminal and type q. Start the MS-DOS command terminal and type q. Copy the q.exe file onto “C:\Windows\System32” and on the run terminal, just type “q”. Copy the q.exe file onto “C:\Windows\System32” and on the run terminal, just type “q”. Here we are assuming that you are working on a Windows platform. The following table provides a list of supported data types − Atoms are single entities, e.g., a single number, a character or a symbol. In the above table (of different data types), all supported data types are atoms. A list is a sequence of atoms or other types including lists. Passing an atom of any type to the monadic (i.e. single argument function) type function will return a negative value, i.e., –n, whereas passing a simple list of those atoms to the type function will return a positive value n. / Note that the comments begin with a slash “ / ” and cause the parser / to ignore everything up to the end of the line. x: `mohan / `mohan is a symbol, assigned to a variable x type x / let’s check the type of x -11h / -ve sign, because it’s single element. y: (`abc;`bca;`cab) / list of three symbols, y is the variable name. type y 11h / +ve sign, as it contain list of atoms (symbol). y1: (`abc`bca`cab) / another way of writing y, please note NO semicolon y2: (`$”symbols may have interior blanks”) / string to symbol conversion y[0] / return `abc y 0 / same as y[0], also returns `abc y 0 2 / returns `abc`cab, same as does y[0 2] z: (`abc; 10 20 30; (`a`b); 9.9 8.8 7.7) / List of different types, z 2 0 / returns (`a`b; `abc), z[2;0] / return `a. first element of z[2] x: “Hello World!” / list of character, a string x 4 0 / returns “oH” i.e. 4th and 0th(first) element Print Add Notes Bookmark this page
[ { "code": null, "e": 2478, "s": 2158, "text": "Kdb+ comes with its built-in programming language that is known as q. It incorporates a superset of standard SQL which is extended for time-series analysis and offers many advantages over the standard version. Anyone familiar with SQL can learn q in a matter of days and be able to quickly write her own ad-hoc queries." }, { "code": null, "e": 2576, "s": 2478, "text": "To start using kdb+, you need to start the q session. There are three ways to start a q session −" }, { "code": null, "e": 2627, "s": 2576, "text": "Simply type “c:/q/w32/q.exe” on your run terminal." }, { "code": null, "e": 2678, "s": 2627, "text": "Simply type “c:/q/w32/q.exe” on your run terminal." }, { "code": null, "e": 2724, "s": 2678, "text": "Start the MS-DOS command terminal and type q." }, { "code": null, "e": 2770, "s": 2724, "text": "Start the MS-DOS command terminal and type q." }, { "code": null, "e": 2857, "s": 2770, "text": "Copy the q.exe file onto “C:\\Windows\\System32” and on the run terminal, just type “q”." }, { "code": null, "e": 2944, "s": 2857, "text": "Copy the q.exe file onto “C:\\Windows\\System32” and on the run terminal, just type “q”." }, { "code": null, "e": 3009, "s": 2944, "text": "Here we are assuming that you are working on a Windows platform." }, { "code": null, "e": 3071, "s": 3009, "text": "The following table provides a list of supported data types −" }, { "code": null, "e": 3290, "s": 3071, "text": "Atoms are single entities, e.g., a single number, a character or a symbol. In the above table (of different data types), all supported data types are atoms. A list is a sequence of atoms or other types including lists." }, { "code": null, "e": 3517, "s": 3290, "text": "Passing an atom of any type to the monadic (i.e. single argument function) type function will return a negative value, i.e., –n, whereas passing a simple list of those atoms to the type function will return a positive value n." }, { "code": null, "e": 4592, "s": 3517, "text": "/ Note that the comments begin with a slash “ / ” and cause the parser\n/ to ignore everything up to the end of the line.\n\nx: `mohan / `mohan is a symbol, assigned to a variable x\ntype x / let’s check the type of x\n-11h / -ve sign, because it’s single element.\n\ny: (`abc;`bca;`cab) / list of three symbols, y is the variable name.\n\ntype y\n11h / +ve sign, as it contain list of atoms (symbol).\n\ny1: (`abc`bca`cab) / another way of writing y, please note NO semicolon\n\ny2: (`$”symbols may have interior blanks”) / string to symbol conversion\ny[0] / return `abc\ny 0 / same as y[0], also returns `abc\ny 0 2 / returns `abc`cab, same as does y[0 2]\n\nz: (`abc; 10 20 30; (`a`b); 9.9 8.8 7.7) / List of different types,\nz 2 0 / returns (`a`b; `abc),\nz[2;0] / return `a. first element of z[2]\n\nx: “Hello World!” / list of character, a string\nx 4 0 / returns “oH” i.e. 4th and 0th(first)\nelement\n" }, { "code": null, "e": 4599, "s": 4592, "text": " Print" }, { "code": null, "e": 4610, "s": 4599, "text": " Add Notes" } ]
How to group and aggregate data using SQL | by Kate Marie Lewis | Towards Data Science
I have been so enjoying engaging with my friends to share my love of data science. We are powering through learning SQL, with three lessons under our belt already. If you would like to start at the beginning here is a link to the first lesson. All of the lessons can also be found here. Otherwise, get stuck into this lesson on grouping and aggregating data using SQL. Last week, we covered filtering data using SQL. Using one of my favourite shows, Charmed for example data, we went through using WHERE clauses in queries. In addition, we explored the use of the keywords IN, AND, OR, LIKE, BETWEEN and NOT. Now that we know how to filter data, we will move onto aggregation. We will learn how to use the keywords MIN and MAX to find the minimum and maximum of our data respectively. We will also practice using the COUNT, AVG and SUM keywords in a similar manner. This will also be the first lesson that we have encountered NULL values. So we will learn how to deal with them in our datasets. It just so happens that all of the friends I am teaching data science to, whilst self-isolating are women. So what better example to use in this lesson than the Spice Girls to celebrate a bit of girl power. We will use data on the first Spice Girls album titled Spice. This is one that was on high rotation in my house growing up. use the keyword MIN to find the minimum value in a column use the keyword MAX to find the maximum value in a column use the keyword COUNT to count the number of rows in a column or table use the keyword AVG to find the mean of a numerical column use the keyword SUM to find the total of a numerical column when all the values are added together use the keyword GROUP BY to group by a column in a table know how NULL values will be handled in each of the above methods understand how aliases work and how to use the AS keyword to create them I think that the first Spice Girls album is the best one. Just in case people don’t believe me, I want to find some data to back it up. Using Australian charts data for the singles released from each Spice Girls album, I think I can prove the first one rules! This dataset contains information on all the tracks in each album that the Spice Girls released. The table contains the length of each track, when each single was released, what position the song peaked at in the Australian charts and how many weeks the song was in the Australian charts. I didn’t include the greatest hits album because I thought that would confuse matters. I got the data for this table from the Spice Girls discography Wikipedia page, the Spice(album) Wikipedia page, Spice World(album) Wikipedia page, Forever(Spice Girls Album) and on an Australian charts website. In this lesson I will teach you how to use the aggregating keywords MIN, MAX, COUNT, SUM and AVG in the SELECT statement. These aggregators may also be used elsewhere in queries. For example, they can be used in a HAVING clause, but that is beyond the scope of this lesson. I have written another story comparing WHERE and HAVING in SQL in case you want to learn more. The MAX keyword can be used to find the maximum value within a column. It can be used on many different datatypes including integers, floats, strings and dates. As you can see below, the syntax to use MAX involves putting the MAX keyword inside the select statement. The MAX keyword has a set of brackets after it, which is where you put the column name you want to find the maximum value of. SELECT MAX(name_column_one) AS 'largest_col_one'FROM name_of_table; Another useful keyword that can be used in conjunction with aggregators is AS. AS is used to create an alias or temporary name for the column created by the aggregator in the returned table. Since the aggregator has been used on column 1, it is useful to give the result a new name so that it is easily identifiable in the resulting table. The keyword AS may also be used to give an alias to a table, but we will cover that in our lesson on joining tables. The MIN keyword is used in much the same way as the MAX keyword. As you would expect, it is used to return the minimum value of the selected column. SELECT MIN(name_column_two) AS 'smallest_col_two'FROM name_of_table; COUNT is a keyword used to count the number of rows in the selected column. So in the example below it would count the total number of rows in the table. SELECT COUNT(name_column_three) AS 'col_three_counts'FROM name_of_table; However, COUNT is more useful when there is some filter or grouping applied to the table. In that case you would be counting the number of rows in the table that meet the filter or grouping conditions. SELECT COUNT(name_column_three) AS 'col_three_counts'FROM name_of_tableWHERE name_column_one = value; Unlike MIN, MAX and COUNT, the keywords SUM and AVG are only able to be used on columns that contain numeric datatypes like integers or floats. AVG is used to return the average value of a column. SELECT AVG(name_column_four) AS 'mean_col_four'FROM name_of_table; SUM adds together the values in a numeric column. The syntax to use SUM is the same as the other aggregators. SELECT SUM(name_column_five) AS 'summed_col_five'FROM name_of_table; Grouping is very useful for summarising data that has repeated values. It is often used in conjunction with the aggregators MIN, MAX, COUNT, SUM and AVG. GROUP BY collects together identical values in the column it is applied to. Then an aggregator can be used on another column based on those groupings. The GROUP BY clause will often be used on a column that contains category values. For example, if you use the AVG aggregator with GROUP BY you can find the average value for one column for each group of values in another column. The syntax for this example is shown below. In this case the table returned would contain the average value from column one for each value in column two. SELECT AVG(name_column_one) AS mean_col_one, name_column_twoFROM name_of_tableGROUP BY name_column_two; A NULL value is what happens when a field has no value entered. So it is like a placeholder to let you know that there is an empty space in the table. It is different from a 0 value or an empty string ‘’ as they are still values. NULL has its own keywords. You can check for NULL values in a column using the IS NULL keyword. This is done in the WHERE statement and will return only the records that contain NULL values in the column specified in the WHERE statement. SELECT *FROM name_of_tableWHERE name_column_one IS NULL; However, the more common scenario would be where you want to exclude all records that contain NULL values. In that case you can add the NOT keyword to your query. In the example below only the records that have no NULL values in column two will be included in the returned table. SELECT *FROM name_of_tableWHERE name_column_two IS NOT NULL; NULL values are ignored by aggregate keywords MIN, MAX, AVG, SUM and COUNT. For MIN and MAX it is fairly straight forward, you will get the minimum or maximum value in the column ignoring all NULL values. Similarly for SUM, all the values in the column that are not NULL will be added together. For AVG you get the average value of the column when all NULL values are removed. COUNT is only slightly more tricky, all the rows in the selected column will be counted, except for the rows containing NULL values. The only exception to that rule is shown below. In this case all of the rows of the table will be counted, regardless of whether there are NULL values. SELECT COUNT(*)FROM name_of_table; In contrast to the aggregators, GROUP BY does not ignore NULL values. Instead they are grouped together as a single grouping category. go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)In the left hand box put the CREATE TABLE and INSERT INTO queries below go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently) In the left hand box put the CREATE TABLE and INSERT INTO queries below CREATE TABLE spice_girls( album varchar(255), title varchar(255), length TIME(0), track_number int, single_released date, peak_chart_position_au int, chart_weeks_au int);INSERT INTO spice_girls( album, title, length, track_number, single_released, peak_chart_position_au, chart_weeks_au)VALUES ("Spice", "Wannabe", '000:02:53', 1, '1996-07-08', 1, 29), ("Spice", "Say You'll Be There", '000:03:55', 2, '1996-10-10', 12, 22), ("Spice", "2 Become 1", '000:04:01', 3, '1996-12-16', 2, 18), ("Spice", "Love Thing", '000:03:38', 4, NULL, NULL, NULL), ("Spice", "Last Time Lover", '000:04:11', 5, NULL, NULL, NULL), ("Spice", "Mama", '000:05:04', 6, '1997-02-27', 13, 14), ("Spice", "Who Do You Think You Are", '000:04:00', 7, '1997-02-27', 13, 14), ("Spice", "Something Kinda Funny", '000:04:05', 8, NULL, NULL, NULL), ("Spice", "Naked", '000:04:25', 9, NULL, NULL, NULL), ("Spice", "If U Can't Dance", '000:03:48', 10, NULL, NULL, NULL), ("Spice World", "Spice Up Your Life", '000:02:53', 1, '1997-10-06', 8, 20), ("Spice World", "Stop", '000:03:24', 2, '1997-01-01', 5, 21), ("Spice World", "Too Much", '000:04:31', 3, '1997-12-08', 9, 15), ("Spice World", "Saturday Night Divas", '000:04:25', 4, NULL, NULL, NULL), ("Spice World", "Never Give Up on the Good Times", '000:04:30', 5, NULL, NULL, NULL), ("Spice World", "Move Over", '000:02:46', 6, NULL, NULL, NULL), ("Spice World", "Do It", '000:04:04', 7, NULL, NULL, NULL), ("Spice World", "Denying", '000:03:46', 8, NULL, NULL, NULL), ("Spice World", "Viva Forever", '000:05:09', 9, '1998-07-20', 2, 21), ("Spice World", "The Lady Is a Vamp", '000:03:09', 10, NULL, NULL, NULL), ("Forever", "Holler", '000:04:15', 1, '2000-10-23', 2, 15), ("Forever", "Tell Me Why", '000:04:13', 2, NULL, NULL, NULL), ("Forever", "Let Love Lead the Way", '000:04:57', 3, '2000-10-23', 2, NULL), ("Forever", "Right Back at Ya", '000:04:09', 4, NULL, NULL, NULL), ("Forever", "Get Down with Me", '000:03:45', 5, NULL, NULL, NULL), ("Forever", "Wasting My Time", '000:04:13', 6, NULL, NULL, NULL), ("Forever", "Weekend Love", '000:04:04', 7, NULL, NULL, NULL), ("Forever", "Time Goes By", '000:04:51', 8, NULL, NULL, NULL), ("Forever", "If You Wanna Have Some Fun", '000:05:25', 9, NULL, NULL, NULL), ("Forever", "Oxygen", '000:04:55', 10, NULL, NULL, NULL), ("Forever", "Goodbye", '000:04:35', 11, '1998-12-07', 3, 16); Note about special characters: In creating this table we come across a new syntactical nuance that we have not seen in the previous lessons. Some of the song names contain apostrophes. So if we surrounded the song name strings with single quotation marks ‘’ like we normally would, there would be an error. This is because the apostrophe would be confused for the closing quotation by the program. So to include a string containing an apostrophe in our table we need to use double quotations around the strings. The reverse can also be done if you need to have a string that contains double quotations. If you would like to learn more about special characters like quotations, this is a great resource. Note about TIME datatype: There is also a datatype in this table that we have not seen in any of the previous lessons. It is the TIME datatype. Time has the format ‘hours:minutes:seconds’. 3. Click the build schema button 4. In the right hand box put your queries 5. Run the query below and see if it returns what you would expect it to: SELECT SUM(length) AS 'total_length'FROM spice_girls; 6. Run the query below and see if it returns what you would expect it to: SELECT SUM(length) AS 'album_length', albumFROM spice_girlsGROUP BY album; 7. Run the query below and see if it returns what you would expect it to: SELECT album, SUM(length) AS 'album_length', AVG(length) AS 'average_song_length', COUNT(length) AS 'number_of_songs', MIN(length) AS 'shortest_song_length', MAX(length) AS 'longest_song_length'FROM spice_girlsGROUP BY albumORDER BY album; Exercise 1: Write a query to show which album is the best, if we define the best album as the one with the highest peak chart position of one of its singles. Exercise 2: Write a query to show which album is the best, if we define the best album as the one with the highest average peak chart position of all of the singles in the album. Exercise 3: Write a query to show which album is the best, if we define the best album as the one with the highest number of singles in the Australian charts for at least 5 weeks. After completing this lesson you should know: how to use the keyword MIN to find the minimum value in a column how to use the keyword MAX to find the maximum value in a column how to use the keyword COUNT to count the number of rows in a column or table how to use the keyword AVG to find the mean of a numerical column how to use the keyword SUM to find the total of a numerical column when all the values are added together how to use the keyword GROUP BY to group by a column in a table understand how NULL values are handled be able to write your own queries using one or more of the above methods be able to use the AS keyword to create an alias for an aggregated column Next week will be our final SQL lesson. We will learn how to join tables together. There are several different ways that we can combine datasets, using the UNION, UNION ALL and JOIN keywords. If you are eager to get into looking at joins before next week I have previously written an article about the difference between inner and outer joins in SQL. In addition to data, my other passion is painting. You can find my wildlife art at www.katemarielewis.com
[ { "code": null, "e": 540, "s": 171, "text": "I have been so enjoying engaging with my friends to share my love of data science. We are powering through learning SQL, with three lessons under our belt already. If you would like to start at the beginning here is a link to the first lesson. All of the lessons can also be found here. Otherwise, get stuck into this lesson on grouping and aggregating data using SQL." }, { "code": null, "e": 780, "s": 540, "text": "Last week, we covered filtering data using SQL. Using one of my favourite shows, Charmed for example data, we went through using WHERE clauses in queries. In addition, we explored the use of the keywords IN, AND, OR, LIKE, BETWEEN and NOT." }, { "code": null, "e": 1037, "s": 780, "text": "Now that we know how to filter data, we will move onto aggregation. We will learn how to use the keywords MIN and MAX to find the minimum and maximum of our data respectively. We will also practice using the COUNT, AVG and SUM keywords in a similar manner." }, { "code": null, "e": 1166, "s": 1037, "text": "This will also be the first lesson that we have encountered NULL values. So we will learn how to deal with them in our datasets." }, { "code": null, "e": 1497, "s": 1166, "text": "It just so happens that all of the friends I am teaching data science to, whilst self-isolating are women. So what better example to use in this lesson than the Spice Girls to celebrate a bit of girl power. We will use data on the first Spice Girls album titled Spice. This is one that was on high rotation in my house growing up." }, { "code": null, "e": 1555, "s": 1497, "text": "use the keyword MIN to find the minimum value in a column" }, { "code": null, "e": 1613, "s": 1555, "text": "use the keyword MAX to find the maximum value in a column" }, { "code": null, "e": 1684, "s": 1613, "text": "use the keyword COUNT to count the number of rows in a column or table" }, { "code": null, "e": 1743, "s": 1684, "text": "use the keyword AVG to find the mean of a numerical column" }, { "code": null, "e": 1842, "s": 1743, "text": "use the keyword SUM to find the total of a numerical column when all the values are added together" }, { "code": null, "e": 1899, "s": 1842, "text": "use the keyword GROUP BY to group by a column in a table" }, { "code": null, "e": 1965, "s": 1899, "text": "know how NULL values will be handled in each of the above methods" }, { "code": null, "e": 2038, "s": 1965, "text": "understand how aliases work and how to use the AS keyword to create them" }, { "code": null, "e": 2298, "s": 2038, "text": "I think that the first Spice Girls album is the best one. Just in case people don’t believe me, I want to find some data to back it up. Using Australian charts data for the singles released from each Spice Girls album, I think I can prove the first one rules!" }, { "code": null, "e": 2674, "s": 2298, "text": "This dataset contains information on all the tracks in each album that the Spice Girls released. The table contains the length of each track, when each single was released, what position the song peaked at in the Australian charts and how many weeks the song was in the Australian charts. I didn’t include the greatest hits album because I thought that would confuse matters." }, { "code": null, "e": 2885, "s": 2674, "text": "I got the data for this table from the Spice Girls discography Wikipedia page, the Spice(album) Wikipedia page, Spice World(album) Wikipedia page, Forever(Spice Girls Album) and on an Australian charts website." }, { "code": null, "e": 3254, "s": 2885, "text": "In this lesson I will teach you how to use the aggregating keywords MIN, MAX, COUNT, SUM and AVG in the SELECT statement. These aggregators may also be used elsewhere in queries. For example, they can be used in a HAVING clause, but that is beyond the scope of this lesson. I have written another story comparing WHERE and HAVING in SQL in case you want to learn more." }, { "code": null, "e": 3415, "s": 3254, "text": "The MAX keyword can be used to find the maximum value within a column. It can be used on many different datatypes including integers, floats, strings and dates." }, { "code": null, "e": 3647, "s": 3415, "text": "As you can see below, the syntax to use MAX involves putting the MAX keyword inside the select statement. The MAX keyword has a set of brackets after it, which is where you put the column name you want to find the maximum value of." }, { "code": null, "e": 3722, "s": 3647, "text": "SELECT MAX(name_column_one) AS 'largest_col_one'FROM name_of_table;" }, { "code": null, "e": 4179, "s": 3722, "text": "Another useful keyword that can be used in conjunction with aggregators is AS. AS is used to create an alias or temporary name for the column created by the aggregator in the returned table. Since the aggregator has been used on column 1, it is useful to give the result a new name so that it is easily identifiable in the resulting table. The keyword AS may also be used to give an alias to a table, but we will cover that in our lesson on joining tables." }, { "code": null, "e": 4328, "s": 4179, "text": "The MIN keyword is used in much the same way as the MAX keyword. As you would expect, it is used to return the minimum value of the selected column." }, { "code": null, "e": 4404, "s": 4328, "text": "SELECT MIN(name_column_two) AS 'smallest_col_two'FROM name_of_table;" }, { "code": null, "e": 4558, "s": 4404, "text": "COUNT is a keyword used to count the number of rows in the selected column. So in the example below it would count the total number of rows in the table." }, { "code": null, "e": 4638, "s": 4558, "text": "SELECT COUNT(name_column_three) AS 'col_three_counts'FROM name_of_table;" }, { "code": null, "e": 4840, "s": 4638, "text": "However, COUNT is more useful when there is some filter or grouping applied to the table. In that case you would be counting the number of rows in the table that meet the filter or grouping conditions." }, { "code": null, "e": 4952, "s": 4840, "text": "SELECT COUNT(name_column_three) AS 'col_three_counts'FROM name_of_tableWHERE name_column_one = value;" }, { "code": null, "e": 5149, "s": 4952, "text": "Unlike MIN, MAX and COUNT, the keywords SUM and AVG are only able to be used on columns that contain numeric datatypes like integers or floats. AVG is used to return the average value of a column." }, { "code": null, "e": 5223, "s": 5149, "text": "SELECT AVG(name_column_four) AS 'mean_col_four'FROM name_of_table;" }, { "code": null, "e": 5333, "s": 5223, "text": "SUM adds together the values in a numeric column. The syntax to use SUM is the same as the other aggregators." }, { "code": null, "e": 5409, "s": 5333, "text": "SELECT SUM(name_column_five) AS 'summed_col_five'FROM name_of_table;" }, { "code": null, "e": 5796, "s": 5409, "text": "Grouping is very useful for summarising data that has repeated values. It is often used in conjunction with the aggregators MIN, MAX, COUNT, SUM and AVG. GROUP BY collects together identical values in the column it is applied to. Then an aggregator can be used on another column based on those groupings. The GROUP BY clause will often be used on a column that contains category values." }, { "code": null, "e": 6097, "s": 5796, "text": "For example, if you use the AVG aggregator with GROUP BY you can find the average value for one column for each group of values in another column. The syntax for this example is shown below. In this case the table returned would contain the average value from column one for each value in column two." }, { "code": null, "e": 6212, "s": 6097, "text": "SELECT AVG(name_column_one) AS mean_col_one, name_column_twoFROM name_of_tableGROUP BY name_column_two;" }, { "code": null, "e": 6469, "s": 6212, "text": "A NULL value is what happens when a field has no value entered. So it is like a placeholder to let you know that there is an empty space in the table. It is different from a 0 value or an empty string ‘’ as they are still values. NULL has its own keywords." }, { "code": null, "e": 6680, "s": 6469, "text": "You can check for NULL values in a column using the IS NULL keyword. This is done in the WHERE statement and will return only the records that contain NULL values in the column specified in the WHERE statement." }, { "code": null, "e": 6747, "s": 6680, "text": "SELECT *FROM name_of_tableWHERE name_column_one IS NULL;" }, { "code": null, "e": 7027, "s": 6747, "text": "However, the more common scenario would be where you want to exclude all records that contain NULL values. In that case you can add the NOT keyword to your query. In the example below only the records that have no NULL values in column two will be included in the returned table." }, { "code": null, "e": 7098, "s": 7027, "text": "SELECT *FROM name_of_tableWHERE name_column_two IS NOT NULL;" }, { "code": null, "e": 7475, "s": 7098, "text": "NULL values are ignored by aggregate keywords MIN, MAX, AVG, SUM and COUNT. For MIN and MAX it is fairly straight forward, you will get the minimum or maximum value in the column ignoring all NULL values. Similarly for SUM, all the values in the column that are not NULL will be added together. For AVG you get the average value of the column when all NULL values are removed." }, { "code": null, "e": 7760, "s": 7475, "text": "COUNT is only slightly more tricky, all the rows in the selected column will be counted, except for the rows containing NULL values. The only exception to that rule is shown below. In this case all of the rows of the table will be counted, regardless of whether there are NULL values." }, { "code": null, "e": 7803, "s": 7760, "text": "SELECT COUNT(*)FROM name_of_table;" }, { "code": null, "e": 7938, "s": 7803, "text": "In contrast to the aggregators, GROUP BY does not ignore NULL values. Instead they are grouped together as a single grouping category." }, { "code": null, "e": 8139, "s": 7938, "text": "go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)In the left hand box put the CREATE TABLE and INSERT INTO queries below" }, { "code": null, "e": 8269, "s": 8139, "text": "go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)" }, { "code": null, "e": 8341, "s": 8269, "text": "In the left hand box put the CREATE TABLE and INSERT INTO queries below" }, { "code": null, "e": 10839, "s": 8341, "text": "CREATE TABLE spice_girls( album varchar(255), title varchar(255), length TIME(0), track_number int, single_released date, peak_chart_position_au int, chart_weeks_au int);INSERT INTO spice_girls( album, title, length, track_number, single_released, peak_chart_position_au, chart_weeks_au)VALUES (\"Spice\", \"Wannabe\", '000:02:53', 1, '1996-07-08', 1, 29), (\"Spice\", \"Say You'll Be There\", '000:03:55', 2, '1996-10-10', 12, 22), (\"Spice\", \"2 Become 1\", '000:04:01', 3, '1996-12-16', 2, 18), (\"Spice\", \"Love Thing\", '000:03:38', 4, NULL, NULL, NULL), (\"Spice\", \"Last Time Lover\", '000:04:11', 5, NULL, NULL, NULL), (\"Spice\", \"Mama\", '000:05:04', 6, '1997-02-27', 13, 14), (\"Spice\", \"Who Do You Think You Are\", '000:04:00', 7, '1997-02-27', 13, 14), (\"Spice\", \"Something Kinda Funny\", '000:04:05', 8, NULL, NULL, NULL), (\"Spice\", \"Naked\", '000:04:25', 9, NULL, NULL, NULL), (\"Spice\", \"If U Can't Dance\", '000:03:48', 10, NULL, NULL, NULL), (\"Spice World\", \"Spice Up Your Life\", '000:02:53', 1, '1997-10-06', 8, 20), (\"Spice World\", \"Stop\", '000:03:24', 2, '1997-01-01', 5, 21), (\"Spice World\", \"Too Much\", '000:04:31', 3, '1997-12-08', 9, 15), (\"Spice World\", \"Saturday Night Divas\", '000:04:25', 4, NULL, NULL, NULL), (\"Spice World\", \"Never Give Up on the Good Times\", '000:04:30', 5, NULL, NULL, NULL), (\"Spice World\", \"Move Over\", '000:02:46', 6, NULL, NULL, NULL), (\"Spice World\", \"Do It\", '000:04:04', 7, NULL, NULL, NULL), (\"Spice World\", \"Denying\", '000:03:46', 8, NULL, NULL, NULL), (\"Spice World\", \"Viva Forever\", '000:05:09', 9, '1998-07-20', 2, 21), (\"Spice World\", \"The Lady Is a Vamp\", '000:03:09', 10, NULL, NULL, NULL), (\"Forever\", \"Holler\", '000:04:15', 1, '2000-10-23', 2, 15), (\"Forever\", \"Tell Me Why\", '000:04:13', 2, NULL, NULL, NULL), (\"Forever\", \"Let Love Lead the Way\", '000:04:57', 3, '2000-10-23', 2, NULL), (\"Forever\", \"Right Back at Ya\", '000:04:09', 4, NULL, NULL, NULL), (\"Forever\", \"Get Down with Me\", '000:03:45', 5, NULL, NULL, NULL), (\"Forever\", \"Wasting My Time\", '000:04:13', 6, NULL, NULL, NULL), (\"Forever\", \"Weekend Love\", '000:04:04', 7, NULL, NULL, NULL), (\"Forever\", \"Time Goes By\", '000:04:51', 8, NULL, NULL, NULL), (\"Forever\", \"If You Wanna Have Some Fun\", '000:05:25', 9, NULL, NULL, NULL), (\"Forever\", \"Oxygen\", '000:04:55', 10, NULL, NULL, NULL), (\"Forever\", \"Goodbye\", '000:04:35', 11, '1998-12-07', 3, 16);" }, { "code": null, "e": 11351, "s": 10839, "text": "Note about special characters: In creating this table we come across a new syntactical nuance that we have not seen in the previous lessons. Some of the song names contain apostrophes. So if we surrounded the song name strings with single quotation marks ‘’ like we normally would, there would be an error. This is because the apostrophe would be confused for the closing quotation by the program. So to include a string containing an apostrophe in our table we need to use double quotations around the strings." }, { "code": null, "e": 11542, "s": 11351, "text": "The reverse can also be done if you need to have a string that contains double quotations. If you would like to learn more about special characters like quotations, this is a great resource." }, { "code": null, "e": 11731, "s": 11542, "text": "Note about TIME datatype: There is also a datatype in this table that we have not seen in any of the previous lessons. It is the TIME datatype. Time has the format ‘hours:minutes:seconds’." }, { "code": null, "e": 11764, "s": 11731, "text": "3. Click the build schema button" }, { "code": null, "e": 11806, "s": 11764, "text": "4. In the right hand box put your queries" }, { "code": null, "e": 11880, "s": 11806, "text": "5. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 11941, "s": 11880, "text": "SELECT SUM(length) AS 'total_length'FROM spice_girls;" }, { "code": null, "e": 12015, "s": 11941, "text": "6. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 12105, "s": 12015, "text": "SELECT SUM(length) AS 'album_length', albumFROM spice_girlsGROUP BY album;" }, { "code": null, "e": 12179, "s": 12105, "text": "7. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 12450, "s": 12179, "text": "SELECT album, SUM(length) AS 'album_length', AVG(length) AS 'average_song_length', COUNT(length) AS 'number_of_songs', MIN(length) AS 'shortest_song_length', MAX(length) AS 'longest_song_length'FROM spice_girlsGROUP BY albumORDER BY album;" }, { "code": null, "e": 12608, "s": 12450, "text": "Exercise 1: Write a query to show which album is the best, if we define the best album as the one with the highest peak chart position of one of its singles." }, { "code": null, "e": 12787, "s": 12608, "text": "Exercise 2: Write a query to show which album is the best, if we define the best album as the one with the highest average peak chart position of all of the singles in the album." }, { "code": null, "e": 12967, "s": 12787, "text": "Exercise 3: Write a query to show which album is the best, if we define the best album as the one with the highest number of singles in the Australian charts for at least 5 weeks." }, { "code": null, "e": 13013, "s": 12967, "text": "After completing this lesson you should know:" }, { "code": null, "e": 13078, "s": 13013, "text": "how to use the keyword MIN to find the minimum value in a column" }, { "code": null, "e": 13143, "s": 13078, "text": "how to use the keyword MAX to find the maximum value in a column" }, { "code": null, "e": 13221, "s": 13143, "text": "how to use the keyword COUNT to count the number of rows in a column or table" }, { "code": null, "e": 13287, "s": 13221, "text": "how to use the keyword AVG to find the mean of a numerical column" }, { "code": null, "e": 13393, "s": 13287, "text": "how to use the keyword SUM to find the total of a numerical column when all the values are added together" }, { "code": null, "e": 13457, "s": 13393, "text": "how to use the keyword GROUP BY to group by a column in a table" }, { "code": null, "e": 13496, "s": 13457, "text": "understand how NULL values are handled" }, { "code": null, "e": 13569, "s": 13496, "text": "be able to write your own queries using one or more of the above methods" }, { "code": null, "e": 13643, "s": 13569, "text": "be able to use the AS keyword to create an alias for an aggregated column" }, { "code": null, "e": 13994, "s": 13643, "text": "Next week will be our final SQL lesson. We will learn how to join tables together. There are several different ways that we can combine datasets, using the UNION, UNION ALL and JOIN keywords. If you are eager to get into looking at joins before next week I have previously written an article about the difference between inner and outer joins in SQL." } ]
Deep embedding’s for categorical variables (Cat2Vec) | by Prajwal Shreyas | Towards Data Science
In this blog I am going to take you through the steps involved in creating a embedding for categorical variables using a deep learning network on top of keras. The concept was originally introduced by Jeremy Howard in his fastai course. Please see the link for more details. Across most of the data sources that we work with we will come across mainly two types of variables: Continuous variables: These are usually integer or decimal numbers and have infinite number of possible values e.g. Computer memory units i.e 1GB, 2GB etc..Categorical variables: These are discrete variables which is used to split the data based on certain characteristics. e.g. Types of computer memory i.e. RAM memory, internal hard disk, external hard disk etc. Continuous variables: These are usually integer or decimal numbers and have infinite number of possible values e.g. Computer memory units i.e 1GB, 2GB etc.. Categorical variables: These are discrete variables which is used to split the data based on certain characteristics. e.g. Types of computer memory i.e. RAM memory, internal hard disk, external hard disk etc. When we build a ML model more often then not it is required for us to transform the categorical variable before we can use it in the algorithm. The transformation applied has a big impact on the performance of the model, especially if the data has a large number of categorical features with high cardinality. Example’s of some of the usual transformation’s applied include: One-Hot encoding: Here we convert each category value into a new column and assign and assign a 1 or 0(True/False) value to the column. Binary encoding: This creates fewer features than one-hot, while preserving some uniqueness of values in the the column. It can work well with higher dimensional ordinal data. These usual transformation’s however do not capture the relationship between the categorical variables. Please see the below link for more information on different type of encoding methods. To demonstrate the application of deep embedding’s let’s take an example of the bicycle sharing data from Kaggle. Also link to the git repo is here. As we can see there are a number of columns in the data set. In order to demonstrate this concept we shall use just the date_dt, cnt and mnth columns from the data. Traditional one-hot encoding would result in 12 columns, one of each month. However in this type of embedding equal importance is given to each day of the week and there is no relationship between each of the months. We can see a seasonal pattern’s of each of the months in the below graph. As we can see months 4 to 9 are the peak months. Months 0, 1, 10,11 are months of low demand for bike hire. Additionally when we plot the daily usage for each month, represented by a different colour, we cam see some weekly patterns within each month. Ideally we would expect such relationships to be captured by use of embeddings. In the next section we will examine the generation of these embeddings using a deep network built on top of keras. The code is as shown below. We will build a perceptron network with dense layer network and a ‘relu’ activation function. The input for the network i.e. ‘x’ variable is the month number. This is a numeric representation of each of the months in the year and ranges from 0 to 11. Hence the input_dim is set to 12. The output for the network i.e. ‘y’ is a scaled column of ‘cnt’. However ‘y’ can be increased to include other continuous variables. Here as we are using a single continuous variable we will set the last number of the output dense layer to 1. We will train the model for 50 iterations or epochs. embedding_size = 3model = models.Sequential()model.add(Embedding(input_dim = 12, output_dim = embedding_size, input_length = 1, name="embedding"))model.add(Flatten())model.add(Dense(50, activation="relu"))model.add(Dense(15, activation="relu"))model.add(Dense(1))model.compile(loss = "mse", optimizer = "adam", metrics=["accuracy"])model.fit(x = data_small_df['mnth'].as_matrix(), y=data_small_df['cnt_Scaled'].as_matrix() , epochs = 50, batch_size = 4) Embedding Layer: Here we specify the embedding size for our categorical variable. I have used 3 in this case, if we were to increase this it will capture more details on the relationship between the categorical variables. Jeremy Howard suggests the following solution for choosing embedding sizes: # m is the no of categories per featureembedding_size = min(50, m+1/ 2) We are using an “adam” optimiser with a mean-square error loss function. Adam is preferred to sgd (stochastic gradient descent) as it is much faster optimiser due to its adaptive learning rate. You can find more details on the different types of optimisers here. The final resulting embedding for each of the months are as follows. Here ‘0’ is for January and ‘11’ for December. When we visualise this using a 3D plot, we can see a clear relationship between the months. The months with similar ‘cnt’ are grouped closer together e.g. months 4 to 9 are very similar to each other. In conclusion we have seen that by using Cat2Vec (categorical variable to vectors) we can represent high cardinality categorical variable using low dimension embedding while preserving the relationship between each of the categories. In the next few blogs we will explore on how we can use these embeddings to build supervised and unsupervised machine learning models with better performance.
[ { "code": null, "e": 447, "s": 172, "text": "In this blog I am going to take you through the steps involved in creating a embedding for categorical variables using a deep learning network on top of keras. The concept was originally introduced by Jeremy Howard in his fastai course. Please see the link for more details." }, { "code": null, "e": 548, "s": 447, "text": "Across most of the data sources that we work with we will come across mainly two types of variables:" }, { "code": null, "e": 913, "s": 548, "text": "Continuous variables: These are usually integer or decimal numbers and have infinite number of possible values e.g. Computer memory units i.e 1GB, 2GB etc..Categorical variables: These are discrete variables which is used to split the data based on certain characteristics. e.g. Types of computer memory i.e. RAM memory, internal hard disk, external hard disk etc." }, { "code": null, "e": 1070, "s": 913, "text": "Continuous variables: These are usually integer or decimal numbers and have infinite number of possible values e.g. Computer memory units i.e 1GB, 2GB etc.." }, { "code": null, "e": 1279, "s": 1070, "text": "Categorical variables: These are discrete variables which is used to split the data based on certain characteristics. e.g. Types of computer memory i.e. RAM memory, internal hard disk, external hard disk etc." }, { "code": null, "e": 1654, "s": 1279, "text": "When we build a ML model more often then not it is required for us to transform the categorical variable before we can use it in the algorithm. The transformation applied has a big impact on the performance of the model, especially if the data has a large number of categorical features with high cardinality. Example’s of some of the usual transformation’s applied include:" }, { "code": null, "e": 1790, "s": 1654, "text": "One-Hot encoding: Here we convert each category value into a new column and assign and assign a 1 or 0(True/False) value to the column." }, { "code": null, "e": 1966, "s": 1790, "text": "Binary encoding: This creates fewer features than one-hot, while preserving some uniqueness of values in the the column. It can work well with higher dimensional ordinal data." }, { "code": null, "e": 2156, "s": 1966, "text": "These usual transformation’s however do not capture the relationship between the categorical variables. Please see the below link for more information on different type of encoding methods." }, { "code": null, "e": 2305, "s": 2156, "text": "To demonstrate the application of deep embedding’s let’s take an example of the bicycle sharing data from Kaggle. Also link to the git repo is here." }, { "code": null, "e": 2470, "s": 2305, "text": "As we can see there are a number of columns in the data set. In order to demonstrate this concept we shall use just the date_dt, cnt and mnth columns from the data." }, { "code": null, "e": 2687, "s": 2470, "text": "Traditional one-hot encoding would result in 12 columns, one of each month. However in this type of embedding equal importance is given to each day of the week and there is no relationship between each of the months." }, { "code": null, "e": 2869, "s": 2687, "text": "We can see a seasonal pattern’s of each of the months in the below graph. As we can see months 4 to 9 are the peak months. Months 0, 1, 10,11 are months of low demand for bike hire." }, { "code": null, "e": 3013, "s": 2869, "text": "Additionally when we plot the daily usage for each month, represented by a different colour, we cam see some weekly patterns within each month." }, { "code": null, "e": 3208, "s": 3013, "text": "Ideally we would expect such relationships to be captured by use of embeddings. In the next section we will examine the generation of these embeddings using a deep network built on top of keras." }, { "code": null, "e": 3330, "s": 3208, "text": "The code is as shown below. We will build a perceptron network with dense layer network and a ‘relu’ activation function." }, { "code": null, "e": 3521, "s": 3330, "text": "The input for the network i.e. ‘x’ variable is the month number. This is a numeric representation of each of the months in the year and ranges from 0 to 11. Hence the input_dim is set to 12." }, { "code": null, "e": 3817, "s": 3521, "text": "The output for the network i.e. ‘y’ is a scaled column of ‘cnt’. However ‘y’ can be increased to include other continuous variables. Here as we are using a single continuous variable we will set the last number of the output dense layer to 1. We will train the model for 50 iterations or epochs." }, { "code": null, "e": 4271, "s": 3817, "text": "embedding_size = 3model = models.Sequential()model.add(Embedding(input_dim = 12, output_dim = embedding_size, input_length = 1, name=\"embedding\"))model.add(Flatten())model.add(Dense(50, activation=\"relu\"))model.add(Dense(15, activation=\"relu\"))model.add(Dense(1))model.compile(loss = \"mse\", optimizer = \"adam\", metrics=[\"accuracy\"])model.fit(x = data_small_df['mnth'].as_matrix(), y=data_small_df['cnt_Scaled'].as_matrix() , epochs = 50, batch_size = 4)" }, { "code": null, "e": 4569, "s": 4271, "text": "Embedding Layer: Here we specify the embedding size for our categorical variable. I have used 3 in this case, if we were to increase this it will capture more details on the relationship between the categorical variables. Jeremy Howard suggests the following solution for choosing embedding sizes:" }, { "code": null, "e": 4641, "s": 4569, "text": "# m is the no of categories per featureembedding_size = min(50, m+1/ 2)" }, { "code": null, "e": 4904, "s": 4641, "text": "We are using an “adam” optimiser with a mean-square error loss function. Adam is preferred to sgd (stochastic gradient descent) as it is much faster optimiser due to its adaptive learning rate. You can find more details on the different types of optimisers here." }, { "code": null, "e": 5020, "s": 4904, "text": "The final resulting embedding for each of the months are as follows. Here ‘0’ is for January and ‘11’ for December." }, { "code": null, "e": 5221, "s": 5020, "text": "When we visualise this using a 3D plot, we can see a clear relationship between the months. The months with similar ‘cnt’ are grouped closer together e.g. months 4 to 9 are very similar to each other." }, { "code": null, "e": 5455, "s": 5221, "text": "In conclusion we have seen that by using Cat2Vec (categorical variable to vectors) we can represent high cardinality categorical variable using low dimension embedding while preserving the relationship between each of the categories." } ]
Eigenfaces — Face Classification in Python | by Dario Radečić | Towards Data Science
Nowadays we can use neural networks to perform state of the art image classification, or face classification in this case. But what about taking a simpler approach? That’s what this article aims to cover. Official repo: access it here to get data and code. The idea of taking raw pixel values as input features might seem stupid at first — and it probably is, mostly because we’d lose all 2D information, and there are also convolutional neural networks to extract important features (as not all pixels are relevant). Today we’ll introduce the idea of the Eigenfaces algorithm — which is simply a principal component analysis applied to face recognition problem. By doing so our hope is to reduce the dimensionality of the dataset, keeping only the components that explain the most variance, and then apply a simple classification algorithm (like SVM) to do the classification task. Sounds like a plan, but what should you know before reading this article? It’s a good question. You should be proficient in Python and its data analysis libraries, and also know what principal component analysis is, at least on the high level. Still reading? Then I guess you’ve got the prerequisites covered. The last thing we want to discuss before jumping into the code is the article structure, and it can be listed as follows: Imports and Dataset Exploration Image visualization Principal Component Analysis Model Training & Evaluation Conclusion Okay, without much ado, let’s get started! As you’ve probably expected, we’ll need the usual suspects — Numpy, Pandas, and Matplotlib, but will also use a bunch of stuff from ScikitLearn — like SVM, PCA, train test split, and some metrics for evaluating model performance. Down below are all of the imports: import numpy as np import pandas as pd import matplotlib.pyplot as pltfrom sklearn.svm import SVCfrom sklearn.model_selection import train_test_splitfrom sklearn.decomposition import PCAfrom sklearn.metrics import confusion_matrix, classification_reportimport warningswarnings.filterwarnings(‘ignore’) As for the dataset, we’ve found it a while back on GitHub but can’t seem to find it now. You can download it from my GitHub page. And here’s how you’d load it into Pandas: df = pd.read_csv(‘face_data.csv’)df.head() Now we can quickly check for the shape of the dataset: df.shape>>> (400, 4097) So, 400 rows and 4097 columns, a strange combination. For the columns we here have normalized pixels values (meaning values in the range (0, 1)), and by the end we have a target column, indicating which person is on the photo. If we take a closer look at the number of unique elements of the target column, we’d get the total number of people in the dataset: df[‘target’].nunique()>>> 40 And since we have 4096 features, it’s a clear indicator of 64x64 images in a single color channel: 64 * 64>>> 4096 Great, we now have some basic information about the dataset, and in the next section we will make some visualizations. To visualize a couple of faces we’ll declare a function which transforms 1D vector to a 2D matrix, and uses Matplotlib’s imshow functionality to show it as a grayscale image: def plot_faces(pixels): fig, axes = plt.subplots(5, 5, figsize=(6, 6)) for i, ax in enumerate(axes.flat): ax.imshow(np.array(pixels)[i].reshape(64, 64), cmap=’gray’) plt.show() But before plotting, we need to separate features from the target, otherwise, our dataset will overflow the 64x64 matrix boundaries: X = df.drop(‘target’, axis=1)y = df[‘target’] And that’s it, now we can use the declared function: And that’s pretty much it for this section. In the next one we’ll perform the train test split and PCA. The goal of this section is to reduce the dimensionality of our problem by keeping only those components that explain the most variance. That in a nutshell is a goal of PCA. But before doing so, we must split the dataset into training and testing portions: X_train, X_test, y_train, y_test = train_test_split(X, y) Now we can apply the PCA on the training features. Then it’s easy to plot the cumulative sum of the explained variance, so we can approximate how many principal components are enough: pca = PCA().fit(X_train)plt.figure(figsize=(18, 7))plt.plot(pca.explained_variance_ratio_.cumsum(), lw=3) Just by looking at the chart, it seems like around 100 principal components will keep around 95% of the variance, but let’s verify that claim: np.where(pca.explained_variance_ratio_.cumsum() > 0.95) Yes, it looks like 105 components will do the trick. Keep in mind that 95% isn’t set in stone, keep free to go for lower or higher percent on your own. Let’s perform the PCA again, but this time with additional n_components argument: pca = PCA(n_components=105).fit(X_train) And finally, we must transform the training features: X_train_pca = pca.transform(X_train) Great! That’s it for this section, and in the next one we’ll train and evaluate the SVM model. By now have the training features transformed. The process of training the model is as simple as making an instance of it and fitting the training data: classifier = SVC().fit(X_train_pca, y_train) Awesome! Model is now trained, and to evaluate it on the test set we’ll first need to bring the test features to the same feature space. Once done, SVM is used to make predictions: X_test_pca = pca.transform(X_test)predictions = classifier.predict(X_test_pca) And now we can finally see it’s performance. For this we’ll use the classification_report from ScikitLearn, as it’s easier to look at than 40x40 confusion matrix: print(classification_report(y_test, predictions)) So around 90% accuracy, certainly not terrible for 40 different classes and default model. And that does it for this article, let’s quickly glance at possible areas of improvement in the next section. This was a rather quick guide — intentionally. You are free to perform a grid search to find optimal hyperparameters for the classifier or even to use a completely different algorithm. Also, try opting for 90% and 99% of the explained variance ratio, to see how the model performance changes. Thanks for reading, feel free to leave your thoughts in the comment section. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 377, "s": 172, "text": "Nowadays we can use neural networks to perform state of the art image classification, or face classification in this case. But what about taking a simpler approach? That’s what this article aims to cover." }, { "code": null, "e": 429, "s": 377, "text": "Official repo: access it here to get data and code." }, { "code": null, "e": 690, "s": 429, "text": "The idea of taking raw pixel values as input features might seem stupid at first — and it probably is, mostly because we’d lose all 2D information, and there are also convolutional neural networks to extract important features (as not all pixels are relevant)." }, { "code": null, "e": 1055, "s": 690, "text": "Today we’ll introduce the idea of the Eigenfaces algorithm — which is simply a principal component analysis applied to face recognition problem. By doing so our hope is to reduce the dimensionality of the dataset, keeping only the components that explain the most variance, and then apply a simple classification algorithm (like SVM) to do the classification task." }, { "code": null, "e": 1299, "s": 1055, "text": "Sounds like a plan, but what should you know before reading this article? It’s a good question. You should be proficient in Python and its data analysis libraries, and also know what principal component analysis is, at least on the high level." }, { "code": null, "e": 1487, "s": 1299, "text": "Still reading? Then I guess you’ve got the prerequisites covered. The last thing we want to discuss before jumping into the code is the article structure, and it can be listed as follows:" }, { "code": null, "e": 1519, "s": 1487, "text": "Imports and Dataset Exploration" }, { "code": null, "e": 1539, "s": 1519, "text": "Image visualization" }, { "code": null, "e": 1568, "s": 1539, "text": "Principal Component Analysis" }, { "code": null, "e": 1596, "s": 1568, "text": "Model Training & Evaluation" }, { "code": null, "e": 1607, "s": 1596, "text": "Conclusion" }, { "code": null, "e": 1650, "s": 1607, "text": "Okay, without much ado, let’s get started!" }, { "code": null, "e": 1880, "s": 1650, "text": "As you’ve probably expected, we’ll need the usual suspects — Numpy, Pandas, and Matplotlib, but will also use a bunch of stuff from ScikitLearn — like SVM, PCA, train test split, and some metrics for evaluating model performance." }, { "code": null, "e": 1915, "s": 1880, "text": "Down below are all of the imports:" }, { "code": null, "e": 2217, "s": 1915, "text": "import numpy as np import pandas as pd import matplotlib.pyplot as pltfrom sklearn.svm import SVCfrom sklearn.model_selection import train_test_splitfrom sklearn.decomposition import PCAfrom sklearn.metrics import confusion_matrix, classification_reportimport warningswarnings.filterwarnings(‘ignore’)" }, { "code": null, "e": 2347, "s": 2217, "text": "As for the dataset, we’ve found it a while back on GitHub but can’t seem to find it now. You can download it from my GitHub page." }, { "code": null, "e": 2389, "s": 2347, "text": "And here’s how you’d load it into Pandas:" }, { "code": null, "e": 2432, "s": 2389, "text": "df = pd.read_csv(‘face_data.csv’)df.head()" }, { "code": null, "e": 2487, "s": 2432, "text": "Now we can quickly check for the shape of the dataset:" }, { "code": null, "e": 2511, "s": 2487, "text": "df.shape>>> (400, 4097)" }, { "code": null, "e": 2738, "s": 2511, "text": "So, 400 rows and 4097 columns, a strange combination. For the columns we here have normalized pixels values (meaning values in the range (0, 1)), and by the end we have a target column, indicating which person is on the photo." }, { "code": null, "e": 2870, "s": 2738, "text": "If we take a closer look at the number of unique elements of the target column, we’d get the total number of people in the dataset:" }, { "code": null, "e": 2899, "s": 2870, "text": "df[‘target’].nunique()>>> 40" }, { "code": null, "e": 2998, "s": 2899, "text": "And since we have 4096 features, it’s a clear indicator of 64x64 images in a single color channel:" }, { "code": null, "e": 3014, "s": 2998, "text": "64 * 64>>> 4096" }, { "code": null, "e": 3133, "s": 3014, "text": "Great, we now have some basic information about the dataset, and in the next section we will make some visualizations." }, { "code": null, "e": 3308, "s": 3133, "text": "To visualize a couple of faces we’ll declare a function which transforms 1D vector to a 2D matrix, and uses Matplotlib’s imshow functionality to show it as a grayscale image:" }, { "code": null, "e": 3501, "s": 3308, "text": "def plot_faces(pixels): fig, axes = plt.subplots(5, 5, figsize=(6, 6)) for i, ax in enumerate(axes.flat): ax.imshow(np.array(pixels)[i].reshape(64, 64), cmap=’gray’) plt.show()" }, { "code": null, "e": 3634, "s": 3501, "text": "But before plotting, we need to separate features from the target, otherwise, our dataset will overflow the 64x64 matrix boundaries:" }, { "code": null, "e": 3680, "s": 3634, "text": "X = df.drop(‘target’, axis=1)y = df[‘target’]" }, { "code": null, "e": 3733, "s": 3680, "text": "And that’s it, now we can use the declared function:" }, { "code": null, "e": 3837, "s": 3733, "text": "And that’s pretty much it for this section. In the next one we’ll perform the train test split and PCA." }, { "code": null, "e": 4094, "s": 3837, "text": "The goal of this section is to reduce the dimensionality of our problem by keeping only those components that explain the most variance. That in a nutshell is a goal of PCA. But before doing so, we must split the dataset into training and testing portions:" }, { "code": null, "e": 4152, "s": 4094, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y)" }, { "code": null, "e": 4336, "s": 4152, "text": "Now we can apply the PCA on the training features. Then it’s easy to plot the cumulative sum of the explained variance, so we can approximate how many principal components are enough:" }, { "code": null, "e": 4442, "s": 4336, "text": "pca = PCA().fit(X_train)plt.figure(figsize=(18, 7))plt.plot(pca.explained_variance_ratio_.cumsum(), lw=3)" }, { "code": null, "e": 4585, "s": 4442, "text": "Just by looking at the chart, it seems like around 100 principal components will keep around 95% of the variance, but let’s verify that claim:" }, { "code": null, "e": 4641, "s": 4585, "text": "np.where(pca.explained_variance_ratio_.cumsum() > 0.95)" }, { "code": null, "e": 4793, "s": 4641, "text": "Yes, it looks like 105 components will do the trick. Keep in mind that 95% isn’t set in stone, keep free to go for lower or higher percent on your own." }, { "code": null, "e": 4875, "s": 4793, "text": "Let’s perform the PCA again, but this time with additional n_components argument:" }, { "code": null, "e": 4916, "s": 4875, "text": "pca = PCA(n_components=105).fit(X_train)" }, { "code": null, "e": 4970, "s": 4916, "text": "And finally, we must transform the training features:" }, { "code": null, "e": 5007, "s": 4970, "text": "X_train_pca = pca.transform(X_train)" }, { "code": null, "e": 5102, "s": 5007, "text": "Great! That’s it for this section, and in the next one we’ll train and evaluate the SVM model." }, { "code": null, "e": 5255, "s": 5102, "text": "By now have the training features transformed. The process of training the model is as simple as making an instance of it and fitting the training data:" }, { "code": null, "e": 5300, "s": 5255, "text": "classifier = SVC().fit(X_train_pca, y_train)" }, { "code": null, "e": 5481, "s": 5300, "text": "Awesome! Model is now trained, and to evaluate it on the test set we’ll first need to bring the test features to the same feature space. Once done, SVM is used to make predictions:" }, { "code": null, "e": 5560, "s": 5481, "text": "X_test_pca = pca.transform(X_test)predictions = classifier.predict(X_test_pca)" }, { "code": null, "e": 5723, "s": 5560, "text": "And now we can finally see it’s performance. For this we’ll use the classification_report from ScikitLearn, as it’s easier to look at than 40x40 confusion matrix:" }, { "code": null, "e": 5773, "s": 5723, "text": "print(classification_report(y_test, predictions))" }, { "code": null, "e": 5864, "s": 5773, "text": "So around 90% accuracy, certainly not terrible for 40 different classes and default model." }, { "code": null, "e": 5974, "s": 5864, "text": "And that does it for this article, let’s quickly glance at possible areas of improvement in the next section." }, { "code": null, "e": 6159, "s": 5974, "text": "This was a rather quick guide — intentionally. You are free to perform a grid search to find optimal hyperparameters for the classifier or even to use a completely different algorithm." }, { "code": null, "e": 6267, "s": 6159, "text": "Also, try opting for 90% and 99% of the explained variance ratio, to see how the model performance changes." }, { "code": null, "e": 6344, "s": 6267, "text": "Thanks for reading, feel free to leave your thoughts in the comment section." } ]
C++ Program to Find LCM
The Least Common Multiple (LCM) of two numbers is the smallest number that is a multiple of both. For example: Let’s say we have the following two numbers: 15 and 9. 15 = 5 * 3 9 = 3 * 3 So, the LCM of 15 and 9 is 45. A program to find the LCM of two numbers is given as follows − Live Demo #include <iostream> using namespace std; int main() { int a=7, b=5, lcm; if(a>b) lcm = a; else lcm = b; while(1) { if( lcm%a==0 && lcm%b==0 ) { cout<<"The LCM of "<<a<<" and "<<b<<" is "<<lcm; break; } lcm++; } return 0; } The LCM of 7 and 5 is 35 In the above program, the variable lcm is set as the larger of the two numbers. This is demonstrated using the following code snippet. if(a>b) lcm = a; else lcm = b; After this, a while loop runs. In this loop, if LCM is divisible by a as well as b, it is the LCM of the two numbers and is displayed. If not, LCM is incremented until this condition is fulfilled. The code snippet that explains this is as follows − while(1) { if( lcm%a==0 && lcm%b==0 ) { cout<<"The LCM of "<<a<<" and "<<b<<" is "<<lcm; break; } lcm++; } Another method of finding the LCM of two numbers is to use the LCM and GCD formula. This formula specifies that the product of two numbers is equal to the product of their LCM and GCD. a * b = GCD * LCM A program to find the LCM of two numbers using the formula is given as follows − Live Demo #include<iostream> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int a = 7, b = 5; cout<<"LCM of "<< a <<" and "<< b <<" is "<< (a*b)/gcd(a, b); return 0; } LCM of 7 and 5 is 35 In the above program, the LCM is found using the formula. First, the GCD of a and b is obtained using gcd(). Itis a recursive function. It has two parameters i.e. a and b. If b is greater than 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b. This is demonstrated using the following code snippet. int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } After the GCD is obtained, the LCM is calculated using the formula. Then it is displayed. This is shown in the following code snippet. cout<<"LCM of "<< a <<" and "<< b <<" is "<< (a*b)/gcd(a, b);
[ { "code": null, "e": 1160, "s": 1062, "text": "The Least Common Multiple (LCM) of two numbers is the smallest number that is a multiple of both." }, { "code": null, "e": 1228, "s": 1160, "text": "For example: Let’s say we have the following two numbers: 15 and 9." }, { "code": null, "e": 1249, "s": 1228, "text": "15 = 5 * 3\n9 = 3 * 3" }, { "code": null, "e": 1280, "s": 1249, "text": "So, the LCM of 15 and 9 is 45." }, { "code": null, "e": 1343, "s": 1280, "text": "A program to find the LCM of two numbers is given as follows −" }, { "code": null, "e": 1354, "s": 1343, "text": " Live Demo" }, { "code": null, "e": 1637, "s": 1354, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a=7, b=5, lcm;\n if(a>b)\n lcm = a;\n else\n lcm = b;\n while(1) {\n if( lcm%a==0 && lcm%b==0 ) {\n cout<<\"The LCM of \"<<a<<\" and \"<<b<<\" is \"<<lcm;\n break;\n }\n lcm++;\n }\n return 0;\n}" }, { "code": null, "e": 1662, "s": 1637, "text": "The LCM of 7 and 5 is 35" }, { "code": null, "e": 1797, "s": 1662, "text": "In the above program, the variable lcm is set as the larger of the two numbers. This is demonstrated using the following code snippet." }, { "code": null, "e": 1828, "s": 1797, "text": "if(a>b)\nlcm = a;\nelse\nlcm = b;" }, { "code": null, "e": 2025, "s": 1828, "text": "After this, a while loop runs. In this loop, if LCM is divisible by a as well as b, it is the LCM of the two numbers and is displayed. If not, LCM is incremented until this condition is fulfilled." }, { "code": null, "e": 2077, "s": 2025, "text": "The code snippet that explains this is as follows −" }, { "code": null, "e": 2205, "s": 2077, "text": "while(1) {\n if( lcm%a==0 && lcm%b==0 ) {\n cout<<\"The LCM of \"<<a<<\" and \"<<b<<\" is \"<<lcm;\n break;\n }\n lcm++;\n}" }, { "code": null, "e": 2390, "s": 2205, "text": "Another method of finding the LCM of two numbers is to use the LCM and GCD formula. This formula specifies that the product of two numbers is equal to the product of their LCM and GCD." }, { "code": null, "e": 2408, "s": 2390, "text": "a * b = GCD * LCM" }, { "code": null, "e": 2489, "s": 2408, "text": "A program to find the LCM of two numbers using the formula is given as follows −" }, { "code": null, "e": 2500, "s": 2489, "text": " Live Demo" }, { "code": null, "e": 2733, "s": 2500, "text": "#include<iostream>\nusing namespace std;\nint gcd(int a, int b) {\n if (b == 0)\n return a;\n return gcd(b, a % b);\n}\nint main() {\n int a = 7, b = 5;\n cout<<\"LCM of \"<< a <<\" and \"<< b <<\" is \"<< (a*b)/gcd(a, b);\n return 0;\n}" }, { "code": null, "e": 2754, "s": 2733, "text": "LCM of 7 and 5 is 35" }, { "code": null, "e": 3074, "s": 2754, "text": "In the above program, the LCM is found using the formula. First, the GCD of a and b is obtained using gcd(). Itis a recursive function. It has two parameters i.e. a and b. If b is greater than 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b." }, { "code": null, "e": 3129, "s": 3074, "text": "This is demonstrated using the following code snippet." }, { "code": null, "e": 3208, "s": 3129, "text": "int gcd(int a, int b) {\n if (b == 0)\n return a;\n return gcd(b, a % b);\n}" }, { "code": null, "e": 3343, "s": 3208, "text": "After the GCD is obtained, the LCM is calculated using the formula. Then it is displayed. This is shown in the following code snippet." }, { "code": null, "e": 3405, "s": 3343, "text": "cout<<\"LCM of \"<< a <<\" and \"<< b <<\" is \"<< (a*b)/gcd(a, b);" } ]
How can we return null from a generic method in C#?
Generics allows us to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time. A generic can be defined using angle brackets <>. A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. Also, we cannot simply return null from a generic method like in normal method. Below is the error that a generic method will throw if we are trying to return null. using System; namespace DemoApplication { class Program { public static void Main() { Add(5, 5); } public static T Add<T>(T parameter1, T parameter2) { return null; } } } So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided. Live Demo using System; namespace DemoApplication { class Program { public static void Main() { Add(5, 5); Console.ReadLine(); } public static T Add<T>(T parameter1, T parameter2) { var defaultVal = default(T); Console.WriteLine(defaultVal); return defaultVal; } } } The output of the code is 0 Here we could see that the default value of integer 0 is returned.
[ { "code": null, "e": 1518, "s": 1062, "text": "Generics allows us to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time. A generic can be defined using angle brackets <>. A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class." }, { "code": null, "e": 1683, "s": 1518, "text": "Also, we cannot simply return null from a generic method like in normal method. Below is the error that a generic method will throw if we are trying to return null." }, { "code": null, "e": 1902, "s": 1683, "text": "using System;\nnamespace DemoApplication {\n class Program {\n public static void Main() {\n Add(5, 5);\n }\n public static T Add<T>(T parameter1, T parameter2) {\n return null;\n }\n }\n}" }, { "code": null, "e": 2062, "s": 1902, "text": "So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided." }, { "code": null, "e": 2073, "s": 2062, "text": " Live Demo" }, { "code": null, "e": 2405, "s": 2073, "text": "using System;\nnamespace DemoApplication {\n class Program {\n public static void Main() {\n Add(5, 5);\n Console.ReadLine();\n }\n public static T Add<T>(T parameter1, T parameter2) {\n var defaultVal = default(T);\n Console.WriteLine(defaultVal);\n return defaultVal;\n }\n }\n}" }, { "code": null, "e": 2431, "s": 2405, "text": "The output of the code is" }, { "code": null, "e": 2433, "s": 2431, "text": "0" }, { "code": null, "e": 2500, "s": 2433, "text": "Here we could see that the default value of integer 0 is returned." } ]
AI with Python – Machine Learning
Learning means the acquisition of knowledge or skills through study or experience. Based on this, we can define machine learning (ML) as follows − It may be defined as the field of computer science, more specifically an application of artificial intelligence, which provides computer systems the ability to learn with data and improve from experience without being explicitly programmed. Basically, the main focus of machine learning is to allow the computers learn automatically without human intervention. Now the question arises that how such learning can be started and done? It can be started with the observations of data. The data can be some examples, instruction or some direct experiences too. Then on the basis of this input, machine makes better decision by looking for some patterns in data. Machine Learning Algorithms helps computer system learn without being explicitly programmed. These algorithms are categorized into supervised or unsupervised. Let us now see a few algorithms − This is the most commonly used machine learning algorithm. It is called supervised because the process of algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. In this kind of ML algorithm, the possible outcomes are already known and training data is also labeled with correct answers. It can be understood as follows − Suppose we have input variables x and an output variable y and we applied an algorithm to learn the mapping function from the input to output such as − Y = f(x) Now, the main goal is to approximate the mapping function so well that when we have new input data (x), we can predict the output variable (Y) for that data. Mainly supervised leaning problems can be divided into the following two kinds of problems − Classification − A problem is called classification problem when we have the categorized output such as “black”, “teaching”, “non-teaching”, etc. Classification − A problem is called classification problem when we have the categorized output such as “black”, “teaching”, “non-teaching”, etc. Regression − A problem is called regression problem when we have the real value output such as “distance”, “kilogram”, etc. Regression − A problem is called regression problem when we have the real value output such as “distance”, “kilogram”, etc. Decision tree, random forest, knn, logistic regression are the examples of supervised machine learning algorithms. As the name suggests, these kinds of machine learning algorithms do not have any supervisor to provide any sort of guidance. That is why unsupervised machine learning algorithms are closely aligned with what some call true artificial intelligence. It can be understood as follows − Suppose we have input variable x, then there will be no corresponding output variables as there is in supervised learning algorithms. In simple words, we can say that in unsupervised learning there will be no correct answer and no teacher for the guidance. Algorithms help to discover interesting patterns in data. Unsupervised learning problems can be divided into the following two kinds of problem − Clustering − In clustering problems, we need to discover the inherent groupings in the data. For example, grouping customers by their purchasing behavior. Clustering − In clustering problems, we need to discover the inherent groupings in the data. For example, grouping customers by their purchasing behavior. Association − A problem is called association problem because such kinds of problem require discovering the rules that describe large portions of our data. For example, finding the customers who buy both x and y. Association − A problem is called association problem because such kinds of problem require discovering the rules that describe large portions of our data. For example, finding the customers who buy both x and y. K-means for clustering, Apriori algorithm for association are the examples of unsupervised machine learning algorithms. These kinds of machine learning algorithms are used very less. These algorithms train the systems to make specific decisions. Basically, the machine is exposed to an environment where it trains itself continually using the trial and error method. These algorithms learn from past experience and tries to capture the best possible knowledge to make accurate decisions. Markov Decision Process is an example of reinforcement machine learning algorithms. In this section, we will learn about the most common machine learning algorithms. The algorithms are described below − It is one of the most well-known algorithms in statistics and machine learning. Basic concept − Mainly linear regression is a linear model that assumes a linear relationship between the input variables say x and the single output variable say y. In other words, we can say that y can be calculated from a linear combination of the input variables x. The relationship between variables can be established by fitting a best line. Linear regression is of the following two types − Simple linear regression − A linear regression algorithm is called simple linear regression if it is having only one independent variable. Simple linear regression − A linear regression algorithm is called simple linear regression if it is having only one independent variable. Multiple linear regression − A linear regression algorithm is called multiple linear regression if it is having more than one independent variable. Multiple linear regression − A linear regression algorithm is called multiple linear regression if it is having more than one independent variable. Linear regression is mainly used to estimate the real values based on continuous variable(s). For example, the total sale of a shop in a day, based on real values, can be estimated by linear regression. It is a classification algorithm and also known as logit regression. Mainly logistic regression is a classification algorithm that is used to estimate the discrete values like 0 or 1, true or false, yes or no based on a given set of independent variable. Basically, it predicts the probability hence its output lies in between 0 and 1. Decision tree is a supervised learning algorithm that is mostly used for classification problems. Basically it is a classifier expressed as recursive partition based on the independent variables. Decision tree has nodes which form the rooted tree. Rooted tree is a directed tree with a node called “root”. Root does not have any incoming edges and all the other nodes have one incoming edge. These nodes are called leaves or decision nodes. For example, consider the following decision tree to see whether a person is fit or not. It is used for both classification and regression problems. But mainly it is used for classification problems. The main concept of SVM is to plot each data item as a point in n-dimensional space with the value of each feature being the value of a particular coordinate. Here n would be the features we would have. Following is a simple graphical representation to understand the concept of SVM − In the above diagram, we have two features hence we first need to plot these two variables in two dimensional space where each point has two co-ordinates, called support vectors. The line splits the data into two different classified groups. This line would be the classifier. It is also a classification technique. The logic behind this classification technique is to use Bayes theorem for building classifiers. The assumption is that the predictors are independent. In simple words, it assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature. Below is the equation for Bayes theorem − $$P\left ( \frac{A}{B} \right ) = \frac{P\left ( \frac{B}{A} \right )P\left ( A \right )}{P\left ( B \right )}$$ The Naïve Bayes model is easy to build and particularly useful for large data sets. It is used for both classification and regression of the problems. It is widely used to solve classification problems. The main concept of this algorithm is that it used to store all the available cases and classifies new cases by majority votes of its k neighbors. The case being then assigned to the class which is the most common amongst its K-nearest neighbors, measured by a distance function. The distance function can be Euclidean, Minkowski and Hamming distance. Consider the following to use KNN − Computationally KNN are expensive than other algorithms used for classification problems. Computationally KNN are expensive than other algorithms used for classification problems. The normalization of variables needed otherwise higher range variables can bias it. The normalization of variables needed otherwise higher range variables can bias it. In KNN, we need to work on pre-processing stage like noise removal. In KNN, we need to work on pre-processing stage like noise removal. As the name suggests, it is used to solve the clustering problems. It is basically a type of unsupervised learning. The main logic of K-Means clustering algorithm is to classify the data set through a number of clusters. Follow these steps to form clusters by K-means − K-means picks k number of points for each cluster known as centroids. K-means picks k number of points for each cluster known as centroids. Now each data point forms a cluster with the closest centroids, i.e., k clusters. Now each data point forms a cluster with the closest centroids, i.e., k clusters. Now, it will find the centroids of each cluster based on the existing cluster members. Now, it will find the centroids of each cluster based on the existing cluster members. We need to repeat these steps until convergence occurs. We need to repeat these steps until convergence occurs. It is a supervised classification algorithm. The advantage of random forest algorithm is that it can be used for both classification and regression kind of problems. Basically it is the collection of decision trees (i.e., forest) or you can say ensemble of the decision trees. The basic concept of random forest is that each tree gives a classification and the forest chooses the best classifications from them. Followings are the advantages of Random Forest algorithm − Random forest classifier can be used for both classification and regression tasks. Random forest classifier can be used for both classification and regression tasks. They can handle the missing values. They can handle the missing values. It won’t over fit the model even if we have more number of trees in the forest. It won’t over fit the model even if we have more number of trees in the forest. 78 Lectures 7 hours Arnab Chakraborty 87 Lectures 9.5 hours DigiFisk (Programming Is Fun) 10 Lectures 1 hours Nikoloz Sanakoevi 15 Lectures 54 mins Mukund Kumar Mishra 11 Lectures 1 hours Gilad James, PhD 20 Lectures 2 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2205, "text": "Learning means the acquisition of knowledge or skills through study or experience. Based on this, we can define machine learning (ML) as follows −" }, { "code": null, "e": 2593, "s": 2352, "text": "It may be defined as the field of computer science, more specifically an application of artificial intelligence, which provides computer systems the ability to learn with data and improve from experience without being explicitly programmed." }, { "code": null, "e": 3010, "s": 2593, "text": "Basically, the main focus of machine learning is to allow the computers learn automatically without human intervention. Now the question arises that how such learning can be started and done? It can be started with the observations of data. The data can be some examples, instruction or some direct experiences too. Then on the basis of this input, machine makes better decision by looking for some patterns in data." }, { "code": null, "e": 3203, "s": 3010, "text": "Machine Learning Algorithms helps computer system learn without being explicitly programmed. These algorithms are categorized into supervised or unsupervised. Let us now see a few algorithms −" }, { "code": null, "e": 3579, "s": 3203, "text": "This is the most commonly used machine learning algorithm. It is called supervised because the process of algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. In this kind of ML algorithm, the possible outcomes are already known and training data is also labeled with correct answers. It can be understood as follows −" }, { "code": null, "e": 3731, "s": 3579, "text": "Suppose we have input variables x and an output variable y and we applied an algorithm to learn the mapping function from the input to output such as −" }, { "code": null, "e": 3741, "s": 3731, "text": "Y = f(x)\n" }, { "code": null, "e": 3899, "s": 3741, "text": "Now, the main goal is to approximate the mapping function so well that when we have new input data (x), we can predict the output variable (Y) for that data." }, { "code": null, "e": 3992, "s": 3899, "text": "Mainly supervised leaning problems can be divided into the following two kinds of problems −" }, { "code": null, "e": 4138, "s": 3992, "text": "Classification − A problem is called classification problem when we have the categorized output such as “black”, “teaching”, “non-teaching”, etc." }, { "code": null, "e": 4284, "s": 4138, "text": "Classification − A problem is called classification problem when we have the categorized output such as “black”, “teaching”, “non-teaching”, etc." }, { "code": null, "e": 4408, "s": 4284, "text": "Regression − A problem is called regression problem when we have the real value output such as “distance”, “kilogram”, etc." }, { "code": null, "e": 4532, "s": 4408, "text": "Regression − A problem is called regression problem when we have the real value output such as “distance”, “kilogram”, etc." }, { "code": null, "e": 4647, "s": 4532, "text": "Decision tree, random forest, knn, logistic regression are the examples of supervised machine learning algorithms." }, { "code": null, "e": 4929, "s": 4647, "text": "As the name suggests, these kinds of machine learning algorithms do not have any supervisor to provide any sort of guidance. That is why unsupervised machine learning algorithms are closely aligned with what some call true artificial intelligence. It can be understood as follows −" }, { "code": null, "e": 5063, "s": 4929, "text": "Suppose we have input variable x, then there will be no corresponding output variables as there is in supervised learning algorithms." }, { "code": null, "e": 5244, "s": 5063, "text": "In simple words, we can say that in unsupervised learning there will be no correct answer and no teacher for the guidance. Algorithms help to discover interesting patterns in data." }, { "code": null, "e": 5332, "s": 5244, "text": "Unsupervised learning problems can be divided into the following two kinds of problem −" }, { "code": null, "e": 5487, "s": 5332, "text": "Clustering − In clustering problems, we need to discover the inherent groupings in the data. For example, grouping customers by their purchasing behavior." }, { "code": null, "e": 5642, "s": 5487, "text": "Clustering − In clustering problems, we need to discover the inherent groupings in the data. For example, grouping customers by their purchasing behavior." }, { "code": null, "e": 5855, "s": 5642, "text": "Association − A problem is called association problem because such kinds of problem require discovering the rules that describe large portions of our data. For example, finding the customers who buy both x and y." }, { "code": null, "e": 6068, "s": 5855, "text": "Association − A problem is called association problem because such kinds of problem require discovering the rules that describe large portions of our data. For example, finding the customers who buy both x and y." }, { "code": null, "e": 6188, "s": 6068, "text": "K-means for clustering, Apriori algorithm for association are the examples of unsupervised machine learning algorithms." }, { "code": null, "e": 6640, "s": 6188, "text": "These kinds of machine learning algorithms are used very less. These algorithms train the systems to make specific decisions. Basically, the machine is exposed to an environment where it trains itself continually using the trial and error method. These algorithms learn from past experience and tries to capture the best possible knowledge to make accurate decisions. Markov Decision Process is an example of reinforcement machine learning algorithms." }, { "code": null, "e": 6759, "s": 6640, "text": "In this section, we will learn about the most common machine learning algorithms. The algorithms are described below −" }, { "code": null, "e": 6839, "s": 6759, "text": "It is one of the most well-known algorithms in statistics and machine learning." }, { "code": null, "e": 7187, "s": 6839, "text": "Basic concept − Mainly linear regression is a linear model that assumes a linear relationship between the input variables say x and the single output variable say y. In other words, we can say that y can be calculated from a linear combination of the input variables x. The relationship between variables can be established by fitting a best line." }, { "code": null, "e": 7237, "s": 7187, "text": "Linear regression is of the following two types −" }, { "code": null, "e": 7376, "s": 7237, "text": "Simple linear regression − A linear regression algorithm is called simple linear regression if it is having only one independent variable." }, { "code": null, "e": 7515, "s": 7376, "text": "Simple linear regression − A linear regression algorithm is called simple linear regression if it is having only one independent variable." }, { "code": null, "e": 7663, "s": 7515, "text": "Multiple linear regression − A linear regression algorithm is called multiple linear regression if it is having more than one independent variable." }, { "code": null, "e": 7811, "s": 7663, "text": "Multiple linear regression − A linear regression algorithm is called multiple linear regression if it is having more than one independent variable." }, { "code": null, "e": 8014, "s": 7811, "text": "Linear regression is mainly used to estimate the real values based on continuous variable(s). For example, the total sale of a shop in a day, based on real values, can be estimated by linear regression." }, { "code": null, "e": 8083, "s": 8014, "text": "It is a classification algorithm and also known as logit regression." }, { "code": null, "e": 8350, "s": 8083, "text": "Mainly logistic regression is a classification algorithm that is used to estimate the discrete values like 0 or 1, true or false, yes or no based on a given set of independent variable. Basically, it predicts the probability hence its output lies in between 0 and 1." }, { "code": null, "e": 8448, "s": 8350, "text": "Decision tree is a supervised learning algorithm that is mostly used for classification problems." }, { "code": null, "e": 8880, "s": 8448, "text": "Basically it is a classifier expressed as recursive partition based on the independent variables. Decision tree has nodes which form the rooted tree. Rooted tree is a directed tree with a node called “root”. Root does not have any incoming edges and all the other nodes have one incoming edge. These nodes are called leaves or decision nodes. For example, consider the following decision tree to see whether a person is fit or not." }, { "code": null, "e": 9276, "s": 8880, "text": "It is used for both classification and regression problems. But mainly it is used for classification problems. The main concept of SVM is to plot each data item as a point in n-dimensional space with the value of each feature being the value of a particular coordinate. Here n would be the features we would have. Following is a simple graphical representation to understand the concept of SVM −" }, { "code": null, "e": 9553, "s": 9276, "text": "In the above diagram, we have two features hence we first need to plot these two variables in two dimensional space where each point has two co-ordinates, called support vectors. The line splits the data into two different classified groups. This line would be the classifier." }, { "code": null, "e": 9918, "s": 9553, "text": "It is also a classification technique. The logic behind this classification technique is to use Bayes theorem for building classifiers. The assumption is that the predictors are independent. In simple words, it assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature. Below is the equation for Bayes theorem −" }, { "code": null, "e": 10031, "s": 9918, "text": "$$P\\left ( \\frac{A}{B} \\right ) = \\frac{P\\left ( \\frac{B}{A} \\right )P\\left ( A \\right )}{P\\left ( B \\right )}$$" }, { "code": null, "e": 10116, "s": 10031, "text": "The Naïve Bayes model is easy to build and particularly useful for large data sets." }, { "code": null, "e": 10623, "s": 10116, "text": "It is used for both classification and regression of the problems. It is widely used to solve classification problems. The main concept of this algorithm is that it used to store all the available cases and classifies new cases by majority votes of its k neighbors. The case being then assigned to the class which is the most common amongst its K-nearest neighbors, measured by a distance function. The distance function can be Euclidean, Minkowski and Hamming distance. Consider the following to use KNN −" }, { "code": null, "e": 10713, "s": 10623, "text": "Computationally KNN are expensive than other algorithms used for classification problems." }, { "code": null, "e": 10803, "s": 10713, "text": "Computationally KNN are expensive than other algorithms used for classification problems." }, { "code": null, "e": 10887, "s": 10803, "text": "The normalization of variables needed otherwise higher range variables can bias it." }, { "code": null, "e": 10971, "s": 10887, "text": "The normalization of variables needed otherwise higher range variables can bias it." }, { "code": null, "e": 11039, "s": 10971, "text": "In KNN, we need to work on pre-processing stage like noise removal." }, { "code": null, "e": 11107, "s": 11039, "text": "In KNN, we need to work on pre-processing stage like noise removal." }, { "code": null, "e": 11377, "s": 11107, "text": "As the name suggests, it is used to solve the clustering problems. It is basically a type of unsupervised learning. The main logic of K-Means clustering algorithm is to classify the data set through a number of clusters. Follow these steps to form clusters by K-means −" }, { "code": null, "e": 11447, "s": 11377, "text": "K-means picks k number of points for each cluster known as centroids." }, { "code": null, "e": 11517, "s": 11447, "text": "K-means picks k number of points for each cluster known as centroids." }, { "code": null, "e": 11599, "s": 11517, "text": "Now each data point forms a cluster with the closest centroids, i.e., k clusters." }, { "code": null, "e": 11681, "s": 11599, "text": "Now each data point forms a cluster with the closest centroids, i.e., k clusters." }, { "code": null, "e": 11768, "s": 11681, "text": "Now, it will find the centroids of each cluster based on the existing cluster members." }, { "code": null, "e": 11855, "s": 11768, "text": "Now, it will find the centroids of each cluster based on the existing cluster members." }, { "code": null, "e": 11911, "s": 11855, "text": "We need to repeat these steps until convergence occurs." }, { "code": null, "e": 11967, "s": 11911, "text": "We need to repeat these steps until convergence occurs." }, { "code": null, "e": 12438, "s": 11967, "text": "It is a supervised classification algorithm. The advantage of random forest algorithm is that it can be used for both classification and regression kind of problems. Basically it is the collection of decision trees (i.e., forest) or you can say ensemble of the decision trees. The basic concept of random forest is that each tree gives a classification and the forest chooses the best classifications from them. Followings are the advantages of Random Forest algorithm −" }, { "code": null, "e": 12521, "s": 12438, "text": "Random forest classifier can be used for both classification and regression tasks." }, { "code": null, "e": 12604, "s": 12521, "text": "Random forest classifier can be used for both classification and regression tasks." }, { "code": null, "e": 12640, "s": 12604, "text": "They can handle the missing values." }, { "code": null, "e": 12676, "s": 12640, "text": "They can handle the missing values." }, { "code": null, "e": 12756, "s": 12676, "text": "It won’t over fit the model even if we have more number of trees in the forest." }, { "code": null, "e": 12836, "s": 12756, "text": "It won’t over fit the model even if we have more number of trees in the forest." }, { "code": null, "e": 12869, "s": 12836, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 12888, "s": 12869, "text": " Arnab Chakraborty" }, { "code": null, "e": 12923, "s": 12888, "text": "\n 87 Lectures \n 9.5 hours \n" }, { "code": null, "e": 12954, "s": 12923, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 12987, "s": 12954, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 13006, "s": 12987, "text": " Nikoloz Sanakoevi" }, { "code": null, "e": 13038, "s": 13006, "text": "\n 15 Lectures \n 54 mins\n" }, { "code": null, "e": 13059, "s": 13038, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 13092, "s": 13059, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 13110, "s": 13092, "text": " Gilad James, PhD" }, { "code": null, "e": 13143, "s": 13110, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 13161, "s": 13143, "text": " Gilad James, PhD" }, { "code": null, "e": 13168, "s": 13161, "text": " Print" }, { "code": null, "e": 13179, "s": 13168, "text": " Add Notes" } ]
How to make a 3D scatter plot in Python?
To get a 3D plot, we can use fig.add_subplot(111, projection='3d') method to instantiate the axis. After that, we can use the scatter method to draw different data points on the x, y, and z axes. Create a new figure, or activate an existing figure. Create a new figure, or activate an existing figure. Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrows = 1, ncols = 1, index = 1 and projection is ‘3d’. Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrows = 1, ncols = 1, index = 1 and projection is ‘3d’. Iterate a list of marks, xs, ys and zs, to make scatter points. Iterate a list of marks, xs, ys and zs, to make scatter points. Set x, y, and z labels using set_xlabel, y_label, and z_label methods. Set x, y, and z labels using set_xlabel, y_label, and z_label methods. Use plt.show() method to plot the figure. Use plt.show() method to plot the figure. import matplotlib.pyplot as plt import numpy as np np.random.seed(1000) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 for m, zl, zh in [('o', -50, -25), ('^', -30, -5)]: xs = (32 - 23) * np.random.rand(n) + 23 ys = (100 - 0) * np.random.rand(n) zs = (zh - zl) * np.random.rand(n) + zl ax.scatter(xs, ys, zs, marker=m) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show()
[ { "code": null, "e": 1258, "s": 1062, "text": "To get a 3D plot, we can use fig.add_subplot(111, projection='3d') method to instantiate the axis. After that, we can use the scatter method to draw different data points on the x, y, and z axes." }, { "code": null, "e": 1311, "s": 1258, "text": "Create a new figure, or activate an existing figure." }, { "code": null, "e": 1364, "s": 1311, "text": "Create a new figure, or activate an existing figure." }, { "code": null, "e": 1495, "s": 1364, "text": "Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrows = 1, ncols = 1, index = 1 and projection is ‘3d’." }, { "code": null, "e": 1626, "s": 1495, "text": "Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrows = 1, ncols = 1, index = 1 and projection is ‘3d’." }, { "code": null, "e": 1690, "s": 1626, "text": "Iterate a list of marks, xs, ys and zs, to make scatter points." }, { "code": null, "e": 1754, "s": 1690, "text": "Iterate a list of marks, xs, ys and zs, to make scatter points." }, { "code": null, "e": 1825, "s": 1754, "text": "Set x, y, and z labels using set_xlabel, y_label, and z_label methods." }, { "code": null, "e": 1896, "s": 1825, "text": "Set x, y, and z labels using set_xlabel, y_label, and z_label methods." }, { "code": null, "e": 1938, "s": 1896, "text": "Use plt.show() method to plot the figure." }, { "code": null, "e": 1980, "s": 1938, "text": "Use plt.show() method to plot the figure." }, { "code": null, "e": 2426, "s": 1980, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(1000)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nn = 100\n\nfor m, zl, zh in [('o', -50, -25), ('^', -30, -5)]:\n xs = (32 - 23) * np.random.rand(n) + 23\n ys = (100 - 0) * np.random.rand(n)\n zs = (zh - zl) * np.random.rand(n) + zl\n ax.scatter(xs, ys, zs, marker=m)\n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()" } ]
GWT - FileUpload Widget
The FileUpload widget wraps the HTML <input type = 'file'> element. This widget must be used with FormPanel if it is to be submitted to a server. Following is the declaration for com.google.gwt.user.client.ui.FileUpload class − public class FileUpload extends Widget implements HasName, HasChangeHandlers Following default CSS Style rules will be applied to all the TextBox widget. You can override it as per your requirements. .gwt-FileUpload {} FileUpload() Constructs a new file upload widget. FileUpload(Element element) This constructor may be used by subclasses to explicitly use an existing element. HandlerRegistration addChangeHandler(ChangeHandler handler) Adds a ChangeEvent handler. java.lang.String getFilename() Gets the filename selected by the user. java.lang.String getName() Gets the widget's name. boolean isEnabled() Gets whether this widget is enabled. void onBrowserEvent(Event event) Fired whenever a browser event is received. void setEnabled(boolean enabled) Sets whether this widget is enabled. void setName(java.lang.String name) Sets the widget's name. static FileUpload wrap(Element element) Creates a FileUpload widget that wraps an existing <input type='file'> element. This class inherits methods from the following classes − com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Widget java.lang.Object java.lang.Object This example will take you through simple steps to show usage of a FileUpload Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter − Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } .gwt-FileUpload { color: green; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>FileUpload Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of FileUpload widget. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { VerticalPanel panel = new VerticalPanel(); //create a FormPanel final FormPanel form = new FormPanel(); //create a file upload widget final FileUpload fileUpload = new FileUpload(); //create labels Label selectLabel = new Label("Select a file:"); //create upload button Button uploadButton = new Button("Upload File"); //pass action to the form to point to service handling file //receiving operation. form.setAction("http://www.tutorialspoint.com/gwt/myFormHandler"); // set form to use the POST method, and multipart MIME encoding. form.setEncoding(FormPanel.ENCODING_MULTIPART); form.setMethod(FormPanel.METHOD_POST); //add a label panel.add(selectLabel); //add fileUpload widget panel.add(fileUpload); //add a button to upload the file panel.add(uploadButton); uploadButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { //get the filename to be uploaded String filename = fileUpload.getFilename(); if (filename.length() == 0) { Window.alert("No File Specified!"); } else { //submit the form form.submit(); } } }); form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { @Override public void onSubmitComplete(SubmitCompleteEvent event) { // When the form submission is successfully completed, this //event is fired. Assuming the service returned a response //of type text/html, we can get the result text here Window.alert(event.getResults()); } }); panel.setSpacing(10); // Add form to the root panel. form.add(panel); RootPanel.get("gwtContainer").add(form); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − Following is the java server page code snippet demonstrating server side capability for file upload. We're using Common IO and Commons FileUpload libraries to add file-upload capability to server side page. File will be uploaded to uploadFiles folder relative to location where upload.jsp is located on server side. <%@page import = "org.apache.commons.fileupload.FileItemFactory"%> <%@page import = "org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@page import = "org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@page import = "org.apache.commons.fileupload.FileItem"%> <%@page import = "org.apache.commons.io.FilenameUtils"%> <%@page import = "java.util.List"%> <%@page import = "java.util.Iterator"%> <%@page import = "java.io.File"%> <%@page import = "java.io.FileOutputStream"%> <%@page import = "java.io.InputStream"%> <% // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); //handling a normal form-field if(item.isFormField()) { System.out.println("Got a form field"); String name = item.getFieldName(); String value = item.getString(); System.out.print("Name:"+name+",Value:"+value); } else { //handling file loads System.out.println("Not form field"); String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName != null) { fileName = FilenameUtils.getName(fileName); } String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); System.out.print("Field Name:"+fieldName +",File Name:"+fileName); System.out.print("Content Type:"+contentType +",Is In Memory:"+isInMemory+",Size:"+sizeInBytes); byte[] data = item.get(); fileName = getServletContext() .getRealPath( "/uploadedFiles/" + fileName); System.out.print("File name:" +fileName); FileOutputStream fileOutSt = new FileOutputStream(fileName); fileOutSt.write(data); fileOutSt.close(); out.print("File Uploaded Successfully!"); } } } catch(Exception e){ out.print("File Uploading Failed!" + e.getMessage()); } %> Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2023, "text": "The FileUpload widget wraps the HTML <input type = 'file'> element. This widget must be used with FormPanel if it is to be submitted to a server. " }, { "code": null, "e": 2252, "s": 2170, "text": "Following is the declaration for com.google.gwt.user.client.ui.FileUpload class −" }, { "code": null, "e": 2339, "s": 2252, "text": "public class FileUpload \n extends Widget\n implements HasName, HasChangeHandlers" }, { "code": null, "e": 2462, "s": 2339, "text": "Following default CSS Style rules will be applied to all the TextBox widget. You can override it as per your requirements." }, { "code": null, "e": 2481, "s": 2462, "text": ".gwt-FileUpload {}" }, { "code": null, "e": 2494, "s": 2481, "text": "FileUpload()" }, { "code": null, "e": 2531, "s": 2494, "text": "Constructs a new file upload widget." }, { "code": null, "e": 2559, "s": 2531, "text": "FileUpload(Element element)" }, { "code": null, "e": 2641, "s": 2559, "text": "This constructor may be used by subclasses to explicitly use an existing element." }, { "code": null, "e": 2701, "s": 2641, "text": "HandlerRegistration addChangeHandler(ChangeHandler handler)" }, { "code": null, "e": 2729, "s": 2701, "text": "Adds a ChangeEvent handler." }, { "code": null, "e": 2760, "s": 2729, "text": "java.lang.String getFilename()" }, { "code": null, "e": 2800, "s": 2760, "text": "Gets the filename selected by the user." }, { "code": null, "e": 2827, "s": 2800, "text": "java.lang.String getName()" }, { "code": null, "e": 2851, "s": 2827, "text": "Gets the widget's name." }, { "code": null, "e": 2871, "s": 2851, "text": "boolean isEnabled()" }, { "code": null, "e": 2908, "s": 2871, "text": "Gets whether this widget is enabled." }, { "code": null, "e": 2941, "s": 2908, "text": "void onBrowserEvent(Event event)" }, { "code": null, "e": 2985, "s": 2941, "text": "Fired whenever a browser event is received." }, { "code": null, "e": 3018, "s": 2985, "text": "void setEnabled(boolean enabled)" }, { "code": null, "e": 3055, "s": 3018, "text": "Sets whether this widget is enabled." }, { "code": null, "e": 3091, "s": 3055, "text": "void setName(java.lang.String name)" }, { "code": null, "e": 3115, "s": 3091, "text": "Sets the widget's name." }, { "code": null, "e": 3155, "s": 3115, "text": "static FileUpload wrap(Element element)" }, { "code": null, "e": 3235, "s": 3155, "text": "Creates a FileUpload widget that wraps an existing <input type='file'> element." }, { "code": null, "e": 3292, "s": 3235, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 3331, "s": 3292, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 3370, "s": 3331, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 3407, "s": 3370, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 3444, "s": 3407, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 3461, "s": 3444, "text": "java.lang.Object" }, { "code": null, "e": 3478, "s": 3461, "text": "java.lang.Object" }, { "code": null, "e": 3678, "s": 3478, "text": "This example will take you through simple steps to show usage of a FileUpload Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −" }, { "code": null, "e": 3780, "s": 3678, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 4389, "s": 3780, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 4467, "s": 4389, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 4692, "s": 4467, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-FileUpload {\n color: green; \n}" }, { "code": null, "e": 4769, "s": 4692, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 5098, "s": 4769, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>FileUpload Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 5229, "s": 5098, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of FileUpload widget." }, { "code": null, "e": 7853, "s": 5229, "text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.user.client.Window;\nimport com.google.gwt.user.client.ui.Button;\nimport com.google.gwt.user.client.ui.FileUpload;\nimport com.google.gwt.user.client.ui.FormPanel;\nimport com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;\nimport com.google.gwt.user.client.ui.Label;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n VerticalPanel panel = new VerticalPanel();\n //create a FormPanel \n final FormPanel form = new FormPanel();\n //create a file upload widget\n final FileUpload fileUpload = new FileUpload();\n //create labels\n Label selectLabel = new Label(\"Select a file:\");\n //create upload button\n Button uploadButton = new Button(\"Upload File\");\n //pass action to the form to point to service handling file \n //receiving operation.\n form.setAction(\"http://www.tutorialspoint.com/gwt/myFormHandler\");\n // set form to use the POST method, and multipart MIME encoding.\n form.setEncoding(FormPanel.ENCODING_MULTIPART);\n form.setMethod(FormPanel.METHOD_POST);\n \n //add a label\n panel.add(selectLabel);\n //add fileUpload widget\n panel.add(fileUpload);\n //add a button to upload the file\n panel.add(uploadButton);\n uploadButton.addClickHandler(new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n //get the filename to be uploaded\n String filename = fileUpload.getFilename();\n if (filename.length() == 0) {\n Window.alert(\"No File Specified!\");\n } else {\n //submit the form\n form.submit();\t\t\t \n }\t\t\t\t\n }\n });\n \n form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {\n @Override\n public void onSubmitComplete(SubmitCompleteEvent event) {\n // When the form submission is successfully completed, this \n //event is fired. Assuming the service returned a response \n //of type text/html, we can get the result text here \n Window.alert(event.getResults());\t\t\t\t\n }\n });\n panel.setSpacing(10);\n\t \n // Add form to the root panel. \n form.add(panel); \n\n RootPanel.get(\"gwtContainer\").add(form);\n }\t\n}" }, { "code": null, "e": 8087, "s": 7853, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 8403, "s": 8087, "text": "Following is the java server page code snippet demonstrating server side capability for file upload. We're using Common IO and Commons FileUpload libraries to add file-upload capability to server side page. File will be uploaded to uploadFiles folder relative to location where upload.jsp is located on server side." }, { "code": null, "e": 10914, "s": 8403, "text": "<%@page import = \"org.apache.commons.fileupload.FileItemFactory\"%>\n<%@page import = \"org.apache.commons.fileupload.disk.DiskFileItemFactory\"%>\n<%@page import = \"org.apache.commons.fileupload.servlet.ServletFileUpload\"%>\n<%@page import = \"org.apache.commons.fileupload.FileItem\"%>\n<%@page import = \"org.apache.commons.io.FilenameUtils\"%>\n<%@page import = \"java.util.List\"%>\n<%@page import = \"java.util.Iterator\"%>\n<%@page import = \"java.io.File\"%>\n<%@page import = \"java.io.FileOutputStream\"%>\n<%@page import = \"java.io.InputStream\"%>\n\n<%\n // Create a factory for disk-based file items\n FileItemFactory factory = new DiskFileItemFactory();\n // Create a new file upload handler\n ServletFileUpload upload = new ServletFileUpload(factory);\n try {\n // Parse the request\n List items = upload.parseRequest(request); \n\n // Process the uploaded items\n Iterator iter = items.iterator();\n\n while (iter.hasNext()) {\n FileItem item = (FileItem) iter.next();\n \n //handling a normal form-field\n if(item.isFormField()) {\n System.out.println(\"Got a form field\");\n String name = item.getFieldName();\n String value = item.getString();\n System.out.print(\"Name:\"+name+\",Value:\"+value);\t\t\t\t\n \n } else { \n \n //handling file loads\n System.out.println(\"Not form field\");\n String fieldName = item.getFieldName();\n String fileName = item.getName();\n if (fileName != null) {\n fileName = FilenameUtils.getName(fileName);\n }\n \n String contentType = item.getContentType();\n boolean isInMemory = item.isInMemory();\n long sizeInBytes = item.getSize();\n System.out.print(\"Field Name:\"+fieldName +\",File Name:\"+fileName);\n System.out.print(\"Content Type:\"+contentType\n +\",Is In Memory:\"+isInMemory+\",Size:\"+sizeInBytes);\t\t\t \n \n byte[] data = item.get();\n fileName = getServletContext()\n .getRealPath( \"/uploadedFiles/\" + fileName);\n System.out.print(\"File name:\" +fileName);\t\t\t\n FileOutputStream fileOutSt = new FileOutputStream(fileName);\n fileOutSt.write(data);\n fileOutSt.close();\n out.print(\"File Uploaded Successfully!\");\n }\t\n }\n } catch(Exception e){\n out.print(\"File Uploading Failed!\" + e.getMessage());\n } \n%>" }, { "code": null, "e": 10921, "s": 10914, "text": " Print" }, { "code": null, "e": 10932, "s": 10921, "text": " Add Notes" } ]
How to Fix: No module named plotly - GeeksforGeeks
22 Nov, 2021 In this article, we are going to see how to fix the no module error of plotly. This type of error is seen when we don’t have a particular module installed in our Python environment. In this tutorial, we will try to reproduce the error and solve it using screenshots. Example: It can be done with pip commands, pip is used to install an external package in Python. Command: pip install plotly It might take some time to install depending on your internet speed. Now we can successfully import Plotly. check if the installation is done or not Picked Python How-to-fix Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24559, "s": 24292, "text": "In this article, we are going to see how to fix the no module error of plotly. This type of error is seen when we don’t have a particular module installed in our Python environment. In this tutorial, we will try to reproduce the error and solve it using screenshots." }, { "code": null, "e": 24568, "s": 24559, "text": "Example:" }, { "code": null, "e": 24656, "s": 24568, "text": "It can be done with pip commands, pip is used to install an external package in Python." }, { "code": null, "e": 24665, "s": 24656, "text": "Command:" }, { "code": null, "e": 24684, "s": 24665, "text": "pip install plotly" }, { "code": null, "e": 24754, "s": 24684, "text": "It might take some time to install depending on your internet speed. " }, { "code": null, "e": 24794, "s": 24754, "text": "Now we can successfully import Plotly. " }, { "code": null, "e": 24835, "s": 24794, "text": "check if the installation is done or not" }, { "code": null, "e": 24842, "s": 24835, "text": "Picked" }, { "code": null, "e": 24860, "s": 24842, "text": "Python How-to-fix" }, { "code": null, "e": 24874, "s": 24860, "text": "Python-Plotly" }, { "code": null, "e": 24881, "s": 24874, "text": "Python" }, { "code": null, "e": 24979, "s": 24881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25011, "s": 24979, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25053, "s": 25011, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25109, "s": 25053, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25151, "s": 25109, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25206, "s": 25151, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25237, "s": 25206, "text": "Python | os.path.join() method" }, { "code": null, "e": 25259, "s": 25237, "text": "Defaultdict in Python" }, { "code": null, "e": 25298, "s": 25259, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25327, "s": 25298, "text": "Create a directory in Python" } ]