#and a function to make the first letter of a string variable capitalized
Explore tagged Tumblr posts
Note
Hi, I wonder how are you creating your wip? Do you write it in google docs and then code it in Twine? I'm starting making my own and I'm looking for some technical tips
Hi! Thanks so much for the ask! It's always good to see new authors starting their own IFs. This might be a bit long so I'll put everything under a read more for those of you who aren't interested.
For me personally, I write in LibreOffice, which is a free alternative to Microsoft Office/Word. But, you can definitely use Google Docs or whatever other writing program you prefer!
As for coding, you can just code in Twine, but I like to code some as I write so I don't forget when to set certain variables. If you don't want to code anything in your draft, then I'd recommend at least leaving yourself reminders at places you'd like to add variables or when you want to have skill checks or anything else of the sort.
I should mention that a lot of people dislike coding in Twine, the code isn't set apart from the text visually and can be confusing for some, so if that's the case for you, I'd recommend checking out something like Notepad++ for coding and then copy and pasting everything into Twine once you're done.
If you do use Notepad++, and you're also using SugarCube, I'd highly recommend downloading and using this to add SugarCube as a custom language to the program so your code is easier to read. (You'll be able to select it as the coding language in Notepad++ after downloading and following the directions, though you may need to exit and restart the program before it shows up in the language list).
Some other great resources I use: The Twine Cookbook (of course), SugarCube Documentation or Harlowe (if you prefer), some templates (including the one I use!) [1] [2] [3], and w3schools tutorials for basics in CSS and JavaScript (assuming you don't know how to code in them already, if you do, that's great!)
If you have any more questions, feel free to ask! I'm no coding expert but I have taken a few classes on Web Dev stuff in college so I know a thing or two.
Best of luck to you on your project anon!😊
#asks#lovely anon#not redo; rewind#hope this helps you with creating your IF anon!#i have some other resources as well that you might want (screenshots from sugarcube's documentation of certain useful things)#like the table with conditional operators so i can just check that real quick without having to try and find it again on the site#and a function to make the first letter of a string variable capitalized#the table for the text styles (bold and italics and all that)#how to code a typing effect (so the text appears on screen as though being typed by someone. you can change how fast or slow it is too!)#and so much more!!#just let me know if you'd like any of that and i can post it all for you!
39 notes
·
View notes
Text
Giant Spinner of Death: Obstacle course
youtube
Finishing off the year 2023, I decided to try something a little bit new and simple to see how far I come, I made a simple little obstacle course to see if I was missing anything that I already should have learned and improved with making mechanics before making more complex mechanics and design in games.
For the first time, I decided to simply use Cinemachine to test out the smooth virtual camera to follow the player.
The goal of this game is to reach the goal while avoiding obstacles as much as you can before time runs out. Don’t collide too many obstacles, or you lose!
I did the best I could to not overload the player with so many obstacles at a time, otherwise, it would be overwhelming and difficult for them to dodge the obstacles.
I needed to make sure the was enough room for the player to move around and dodge obstacles, especially the dropped obstacles which I intentionally put close to walls so the player can navigate around them a little easier after being dropped. The giant spinner of death I wanted to be the main threat to the player so the player is forced to keep their eyes on it at all times otherwise it will collide with the player and knock them towards another wall or obstacle.
I put a timer in the game to challenge the player to get to the end goal in time before it runs out. It would be a little too easy and not as challenging for the player if there was no timer since they could just wait a long time before all obstacles are dropped and go slow and steady around obstacles.
WHAT I IMPROVED:
Combining 2 strings and an int making into one sentence with a number countdown which is “you have” + “seconds” + “secs left”.
Got into the habit of making code much cleaner to read by separating some code into functions to avoid writing the same code again, So instead It calls certain functions at appropriate times ( e.g if the player loses by colliding too many objects or time ran out, it calls the function “displayLoseText” to display lose text.
WHAT I LEARNED:
How to set up the virtual camera from the cinemachine package.
How effective it is to make the cinemachine virtual camera smoothly follow the player.
How to turn on and off gravity on game objects by code.
It’s a good idea to start variables with lowercase letters.
Get axis movement is a method.
Delta time makes updating independent by making the time of frames consistent with the user’s computer. It uses the getaxis value multiplys by delta time movement value speed consistent with the user’s computer as it creates a single value.
The spinners that move without using delta time when timescale is 0 will still move. Possibly due to the fact it's not accessing time as it moves on its own.
Using Enumerators to drop obstacles in certain periods of seconds instead of using Time works best if the game level needs to be played again if players lose or win, otherwise the obstacles will not reset is drop counter and drop too quickly because Time has not been reset to zero when replaying the level.
Can change game objects tag names in code.
Tag is actually a property.
OnCollisionEnter is a callback.
Collision is a variable while "other" is a parameter. “other” stores information about what the gameobject might hit and what it might do with that information. I’ve known OnCollisionEnter for a while, but it's good to know more details about it.
Rotate (transform.Rotate) is a method. Methods are in capital letters.
The difference between defining and calling a method.
WHAT WENT WRONG? WHAT I COULD HAVE DONE BETTER?:
I couldn’t get the walls to always stop the player in its tracks, it is a difficult problem to solve. It could be because the player is moving so fast that it can pass through thin walls. I could have made thicker walls.
The player can also pass through walls by holding a move key as soon as the play button on the unity editor is pressed. The player can pass through corners for some reason, I tried to cover the corners as best as I could, but there was no luck succeeding. Thick walls wouldn’t be right for an obstacle course since most of the walls needed to be avoided by the player. So, the easiest solution I did was to add a timer that would pause the game and offer the player to try again if time is up.
When the player moves towards the wall, it shakes rapidly. I tried to see if I could give it a physics material to reduce the wall shaking, but for some reason, it had no effect, so sadly I had to let it go. I will need to find out more about creating physics materials to make it work as intended depending on the game mechanics and player collision.
OVERALL:
Even though I knew most of these data types beforehand, I learned some new details about them which is important for me to understand and how they work so I can work with them (or around them).
I need to get an understanding of some knowledge I may not have known 100% before (e.g. How player cube is not so bouncy on walls) and may need to research more to prevent or reduce the unwanted executions from code.
I could have tested it with a player, but I thought it wasn’t too important for now. The intention was to be more of a programming exercise to see what I know and what I don’t know, not a playable commercial game that the public can play.
#pc#gamedev#gamedevelopment#indiedev#soledevoloper#australiangamedevoloper#indiegames#indiegame#indie#pc games#indiegamedev#indiegaming#casualgames#Lookingforwork#casual#GameDesigner#MechanicTest#Unity3D#SoleDevoloper#indie games#Youtube
1 note
·
View note
Text
[Python Study] Week 1: Intro To Python 1/7
��� 1) First Python Program
Here I used the website Online IDE and learned how to use the print() and made to print statements; 'Hello World' and "My first Python program", which ran successfully. The print () function prints the specified message to the screen. Above, I used a string which is a data type that is made up of a sequence of characters (letters, numbers, punctuation, etc).
🧼 2) Python Identifiers, Keywords, and Indentation
Python's Keywords are words that are reserved in the Python language, meaning we can't use them as an identifier e.g. variable name or function name. They all have their individual meaning in Python and cant be changed!
What are Identifiers?
They are the names you give things, e.g. variables, classes, functions, etc. :
age = 24
But identifiers have strict rules.
Identifiers Rules
Can't start with a number - 2happy = True ❌
Can have a combo of lowercase, uppercase, numbers and have an underscore ( _ ) - myClass ✔️
If you want to say 2+ words, it's good practice for the first word of the identifier to be with a lowercase then capitalize the words after - myAgeAndName ✔️
Don't use keywords as mentioned before - finally = 25 ❌
Don't use special symbols - real@Gangsta = 0 ❌
No length limit for identifiers - mySuperHeroIsSpidermanBecauseWhyNot = 3.14 ✔️
Indentation
Back to OnlineIDE! Indentation is very important in Python. It ensures the code is organized and readable. If there is no appropriate indentation in the code, the program will not run properly and issue a syntax error.
It helps group blocks of code that are directly relevant to each other e.g. if-statements shown above!
🧼 3) Comments and document interlude in Python
Comments
I learned how to comment out code so I can make little texts that the program won't run. Using # ( for single lines), ''' ''' and """ """ (for multiple lines. It's interesting how you can even comment out code inline of the code you want to run as well. This is helpful in the future as I can make comments to myself to understand the code I write if I ever get stuck reading it!
Document Interlude
Here I learned about document interlude/documentation strings are. They are commonly are called docstrings.
They are the string literals that appear right after the definition (def) of a function, method, class, or module. They are basically comments within a def!
Docstrings must go right after ':' of the def or it will NOT work and become just a simple comment.
It's possible to print the doctstrings by writing a statement with the .__doc__attribute:
print(take_number.__doc__)
This helps will accessing comments that other programmers made for exampling functions, classes, etc.
------------------- ❥
That is all! Thank you for reading! If you are confused about anything, please refer to my post LEARNING PYTHON: WEEK 1 ! Always have fun coding!!
#100 days of code#python programming#how to learn python#Coding#Programming#Computer Science#backend#python#study plan#sharing is caring
5 notes
·
View notes
Text
Just like with determining what skills the player has equipped I wanted to have an easy way of determining who the speaker of a line of dialogue is without getting messy with structures and I decided to try it in a similar to how I set up the skill system by using strings. I thought that the best way to determine a speaker would be to use the first letter of a string to say whos speaker, if I put a capital A it would be the author speaking and if I put a capital W it would be the wizard speaking.
I created a simple function that takes in a string as an input and then uses get substring starting from index 0 and at length 1 which means that the new substring will just be the first character and then check if that character is a W, if it is a W then speaker is set to wizard and if not then speaker is set to author. it then turns the given string into a character array, removes the first index, and then turns it back into a regular string and then gives that as the dialogue output and gives the speaker as the speaker output. I then append the two outputs together and print them on screen to see if its working which it has.
What this system means is that I can have a structure that consists entirely of string arrays and nothing else since the speaker of each line is determined within the lines themselves instead of needing to do it through separate variables in the structure which I think could get messy.
I very quickly brought this system on screen by creating a new widget with one text element for the speakers name and one text element for the dialogue, both simply being binded to the variables speaker name and dialogue respectively, with a small difference to dialogue I'll mention later.. I put in a custom event which takes in speaker name and dialogue as inputs which it then sets to speaker name and dialogue within the widget itself. It then also sets current dialogue index to 0, this integer is used to make the dialogue appear on the screen one letter at a time by setting the on screen text to be a substring of current dialogue, with its length set at current dialogue index so another letter will appear each time it goes up. The Boolean dialogue displaying? is then set to true and the custom event next dialogue index runs. This checks if dialogue displaying is true, waits a very short duration and then increments current dialogue index by 1 which means the next letter will appear on screen. It then checks if current dialogue index is equal to the length (how many characters it has) of current dialogue. If it is then dialogue being displayed is set to false and if not then the custom event runs again for another letter to appear.
I changed the dialogue manager to be a pawn class so that it could take input from the player and then added an event from when the right spell input action is made since that's tied to the right mouse click for when spells are being used in other parts of the game. When the right mouse button is clicked it checks if dialogue is being displayed in the widget. If true then it runs the end dialogue event in the widget which sets current dialogue index to the length of current dialogue and sets dialogue displayed to false, ending that current line. If dialogue displayed if false meaning that the line is already over, it checks the length of the conversation array(this includes all line for the current scene) and if the player hasn't reached the end it runs the start dialogue function which is the same as it was at the star but instead of giving speaker name and finished dialogue as outputs it runs them directly into the new dialogue custom event in the widget. If the player has reached the end of the conversation it runs the function with a blank string as the input so no more dialogue appears on screen.
This is the quickest I've ever set up a dialogue system and code wise its the cleanest and most efficient one I've set up and I don't think I'll have much problem at all creating longer dialogue moments out of it since I can just give one string array for each conversation rather than needing at least two arrays to determine the speaker of the line and other things. The next main problems with the dialogue system will come from the visual elements, the models and the subtle animations which I will start working on quite soon.
0 notes
Text
Java Hello World Program In Hindi

Java First Program in Hindi
Input class first1{ public static void main(Stringargs) { System.out.println("hello world"); } } Output hello world • class :- हम java में जो भी programm लिखते है वह class के अंदर ही लिखते है। क्युकी यह OOPS के concepts को follow करता है। class को हम objects का collection कहते है क्युकी class के अंदर हम बहुत सारे object को defined करते है। class बिलकुल भी memory consume नहीं करता। यह object का blueprint or logical entity hota है। class को हम class name से defined करते है जैसे हमारी class का नाम first1 है। classfirst1{ } Public static void main(Stringargs) - Public :- Public एक acces modifier है। इसका का use हम main method को class के बहार से acces करने के लिए करते है JVM हमारे program को run करता है। but हमारी main method ही public नहीं होगी तोः jvm program को run नहीं कर पायेगा। - static :- main method को static इसलिए किया जाता है क्युकी हम class के object को बिना बनाये main method को acces करपये। जितने भी static member होते है वह object से deal नहीं करते है। but हम static का use नहीं करते है तोह हमे class के अंदर objects को defined करना पड़ेगा - Void :- void एक data type है जिसको हम function के पहले लिखते है। void का मतलब हमे कोई भी value return नहीं करनी है। - String :- String एक pre defined class होती है जितने भी Java में predefined class होती है।उनका first letter capital होता है 'String'. args एक array type का variable है जिसका use हम main method में कोई भी information pass कर सके इसलिए होता है। यदि हमे कोई भी information pass नहीं करना तोह भी हमे Stringargs को main method में defined करना पड़ेगा क्युकी यह syntax का part है। System.out.println("hello world"); - System :- System एक predefined class है जो 'Java.lang' package के अंदर defined है। - OUT :- out जो है print stream class का object है - println :- println एक method है जो हमारे message को output screen पर print करता है। ln curser एक line से next line पर move करता है। What is class in java Whatever program we write in java, we write it inside the class itself. Because it follows the concepts of OOPS. We call a class a collection of objects because we define many objects inside the class. The class does not consume memory at all. This is the blueprint or logical entity of the object. We define class by class name like our class name is first1. Public static void main(Stringargs) Public :- Public is an access modifier. We use this to access the main method from outside the class, JVM runs our program. But if our main method will not be public then: jvm will not be able to run the program. Static:- Main method is made static because we can access the main method without making the object of the class. All the static members are there, they do not deal with the object. But we do not use static, so we have to define the objects inside the class. Void: - void is a data type, which we write before the function. void means we do not have to return any value. String :- String is a pre defined class, as many predefined classes in Java. Their first letter capital is 'String'. args is an array type variable that is used so that we can pass any information to the main method. Even if we do not pass any information, we have to define String args in the main method because it is part of the syntax. System.out.println("hello world"); System :- System is a predefined class which is defined inside 'Java.lang' package. OUT :- out which is the object of print stream class println: - println is a method which prints our message on the output screen. The ln curser moves from one line to the next. Read the full article
0 notes
Text
Methods in Java
What is a Method
Methods in Java or a function is a block of code that contains execution statements and operations. It mainly describes what your code can do. It is similar to the mathematical function like sqrt(square root) which finds the square root of a number. Similarly in Java, we can have functions or methods that describe a specific code behavior. We should always write methods only within a class.
Advantage of Methods in Java
- Reusability: Methods allow us to reuse the code by just calling the specific function. This prevents us from writing redundant code and enhances reusability. - Readability: It makes the code more readable and understandable since we group the related actions together in a method. - Maintainability: Methods help us to maintain the code easier and allow us to refactor it easily when changes are required.
Types of Methods in Java
Java supports two different types of class methods:
Standard Library Methods These are pre-defined methods that are present in the Java library. We can use these methods without any changes. For example, we have the print() method of the System class that allows us to print a statement. We can invoke this method directly to print the statement as you can see in the below example. public class StandardMethod { public static void main(String args) { System.out.println("This is a standard library method"); } } This is a standard library method User-defined Methods When we create our own function or method, we call it a user-defined method. We can group similar actions together in a function. For example, add() is a method that adds numbers. Hence methods are used to define a task or functionality. Next, let's see how to create and invoke user-defined methods in Java.
Create a method
We must always create a method inside a class. A method contains a method name followed by parentheses(). Below is the syntax to create a method. access_type return_type method_name(arguments) { //method body } access_type: it specifies the access modifier like public, private, protected. return_type: Specifies if the method returns any value. It may be void(no return type) or specify a type like String or int method_name: Any valid name that suites the method behavior arguments: If the method requires any parameters or arguments to perform an operation. It is optional. method body: Functionality of the method Below is an example of creating a user-defined method. Here we have created a method add which has void return type and public access type. Inside the method body, we have a print statement. public class MethodExample { public void add() { System.out.println("Addition method"); } }
Naming convention of a method
- Method name always starts with a lowercase - It should always be a verb. Eg: add() - If the name contains more than two words, it should start with a verb followed by an adjective or noun. Eg: getName() - If there are multiple words for a method name, the first letter of the words other than the first word should start with a capital letter. Eg: getAddressDetails()
Invoke a Java method
A method is usable only when we invoke a call a method. We can call a method using the method name followed by the arguments if any within the parentheses. method_name(arguments); Below is a simple example of invoking a method. Since the methods are defined within a class, we can invoke the method by only using the class instance. In this example, add is the method and m is the class object. public class MethodExample { public void add() { System.out.println("Addition method"); } public static void main(String args) { MethodExample m = new MethodExample(); m.add(); } } Addition method
Method with no parameter and no return type
Below is an example of a java method that does not have any arguments or return types. When the method does not return any value, we mention the void keyword as the return type. When the method has no arguments, we mention it with empty parentheses. We initialize the integer variables x, y using constructor, and use this value directly inside the add method. This method does not have any parameters and no return type. public class Addition { int x,y; Addition(int x, int y) { this.x = x; this.y = y; } public void add() { int sum = x + y; System.out.println("Sum is: " + sum); } public static void main(String args) { Addition a = new Addition(5,8); a.add(); } } Sum is: 13
Method with parameters but no return type
The below example illustrates a method with parameters but does not return any value. The method difference accepts two parameters both of integer type. Hence when we call the method, we need to pass the values to the method which assigns to the parameter variables inside the method. Here, x and y parameters take the values 4 and 5 respectively. public class Subtraction { public void difference(int x, int y) { int diff = x - y; System.out.println("Difference is: " + diff); } public static void main(String args) { Subtraction s = new Subtraction(); s.difference(10, 4); } } Difference is: 6 The main difference between class variables and parameter variables is that class variables can be used in the entire class where as parameter variables can be used only within the method.
Method that has return type but no parameters
In the below example, the method product returns a value of integer type. Any method that has a return value should have the return statement with the value that needs to be returned. In this case, the variable product is the return value. Similarly, while invoking a method with the return type, we need to have a variable of the same type that receives the function output. Hence we use int prod = m.multiply(). public class Multiplication { int product,x, y; Multiplication(int x, int y) { this.x = x; this.y = y; } public int multiply() { product = x * y; return product; } public static void main(String args) { Multiplication m = new Multiplication(4,8); int prod = m.multiply(); System.out.println("Product is: " + prod); } } Product is: 32
Method with parameter and return type
In this example, the method greaterNumber has both parameters and return value. Hence when calling the method, we should pass arguments as well as have a variable to assign the return value from the method. In this case, x and y values have 47 and 29 respectively and return the variable max from the method. While invoking the method, we have the variable value that receives the output of this method. public class Compare { int max; public int greaterNumber(int x, int y) { if(x > y) max = x; else max = y; return max; } public static void main(String args) { Compare c = new Compare(); int value = c.greaterNumber(47, 29); System.out.println("Greater value is: " + value); } } Greater value is: 47
Static Java Method
We have seen in the Java Static keyword tutorial, that we can use the static keyword for the methods. In this case, we do not need any class object to invoke the static method and can call using the method name directly. public class MethodExample { public static void add() { System.out.println("Addition method"); } public static void main(String args) { add(); } } Addition method
Instance Methods
Methods which are non-static and that belongs to a class is called an instance method. These methods require an object or class instance to make a call to the function. This is in contrast to the static methods which do not require any object. In this example, we can understand the difference in invoking an instance method and a static method. add is a static method and subtract is an instance method. public class MethodExample { //Static method public static void add() { System.out.println("Addition method"); } //Instance method public void subtract() { System.out.println("Subtraction method"); } public static void main(String args) { MethodExample m = new MethodExample(); //Invoking a static method add(); //Invoking an instance method m.subtract(); } } Types of instance methods - Accessor method: We use this method to read the instance variables. Generally, these methods have a prefix get. Accessor methods can also be called as getters to read the values of private variables. - Mutator method: We use this method to modify the instance variable value. They have a prefix set. These are also called as setters and are used to set the values of private variables. These methods are used to read and update private variables from different classes. Example: public class InstanceMethodDemo { private String name; //Getter method public String getName() { return name; } //Setter method public void setName(String name) { this.name = name; } public static void main(String args) { } }
Abstract method
An abstract method has only a function declaration and no definition. This means, that it does not contain a method body. We use abstract methods to implement abstraction. Abstract class contains abstract methods. The class which extends the abstract class implements the functionality of the abstract method. abstract class class_name { //abstract method abstract void method_name(); } Reference Read the full article
0 notes
Text
300+ TOP RUBY Interview Questions and Answers
RUBY Interview Questions for freshers experienced :-
1. What is Ruby programming language? Ruby is a dynamic, reflective, general purpose, open source programming language that focuses on simplicity and productivity. Ruby has a mixed features of Perl, small talk, Eiffel, Ada and Lisp. Ruby was designed to create a new language which makes a balance with the functionality of Imperative languages. 2. Who is the developer of Ruby? Ruby is designed and developed by Yukihiro "martz" Matsumoto in mid 1990 in Japan. 3. Why Ruby is known as a language of flexibility? Ruby is known as a language of flexibility because it facilitates its author to alter the programming elements. Some specific parts of the language can be removed or redefined. Ruby does not restrict the user. For example, to add two numbers, Ruby allows to use + sign or the word 'plus'. This alteration can be done with Ruby's built-in class Numeric. 4. List some features of Ruby? Ruby has many features. Some of them are listed below. Object-oriented Flexible Dynamic typing and Duck typing Garbage collector Keyword arguments 5. Explain some differences between Ruby and Python. Similarities: High level language Support multiple platforms Use interactive prompt called irb Server side scripting language Differences: Ruby is fully object oriented while Python is not. Ruby supports EclipseIDE while Python supports multiple IDEs. Ruby use Mixins while Python doesn't. Ruby supports blocks, procs and lambdas while Python doesn't. 6. Write the command to get installed Ruby version in your system. ruby -v 7. What are class libraries in Ruby? Ruby class libraries contain variety of domain such as thread programming, data types, various domains. Following is a list of domains which has relevant class libraries: Text processing CGI Programming Network programming GUI programming XML programming 8. Name some operators used in Ruby. Operators are a symbol which is used to perform different operations. Unary operator Airthmetic operator Bitwise operator Logical operator Ternary operator 9. What is RubyGems in Ruby programming language? RubyGems provides a standard format for distributing ruby programs and libraries. It works as a package manager for the Ruby programming language. RubyGems is now a part of the standard library from Ruby version 1.9. 10. What are Ruby variables. Ruby variables hold data which can be used later in a program. Each variable act as a memory and shas a different name. There are four types of variables in Ruby: Local variable Class variable Instance variable Global variable
RUBY Interview Questions 11. What is the difference between nil and false in Ruby? nil false nil cannot be a value. false can be a value. nil is returned where there is no predicate. in case of a predicate, true or false is returned by a method. nil is not a boolean data type. false is a boolean data type. nil is an object of nilclass. false is an object of falseclass. 12. Explain Ruby data types. Ruby data types represent type of data such as text, string, numbers, etc. There are different data types in Ruby: Numbers Strings Symbols Hashes Arrays Booleans 13. What is the use of load and require in Ruby? In Ruby, load and require both are used for loading the available code into the current code. In cases where loading the code required every time when changed or every times someone hits the URL, it is suggested to use 'load'. It case of autoload, it is suggested to use 'require'. 14. Explain Ruby if-else statement. The Ruby if-else statement is used to test condition. There are various types of statement in Ruby. if statement if-else statement if-else-if (elsif. statement ternary statement 15. Explain case statement in Ruby. In Ruby, we use 'case' instead of 'switch' and 'when' instead of 'case'. The case statement matches one statement with multiple conditions just like a switch statement in other languages. 16. Explain for loop in Ruby. Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of itrerations. Ruby for loop will execute once for each element in expression. 17. Explain while loop in Ruby. Ruby while loop is used to iterate a program several times. If the number of iterations is not fixed for a program, while loop is used. 18. Explain do while loop in Ruby. Ruby do while loop iterates a part of program several times. In this, loop will execute at least once because do while condition is written at the end. 19. Explain until loop in Ruby. Ruby until loop runs until the given condition evaluates to true. It exits the loop when condition becomes true. It is opposite of the while loop. 20. Explain break statement in Ruby. Ruby break statement is used to terminate a loop. It is mostly used in while loop where value is printed till the condition is true. 21. Explain next statement in Ruby. Ruby next statement is used to skip loop's next iteration. Once the next statement is executed, no further iteration will be performed. 22. Explain redo statement in Ruby. Ruby redo statement is used to repeat the current iteration of the loop. The redo statement is executed without evaluating loop's condition. 23. Explain retry statement in Ruby. Ruby retry statement is used to repeat the whole loop iteration from the start. 24. How will you comment in Ruby. Ruby comments are non-executable lines in a program. They do not take part in the execution of a program. Single line comment syntax: #This is single line comment. Multi line comment syntax: =begin This is multi line comment =end 25. Explain Ruby object. Object is the default root of all Ruby objects. Ruby objects inherit from BasicObject which allows creating alternate object hierarchies. 26. How to create Ruby object? Objects in Ruby are created by calling new method of the class. It is a unique type of method and predefined in Ruby library. Syntax: objectName=className.new 27. Explain Ruby class. Each Ruby class is an instance of Ruby class. Classes in Ruby are first class objects. It always starts with a keyword class followed by the class name. Syntax: class ClassName codes... end 28. Define Ruby methods. Ruby method prevent us from writing the same code in a program again and again. Ruby methods are similar to functions in other languages. 29. How to use Ruby methods. To use a Ruby method, we need to first define it. It is defined with def and end keyword. Method name should always start with a lowercase letter. Syntax: def methodName code... end 30. What are Ruby blocks. Ruby code blocks are called closures in other programming languages. It consist of a group of codes which is always enclosed with braces or written between do...end. 31. In how many ways a block is written in Ruby. A block is written in two ways: Multi-line between do and end Inline between braces {} Both are same and have the same functionality. syntax: block_name{ statement1 statement2 .......... } 32. What is yield statement in Ruby. The yield statement is used to call a block within a method with a value. 33. Explain ampersand parameter (&block. in Ruby) The &block is a way to pass a reference (instead of a local variable) to the block to a method. Here, block word after the & is just a name for the reference, any other name can be used instead of this. 34. Explain Ruby module. Ruby module is a collection of methods and constants. A module method may be instance method or module method. They are similar to classes as they hold a collection of methods, class definitions, constants and other modules. They are defined like classes. Objects or subclasses can not be created using modules. There is no module hierarchy of inheritance. Modules basically serve two purposes: They act as namespace. They prevent the name clashes. They allow the mixin facility to share functionality between classes. Syntax: module ModuleName statement1 statement2 ........... end Module name should start with a capital letter. 35. Explain module mixins in Ruby. Ruby doesn't support multiple inheritance. Modules eliminate the need of multiple inheritance using mixin in Ruby. A module doesn't have instances because it is not a class. However, a module can be included within a class. When you include a module within a class, the class will have access to the methods of the module. 36. Explain Ruby strings. Ruby string object holds and manipulates an arbitary sequence of bytes, typically representing characters. They are created using String::new or as literals. 37. How to access Ruby strings elements in an application. You can access Ruby string elements in different parts with the help of square brackets . Within square brackets write the index or string. 38. How to write multiline string in Ruby. Writing multiline string is very simple in Ruby language. We will show three ways to print multiline string. String can be written within double quotes. The % character is used and string is enclosed within / character. In heredoc syntax, we use Read the full article
0 notes
Photo
Getting up and Running with the Vue.js 2.0 Framework
This article was updated in November 2018, primarily to bring the tooling section up to date.
As soon as the popular JavaScript framework Vue.js released v2, I was eager to give it a spin and see what it’s like to work with. As someone who’s pretty familiar with Angular and React, I was looking forward to seeing the similarities and differences between them and Vue.
Vue 2 sports excellent performance stats, a relatively small payload (the bundled runtime version of Vue weighs in at 30KB once minified and gzipped), along with updates to companion libraries like vue-router and Vuex, the state management library for Vue. There’s far too much to cover in just one article, but keep an eye out for some later articles where we’ll look more closely at various libraries that couple nicely with the core framework.
Inspiration from Other Libraries
As we go through this tutorial, you’ll see many features that Vue has that are clearly inspired by other frameworks. This is a good thing; it’s great to see new frameworks take some ideas from other libraries and improve on them. In particular, you’ll see Vue’s templating is very close to Angular’s, but its components and component lifecycle methods are closer to React’s (and Angular’s, as well).
One such example of this is that, much like React and nearly every framework in JavaScript land today, Vue uses the idea of a virtual DOM to keep rendering efficient. Vue uses a fork of snabbdom, one of the more popular virtual DOM libraries. The Vue site includes documentation on its Virtual DOM rendering, but as a user all you need to know is that Vue is very good at keeping your rendering fast (in fact, it performs better than React in many cases), meaning you can rest assured you’re building on a solid platform.
Components, Components, Components
Much like other frameworks these days, Vue’s core building block is the component. Your application should be a series of components that build on top of each other to produce the final application. Vue.js goes one step further by suggesting (although not enforcing) that you define your components in a single .vue file, which can then be parsed by build tools (we’ll come onto those shortly). Given that the aim of this article is to fully explore Vue and what it feels like to work with, I’m going to use this convention for my application.
A Vue file looks like so:
<template> <p>This is my HTML for my component</p> </template> <script> export default { // all code for my component goes here } </script> <style scoped> /* CSS here * by including `scoped`, we ensure that all CSS * is scoped to this component! */ </style>
Alternatively, you can give each element a src attribute and point to a separate HTML, JS or CSS file respectively if you don’t like having all parts of the component in one file.
Setting Up a Project
Whilst the excellent Vue CLI exists to make setting up a full project easy, when starting out with a new library I like to do it all from scratch so I get more of an understanding of the tools.
These days, webpack is my preferred build tool of choice, and we can couple that with the vue-loader plugin to support the Vue.js component format that I mentioned previously. We’ll also need Babel and the env preset, so we can write all our code using modern JavaScript syntax, as well as the webpack-dev-server, which will update the browser when it detects a file change.
Let’s initialize a project and install the dependencies:
mkdir vue2-demo-project cd vue2-demo-project npm init -y npm i vue npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev
Then create the initial folders and files:
mkdir src touch webpack.config.js src/index.html src/index.js
The project structure should look like this:
. ├── package.json ├── package-lock.json ├── src │ ├── index.html │ └── index.js └── webpack.config.js
Now let’s set up the webpack configuration. This boils down to the following:
Tell webpack to use the vue-loader for any .vue files
Tell webpack to use Babel and the env preset for any .js files
Tell webpack to generate an HTML file for the dev-server to serve, using src/index.html as a template:
//webpack.config.js const VueLoaderPlugin = require('vue-loader/lib/plugin') const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new VueLoaderPlugin(), new HtmlWebPackPlugin({ template: "./src/index.html" }) ] }
Finally, we’ll add some content to the HTML file and we’re ready to go!
<!-- src/index.html --> <!DOCTYPE html> <html> <head> <title>My Vue App</title> </head> <body> <div id="app"></div> </body> </html>
We create an empty div with the ID of app, as this is the element that we’re going to place our Vue application in. I always prefer to use a div, rather than just the body element, as that lets me have control over the rest of the page.
Writing Our First Vue.js App
We’re going to stay true to every programming tutorial ever and write a Vue application that puts “Hello, World!” onto the screen before we dive into something a bit more complicated.
Each Vue app is created by importing the library and then instantiating a new Vue instance:
import Vue from 'vue' const vm = new Vue({ el: '#app', })
We give Vue an element to render onto the page, and with that, we’ve created a Vue application! We pass a selector for the element that we want Vue to replace with our application. This means when Vue runs it will take the div#app that we created and replace it with our application.
The reason we use the variable name vm is because it stands for “View Model”. Although not strictly associated with the “Model View View-Model” (MVVM) pattern, Vue was inspired in part by it, and the convention of using the variable name vm for Vue applications has stuck. Of course, you can call the variable whatever you’d like!
So far, our application isn’t doing anything, though, so let’s create our first component, App.vue, that will actually render something onto the page.
Vue doesn’t dictate how your application is structured, so this one is up to you. I ended up creating one folder per component, in this case App (I like the capital letter, signifying a component), with three files in it:
index.vue
script.js
style.css
mkdir src/App touch src/App/{index.vue,script.js,style.css}
The file structure should now be:
. ├── package.json ├── package-lock.json ├── src │ ├── App │ │ ├── index.vue │ │ ├── srcipt.js │ │ └── style.css │ ├── index.html │ └── index.js └── webpack.config.js
App/index.vue defines the template, then imports the other files. This is in keeping with the structure recommended in the What About Separation of Concerns? section of Vue’s docs.
<!-- src/App/index.vue --> <template> <p>Hello, World!</p> </template> <script src="./script.js"></script> <style scoped src="./style.css"></style>
I like calling it index.vue, but you might want to call it app.vue too so it’s easier to search for. I prefer importing App/index.vue in my code versus App/app.vue, but again you might disagree, so feel free to pick whatever you and your team like best.
For now, our template is just <p>Hello, World!</p>, and I’ll leave the CSS file blank. The main work goes into script.js, which looks like so:
export default { name: 'App', data() { return {} }, }
Doing this creates a component which we’ll give the name App, primarily for debugging purposes, which I’ll come to later, and then defines the data that this component has and is responsible for. For now, we don’t have any data, so we can just tell Vue that by returning an empty object. Later on, we’ll see an example of a component using data.
Now we can head back into src/index.js and tell the Vue instance to render our App component:
import Vue from 'vue' import AppComponent from './App/index.vue' const vm = new Vue({ el: '#app', components: { app: AppComponent, }, render: h => h('app'), })
Firstly, we import the component, trusting webpack and the vue-loader to take care of parsing it. We then declare the component. This is an important step: by default, Vue components are not globally available. Each component must have a list of all the components they’re going to use, and the tag that it will be mapped to. In this case, because we register our component like so:
components: { app: AppComponent, }
This means that in our templates we’ll be able to use the app element to refer to our component.
Finally, we define the render function. This function is called with a helper — commonly referred to as h — that’s able to create elements. It’s not too dissimilar to the React.createElement function that React uses. In this case, we give it the string 'app', because the component we want to render is registered as having the tag app.
More often than not (and for the rest of this tutorial) we won’t use the render function on other components, because we’ll define HTML templates. But the Vue.js guide to the render function is worth a read if you’d like more information.
Once we’ve done that, the final step is to create an npm script in package.json:
"scripts": { "start": "webpack-dev-server --mode development --open" },
Now, run npm run start. Your default browser should open at http://localhost:8080/ and you should see “Hello, World!” on the screen.
Try editing src/index.vue to change the message to something else. If all has gone correctly, webpack-dev-server should refresh the page to reflect your changes.
Yay! We’re up and running with Vue.js.
The post Getting up and Running with the Vue.js 2.0 Framework appeared first on SitePoint.
by Jack Franklin via SitePoint http://bit.ly/2UhqBca
0 notes
Quote
Welcome If you want to learn how to work with the sort() method in your Python projects, then this article is for you. This method is very powerful and you can customize it to fit your needs, so let's see how it works in detail. You will learn: How to use this method and customize its functionality. When to use it and when not to use it. How to call it passing different combinations of arguments. How to sort a list in ascending and descending order. How to compare the elements of a list based on intermediate values. How you can pass lambda functions to this method. How this method compares to the sorted() function. Why the sort() method performs a stable sort. How the process of mutation works behind the scenes. Are you ready? Let's begin! ⭐ Purpose and Use Cases With the sort() method, you can sort a list in either: Ascending Order Descending Order Particularly, this method is used to sort a list in place, which means that it mutates it or modifies it directly without creating additional copies, so remember: You will learn more about mutation in this article (I promise!) but for now it's very important that you know that the sort() method modifies the list, so its original version is lost permanently in the program. Because of this, you should only use this method if: You want to modify (sort) the list permanently. You don't need to keep the original version of the list. If this fits your needs, then the .sort() method is exactly what you are looking for. 🔸 Syntax and Arguments Let's see how you can call .sort() to take advantage of its full power. This is the most basic call (with no arguments): If you don't pass any arguments, by default: The list will be sorted in ascending order. The elements of the list will be compared directly using their values, with the >> b = [6, 3, 8, 2, 7, 3, 9] >>> b.sort() >>> b [2, 3, 3, 6, 7, 8, 9] # Sorted! Custom Arguments To customize how the sort() method works, you can pass two optional arguments: Key Reverse Let's see how they change the behavior of this method. Here we have a method call with these two arguments: Before explaining how they work, I would like to explain something that you probably noticed in the diagram (above): in the method call, the names of the parameters have to be included before their corresponding values, like this: key= reverse= This is because they are keyword-only arguments. If you are passing a custom value for them, their names have to be specified in the method call, followed by an equal sign = and their corresponding values, like this: Otherwise, if you try to pass the arguments directly as we normally do for positional parameters, you will see this error because the function will not know which argument corresponds to which parameter: TypeError: sort() takes no positional arguments Reverse Now that you now what keyword-only arguments are, let's start with reverse. The value of reverse can be either True or False: False means that the list will be sorted in ascending order. True means that the list will be sorted in descending (reverse) order. 💡 Tip: By default, its value is False if you don't pass any arguments for this parameter, so the list is sorted in ascending order. Here we have a few examples: By default, reverse is False# List of Integers >>> b = [6, 3, 8, 2, 7, 3, 9] >>> b.sort() >>> b [2, 3, 3, 6, 7, 8, 9] # List of Strings >>> c = ["A", "Z", "D", "T", "U"] >>> c.sort() >>> c ['A', 'D', 'T', 'U', 'Z'] 💡 Tip: If the elements of the list are strings, they are sorted alphabetically. To specify that reverse is True, so the list has to be sorted in descending (reverse) order.# List of Integers >>> b = [6, 3, 8, 2, 7, 3, 9] >>> b.sort(reverse=True) >>> b [9, 8, 7, 6, 3, 3, 2] # List of Strings >>> c = ["A", "Z", "D", "T", "U"] >>> c.sort(reverse=True) >>> c ['Z', 'U', 'T', 'D', 'A'] 💡 Tip: Notice how the list is sorted in descending order if reverse is True. Key Now that you know how to work with the reverse parameter, let's see the key parameter. This parameter is a little bit more detailed because it determines how the elements of the list are be compared during the sorting process. Basic SyntaxThe value of key is either: None, which means that the elements of the list will be compared directly. For example, in a list of integers, the integers themselves can be used for the comparison. A function of one argument that generates an intermediate value for each element. This intermediate value is calculated only once and it's used to make the comparisons during the entire sorting process. We use this when we don't want to compare the elements directly, for example, when we want to compare strings based on their length (the intermediate value). 💡 Tip: By default, the value of key is None, so the elements are compared directly. For example: Let's say that we want to sort a list of strings based on their length, from the shortest string to the longest string. We can pass the function len as the value of key, like this: >>> d = ["aaa", "bb", "c"] >>> d.sort(key=len) >>> d ['c', 'bb', 'aaa'] 💡 Tip: Notice that we are only passing the name of the function (len) without parenthesis because we are not calling the function. This is very important. Notice the difference between comparing the elements directly and comparing their length (see below). Using the default value of key (None) would have sorted the strings alphabetically (left) but now we are sorting them based on their length (right): What happens behind the scenes? Each element is passed as argument to the len() function and the value returned by this function call is used to perform the comparisons during the sorting process: This results in a list with a different sorting criteria: length. Here we have another example: Another interesting example is sorting a list of strings as if they were all written in lowercase letters (for example, make "Aa" equivalent to "aa"). According to lexicographical order, capital letters come before lowercase letters: >>> "E" So the string >> "Emma" < "emily" True >>> "emma" < "emily" False To avoid distinguishing between capital and lowercase letters, we can pass the function str.lower as key. This will generate a lowercase version of the strings that will be used for the comparisons: >>> e = ["Emma", "emily", "Amy", "Jason"] >>> e.sort(key=str.lower) >>> e ['Amy', 'emily', 'Emma', 'Jason'] Notice that now, "emily" comes before "Emma" in the sorted list, which is exactly what we wanted. 💡 Tip: if we had used the default sorting process, all the strings that started with an uppercase letter would have come before all the strings that started with a lowercase letter: >>> e = ["Emma", "emily", "Amy", "Jason"] >>> e.sort() >>> e ['Amy', 'Emma', 'Jason', 'emily'] And... This is an example using Object-Oriented Programming (OOP): If we have this very simple Python class: >>> class Client: def __init__(self, age): self.age = age And we create four instances: >>> client1 = Client(67) >>> client2 = Client(23) >>> client3 = Client(13) >>> client4 = Client(35) We can make a list that references them: >>> clients = [client1, client2, client3, client4] Then, if we define a function to get the age of these instances: >>> def get_age(client): return client.age We can sort the list based on their age, passing the function as argument: >>> clients.sort(key=get_age) This is the final, sorted version of the list. We use a for loop to print the age of the instances in the order that they appear in the list: >>> for client in clients: print(client.age) 13 23 35 67 Exactly what we wanted, now the list is sorted in ascending order based on the age of the instances. 💡 Tip: Instead of defining a get_age function, we could have used a lambda function to get the age of each instance, like this: >>> clients.sort(key=lambda x: x.age) Lambda functions are small and simple anonymous functions, which means that they don't have a name. They are very helpful for these scenarios, when we only want to use them in particular places for a very short period of time. This is the basic structure of the lambda function that we are using to sort the list: Basic Structure of a Lambda Function Passing Both Arguments Awesome! Now you know to customize the functionality of the sort() method, but you can take your skills to a whole new level by combining the effect of key and reverse in the same method call: >>> f = ["A", "a", "B", "b", "C", "c"] >>> f.sort(key=str.lower, reverse=True) >>> f ['C', 'c', 'B', 'b', 'A', 'a'] Sort the list in reverse order as if the strings were in all lowercase.These are the different combinations of the arguments and their effect: The Order of Keyword-Only Arguments Doesn't Matter Since we are specifying the names of the arguments, we already know which value corresponds to which parameter, so we can include either key or reverse first in the list and the effect will be exactly the same. So this method call: Is equivalent to: This is an example: >>> a = ["Zz", "c", "y", "o", "F"] >>> a.sort(key=str.lower, reverse=True) >>> a ['Zz', 'y', 'o', 'F', 'c'] If we change the order of the arguments, we get the exact same result: >>> a = ["Zz", "c", "y", "o", "F"] >>> a.sort(reverse=True, key=str.lower) >>> a ['Zz', 'y', 'o', 'F', 'c'] 🔹 Return Value Now let's talk a little bit about the return value of this method. The sort() method returns None, it does not return a sorted version of the list, like we might intuitively expect. According to the Python Documentation: To remind users that it operates by side effect, it does not return the sorted sequence. Basically, this is used to remind us that we are modifying the original list in memory, not generating a new copy of the list. This is an example of the return value of sort(): >>> nums = [6.5, 2.4, 7.3, 3.5, 2.6, 7.4] # Assign the return value to this variable: >>> val = nums.sort() # Check the return value: >>> print(val) None See? None was returned by the method call. 💡 Tip: It is very important not to confuse the sort() method with the sorted() function, which is a function that works very similarly but doesn't modify the original list (it generates and returns a new copy of the list, already sorted). This is an example that we can use to compare them: # The sort() method returns None >>> nums = [6.5, 2.4, 7.3, 3.5, 2.6, 7.4] >>> val = nums.sort() >>> print(val) None Example of .sort()# sorted() returns a new list, a sorted copy of the original list >>> nums = [6.5, 2.4, 7.3, 3.5, 2.6, 7.4] >>> val = sorted(nums) >>> val [2.4, 2.6, 3.5, 6.5, 7.3, 7.4] # But it doesn't modify the original list >>> nums [6.5, 2.4, 7.3, 3.5, 2.6, 7.4] Example of sorted()This is very important because their effect is very different. Using the sort() method when you intended to use sorted() can introduce serious bugs to your program because you might not realize that the list is being mutated. 🔸 The sort() Method Performs a Stable Sort Now let's talk a little bit about the characteristics of the sorting algorithm used by sort(). This method performs a stable sort because it works with an implementation of TimSort, a very efficient and stable sorting algorithm. According to the Python Documentation: A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). This means that if two elements have the same value or intermediate value (key), they are guaranteed to stay in the same order relative to each other. Let's see what I mean with this. Please take a look at this example for a few moments: >>> d = ["BB", "AA", "CC", "A", "B", "AAA", "BBB"] >>> d.sort(key=len) >>> d ['A', 'B', 'BB', 'AA', 'CC', 'AAA', 'BBB'] We are comparing the elements based on their length because we passed the len function as the argument for key. We can see that there are three elements with length 2: "BB", "AA", and "CC" in that order. Now, notice that these three elements are in the same relative order in the final sorted list: This is because the algorithm is guaranteed to be stable and the three of them had the same intermediate value (key) during the sorting process (their length was 2, so their key was 2). 💡 Tip: The same happened with "A" and "B" (length 1) and "AAA" and "BBB" (length 3), their original order relative to each other was preserved. Now you know how the sort() method works, so let's dive into mutation and how it can affect your program. 🔹 Mutation and Risks As promised, let's see how the process of mutation works behind the scenes: When you define a list in Python, like this: a = [1, 2, 3, 4] You create an object at a specific memory location. This location is called the "memory address" of the object, represented by a unique integer called an id. You can think of an id as a "tag" used to identify a specific place in memory: You can access a list's id using the id() function, passing the list as argument: >>> a = [1, 2, 3, 4] >>> id(a) 60501512 When you mutate the list, you change it directly in memory. You may ask, why is this so risky? It's risky because it affects every single line of code that uses the list after the mutation, so you may be writing code to work with a list that is completely different from the actual list that exists in memory after the mutation. This is why you need to be very careful with methods that cause mutation. In particular, the sort() method mutates the list. This is an example of its effect: Here is an example: # Define a list >>> a = [7, 3, 5, 1] # Check its id >>> id(a) 67091624 # Sort the list using .sort() >>> a.sort() # Check its id (it's the same, so the list is the same object in memory) >>> id(a) 67091624 # Now the list is sorted. It has been mutated! >>> a [1, 3, 5, 7] The list was mutated after calling .sort(). Every single line of code that works with list a after the mutation has occurred will use the new, sorted version of the list. If this was not what you intended, you may not realize that other parts of your program are working with the new version of the list. Here is another example of the risks of mutation within a function: # List >>> a = [7, 3, 5, 1] # Function that prints the elements of the list in ascending order. >>> def print_sorted(x): x.sort() for elem in x: print(elem) # Call the function passing 'a' as argument >>> print_sorted(a) 1 3 5 7 # Oops! The original list was mutated. >>> a [1, 3, 5, 7] The list a that was passed as argument was mutated, even if that wasn't what you intended when you initially wrote the function. 💡 Tip: If a function mutates an argument, it should be clearly stated to avoid this sort of problems that could definitely introduce bugs in your program. 🔸 Summary of the sort() Method The sort() method lets you sort a list in ascending or descending order. It takes two keyword-only arguments: key and reverse. reverse determines if the list is sorted in ascending or descending order. key is a function that generates an intermediate value for each element, and this value will be used to do the comparisons during the sorting process. The sort() method mutates the list, causing permanent changes. You need to be very careful and only use it if you will not need the original version of the list. I really hope that you liked my article and found it helpful.
http://damianfallon.blogspot.com/2020/04/the-python-sort-list-array-method.html
0 notes
Text
The Ultimate Guide to JavaScript Algorithms: Anagrams
Hooray! This article marks the last string manipulation challenge in this section of this course. We've come a long way!
In this challenge, we consider two ways to detect anagrams in JavaScript.
What is an Anagram?
A word is said to be an anagram of another when it can be formed by rearranging the letters of the other word using each letter just once. E.g listen is an anagram of silent.
Let’s get busy, shall we?
You should already have your development environment setup for this course. Update your cloned repository by running the command git pull. Inside the Beginner folder, navigate to the isAnagram folder. Our work for this challenge will be done in here. Make sure to follow along in theindex-START.js file.
The Challenge
Given two strings, write an algorithm to check if they are anagrams of each other. Return true if they pass the test and false if they don't. E.g
isAnagram('silent', 'listen') // should return true
Algorithmic Thinking
In solving this challenge, we write a function that'd accept two parameters i.e the two strings to be compared.
Within the function, we compare both words to see if they contain the same characters used the same number of times. To avoid errors, we sanitize the string thus getting rid of unwanted characters and spaces since these are not letters of the alphabet.
We also convert all characters to a common letter case before carrying out any comparisons to avoid errors due to varying capitalization. Checking that both words are of the same length is also very important as this is a primary factor for a valid comparison.
Let's do this.
Code Implementation
We will now consider two ways to implement our solution following our algorithmic logic above. They are:
Direct Comparison
Character Map Comparison
Direct comparison
In this approach, we define a function that accepts two parameters i.e the two strings to be compared. We then go ahead to clean up both strings to ensure that we are comparing only letters and in a common case.
Cleaning Up the String To clean up the string, we create a function sanitizeString. This function accepts the string to be sanitized as a parameter and the uses the .toLowerCase(), .replace(), .split(), .sort() and .join() methods to manipulate the string as shown below:
const sanitizeString = function (str) { return str.toLowerCase().replace(/[^a-z\d]/g, '').split('').sort().join(''); }
Lets break things down a little:
First, we convert the entire string to lowercase using the .toLowerCase() method.
Next, we use the .replace() method to search through the string using the specified regular expression pattern and replace every non alphabetical character with an empty string. This leaves us with only letters. No spaces, no symbols!
Next, we call .split() to split the string into an array of characters.
Using the .sort() method, we sort the letters (elements) within the array in alphabetical order.
And finally, we join the now alphabetically ordered array of letters back together to form a string once again.
This string is what we return as the sanitized string.
Smooth! Right?
Comparing the Sanitized Strings Sanitizing the string as done above is perhaps the trickiest part of this solution. Next, we simply clean up the strings received using the sanitizeString function and compare the results. If both strings match, we return true signifying that they pass as anagrams. If they do not match, we return false signifying that they aren't.
See the complete solution below:
function isAnagram(stringA, stringB) { const sanitizeString = function (str) { return str.toLowerCase().replace(/[^a-z\d]/g, '').split('').sort().join(''); } return sanitizeString(stringA) == sanitizeString(stringB) }
One down! Let's get weirder! 😈
As you'll see, the approach we shall now consider follows a more step-by-step procedure to solving the problem.
Character Map Comparison
In this approach, we first generate a character map using our createCharMap function.
What is a character map?
As used in this context , a character map object is an object that maps every character in a string to the number of times it occurs within the string.
Creating the Character Map In our createCharMap function below, we use a for…of loop to iterate through each character of the string received.
function createCharMap(text) { let charMap = {} for (let char of text) { if (charMap.hasOwnProperty(char)) { charMap[char]++ } else { charMap[char] = 1 } } return charMap }
For each character, we check if the character already exist as a property in the charcter map charMap using the .hasOwnProperty() method. If it does, we increment it's value and if it doesn't, we add the character as a property and set it's value to 1.
In the end, we return charMap which is the character map object.
Comparing Character Maps Now that we have a way of generating the character maps, the next step will be to compare the character maps for both strings as shown in the complete solution below:
function isAnagram(stringA, stringB) { function createCharMap(text) { let charMap = {} for (let char of text) { if (charMap.hasOwnProperty(char)) { charMap[char]++ } else { charMap[char] = 1 } } return charMap } if (stringA.length === stringB.length) { let stringAMap = createCharMap(stringA) let stringBMap = createCharMap(stringB) for (let char in stringAMap) { if (stringAMap[char] !== stringBMap[char]) { return false } } return true } else { return false } }
Notice that we first check if the length of both strings are equal. If they aren't, we return false as this is an indicator that they can never be anagrams. If they are however, we go further to generate their character maps stored as variables stringAMap and stringBMap.
Next, we use the for…in loop to compare every character and value in stringAMap to the character’s corresponding value in stringBMap. If any values do not match, we return false as an indication that the strings aren't anagrams. However, if all values match, the test is passed and we return true as an indication that the tested strings are anagrams indeed.
We made it. A longer implementation indeed but it's definitely a more explanatory one.
Lets run our tests now, shall we?
Testing
Testing Correctness with Jest
To test each solution above, run the following command from your terminal:
npm run test isAnagram
Direct Comparison
Character Map Comparison
It appears we always do great! We passed all tests.
Testing Performance with JSPerf
Here, we run a performance test to determine which solution is faster. Find a screenshot of the result below:
From the result, we observe that:
The faster implementation is the Character Map Comparison approach and the Direct Comparison method though concise is approximately 52% slower.
**Surprising isn’t it? The metrics never lie though!**
Practical Application
The algorithms explored above may be applied in various ways. These include:
Encryption
Password Generation
Trusted Time-stamping
Coding Interviews
Generating Mnemonics
Word games
Conclusion
While considering the techniques and concepts explored above, we have learnt valuable ways to manipulate strings in order to determine if they are anagrams. We also explored various areas in which this knowledge can be directly utilized.
After running our performance tests we can now conclude that the most optimal approach to solving this problem is the Character Map Comparison method.
Further Reading
To learn more about the concepts and techniques highlighted above, you may use the following links:
Regular Expressions
.replace()
.split()
.sort()
.join()
.hasOwnProperty()
For…of vs for…in loop
See you in the next set of articles focused on array manipulation algorithms!✌🏿
The Ultimate Guide to JavaScript Algorithms: Anagrams published first on https://deskbysnafu.tumblr.com/
0 notes
Text
How to secure your WordPress website in 2019
I’ve worked with WordPress more or less since it was released in 2004. In that time I’ve lost count of the amount of conversations I’ve had with website owners (and a few IT professionals) adamant that WordPress isn’t secure. This is only partially true. A bit like your computer at home, if you don’t add some sort of security you leave it open to attack.
WordPress is the most popular content management system (CMS) in the world today. Powering around 30% of all websites and 60% of all CMS’, the scale that WordPress is used makes it a natural target for hackers.
There are however a number of simple ways you can secure your WordPress website. These simple steps will give you the advantage as hackers are more likely to try and hack a website with no security (and there are a lot of those) than waste time trying to hack a site that has already been secured.
Change the default username
Up until recently installing WordPress using the famous 5-minute install resulted in the default username being set to ‘admin’. As this was the same for all WordPress installs this meant hackers were already one step closer to gaining access to a site, when you know the username, all you have to do is guess the password.
Hackers will try and gain access to a WordPress website by doing what’s called a brute force attack. A brute force attack is a trial-and-error method used to try and guess the password of a WordPress website, if they already know ‘admin’ is being used as a username, a script can be created to simply run thousands of combinations of passwords until the correct one is guessed.
So, if your WordPress website still has ‘admin’ as a username, change it immediately. Make the username and password combinations as complex as possible to ensure brute force attacks don’t happen in the first place.
Rename the default login url
All WordPress websites have the same admin area login url which is /wp-admin. This makes it easy for hackers to target the login page as all they have to do is add /wp-admin to the end of a WordPress domain and they know the location to hack.
You’ll need a plugin to be able change the admin url. There are free options available but we would recommend Manage WP or WPMU Defender. Changing the admin url to something complex as opposed to /login is also highly recommended.
Add Google reCAPTCHA to your login url
Once you’ve updated your admin url you can further secure the page by adding Google reCAPTCHA. Google reCAPTCHA is a free service that helps to protect all websites (not just WordPress) against spam and abuse. Now onto reCAPTCHA version 3, the irritating pop ups from version 2 asking you to select all the pictures of ‘buses’ or ‘store fronts’ have long gone. reCAPTCHA 3 works behind the scenes to keep bots and automated software from accessing and abusing your website.
You will need a plugin to secure the WordPress admin area. We use WordPress ReCaptcha Integration. You will need to set up valid API keys from the official Google reCAPTCHA website. Once setup it adds an extra layer of security to your websites and helps keep the hackers at bay.
Keep WordPress core files up to date
WordPress core files are the files needed to make your WordPress website work. These files are the same for every WordPress install. They control the admin area and give developers the control and functionality they need to design and build your website.
The team behind WordPress constantly work to further develop and improve the platform. Part of their job is to ensure WordPress remains safe and secure, so they regularly provide bug fixes and security updates.
WordPress updates come in two forms, major and minor updates. Major updates usually contain new functionality. Minor updates usually contain bug-fixes and security patches. That is why it is important to keep your WordPress install up to date. Older versions of WordPress may contain vulnerabilities which hackers may be able to exploit. Keeping your WordPress install up to date makes hacking your site a lot more difficult.
Keep your themes and plugins up to date
The majority of themes and plugins aren’t built by the WordPress team, they are usually built by third parties. There are pros and cons to this.
The pros are there are thousands of themes available and well over 50,000 plugins on the WordPress Plugins directory.
The cons are a lot themes and plugins aren’t built very well. It’s usually the smaller, less supported themes and plugins that cause problems as they are not kept up to date as they should be.
Hackers are always looking to exploit vulnerabilities in WordPress and themes and plugins are a good place to start. Once a hacker has found a way to exploit the code in a theme or plugin they can gain access to your website and cause all manor of chaos.
If you have a theme or plugins that need to be updated it is likely because the theme or plugin developer has issued an update to tackle bug-fixes or other security issues. If the update contains a bug or security fix it’s important to run the theme or plugin update to ensure your website is protected.
Ban undesirable users
Another way to further secure the WordPress admin area is to ban users after too many failed login attempts. Using the WPMU Defender plugin you can set a limit of three failed login attempts before a user is blocked from the site. They can log in again after a few hours just in case it is a genuine failed login attempt.
The WPMU Defender plugin also allows you to create a username blacklist. You can add usernames such as “admin” and “administrator” so any hackers using these username get instantly banned from your WordPress website.
Create strong passwords
This is a bit of a no brainer this one. When selecting a new password, or reseting one make sure you follow the prompts WordPress gives you and select something complex. The weaker the password the easier it is for hackers to guess it. Ensure you use a mix of small letters, capital letters, numbers and special characters.
Reset your WordPress security keys
WordPress security keys can be found in the installs wp-config.php file. Security keys are a string of random variables used for the authorisation and encryption of cookies generated by WordPress. Usually these cookies are used to verify the identity of logged in users and commenters. During the install process there is no need to set these keys as WordPress takes care of this as part of the installation process. However once your website is up and running it is recommend to reset these keys every 60 days or so. You can do this manually or to make life easier you can use a plugin such as WPMU Defender Pro.
Automatically log out idle users
If you work in an office environment and have several administrators managing your WordPress website it may be worth setting up the Bullet Proof Security Pro plugin to log out any idle users. This is to protect against anyone leaving the admin area open when they are away from their computer. If you manage your WordPress website from home this may not be such a big issue.
Make regular backups
If the worst does happen and your WordPress website does get hacked an easy way to deal with the hacked content is to perform a restore of your websites files and database.
Restoring the website to an earlier date can save you a heap of time. Rather than trying to remove all the hacked content from your website, a simple restore will take the site back to before the attack happened. You can then secure your website by checking through the steps above, changing all passwords to both the WordPress admin area and the database.
Your hosting provider may already include a backup feature as part of your websites hosting. If not, then you can use one of the many WordPress plugins available such as VaultPress or Snapshot Pro. Website files and databases can be uploaded to a number of cloud storage providers such as Google Drive and Dropbox.
Use an SSL to encrypt WordPress data
You may have noticed that some website addresses start with https:// rather than http://. The ’s’ lets you know that the website you are on has an SSL installed. An SSL stands for Secure Sockets Layer. It is a standard security protocol and means your connection to a website is secure and encrypted.
The primary reason to use an SSL is to encrypt the data sent from a users computer to the websites server. This is important because without an SSL any information sent would be unencrypted and therefore potentially viewable to hackers and identity thieves. Data sent through your website will usually be done through some sort of form, maybe a contact form containing name, email and telephone details. If you have an e-commerce website customers might place an order using a credit card, it’s absolutely crucial this information in encrypted so that the information doesn’t fall into the wrong hands.
As well as the security benefits to using an SSL there are also some SEO benefits. Google has over 200 ranking factors and one of them is whether or not a website is secure. Additionally, in July 2018 Google began its clamp down on unencrypted websites. From Chrome 68 onwards any website that doesn’t have an SSL is marked as ‘Not secure’. Although this doesn’t impact SEO directly, it isn’t great for your website visitors to see a ‘Not secure’ notification right next to your domain name.
You can purchase SSL certificates from a number of providers but it is worth doing some research on what SSL is best for your business. If you have an e-commerce website you may need an SSL with extended validation (EV SSL) or if you have a web site with a subdomain you may be better off with a wildcard SSL.
Why do people want to hack a WordPress website?
This is a good question. Don’t be too blasé about security on your website, there are a number of reasons hackers will try and hack your WordPress website. It isn’t just big corporations hackers are looking to target, even small websites are of interest.
One of the more common hacking methods is to inject malicious code into your site. The code may contain links to a website the hacker is trying to drive a lot fo traffic too in a short space of time, in an attempt to cheat the search engine result pages (SERP’s). These links can be added through comment spam, hijacking your sites email or even added directly to your WordPress sites theme files.
Another way hackers can target your website is by spreading malware and viruses. This can be done by injecting malicious code into the backend of the website, either into the WordPress core files or by adding additional files that shouldn’t be there. When your site visitors then interact with this code hackers can gain the users information or spread the virus directly to their computer or website.
One of the more obvious reasons a website might hacked is to steal your customers information. This might not be such as issue if you don’t store any customer data on your website, but if you have an e-commerce website you may well have customer names, emails, phone numbers, address’ and maybe even their credit card information. If this data were to get into the hands of hackers then it would be clear violation of the new GDPR laws that came into place on 25th May 2018. The reasons for hackers wanting these details is usually for a monetary gain, either by using a customers credit card or selling the data onto third parties.
Another method is when hackers try to overload a web server with an influx of hits, otherwise known as a denial of service, or a DDoS attack. Once your website hits it’s bandwidth threshold limit, your website goes offline. This doesn’t usually happen with smaller websites as a DDoS attack is usually when hackers are looking to show off, or perhaps they have a personal dislike of the brand they are attacking. They may even send ransom demands.
What happens if my WordPress site gets hacked?
First off, don’t panic. A hacked WordPress website is usually fairly easy to deal with. The first thing you should do is change all of your passwords. This includes all the passwords for the user accounts in the admin area. If you have access and are capable, also change your database password. You should be able to do this from your hosting control panel. The password will also need updating in the wp-config.php file. Remember to use complex passwords. Changing these passwords stops any further attacks on your website.
Once you changed your passwords you can deal with the hacked content. There are a number of ways you can do this. If you are confident FTP’ing onto your server and accessing your WordPress installation files then you can try and identify any files that shouldn’t be there, or any code that has been injected into files where it shouldn’t be. There are a number of WordPress plugins that will help you identify these files. Wordfence WordPress Security Plugin and MPMU Defender Pro are a couple of the better ones. They will scan the entire WordPress directory on your server and highlight any files that shouldn’t be there, or any files with code that shouldn’t be there and present you with a report. You can then work through the report and remove the infected files and code. If the site has been heavily infected there might be many thousands of files you need to go through. In this scenario it is often better to start with a completely fresh install of WordPress and plugins. Then it’s just the theme folder you need to manually tidy up.
If you would rather have an expert deal with your hacked WordPress website there are a number of companies online that offer these services. We would be wary of anyone offering to do it at a low cost as even dealing with a simple hacked WordPress site is probably a few hours work if it is done correctly.
The above said, prevention is always better than cure. If you can action the points mentioned in this article it’s unlikely you will ever get hacked. We mentioned earlier in the article that hackers like an easy target. According to research carried out by Alexa, statistics from 40,000 WordPress websites in Alexa’s top 1 million websites show that more than 70% of WordPress installations are vulnerable to hackers. That means only 30% have at least some security in place. If you can make your website one of those 30% it’s likely hackers will leave you alone and concentrate on the 70% of websites that are vulnerable.
Find out more
We’ve been working with WordPress since it launched in 2004, there aren’t many technical issues we haven’t dealt with and have fixed numerous hacked WordPress websites. If you need some help securing your WordPress website or dealing with a hacked WordPress website please call us on 01626 245061 or email us at [email protected].
The post How to secure your WordPress website in 2019 appeared first on Priority Pixels.
Article source here: How to secure your WordPress website in 2019
0 notes
Text
Java Hello World Program In Hindi

Java First Program in Hindi
Input class first1{ public static void main(Stringargs) { System.out.println("hello world"); } } Output hello world • class :- हम java में जो भी programm लिखते है वह class के अंदर ही लिखते है। क्युकी यह OOPS के concepts को follow करता है। class को हम objects का collection कहते है क्युकी class के अंदर हम बहुत सारे object को defined करते है। class बिलकुल भी memory consume नहीं करता। यह object का blueprint or logical entity hota है। class को हम class name से defined करते है जैसे हमारी class का नाम first1 है। classfirst1{ } Public static void main(Stringargs) - Public :- Public एक acces modifier है। इसका का use हम main method को class के बहार से acces करने के लिए करते है JVM हमारे program को run करता है। but हमारी main method ही public नहीं होगी तोः jvm program को run नहीं कर पायेगा। - static :- main method को static इसलिए किया जाता है क्युकी हम class के object को बिना बनाये main method को acces करपये। जितने भी static member होते है वह object से deal नहीं करते है। but हम static का use नहीं करते है तोह हमे class के अंदर objects को defined करना पड़ेगा - Void :- void एक data type है जिसको हम function के पहले लिखते है। void का मतलब हमे कोई भी value return नहीं करनी है। - String :- String एक pre defined class होती है जितने भी Java में predefined class होती है।उनका first letter capital होता है 'String'. args एक array type का variable है जिसका use हम main method में कोई भी information pass कर सके इसलिए होता है। यदि हमे कोई भी information pass नहीं करना तोह भी हमे Stringargs को main method में defined करना पड़ेगा क्युकी यह syntax का part है। System.out.println("hello world"); - System :- System एक predefined class है जो 'Java.lang' package के अंदर defined है। - OUT :- out जो है print stream class का object है - println :- println एक method है जो हमारे message को output screen पर print करता है। ln curser एक line से next line पर move करता है। What is class in java Whatever program we write in java, we write it inside the class itself. Because it follows the concepts of OOPS. We call a class a collection of objects because we define many objects inside the class. The class does not consume memory at all. This is the blueprint or logical entity of the object. We define class by class name like our class name is first1. Public static void main(Stringargs) Public :- Public is an access modifier. We use this to access the main method from outside the class, JVM runs our program. But if our main method will not be public then: jvm will not be able to run the program. Static:- Main method is made static because we can access the main method without making the object of the class. All the static members are there, they do not deal with the object. But we do not use static, so we have to define the objects inside the class. Void: - void is a data type, which we write before the function. void means we do not have to return any value. String :- String is a pre defined class, as many predefined classes in Java. Their first letter capital is 'String'. args is an array type variable that is used so that we can pass any information to the main method. Even if we do not pass any information, we have to define String args in the main method because it is part of the syntax. System.out.println("hello world"); System :- System is a predefined class which is defined inside 'Java.lang' package. OUT :- out which is the object of print stream class println: - println is a method which prints our message on the output screen. The ln curser moves from one line to the next. Read the full article
0 notes
Text
What Are Bitcoins
Bitcoins Explained
Bitcoin is a form of virtual currency. With them, you do not have to physically buy goods by handing tokens or notes. They are mostly used for electronic transfers and purchases. You can, therefore, use Bitcoins to pay merchants or even friends. With Bitcoin, every purchase that one makes is logged in on the transaction log, which tracks vital information such as who owns Bitcoins and the time of purchase. To easily understand how the Bitcoin system works, think of the transaction as an audit trail that contains every single piece of vital information of every Bitcoin. This digital transaction is what is referred to as Block-Chain. Why the Price of a Bitcoin is Different at each Exchange
Bitcoins are more or less like other currencies when it comes to value. They simply fluctuate in values that are relative to other currencies. Just like how the Indian rupee had its value swinging wildly against major currencies like the US dollar; Bitcoins have had drastic fluctuations on Bitcoin charts. Since there is no centralized exchange for Bitcoin, its value is constantly changing on Bitcoin charts. Any time a Bitcoin changes ownership from a seller to a buyer, the two parties involved in the transaction must agree on a price. There is no such thing as a fixed price. It is simply the seller’s responsibility to give the buyer a fair valuation based on what Bitcoin charts indicate. All these can be understood since there is no bank that prints Bitcoins and sets relative values on Bitcoin charts. It always depends on supply and demand.
There are three major Bitcoin exchanges MTGOX, BTC-e and BitStamp. MTGOX is simply an exchange that allows Bitcoin users to trade Bitcoins for currencies like the US dollar, British Pound or Indian Rupee. It is based in Japan. BTC-e, on the other hand, is a Russian trade platform solely meant for selling Bitcoin and a number of other crypto-currencies. The last Bitcoin exchange is Bitsmap. It is based in Slovenia and allows Bitcoin users to exchange Bitcoins for US dollars.
Note that there is a big difference between bitcoin and Bitcoin. The difference lies in capitalization of the letter ‘b’. bitcoin refers to the entire system while Bitcoin refers to the currency. You have to understand the difference as most Bitcoin news and traders assume that all the other users understand the difference. Speaking of news, Bitcoin news in most journals and media outlets will not only help you to understand Bitcoin Charts live but the Day Trade Bitcoin which keeps changing from time to time. This means that you will always have to keep abreast with the Bitcoin news so as to know of the best Bitcoin exchange rates and understand more about Bitcoin charts.
Bitcoin Transactions
Bitcoin users can send and receive payments using client software on their personal computer, mobile device or via a web application. Transactions do not explicitly identify the payer and payee by name, a transaction transfers ownership from one Bitcoin address to another. Approximately every ten minutes, a block of transactions is confirmed to a shared public record called the block chain. This competitive mining process carries a reward of 25 bitcoins per block.
Example Bitcoin Address: 1JdGHcZ9FzVSwLhTxxp2XkYw8uUPEdADHH Bitcoin Software
Bitcoin client software, allows a user to transfer bitcoins. The first software was released in 2009 by Satoshi Nakamoto as an open source code (Bitcoin-QT). Bitcoin-Qt can be used as a desktop client for regular payments or as a utility for merchants or other payment services. Bitcoin-Qt has also supported mining, but this feature was removed because specialized mining clients seem more efficient. Wallets An Example of a Physical bitcoin A paper wallet Showing QR codes
Bitcoin creates public key cryptography, in which pairs of keys, one public and one private, get generated. A collection of keys is known as a wallet. A Bitcoin transaction transfers ownership to a new address, an alphanumeric string of the form.
The private keys create a safeguard; a valid payment message from an address must contain the associated public key and a digital signature proving possession of the associated private key verified by a bitcoin miner. Because anyone with a private key can spend all of the bitcoins sent to the corresponding address, the essence of Bitcoin security is protection of private keys.
Theft of bitcoins has occurred in the past. The practical security of Bitcoin wallets remains an to be a concern. Risk of theft can be reduced by generating keys offline on an un-compromised computer and saving them on external storage or paper printouts, like cheques.
Many vendors currently produce physical bitcoins. Bitcoin Block chain
Important to Bitcoin is a public database and a record of all transactions, known as the block chain. The block chain records current bitcoin ownership as well as a history of past bitcoin ownership. By keeping a record of transactions, the block chain eliminates the possibility of double-spending. Those that maintain the block chain are called miners. Payment processing work done by miners verifies each transaction and adds it to the block chain. Bitcoin processing fees are optional and generally lower than those of credit cards or electronic money transfers. By 2140 there will be approximately 21 million bitcoins in existence and transaction processing will be by transaction fees. Today’s transactions that pay a fee may be processed more quickly. Exchanges Further information: Digital currency exchanger
Through bitcoin exchanges, bitcoins get bought and sold at a variable price against the value of other currencies. While there may be a seemingly large number of bitcoin exchanges, they regularly fail taking client bitcoins with them. Bitcoin Economics
Bitcoin’s supply is predefined by the Bitcoin network. Currently there are over 12 million bitcoins in circulation, with a creation rate of 25 bitcoins approximately every ten minutes.
Since the money supply is fixed bitcoin is known as “inflation-proof”. At present the price of a bitcoin is volatile, which has led to some questions about it functioning as a currency. Some may say that this is a necessary “growing pain”, and that Bitcoin needs to grow to achieve stability.
Volatility has little effect on Bitcoin’s uses as a payment option for goods since merchants don’t need to price their goods in bitcoin and can immediately exchange their bitcoins for dollars. Processing fees are substantially lower than those of credit cards or money transfers making bitcoin attractive to merchants. Bitcoin is a good Alternative to national currencies
Bitcoins are accepted in this caf in the Netherlands as of 2013
Some people say that Bitcoin is gaining popularity in countries with problem-plagued currencies, as it can be used to circumvent inflation, capital controls, and international sanctions, bitcoin can be a solution to increases in national debt.
Bitcoins are being used by some Argentinians as an alternative to the official currency, which is hampered by inflation and strict capital controls. In addition, some Iranians use bitcoins to evade currency fees and online purchases.
https://ift.tt/2J9FJU8
0 notes
Text
NCERT Class 12 Computer Science Chapter 1 Review of Python
NCERT Class 12 Computer Science Python Solutions for Chapter 1 :: Review of Python
TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)
Question 1.Name the Python Library modules which need to be imported to invoke the following functions:
load ()
pow () [CBSE Delhi 2016]
Answer:
pickle
math
Question 2.Name the modules to which the following func-tions belong:
Uniform ()
fabs () [CBSE SQP 2016]
Answer:
random ()
math ()
Question 3.Differentiate between the round() and floor() functions with the help of suitable example.[CBSE Comptt. 2016]Answer:The function round() is used to convert a fractional number into whole as the nearest next whereas the function floor() is used convert to the nearest lower whole number, e.g.,round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks):
Question 1.Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]Answer:Total * Tax, class, 3rd Row, finally
Question 2.Name the Python Library modules which need to be imported to invoke the follwing functions :
sqrt()
dump() (CBSE Outside Delhi-2016)
Answer:
math
pickle
Question 3.Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]_Cost, Price*Qty, float, switch, Address one, Delete, Number12, doAnswer:Price *Qty, float, Address one, do
Question 4.Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python Program:Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My cityAnswer:Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of being either keyword or including space or operator or starting with integar.
Question 5.Name the function / method required for [CBSE SQP 2015]
Finding second occurrence of m in madam.
get the position of an item in the list.
Answer:
find
index
Question 6.Which string method is used to implement the following:
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character. [CBSE TextBook]
Answer:
len(str)
str.capitalize()
ch.isalnum()
str.upper()
str.replace(old,new)
Question 7.What is the difference between input() and raw_input()?Answer:raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically determines the correct type. We use the inputQ function when you are expecting an integer from the end-user, and raw_input when you are expecting a string.
Question 8.What are the two ways of output using print()?Answer:Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to combine the results of multiple print statements into a single line.
Question 9.Why does the expression 2 + 3*4 result in the value 14 and not the value 24?Answer:Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.
Question 10.How many times will Python execute the code inside the following while loop? You should answer the question without using the interpreter! Justify your answers.
i = 0 while i < 0 and i > 2 : print “Hello ...” i = i+1
Answer:0 times.
Question 11.How many times will Python execute the code inside the following while loop?
i = 1 while i < 10000 and i > 0 and 1: print “ Hello ...” i = 2 * i
Answer:14.
Question 12.Convert the following for loop into while loop, for i in range (1,100):
if i % 4 == 2 : print i, “mod”, 4 , “= 2”
Answer:
i=1 while i < 100: if i % 4 == 2: print i, “mod”, 4 , “= 2” i = i +1
Question 13.Convert the following for loop into while loop.
for i in range(10): for j in range(i): print '$', print"
Answer:
i=0 while i < 10: j=0 while j < i: print '$’ print"
Question 14.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(25,500,25): print a
Answer:
a=25 while a < 500: print a a = a + 25
Question 15.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9): print a
Answer:
a = 90 while a > 9: print a a = a-9
Question 16.Convert the following while loop into for loop:
i = 0 while i < 100: if i % 2 == 0: print i, “is even” else: print i, “is odd” i = i + 1
Answer:
for i in range(100): if i % 2 == 0: print i, “is even” else : print i, “is odd”
Question 17.Convert the following while loop into for loop
char = "" print “Press Tab Enter to stop ...” iteration = 0 while not char == “\t” and not iteration > 99: print “Continue?” char = raw_input() iteration+ = 1
Answer:
char = "" print “Press Tab Enter to stop ...” for iteration in range(99): if not char == ‘\t’: print “Continue?” char = raw_input()
Question 18.Rewrite the following while loop into for loop:
i = 10 while i<250: print i i = i+50
Answer:
for i in range(10, 250, 50): print i
Question 19.Rewrite the following while loop into for loop:
i=88 while(i>=8): print i i- = 8
Answer:
for i in range(88, 9, -8) print i
Question 20.Write for statement to print the series 10,20,30, ……., 300Answer:
for i in range(10, 301, 10): print i
Question 21.Write for statement to print the series 105,98,91,… .7Answer:
for i in range(105, 8, -7): print i
Question 22.Write the while loop to print the series: 5,10,15,…100Answer:
i=5 while i <= 100: print i i = i + 5
Question 23.How many times is the following loop executed? [CBSE Text Book]for a in range(100,10,-10):print aAnswer:9 times.
Question 24.How many times is the following loop executed? [CBSE Text Book]
i = 100 while (i<=200): print i i + =20
Answer:6 times
Question 25.State whether the statement is True or False? No matter the underlying data type if values are equal returns true,
char ch1, ch2; if (ch1==ch2) print “Equal”
Answer:True. Two values of same data types can be equal.
Question 26.What are the logical operators of Python?Answer:or, and, not
Question 27.What is the difference between ‘/’ and ‘//’ ?Answer:
// is Integer or Floor division whereas / is normal division (eg) 7.0 // 2 → 3.0 7.0/2 → 3.5
Question 28.How can we import a module in Python?Answer:1. using import
Syntax: import[,,...] Example: import math, cmath
2. using from
Syntax: fromimport[, ,.. ,] Example: . from fib. import fib, fib2.
Question 29.What is the difference between parameters and arguments?Answer:
S.No.ParametersArguments1Values provided in function headerValues provided in function call.2(eg) def area (r):—> r is the parameter(eg) def main() radius = 5.0 area (radius)—> radius is the argument
Question 30.What are default arguments?Answer:Python allowes function arguments to have default values; if the function is called without the argument, the argument gets its default value
Question 31.What are keyword arguments?Answer:If there is a function with many parameters and we want to specify only some of them in function call,then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6) ' def simpleinterest(p, r=0.2, n=3)
Question 32.What are the advantages of keyword arguments?Answer:It is easier to use since we need not remember the order of the arguments.We can specify the values for only those parameters which we want, and others have default values.
Question 33.What does “in” do?Answer:“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :Otherwise i+evaluates to false.
(eg) S = “Hello World" if “Hell” in S: print “True” will print True.
Question 34.What does “not in” do?Answer:“not in” is a membership operator. It evaluates to true if it does not finds a variable/stringin the specified sequence. Otherwise it evaluates to false,
(eg) S = “Hello World” if “Hell” not in S: print “False” will print False.
Question 35.What does “slice” do?Answer:The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.
(eg) S = “Hello World” print s[0:4] → Hell
Question 36.What is the use of negative indices in slicing?Answer:Python counts from the end (right) if negative indices are given.
(eg) S = “Hello” print S[:-3] >> He print S[-3:] >> llo
Question 37.Explain find() function?Answer:find (sub[,start[,end]])This function is used to search the first occurrence of the substring in the given string.It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.
(eg) str = “computer” - str.findf("om”) → 1
Question 38.What are the differences between arrays and lists?Answer:An array holds fixed number of values. List is of variable-length – elements can be dynamically added or removedAn array holds values of a single type. List in Python can hold values of mixed data type.
Question 39.What is the difference between a tuple and a list?Answer:A tuple is immutable whereas a list is a mutable.A tuple cannot be changed whereas a list can be changed internally.A tuple uses parenthess (()) whereas a list uses square brackets ([]).tuple initialization: a = (2, 4, 5)list initialization: a = [2, 4, 5]
Question 40.Carefully observe the following python code and answer the question that follows:x=5def func2():x=3global xx=x+1print xprint xOn execution the above code produces the following output.63Explain the output with respect to the scope of the variables.Answer:Names declared with global keyword have to be referred at the file level. This is because the global scope.If no global statement is being used the variable with the local scope is accessed.Hence, in the above code the statement succeeding the statement global x informs Python to incrementthe global variable xHence, the output is 6 i.e. 5 + 1 which is also the value for global x.When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)
Question 41.Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]Answer:Pythonuses two strategies for memory allocation-(i) Reference counting(ii) Automatic garbage collectionReference Counting: works by counting the number of times an object is referenced by other in the system.When an object’s reference count reaches zero, Python collects it automatically.Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater that the threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.
TOPIC – 2Writing Python Programs
Question 1.Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the code. [CBSE Delhi-2016]for Name in [Amar, Shveta, Parag]if Name [0] = ‘s’:Print (Name)Answer:
for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] : if Name [0] E == ‘S’ : Print (Name)
Question 2.Rewrite the following code is Python after removing all syntax errors(s).Underline each correction done in the code. [CBSE Outside Delhi-2016]for Name in [Ramesh, Suraj, Priya]if Name [0] = ‘S’:Print (Name)Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”] if Name [0] =_=‘S’ : print (Name)
Question 3.What will be the output of the following python code considering the following set of inputs?AMARTHREEA1231200Also, explain the try and except used in the code.Start = 0while True :Try:Number = int (raw input (“Enter Number”))breakexcept valueError : start=start+2print (“Re-enter an integer”)Print (start)Answer:Output:
Enter Number AMAR Re-enter an integer Enter Number THREE Re-enter an integer Enter Number A123 Re-enter an integer Enter Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the user.When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.
Question 4.Give the output of following with justification. [CBSE SQP 2015]
x = 3 x+ = x-x print x
Answer:Output: 3Working:
x = 3 x = (x+ x-x ):x = 3 + 3 - 3 = 3
Question 5.What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person: def init (self,id): self.id = id arjun = person(150) arjun. diet [‘age’] = 50 print arjun.age + len(arjun. diet )
Justify your answer.Answer:52arjun.age = 50arjun.dict has 2 attributes so length of it is 2. So total = 52.
Question 6.What would be the output of the following code snippets?print 4+9print “4+9”Answer:13 (addition), 49 (concatenation).
Question 7.Highlight the literals in the following programand also predict the output. Mention the types ofvariables in the program.
a=3 b='1' c=a-2 d=a-c e=“Kathy” f=‘went to party.’ g=‘with Sathy’ print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:a, c,d = integerb, e,f,g = stringOutput: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to party.
Question 8.What is the result of 4+4/2+2?Answer:4 + (4/2) + 2 = 8.
Question 9.Write the output from the following code: [CBSE Text Book]
x= 10 y = 20 if (x>y): print x+y else: print x-y
Answer:– 10
Question 10.Write the output of the following code:print “Python is an \n interpreted \t Language”Answer:Python is an interpreted Language
Question 11.Write the output from the following code:
s = 0 for I in range(10,2,-2): s+=I print “sum= ",s
Answer:sum= 28
Question 12.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 13.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 14.Observe the following program and answer the question that follows:import randomx = 3N = random, randint (1, x)for 1 in range (N):print 1, ‘#’, 1 + 1a. What is the minimum and maximum number of times the loop will execute?b. Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?i. 0#1ii. 1#2iii. 2#3iv. 3#4Answer:a. Minimum Number = 1Maximum number = 3b. Line iv is not expected to be a part of the output.
Question 15.Observe the following Python code carefully and obtain the output, which will appear on the screen after execution of it. [CBSE SQP 2016]
def Findoutput (): L = "earn" X = " " count = 1 for i in L: if i in ['a', 'e',' i', 'o', 'u']: x = x + 1. Swapcase () else: if (count % 2 ! = 0): x = x + str (len (L[:count])) else: x = x + 1 count = count + 1 print x Findoutput ()
Answer:EA3n
Question 16.Find and write the output of the following Python code:
Number = [9,18,27,36] for N in Numbers: print (N, "#", end = " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1#001#(1#)(1#)2#(1#)(1#2#)1#(2#)(1#2#3#)2#(1#)1#3#(2#)1#2#(3#)1#2#3#
Question 17.What are the possible outcome(s) executed from the following code? Also,specify the maximum and import random. [CBSE Delhi 2016]
PICK=random.randint (0,3) CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]; for I in CITY : for J in range (1, PICK) print (I, end = " ") Print ()
(i)(ii)DELHIDELHIDELHIMUMBAIMUMBAIDELHIMUMBAICHENNAICHENNAIDELHIMUMBAICEHNNAIKOLKATAKOLKATA(iii)(iv)DELHIDELHIMUMBAIMUMBAIMUMBAICHENNAIKOLKATAKOLKATAKOLKATAKOLKATA
Answer:Option (i) and (iii) are possible option (i) onlyPICKER maxval = 3 minval = 0
Question 18.Find and write the output of the following Python code : [CBSE Outside Delhi-2016]
Values = [10,20,30,40] for val in Values: for I in range (1, Val%9): print (I," * ", end= " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1*001*(1.*)(1*)2*0(1*2*)1*(1,*)(1*2*3*)2*(2.*)1*3*01*2*(1.*)1*2*3*(2,* )(3,* )
Question 19.Write the output from the following code:
y = 2000 if (y%4==0): print “Leap Year” else: print “Not leap year”
Answer:Leap Year.
Question 20.What does the following print?
for i in range (1,10): for j in'range (1,10): print i * j, print
Answer:1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
Question 21.What will be the output of the following statement? Also, justify the answer.
>> print ‘Radhsa’s dress is pretty’.
Answer:SyntaxError: invalid syntax.The single quote needs to be replaced by V to get the expected output.
Question 22.Give the output of the following statements :
>>> str=‘Honesty is the best policy’ >>> str.replace(‘o’,‘*’)
Answer:‘H*nesty is the best p*licy’.
Question 23.Give the output of the following statements :
>> str=‘Hello Python’ >>> str.istitle()
Answer:True.
Question 24.Give the output of the following statements:
>> str=‘Hello Python’ >>> print str.lstrip(“Hel”)
Answer:Hello Python
Question 25.Write the output for the following codes:
A={10:1000,20:2000,30:3000,40:4000,50:5000} print A.items() print A.keys() print A.values()
Answer:[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]
Question 26.Write the output from the following code:
t=(10,20,30,40,50) print len(t)
Answer:5
Question 27.Write the output from the following code:
t=(‘a’,‘b’,‘c’,‘A’,‘B’) print max(t) print min(t)
Answer:‘c’A’
Question 28.Find the output from the following code:
T=(10,30,2,50,5,6,100,65) print max(T) print min(T)
Answer:1002
Question 29.Write the output from the following code:
T1=(10,20,30,40,50) T2 =(10,20,30,40,50) T3 =(100,200,300) cmp(T1, T2) cmp(T2,T3) cmp(T3,T1)
Answer:0-11
Question 30.Write the output from the following code:
T1=(10,20,30,40,50) T2=(100,200,300) T3=T1+T2 print T3
Answer:(10,20,30,40,50,100,200,300)
Question 31.Find the output from the following code:
t=tuple() t = t +(‘Python’,) print t print len(t) t1=(10,20,30) print len(t1)
Answer:(‘Python’,)13
Question 32.Rewrite the following code in Python after remo¬ving all syntax error(s).Underline each correction done in the code.
for student in [Jaya, Priya, Gagan] If Student [0] = ‘S’: print (student)
Answer:for studednt in values [“Jaya”, “Priya”, “Gagan”]:if student [0] = = “S”print (student)
Question 33.Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Values: for NV in range (1, V%10): print (NV, V)
Answer:1, 112,223,334, 44
Question 34.What are the possible outcome(s) executed from the following code? Also, specify the maximum and minimum values that can be assigned to variable SEL.
import random SEL=random. randint (0, 3) ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]; for A in ANIMAL: for AAin range (1, SEL): print (A, end =“”) print ()
(i)(ii)(iii)(iv)DEERDEERDEERDEERDEERMONKEYMONKEYDELHIMONKEYMONKEYMONKEYMONKEYCOWCOWDELHIMONKEYCOWCOWKANGAROOKANGAROOKANGAROOKANGAROOKANGAROOKANGAROO
Answer:Maximum value of SEL is 3.The possible output is belowDEERMonkey MonkeyKangaroo Kangaroo KangarooThus (iv) is the correct option.
TOPIC-3Random Functions
Question 1.What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE Outside Delhi-2016]
import random PICKER = random randint (0, 3) COLOR = ["BLUE", "PINK", "GREEN", "RED"]: for I in COLOR : for J in range (1, PICKER): Print (I, end = " ") Print ()
(i)(ii)(iii) (iv)BLUEBLUEPINKSLUEBLUEPINKBLUEPINKPINKGREENPINKPINKGREENBLUEPINKGREENGREENREDGREENGREENREDBLUEPINKGREENREDREDRED
Answer:Option (i) and (iv) are possibleORoption (i) onlyPICKER maxval = 3 minval = 0
Question 2.What are the possible outcome(s) expected from the following python code? Also specifymaximum and minimum value, which we can have. [CBSE SQP 2015]
def main(): p = ‘MY PROGRAM’ i = 0 while p[i] != ‘R’: l = random.randint(0,3) + 5 print p[l],’-’, i += 1
(i) R – P – O – R –(ii) P – O – R – Y –(iii) O -R – A – G –(iv) A- G – R – M –Answer:Minimum value=5Maximum value=8So the only possible values are O, G, R, AOnly option (iii) is possible.
TOPIC-4Correcting The Errors
Question 1.Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.[CBSE SQP 2015]
def main(): r = raw-input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ” + a
Answer:
def main (): r = raw_input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ”, a
Question 2.Rectify the error (if any) in the given statements.
>> str=“Hello Python” >>> str[6]=‘S’
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment. str.replace(str[6],‘S’).
Question 3.Find the errors from the following code:T=[a,b,c]print TAnswer:NameError: name ‘a’ is not defined .T=[‘a’,‘b’,‘c’]
Question 4.Find the errors from the following code:for i in 1 to 100:print IAnswer:for i in range (1,100):print i
Question 5.Find the errors from the following code:
i=10 ; while [i<=n]: print i i+=10
Answer:
i=10 n=100 while (i<=n): print i i+=10
Question 6.Find the errors from the following code:
if (a>b) print a: else if (a<b) print b: else print “both are equal”
Answer:
if (a>b) // missing colon print a: else if (a<b) // missing colon // should be elif print b: else // missing colon print “both are equal"
Question 7.Find errors from the following codes:
c=dict() n=input(Enter total number) i=1 while i<=n: a=raw_input(“enter place”) b=raw_input(“enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[a[i]]
Answer:
c=dict() n=input(‘‘Enter total number”) i=1 while i<=n : a=raw_input(“enter place”) b=raw_inputf enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[i]
Question 8.Observe the following class definition and answer the question that follows : [CBSE SQP 2016]
class info: ips=0 def _str_(self): #Function 1 return "Welcome to the Info Systems" def _init_(Self): self. _ Sstemdate= " " self. SystemTime = " " def getinput (self): self . Systemdate = raw_input ("enter data") self , SystemTime = raw_Input ("enter data") Info, incrips () Estaiomethod # Statement 1 def incrips (): Info, ips, "times" I = Info () I. getinput () Print I. SystemTime Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.ii. On Executing the above code, Statement 2 is giving an error explain.Answer:i. print Iii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed outside the class.
TOPIC – 5Short Programs
Question 1.Write a program to calculate the area of a rectangle. The program should get the length and breadth ;values from the user and print the area.Answer:
length = input(“Enter length”) breadth = input(“Enter breadth”) print “Area of rectangle =”,length*breadth
Question 2.Write a program to calculate the roots of a quadratic equation.Answer:
import math a = input(“Enter co-efficient of x^2”) b = input(“Enter co-efficient of x”) c = inputfEnter constant term”) d = b*b - 4*a*c if d == 0: print “Roots are real and equal” root1 = root2 = -b / (2*a) elif d > 0: print “Roots are real and distinct” root1 = (- b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) else: print “Roots are imaginary” print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.Write a program to input any number and to print all the factors of that number.Answer:
n = inputfEnter the number") for i in range(2,n): if n%i == 0: print i,“is a factor of’.n
Question 4.Write a program to input ,.any number and to check whether given number is Armstrong or not.(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)Answer:
n = inputfEnter the number”) savedn = n sum=0 while n > 0: a = n%10 sum = sum + a*a*a n = n/10 if savedn == sum: print savedn,“is an Armstrong Number” else: print savedn,”is not an Armstrong Number”
Question 5.Write a program to find all the prime numbers up to a given numberAnswer:
n = input("Enter the number”) i = 2 flag = 0 while (i < n): if (n%i)==0: flag = 1 print n,“is composite” break i = i+ 1 if flag ==0 : print n,“is prime”
Question 6.Write a program to convert decimal number to binary.Answer:
i=1 s=0 dec = int ( raw_input(“Enter the decimal to be converted:”)) while dec>0: rem=dec%2 s=s + (i*rem) dec=dec/2 i=i*10 print “The binary of the given number is:”,s raw_input()
Question 7.Write a program to convert binary to decimalAnswer:
binary = raw_input(“Enter the binary string”) decimal=0 for i in range(len(str(binary))): power=len (str (binary)) - (i+1) decimal+=int(str(binary)[i])*(2**power) print decimal
Question 8.Write a program to input two complex numbers and to find sum of the given complex numbers.Answer:
areal = input("Enter real part of first complex number”) aimg = input("Enter imaginary part of first complex number”) breal = input("Enter real part of second complex number”) bimg = input("Enter imaginary part of second complex number”) totreal = areal + breal totimg = aimg + bimg print “Sum of the complex numbers=",totreal, “+i”, totimg
Question 9.Write a program to input two complex numbers and to implement multiplication of the given complex numbers.Answer:
a = input("Enter real part of first complex number”) b = input("Enter imaginary part of first complex number”) c = input("Enter real part of second complex number”) d = input("Enter imaginary part of second complex number”) real= a*c - b*d img= a*d + b*c print “Product of the complex numbers=",real, “+i”,img
Question 10.Write a program to find the sum of all digits of the given number.Answer:
n = inputfEnter the number”) rev=0 while (n>0): a=n%10 sum = sum + a n=n/10 print “Sum of digits=”,sum
Question 11.Write a program to find the reverse of a number.Answer:
n = input("Enter the number”) rev=0 while (n>0): a=n%10 rev=(rev*10)+a n=n/10 print “Reversed number=”,rev
Question 12.Write a program to print the pyramid.12 23 3 34 4 4 45 5 5 5 5Answer:
for i in range(1,6): for j in range(1,i+1): print i, print
Question 13.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(username.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 14.Write a generator function generatesq () that displays the squareroots of numbers from 100 to nwhere n is passed as an argument.Answer:
import math def generatesq (n) : for i in range (100, n) : yield (math, sqrt (i))
Question 15.Write a method in Python to find and display the prime number between 2 to n.Pass n as argument to the method.Answer:
def prime (N) : for a in range (2, N): for I in range (2, a): if N%i ==0 : break print a OR def prime (N): for a in range (2, N): for I in range (2, a) : if a%1= = 0 : break else : print a
Question 16.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(usemame.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 17.Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str[i])
str.replace(char, newchar)
Question 18.Write a program to input any string and to find the number of words in the string.Answer:
str = “Honesty is the best policy” words = str.split() print len(words)
Question 19.Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input(“Enter no. of values") num=[] for i in range (n): number=input(“Enter the number") num.append(number) newno = input(“Enter the number to be inserted”) pos = input(“Enter position”) num.insert(newno,pos) print num
Question 20.Write a program to input n numbers and to search any number from the list.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) search = input(“Enter number to be searched") for i in range(n): if num[i]==search: print search,“found at position”,i flag=1 if flag==0: print search, “not found in list”
Question 21.Write a program to search input any customer name and display customer phone numberif the customer name is exist in the list.Answer:
def printlist(s): i=0 for i in range(len(s)): print i,s[i] i = 0 phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’] flag=0 number = raw_input(“Enter the phone number to be searched") number = number.strip() try: i = phonenumbers.index(number) if i >= 0: flag=1 except ValueError: pass if(flag <>0): print “\nphone number found in Phonebook at index”, i else: print'\iphonenumbernotfoundin phonebook” print “\nPHONEBOOK” printlist(phonenumbers)
Question 22.Write a program to input n numbers and to reverse the set of numbers without using functions.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j] = num[j],num[i] j=j-1 else: break print num
Question 23.Find and write the output of the following Python code: [CBSE Complementry-2016]
class Client: def init (self, ID = 1, NM=”Noname”) # constructor self.CID = ID self. Name = NM def Allocate (self, changelD, Title) : self.CID = self.CID + Changeld self.Name = Title + self. Name def Display (self) : print (self. CID). "#”, self. Name) C1 = Client () C2 = Client (102) C3 = Client (205, ‘’Fedrick”) C1 . Display () C2 . Display () C3 . Display () C2 . Allocate (4, "Ms.”) C3 .Allocate (2, "Mr.”) C1. Allocate (1, "Mrs.”) C1. Display () C2 . Display () C3 . Display ()
Answer:
CID Name — Fedrick 102 Mr. Fedrick 205 Mrs. Fedrick — Mr. & Mrs. Fedrick
Question 24.What will be the output of the following Python code considering the following set of inputs?
MAYA Your 5 Apples Mine2 412 Also, explain the try and except used in the code. Count = 0 while True : try: Number=int (raw input ("Input a Number :")) break Except valueError : Count=Count + 2 # For later versions of python, raw_input # Should be consider as input
mehtods:– DenCal () # Method to calcualte Density as People/Area– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod– View () # Method to display all the data members also display a message “”High Population”if the Density is more than 8000.Answer:Output is below2 Re Enter Number10 Re Enter Number5 Input = Number3 Input = numberTry and except are used for handling exception in the Pythan code.
Question 25.Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.Answer:
def prime (N) : for a in range (2, N) Prime=1 for I in range (2, a): if a%i= = 0 : Prime = 0 if Prime = = 1: print a OR def prime (N) : for a in range (2, N): for I in range (2, a) : if a%i = = 0: break else : print a OR Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.Aastha wnats to create a program that accepts a string and display the characters in the reversein the same line using a Stack. She has created the following code, help her by completing thedefinitions on the basis of requirements given below:[CBSE SQP 2016]
Class mystack : def inin (self): selfe. mystr= # Accept a string self.mylist= # Convert mystr to a list # Write code to display while removing element from the stack. def display (self) : : :
Answer:
class mystack : def _init_ (self) : self.myster= rawjnput ("Enter the string”) self.mylist = list (self.mystr) def display (self) : x = len (self. mylist) if (x > 0) : for i in range (x) : print self.mylist.pop (), else : print "Stack is empty”
via Blogger https://ift.tt/3kkMk05
0 notes
Text
NCERT Class 12 Computer Science Chapter 1 Review of Python
NCERT Class 12 Computer Science Python Solutions for Chapter 1 :: Review of Python
TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)
Question 1.Name the Python Library modules which need to be imported to invoke the following functions:
load ()
pow () [CBSE Delhi 2016]
Answer:
pickle
math
Question 2.Name the modules to which the following func-tions belong:
Uniform ()
fabs () [CBSE SQP 2016]
Answer:
random ()
math ()
Question 3.Differentiate between the round() and floor() functions with the help of suitable example.[CBSE Comptt. 2016]Answer:The function round() is used to convert a fractional number into whole as the nearest next whereas the function floor() is used convert to the nearest lower whole number, e.g.,round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks):
Question 1.Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]Answer:Total * Tax, class, 3rd Row, finally
Question 2.Name the Python Library modules which need to be imported to invoke the follwing functions :
sqrt()
dump() (CBSE Outside Delhi-2016)
Answer:
math
pickle
Question 3.Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]_Cost, Price*Qty, float, switch, Address one, Delete, Number12, doAnswer:Price *Qty, float, Address one, do
Question 4.Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python Program:Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My cityAnswer:Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of being either keyword or including space or operator or starting with integar.
Question 5.Name the function / method required for [CBSE SQP 2015]
Finding second occurrence of m in madam.
get the position of an item in the list.
Answer:
find
index
Question 6.Which string method is used to implement the following:
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character. [CBSE TextBook]
Answer:
len(str)
str.capitalize()
ch.isalnum()
str.upper()
str.replace(old,new)
Question 7.What is the difference between input() and raw_input()?Answer:raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically determines the correct type. We use the inputQ function when you are expecting an integer from the end-user, and raw_input when you are expecting a string.
Question 8.What are the two ways of output using print()?Answer:Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to combine the results of multiple print statements into a single line.
Question 9.Why does the expression 2 + 3*4 result in the value 14 and not the value 24?Answer:Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.
Question 10.How many times will Python execute the code inside the following while loop? You should answer the question without using the interpreter! Justify your answers.
i = 0 while i < 0 and i > 2 : print “Hello ...” i = i+1
Answer:0 times.
Question 11.How many times will Python execute the code inside the following while loop?
i = 1 while i < 10000 and i > 0 and 1: print “ Hello ...” i = 2 * i
Answer:14.
Question 12.Convert the following for loop into while loop, for i in range (1,100):
if i % 4 == 2 : print i, “mod”, 4 , “= 2”
Answer:
i=1 while i < 100: if i % 4 == 2: print i, “mod”, 4 , “= 2” i = i +1
Question 13.Convert the following for loop into while loop.
for i in range(10): for j in range(i): print '$', print"
Answer:
i=0 while i < 10: j=0 while j < i: print '$’ print"
Question 14.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(25,500,25): print a
Answer:
a=25 while a < 500: print a a = a + 25
Question 15.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9): print a
Answer:
a = 90 while a > 9: print a a = a-9
Question 16.Convert the following while loop into for loop:
i = 0 while i < 100: if i % 2 == 0: print i, “is even” else: print i, “is odd” i = i + 1
Answer:
for i in range(100): if i % 2 == 0: print i, “is even” else : print i, “is odd”
Question 17.Convert the following while loop into for loop
char = "" print “Press Tab Enter to stop ...” iteration = 0 while not char == “\t” and not iteration > 99: print “Continue?” char = raw_input() iteration+ = 1
Answer:
char = "" print “Press Tab Enter to stop ...” for iteration in range(99): if not char == ‘\t’: print “Continue?” char = raw_input()
Question 18.Rewrite the following while loop into for loop:
i = 10 while i<250: print i i = i+50
Answer:
for i in range(10, 250, 50): print i
Question 19.Rewrite the following while loop into for loop:
i=88 while(i>=8): print i i- = 8
Answer:
for i in range(88, 9, -8) print i
Question 20.Write for statement to print the series 10,20,30, ……., 300Answer:
for i in range(10, 301, 10): print i
Question 21.Write for statement to print the series 105,98,91,… .7Answer:
for i in range(105, 8, -7): print i
Question 22.Write the while loop to print the series: 5,10,15,…100Answer:
i=5 while i <= 100: print i i = i + 5
Question 23.How many times is the following loop executed? [CBSE Text Book]for a in range(100,10,-10):print aAnswer:9 times.
Question 24.How many times is the following loop executed? [CBSE Text Book]
i = 100 while (i<=200): print i i + =20
Answer:6 times
Question 25.State whether the statement is True or False? No matter the underlying data type if values are equal returns true,
char ch1, ch2; if (ch1==ch2) print “Equal”
Answer:True. Two values of same data types can be equal.
Question 26.What are the logical operators of Python?Answer:or, and, not
Question 27.What is the difference between ‘/’ and ‘//’ ?Answer:
// is Integer or Floor division whereas / is normal division (eg) 7.0 // 2 → 3.0 7.0/2 → 3.5
Question 28.How can we import a module in Python?Answer:1. using import
Syntax: import[,,...] Example: import math, cmath
2. using from
Syntax: fromimport[, ,.. ,] Example: . from fib. import fib, fib2.
Question 29.What is the difference between parameters and arguments?Answer:
S.No.ParametersArguments1Values provided in function headerValues provided in function call.2(eg) def area (r):—> r is the parameter(eg) def main() radius = 5.0 area (radius)—> radius is the argument
Question 30.What are default arguments?Answer:Python allowes function arguments to have default values; if the function is called without the argument, the argument gets its default value
Question 31.What are keyword arguments?Answer:If there is a function with many parameters and we want to specify only some of them in function call,then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6) ' def simpleinterest(p, r=0.2, n=3)
Question 32.What are the advantages of keyword arguments?Answer:It is easier to use since we need not remember the order of the arguments.We can specify the values for only those parameters which we want, and others have default values.
Question 33.What does “in” do?Answer:“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :Otherwise i+evaluates to false.
(eg) S = “Hello World" if “Hell” in S: print “True” will print True.
Question 34.What does “not in” do?Answer:“not in” is a membership operator. It evaluates to true if it does not finds a variable/stringin the specified sequence. Otherwise it evaluates to false,
(eg) S = “Hello World” if “Hell” not in S: print “False” will print False.
Question 35.What does “slice” do?Answer:The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.
(eg) S = “Hello World” print s[0:4] → Hell
Question 36.What is the use of negative indices in slicing?Answer:Python counts from the end (right) if negative indices are given.
(eg) S = “Hello” print S[:-3] >> He print S[-3:] >> llo
Question 37.Explain find() function?Answer:find (sub[,start[,end]])This function is used to search the first occurrence of the substring in the given string.It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.
(eg) str = “computer” - str.findf("om”) → 1
Question 38.What are the differences between arrays and lists?Answer:An array holds fixed number of values. List is of variable-length – elements can be dynamically added or removedAn array holds values of a single type. List in Python can hold values of mixed data type.
Question 39.What is the difference between a tuple and a list?Answer:A tuple is immutable whereas a list is a mutable.A tuple cannot be changed whereas a list can be changed internally.A tuple uses parenthess (()) whereas a list uses square brackets ([]).tuple initialization: a = (2, 4, 5)list initialization: a = [2, 4, 5]
Question 40.Carefully observe the following python code and answer the question that follows:x=5def func2():x=3global xx=x+1print xprint xOn execution the above code produces the following output.63Explain the output with respect to the scope of the variables.Answer:Names declared with global keyword have to be referred at the file level. This is because the global scope.If no global statement is being used the variable with the local scope is accessed.Hence, in the above code the statement succeeding the statement global x informs Python to incrementthe global variable xHence, the output is 6 i.e. 5 + 1 which is also the value for global x.When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)
Question 41.Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]Answer:Pythonuses two strategies for memory allocation-(i) Reference counting(ii) Automatic garbage collectionReference Counting: works by counting the number of times an object is referenced by other in the system.When an object’s reference count reaches zero, Python collects it automatically.Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater that the threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.
TOPIC – 2Writing Python Programs
Question 1.Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the code. [CBSE Delhi-2016]for Name in [Amar, Shveta, Parag]if Name [0] = ‘s’:Print (Name)Answer:
for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] : if Name [0] E == ‘S’ : Print (Name)
Question 2.Rewrite the following code is Python after removing all syntax errors(s).Underline each correction done in the code. [CBSE Outside Delhi-2016]for Name in [Ramesh, Suraj, Priya]if Name [0] = ‘S’:Print (Name)Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”] if Name [0] =_=‘S’ : print (Name)
Question 3.What will be the output of the following python code considering the following set of inputs?AMARTHREEA1231200Also, explain the try and except used in the code.Start = 0while True :Try:Number = int (raw input (“Enter Number”))breakexcept valueError : start=start+2print (“Re-enter an integer”)Print (start)Answer:Output:
Enter Number AMAR Re-enter an integer Enter Number THREE Re-enter an integer Enter Number A123 Re-enter an integer Enter Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the user.When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.
Question 4.Give the output of following with justification. [CBSE SQP 2015]
x = 3 x+ = x-x print x
Answer:Output: 3Working:
x = 3 x = (x+ x-x ):x = 3 + 3 - 3 = 3
Question 5.What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person: def init (self,id): self.id = id arjun = person(150) arjun. diet [‘age’] = 50 print arjun.age + len(arjun. diet )
Justify your answer.Answer:52arjun.age = 50arjun.dict has 2 attributes so length of it is 2. So total = 52.
Question 6.What would be the output of the following code snippets?print 4+9print “4+9”Answer:13 (addition), 49 (concatenation).
Question 7.Highlight the literals in the following programand also predict the output. Mention the types ofvariables in the program.
a=3 b='1' c=a-2 d=a-c e=“Kathy” f=‘went to party.’ g=‘with Sathy’ print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:a, c,d = integerb, e,f,g = stringOutput: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to party.
Question 8.What is the result of 4+4/2+2?Answer:4 + (4/2) + 2 = 8.
Question 9.Write the output from the following code: [CBSE Text Book]
x= 10 y = 20 if (x>y): print x+y else: print x-y
Answer:– 10
Question 10.Write the output of the following code:print “Python is an \n interpreted \t Language”Answer:Python is an interpreted Language
Question 11.Write the output from the following code:
s = 0 for I in range(10,2,-2): s+=I print “sum= ",s
Answer:sum= 28
Question 12.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 13.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 14.Observe the following program and answer the question that follows:import randomx = 3N = random, randint (1, x)for 1 in range (N):print 1, ‘#’, 1 + 1a. What is the minimum and maximum number of times the loop will execute?b. Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?i. 0#1ii. 1#2iii. 2#3iv. 3#4Answer:a. Minimum Number = 1Maximum number = 3b. Line iv is not expected to be a part of the output.
Question 15.Observe the following Python code carefully and obtain the output, which will appear on the screen after execution of it. [CBSE SQP 2016]
def Findoutput (): L = "earn" X = " " count = 1 for i in L: if i in ['a', 'e',' i', 'o', 'u']: x = x + 1. Swapcase () else: if (count % 2 ! = 0): x = x + str (len (L[:count])) else: x = x + 1 count = count + 1 print x Findoutput ()
Answer:EA3n
Question 16.Find and write the output of the following Python code:
Number = [9,18,27,36] for N in Numbers: print (N, "#", end = " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1#001#(1#)(1#)2#(1#)(1#2#)1#(2#)(1#2#3#)2#(1#)1#3#(2#)1#2#(3#)1#2#3#
Question 17.What are the possible outcome(s) executed from the following code? Also,specify the maximum and import random. [CBSE Delhi 2016]
PICK=random.randint (0,3) CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]; for I in CITY : for J in range (1, PICK) print (I, end = " ") Print ()
(i)(ii)DELHIDELHIDELHIMUMBAIMUMBAIDELHIMUMBAICHENNAICHENNAIDELHIMUMBAICEHNNAIKOLKATAKOLKATA(iii)(iv)DELHIDELHIMUMBAIMUMBAIMUMBAICHENNAIKOLKATAKOLKATAKOLKATAKOLKATA
Answer:Option (i) and (iii) are possible option (i) onlyPICKER maxval = 3 minval = 0
Question 18.Find and write the output of the following Python code : [CBSE Outside Delhi-2016]
Values = [10,20,30,40] for val in Values: for I in range (1, Val%9): print (I," * ", end= " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1*001*(1.*)(1*)2*0(1*2*)1*(1,*)(1*2*3*)2*(2.*)1*3*01*2*(1.*)1*2*3*(2,* )(3,* )
Question 19.Write the output from the following code:
y = 2000 if (y%4==0): print “Leap Year” else: print “Not leap year”
Answer:Leap Year.
Question 20.What does the following print?
for i in range (1,10): for j in'range (1,10): print i * j, print
Answer:1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
Question 21.What will be the output of the following statement? Also, justify the answer.
>> print ‘Radhsa’s dress is pretty’.
Answer:SyntaxError: invalid syntax.The single quote needs to be replaced by V to get the expected output.
Question 22.Give the output of the following statements :
>>> str=‘Honesty is the best policy’ >>> str.replace(‘o’,‘*’)
Answer:‘H*nesty is the best p*licy’.
Question 23.Give the output of the following statements :
>> str=‘Hello Python’ >>> str.istitle()
Answer:True.
Question 24.Give the output of the following statements:
>> str=‘Hello Python’ >>> print str.lstrip(“Hel”)
Answer:Hello Python
Question 25.Write the output for the following codes:
A={10:1000,20:2000,30:3000,40:4000,50:5000} print A.items() print A.keys() print A.values()
Answer:[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]
Question 26.Write the output from the following code:
t=(10,20,30,40,50) print len(t)
Answer:5
Question 27.Write the output from the following code:
t=(‘a’,‘b’,‘c’,‘A’,‘B’) print max(t) print min(t)
Answer:‘c’A’
Question 28.Find the output from the following code:
T=(10,30,2,50,5,6,100,65) print max(T) print min(T)
Answer:1002
Question 29.Write the output from the following code:
T1=(10,20,30,40,50) T2 =(10,20,30,40,50) T3 =(100,200,300) cmp(T1, T2) cmp(T2,T3) cmp(T3,T1)
Answer:0-11
Question 30.Write the output from the following code:
T1=(10,20,30,40,50) T2=(100,200,300) T3=T1+T2 print T3
Answer:(10,20,30,40,50,100,200,300)
Question 31.Find the output from the following code:
t=tuple() t = t +(‘Python’,) print t print len(t) t1=(10,20,30) print len(t1)
Answer:(‘Python’,)13
Question 32.Rewrite the following code in Python after remo¬ving all syntax error(s).Underline each correction done in the code.
for student in [Jaya, Priya, Gagan] If Student [0] = ‘S’: print (student)
Answer:for studednt in values [“Jaya”, “Priya”, “Gagan”]:if student [0] = = “S”print (student)
Question 33.Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Values: for NV in range (1, V%10): print (NV, V)
Answer:1, 112,223,334, 44
Question 34.What are the possible outcome(s) executed from the following code? Also, specify the maximum and minimum values that can be assigned to variable SEL.
import random SEL=random. randint (0, 3) ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]; for A in ANIMAL: for AAin range (1, SEL): print (A, end =“”) print ()
(i)(ii)(iii)(iv)DEERDEERDEERDEERDEERMONKEYMONKEYDELHIMONKEYMONKEYMONKEYMONKEYCOWCOWDELHIMONKEYCOWCOWKANGAROOKANGAROOKANGAROOKANGAROOKANGAROOKANGAROO
Answer:Maximum value of SEL is 3.The possible output is belowDEERMonkey MonkeyKangaroo Kangaroo KangarooThus (iv) is the correct option.
TOPIC-3Random Functions
Question 1.What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE Outside Delhi-2016]
import random PICKER = random randint (0, 3) COLOR = ["BLUE", "PINK", "GREEN", "RED"]: for I in COLOR : for J in range (1, PICKER): Print (I, end = " ") Print ()
(i)(ii)(iii) (iv)BLUEBLUEPINKSLUEBLUEPINKBLUEPINKPINKGREENPINKPINKGREENBLUEPINKGREENGREENREDGREENGREENREDBLUEPINKGREENREDREDRED
Answer:Option (i) and (iv) are possibleORoption (i) onlyPICKER maxval = 3 minval = 0
Question 2.What are the possible outcome(s) expected from the following python code? Also specifymaximum and minimum value, which we can have. [CBSE SQP 2015]
def main(): p = ‘MY PROGRAM’ i = 0 while p[i] != ‘R’: l = random.randint(0,3) + 5 print p[l],’-’, i += 1
(i) R – P – O – R –(ii) P – O – R – Y –(iii) O -R – A – G –(iv) A- G – R – M –Answer:Minimum value=5Maximum value=8So the only possible values are O, G, R, AOnly option (iii) is possible.
TOPIC-4Correcting The Errors
Question 1.Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.[CBSE SQP 2015]
def main(): r = raw-input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ” + a
Answer:
def main (): r = raw_input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ”, a
Question 2.Rectify the error (if any) in the given statements.
>> str=“Hello Python” >>> str[6]=‘S’
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment. str.replace(str[6],‘S’).
Question 3.Find the errors from the following code:T=[a,b,c]print TAnswer:NameError: name ‘a’ is not defined .T=[‘a’,‘b’,‘c’]
Question 4.Find the errors from the following code:for i in 1 to 100:print IAnswer:for i in range (1,100):print i
Question 5.Find the errors from the following code:
i=10 ; while [i<=n]: print i i+=10
Answer:
i=10 n=100 while (i<=n): print i i+=10
Question 6.Find the errors from the following code:
if (a>b) print a: else if (a<b) print b: else print “both are equal”
Answer:
if (a>b) // missing colon print a: else if (a<b) // missing colon // should be elif print b: else // missing colon print “both are equal"
Question 7.Find errors from the following codes:
c=dict() n=input(Enter total number) i=1 while i<=n: a=raw_input(“enter place”) b=raw_input(“enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[a[i]]
Answer:
c=dict() n=input(‘‘Enter total number”) i=1 while i<=n : a=raw_input(“enter place”) b=raw_inputf enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[i]
Question 8.Observe the following class definition and answer the question that follows : [CBSE SQP 2016]
class info: ips=0 def _str_(self): #Function 1 return "Welcome to the Info Systems" def _init_(Self): self. _ Sstemdate= " " self. SystemTime = " " def getinput (self): self . Systemdate = raw_input ("enter data") self , SystemTime = raw_Input ("enter data") Info, incrips () Estaiomethod # Statement 1 def incrips (): Info, ips, "times" I = Info () I. getinput () Print I. SystemTime Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.ii. On Executing the above code, Statement 2 is giving an error explain.Answer:i. print Iii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed outside the class.
TOPIC – 5Short Programs
Question 1.Write a program to calculate the area of a rectangle. The program should get the length and breadth ;values from the user and print the area.Answer:
length = input(“Enter length”) breadth = input(“Enter breadth”) print “Area of rectangle =”,length*breadth
Question 2.Write a program to calculate the roots of a quadratic equation.Answer:
import math a = input(“Enter co-efficient of x^2”) b = input(“Enter co-efficient of x”) c = inputfEnter constant term”) d = b*b - 4*a*c if d == 0: print “Roots are real and equal” root1 = root2 = -b / (2*a) elif d > 0: print “Roots are real and distinct” root1 = (- b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) else: print “Roots are imaginary” print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.Write a program to input any number and to print all the factors of that number.Answer:
n = inputfEnter the number") for i in range(2,n): if n%i == 0: print i,“is a factor of’.n
Question 4.Write a program to input ,.any number and to check whether given number is Armstrong or not.(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)Answer:
n = inputfEnter the number”) savedn = n sum=0 while n > 0: a = n%10 sum = sum + a*a*a n = n/10 if savedn == sum: print savedn,“is an Armstrong Number” else: print savedn,”is not an Armstrong Number”
Question 5.Write a program to find all the prime numbers up to a given numberAnswer:
n = input("Enter the number”) i = 2 flag = 0 while (i < n): if (n%i)==0: flag = 1 print n,“is composite” break i = i+ 1 if flag ==0 : print n,“is prime”
Question 6.Write a program to convert decimal number to binary.Answer:
i=1 s=0 dec = int ( raw_input(“Enter the decimal to be converted:”)) while dec>0: rem=dec%2 s=s + (i*rem) dec=dec/2 i=i*10 print “The binary of the given number is:”,s raw_input()
Question 7.Write a program to convert binary to decimalAnswer:
binary = raw_input(“Enter the binary string”) decimal=0 for i in range(len(str(binary))): power=len (str (binary)) - (i+1) decimal+=int(str(binary)[i])*(2**power) print decimal
Question 8.Write a program to input two complex numbers and to find sum of the given complex numbers.Answer:
areal = input("Enter real part of first complex number”) aimg = input("Enter imaginary part of first complex number”) breal = input("Enter real part of second complex number”) bimg = input("Enter imaginary part of second complex number”) totreal = areal + breal totimg = aimg + bimg print “Sum of the complex numbers=",totreal, “+i”, totimg
Question 9.Write a program to input two complex numbers and to implement multiplication of the given complex numbers.Answer:
a = input("Enter real part of first complex number”) b = input("Enter imaginary part of first complex number”) c = input("Enter real part of second complex number”) d = input("Enter imaginary part of second complex number”) real= a*c - b*d img= a*d + b*c print “Product of the complex numbers=",real, “+i”,img
Question 10.Write a program to find the sum of all digits of the given number.Answer:
n = inputfEnter the number”) rev=0 while (n>0): a=n%10 sum = sum + a n=n/10 print “Sum of digits=”,sum
Question 11.Write a program to find the reverse of a number.Answer:
n = input("Enter the number”) rev=0 while (n>0): a=n%10 rev=(rev*10)+a n=n/10 print “Reversed number=”,rev
Question 12.Write a program to print the pyramid.12 23 3 34 4 4 45 5 5 5 5Answer:
for i in range(1,6): for j in range(1,i+1): print i, print
Question 13.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(username.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 14.Write a generator function generatesq () that displays the squareroots of numbers from 100 to nwhere n is passed as an argument.Answer:
import math def generatesq (n) : for i in range (100, n) : yield (math, sqrt (i))
Question 15.Write a method in Python to find and display the prime number between 2 to n.Pass n as argument to the method.Answer:
def prime (N) : for a in range (2, N): for I in range (2, a): if N%i ==0 : break print a OR def prime (N): for a in range (2, N): for I in range (2, a) : if a%1= = 0 : break else : print a
Question 16.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(usemame.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 17.Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str[i])
str.replace(char, newchar)
Question 18.Write a program to input any string and to find the number of words in the string.Answer:
str = “Honesty is the best policy” words = str.split() print len(words)
Question 19.Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input(“Enter no. of values") num=[] for i in range (n): number=input(“Enter the number") num.append(number) newno = input(“Enter the number to be inserted”) pos = input(“Enter position”) num.insert(newno,pos) print num
Question 20.Write a program to input n numbers and to search any number from the list.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) search = input(“Enter number to be searched") for i in range(n): if num[i]==search: print search,“found at position”,i flag=1 if flag==0: print search, “not found in list”
Question 21.Write a program to search input any customer name and display customer phone numberif the customer name is exist in the list.Answer:
def printlist(s): i=0 for i in range(len(s)): print i,s[i] i = 0 phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’] flag=0 number = raw_input(“Enter the phone number to be searched") number = number.strip() try: i = phonenumbers.index(number) if i >= 0: flag=1 except ValueError: pass if(flag <>0): print “\nphone number found in Phonebook at index”, i else: print'\iphonenumbernotfoundin phonebook” print “\nPHONEBOOK” printlist(phonenumbers)
Question 22.Write a program to input n numbers and to reverse the set of numbers without using functions.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j] = num[j],num[i] j=j-1 else: break print num
Question 23.Find and write the output of the following Python code: [CBSE Complementry-2016]
class Client: def init (self, ID = 1, NM=”Noname”) # constructor self.CID = ID self. Name = NM def Allocate (self, changelD, Title) : self.CID = self.CID + Changeld self.Name = Title + self. Name def Display (self) : print (self. CID). "#”, self. Name) C1 = Client () C2 = Client (102) C3 = Client (205, ‘’Fedrick”) C1 . Display () C2 . Display () C3 . Display () C2 . Allocate (4, "Ms.”) C3 .Allocate (2, "Mr.”) C1. Allocate (1, "Mrs.”) C1. Display () C2 . Display () C3 . Display ()
Answer:
CID Name — Fedrick 102 Mr. Fedrick 205 Mrs. Fedrick — Mr. & Mrs. Fedrick
Question 24.What will be the output of the following Python code considering the following set of inputs?
MAYA Your 5 Apples Mine2 412 Also, explain the try and except used in the code. Count = 0 while True : try: Number=int (raw input ("Input a Number :")) break Except valueError : Count=Count + 2 # For later versions of python, raw_input # Should be consider as input
mehtods:– DenCal () # Method to calcualte Density as People/Area– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod– View () # Method to display all the data members also display a message “”High Population”if the Density is more than 8000.Answer:Output is below2 Re Enter Number10 Re Enter Number5 Input = Number3 Input = numberTry and except are used for handling exception in the Pythan code.
Question 25.Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.Answer:
def prime (N) : for a in range (2, N) Prime=1 for I in range (2, a): if a%i= = 0 : Prime = 0 if Prime = = 1: print a OR def prime (N) : for a in range (2, N): for I in range (2, a) : if a%i = = 0: break else : print a OR Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.Aastha wnats to create a program that accepts a string and display the characters in the reversein the same line using a Stack. She has created the following code, help her by completing thedefinitions on the basis of requirements given below:[CBSE SQP 2016]
Class mystack : def inin (self): selfe. mystr= # Accept a string self.mylist= # Convert mystr to a list # Write code to display while removing element from the stack. def display (self) : : :
Answer:
class mystack : def _init_ (self) : self.myster= rawjnput ("Enter the string”) self.mylist = list (self.mystr) def display (self) : x = len (self. mylist) if (x > 0) : for i in range (x) : print self.mylist.pop (), else : print "Stack is empty”
via Blogger https://ift.tt/3kkMk05
0 notes
Text
NCERT Class 12 Computer Science Chapter 1 Review of Python
NCERT Class 12 Computer Science Python Solutions for Chapter 1 :: Review of Python
TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)
Question 1.Name the Python Library modules which need to be imported to invoke the following functions:
load ()
pow () [CBSE Delhi 2016]
Answer:
pickle
math
Question 2.Name the modules to which the following func-tions belong:
Uniform ()
fabs () [CBSE SQP 2016]
Answer:
random ()
math ()
Question 3.Differentiate between the round() and floor() functions with the help of suitable example.[CBSE Comptt. 2016]Answer:The function round() is used to convert a fractional number into whole as the nearest next whereas the function floor() is used convert to the nearest lower whole number, e.g.,round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks):
Question 1.Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]Answer:Total * Tax, class, 3rd Row, finally
Question 2.Name the Python Library modules which need to be imported to invoke the follwing functions :
sqrt()
dump() (CBSE Outside Delhi-2016)
Answer:
math
pickle
Question 3.Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]_Cost, Price*Qty, float, switch, Address one, Delete, Number12, doAnswer:Price *Qty, float, Address one, do
Question 4.Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python Program:Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My cityAnswer:Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of being either keyword or including space or operator or starting with integar.
Question 5.Name the function / method required for [CBSE SQP 2015]
Finding second occurrence of m in madam.
get the position of an item in the list.
Answer:
find
index
Question 6.Which string method is used to implement the following:
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character. [CBSE TextBook]
Answer:
len(str)
str.capitalize()
ch.isalnum()
str.upper()
str.replace(old,new)
Question 7.What is the difference between input() and raw_input()?Answer:raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically determines the correct type. We use the inputQ function when you are expecting an integer from the end-user, and raw_input when you are expecting a string.
Question 8.What are the two ways of output using print()?Answer:Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to combine the results of multiple print statements into a single line.
Question 9.Why does the expression 2 + 3*4 result in the value 14 and not the value 24?Answer:Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.
Question 10.How many times will Python execute the code inside the following while loop? You should answer the question without using the interpreter! Justify your answers.
i = 0 while i < 0 and i > 2 : print “Hello ...” i = i+1
Answer:0 times.
Question 11.How many times will Python execute the code inside the following while loop?
i = 1 while i < 10000 and i > 0 and 1: print “ Hello ...” i = 2 * i
Answer:14.
Question 12.Convert the following for loop into while loop, for i in range (1,100):
if i % 4 == 2 : print i, “mod”, 4 , “= 2”
Answer:
i=1 while i < 100: if i % 4 == 2: print i, “mod”, 4 , “= 2” i = i +1
Question 13.Convert the following for loop into while loop.
for i in range(10): for j in range(i): print '$', print"
Answer:
i=0 while i < 10: j=0 while j < i: print '$’ print"
Question 14.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(25,500,25): print a
Answer:
a=25 while a < 500: print a a = a + 25
Question 15.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9): print a
Answer:
a = 90 while a > 9: print a a = a-9
Question 16.Convert the following while loop into for loop:
i = 0 while i < 100: if i % 2 == 0: print i, “is even” else: print i, “is odd” i = i + 1
Answer:
for i in range(100): if i % 2 == 0: print i, “is even” else : print i, “is odd”
Question 17.Convert the following while loop into for loop
char = "" print “Press Tab Enter to stop ...” iteration = 0 while not char == “\t” and not iteration > 99: print “Continue?” char = raw_input() iteration+ = 1
Answer:
char = "" print “Press Tab Enter to stop ...” for iteration in range(99): if not char == ‘\t’: print “Continue?” char = raw_input()
Question 18.Rewrite the following while loop into for loop:
i = 10 while i<250: print i i = i+50
Answer:
for i in range(10, 250, 50): print i
Question 19.Rewrite the following while loop into for loop:
i=88 while(i>=8): print i i- = 8
Answer:
for i in range(88, 9, -8) print i
Question 20.Write for statement to print the series 10,20,30, ……., 300Answer:
for i in range(10, 301, 10): print i
Question 21.Write for statement to print the series 105,98,91,… .7Answer:
for i in range(105, 8, -7): print i
Question 22.Write the while loop to print the series: 5,10,15,…100Answer:
i=5 while i <= 100: print i i = i + 5
Question 23.How many times is the following loop executed? [CBSE Text Book]for a in range(100,10,-10):print aAnswer:9 times.
Question 24.How many times is the following loop executed? [CBSE Text Book]
i = 100 while (i<=200): print i i + =20
Answer:6 times
Question 25.State whether the statement is True or False? No matter the underlying data type if values are equal returns true,
char ch1, ch2; if (ch1==ch2) print “Equal”
Answer:True. Two values of same data types can be equal.
Question 26.What are the logical operators of Python?Answer:or, and, not
Question 27.What is the difference between ‘/’ and ‘//’ ?Answer:
// is Integer or Floor division whereas / is normal division (eg) 7.0 // 2 → 3.0 7.0/2 → 3.5
Question 28.How can we import a module in Python?Answer:1. using import
Syntax: import[,,...] Example: import math, cmath
2. using from
Syntax: fromimport[, ,.. ,] Example: . from fib. import fib, fib2.
Question 29.What is the difference between parameters and arguments?Answer:
S.No.ParametersArguments1Values provided in function headerValues provided in function call.2(eg) def area (r):—> r is the parameter(eg) def main() radius = 5.0 area (radius)—> radius is the argument
Question 30.What are default arguments?Answer:Python allowes function arguments to have default values; if the function is called without the argument, the argument gets its default value
Question 31.What are keyword arguments?Answer:If there is a function with many parameters and we want to specify only some of them in function call,then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6) ' def simpleinterest(p, r=0.2, n=3)
Question 32.What are the advantages of keyword arguments?Answer:It is easier to use since we need not remember the order of the arguments.We can specify the values for only those parameters which we want, and others have default values.
Question 33.What does “in” do?Answer:“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :Otherwise i+evaluates to false.
(eg) S = “Hello World" if “Hell” in S: print “True” will print True.
Question 34.What does “not in” do?Answer:“not in” is a membership operator. It evaluates to true if it does not finds a variable/stringin the specified sequence. Otherwise it evaluates to false,
(eg) S = “Hello World” if “Hell” not in S: print “False” will print False.
Question 35.What does “slice” do?Answer:The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.
(eg) S = “Hello World” print s[0:4] → Hell
Question 36.What is the use of negative indices in slicing?Answer:Python counts from the end (right) if negative indices are given.
(eg) S = “Hello” print S[:-3] >> He print S[-3:] >> llo
Question 37.Explain find() function?Answer:find (sub[,start[,end]])This function is used to search the first occurrence of the substring in the given string.It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.
(eg) str = “computer” - str.findf("om”) → 1
Question 38.What are the differences between arrays and lists?Answer:An array holds fixed number of values. List is of variable-length – elements can be dynamically added or removedAn array holds values of a single type. List in Python can hold values of mixed data type.
Question 39.What is the difference between a tuple and a list?Answer:A tuple is immutable whereas a list is a mutable.A tuple cannot be changed whereas a list can be changed internally.A tuple uses parenthess (()) whereas a list uses square brackets ([]).tuple initialization: a = (2, 4, 5)list initialization: a = [2, 4, 5]
Question 40.Carefully observe the following python code and answer the question that follows:x=5def func2():x=3global xx=x+1print xprint xOn execution the above code produces the following output.63Explain the output with respect to the scope of the variables.Answer:Names declared with global keyword have to be referred at the file level. This is because the global scope.If no global statement is being used the variable with the local scope is accessed.Hence, in the above code the statement succeeding the statement global x informs Python to incrementthe global variable xHence, the output is 6 i.e. 5 + 1 which is also the value for global x.When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)
Question 41.Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]Answer:Pythonuses two strategies for memory allocation-(i) Reference counting(ii) Automatic garbage collectionReference Counting: works by counting the number of times an object is referenced by other in the system.When an object’s reference count reaches zero, Python collects it automatically.Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater that the threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.
TOPIC – 2Writing Python Programs
Question 1.Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the code. [CBSE Delhi-2016]for Name in [Amar, Shveta, Parag]if Name [0] = ‘s’:Print (Name)Answer:
for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] : if Name [0] E == ‘S’ : Print (Name)
Question 2.Rewrite the following code is Python after removing all syntax errors(s).Underline each correction done in the code. [CBSE Outside Delhi-2016]for Name in [Ramesh, Suraj, Priya]if Name [0] = ‘S’:Print (Name)Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”] if Name [0] =_=‘S’ : print (Name)
Question 3.What will be the output of the following python code considering the following set of inputs?AMARTHREEA1231200Also, explain the try and except used in the code.Start = 0while True :Try:Number = int (raw input (“Enter Number”))breakexcept valueError : start=start+2print (“Re-enter an integer”)Print (start)Answer:Output:
Enter Number AMAR Re-enter an integer Enter Number THREE Re-enter an integer Enter Number A123 Re-enter an integer Enter Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the user.When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.
Question 4.Give the output of following with justification. [CBSE SQP 2015]
x = 3 x+ = x-x print x
Answer:Output: 3Working:
x = 3 x = (x+ x-x ):x = 3 + 3 - 3 = 3
Question 5.What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person: def init (self,id): self.id = id arjun = person(150) arjun. diet [‘age’] = 50 print arjun.age + len(arjun. diet )
Justify your answer.Answer:52arjun.age = 50arjun.dict has 2 attributes so length of it is 2. So total = 52.
Question 6.What would be the output of the following code snippets?print 4+9print “4+9”Answer:13 (addition), 49 (concatenation).
Question 7.Highlight the literals in the following programand also predict the output. Mention the types ofvariables in the program.
a=3 b='1' c=a-2 d=a-c e=“Kathy” f=‘went to party.’ g=‘with Sathy’ print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:a, c,d = integerb, e,f,g = stringOutput: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to party.
Question 8.What is the result of 4+4/2+2?Answer:4 + (4/2) + 2 = 8.
Question 9.Write the output from the following code: [CBSE Text Book]
x= 10 y = 20 if (x>y): print x+y else: print x-y
Answer:– 10
Question 10.Write the output of the following code:print “Python is an \n interpreted \t Language”Answer:Python is an interpreted Language
Question 11.Write the output from the following code:
s = 0 for I in range(10,2,-2): s+=I print “sum= ",s
Answer:sum= 28
Question 12.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 13.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 14.Observe the following program and answer the question that follows:import randomx = 3N = random, randint (1, x)for 1 in range (N):print 1, ‘#’, 1 + 1a. What is the minimum and maximum number of times the loop will execute?b. Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?i. 0#1ii. 1#2iii. 2#3iv. 3#4Answer:a. Minimum Number = 1Maximum number = 3b. Line iv is not expected to be a part of the output.
Question 15.Observe the following Python code carefully and obtain the output, which will appear on the screen after execution of it. [CBSE SQP 2016]
def Findoutput (): L = "earn" X = " " count = 1 for i in L: if i in ['a', 'e',' i', 'o', 'u']: x = x + 1. Swapcase () else: if (count % 2 ! = 0): x = x + str (len (L[:count])) else: x = x + 1 count = count + 1 print x Findoutput ()
Answer:EA3n
Question 16.Find and write the output of the following Python code:
Number = [9,18,27,36] for N in Numbers: print (N, "#", end = " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1#001#(1#)(1#)2#(1#)(1#2#)1#(2#)(1#2#3#)2#(1#)1#3#(2#)1#2#(3#)1#2#3#
Question 17.What are the possible outcome(s) executed from the following code? Also,specify the maximum and import random. [CBSE Delhi 2016]
PICK=random.randint (0,3) CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]; for I in CITY : for J in range (1, PICK) print (I, end = " ") Print ()
(i)(ii)DELHIDELHIDELHIMUMBAIMUMBAIDELHIMUMBAICHENNAICHENNAIDELHIMUMBAICEHNNAIKOLKATAKOLKATA(iii)(iv)DELHIDELHIMUMBAIMUMBAIMUMBAICHENNAIKOLKATAKOLKATAKOLKATAKOLKATA
Answer:Option (i) and (iii) are possible option (i) onlyPICKER maxval = 3 minval = 0
Question 18.Find and write the output of the following Python code : [CBSE Outside Delhi-2016]
Values = [10,20,30,40] for val in Values: for I in range (1, Val%9): print (I," * ", end= " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1*001*(1.*)(1*)2*0(1*2*)1*(1,*)(1*2*3*)2*(2.*)1*3*01*2*(1.*)1*2*3*(2,* )(3,* )
Question 19.Write the output from the following code:
y = 2000 if (y%4==0): print “Leap Year” else: print “Not leap year”
Answer:Leap Year.
Question 20.What does the following print?
for i in range (1,10): for j in'range (1,10): print i * j, print
Answer:1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
Question 21.What will be the output of the following statement? Also, justify the answer.
>> print ‘Radhsa’s dress is pretty’.
Answer:SyntaxError: invalid syntax.The single quote needs to be replaced by V to get the expected output.
Question 22.Give the output of the following statements :
>>> str=‘Honesty is the best policy’ >>> str.replace(‘o’,‘*’)
Answer:‘H*nesty is the best p*licy’.
Question 23.Give the output of the following statements :
>> str=‘Hello Python’ >>> str.istitle()
Answer:True.
Question 24.Give the output of the following statements:
>> str=‘Hello Python’ >>> print str.lstrip(“Hel”)
Answer:Hello Python
Question 25.Write the output for the following codes:
A={10:1000,20:2000,30:3000,40:4000,50:5000} print A.items() print A.keys() print A.values()
Answer:[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]
Question 26.Write the output from the following code:
t=(10,20,30,40,50) print len(t)
Answer:5
Question 27.Write the output from the following code:
t=(‘a’,‘b’,‘c’,‘A’,‘B’) print max(t) print min(t)
Answer:‘c’A’
Question 28.Find the output from the following code:
T=(10,30,2,50,5,6,100,65) print max(T) print min(T)
Answer:1002
Question 29.Write the output from the following code:
T1=(10,20,30,40,50) T2 =(10,20,30,40,50) T3 =(100,200,300) cmp(T1, T2) cmp(T2,T3) cmp(T3,T1)
Answer:0-11
Question 30.Write the output from the following code:
T1=(10,20,30,40,50) T2=(100,200,300) T3=T1+T2 print T3
Answer:(10,20,30,40,50,100,200,300)
Question 31.Find the output from the following code:
t=tuple() t = t +(‘Python’,) print t print len(t) t1=(10,20,30) print len(t1)
Answer:(‘Python’,)13
Question 32.Rewrite the following code in Python after remo¬ving all syntax error(s).Underline each correction done in the code.
for student in [Jaya, Priya, Gagan] If Student [0] = ‘S’: print (student)
Answer:for studednt in values [“Jaya”, “Priya”, “Gagan”]:if student [0] = = “S”print (student)
Question 33.Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Values: for NV in range (1, V%10): print (NV, V)
Answer:1, 112,223,334, 44
Question 34.What are the possible outcome(s) executed from the following code? Also, specify the maximum and minimum values that can be assigned to variable SEL.
import random SEL=random. randint (0, 3) ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]; for A in ANIMAL: for AAin range (1, SEL): print (A, end =“”) print ()
(i)(ii)(iii)(iv)DEERDEERDEERDEERDEERMONKEYMONKEYDELHIMONKEYMONKEYMONKEYMONKEYCOWCOWDELHIMONKEYCOWCOWKANGAROOKANGAROOKANGAROOKANGAROOKANGAROOKANGAROO
Answer:Maximum value of SEL is 3.The possible output is belowDEERMonkey MonkeyKangaroo Kangaroo KangarooThus (iv) is the correct option.
TOPIC-3Random Functions
Question 1.What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE Outside Delhi-2016]
import random PICKER = random randint (0, 3) COLOR = ["BLUE", "PINK", "GREEN", "RED"]: for I in COLOR : for J in range (1, PICKER): Print (I, end = " ") Print ()
(i)(ii)(iii) (iv)BLUEBLUEPINKSLUEBLUEPINKBLUEPINKPINKGREENPINKPINKGREENBLUEPINKGREENGREENREDGREENGREENREDBLUEPINKGREENREDREDRED
Answer:Option (i) and (iv) are possibleORoption (i) onlyPICKER maxval = 3 minval = 0
Question 2.What are the possible outcome(s) expected from the following python code? Also specifymaximum and minimum value, which we can have. [CBSE SQP 2015]
def main(): p = ‘MY PROGRAM’ i = 0 while p[i] != ‘R’: l = random.randint(0,3) + 5 print p[l],’-’, i += 1
(i) R – P – O – R –(ii) P – O – R – Y –(iii) O -R – A – G –(iv) A- G – R – M –Answer:Minimum value=5Maximum value=8So the only possible values are O, G, R, AOnly option (iii) is possible.
TOPIC-4Correcting The Errors
Question 1.Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.[CBSE SQP 2015]
def main(): r = raw-input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ” + a
Answer:
def main (): r = raw_input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ”, a
Question 2.Rectify the error (if any) in the given statements.
>> str=“Hello Python” >>> str[6]=‘S’
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment. str.replace(str[6],‘S’).
Question 3.Find the errors from the following code:T=[a,b,c]print TAnswer:NameError: name ‘a’ is not defined .T=[‘a’,‘b’,‘c’]
Question 4.Find the errors from the following code:for i in 1 to 100:print IAnswer:for i in range (1,100):print i
Question 5.Find the errors from the following code:
i=10 ; while [i<=n]: print i i+=10
Answer:
i=10 n=100 while (i<=n): print i i+=10
Question 6.Find the errors from the following code:
if (a>b) print a: else if (a<b) print b: else print “both are equal”
Answer:
if (a>b) // missing colon print a: else if (a<b) // missing colon // should be elif print b: else // missing colon print “both are equal"
Question 7.Find errors from the following codes:
c=dict() n=input(Enter total number) i=1 while i<=n: a=raw_input(“enter place”) b=raw_input(“enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[a[i]]
Answer:
c=dict() n=input(‘‘Enter total number”) i=1 while i<=n : a=raw_input(“enter place”) b=raw_inputf enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[i]
Question 8.Observe the following class definition and answer the question that follows : [CBSE SQP 2016]
class info: ips=0 def _str_(self): #Function 1 return "Welcome to the Info Systems" def _init_(Self): self. _ Sstemdate= " " self. SystemTime = " " def getinput (self): self . Systemdate = raw_input ("enter data") self , SystemTime = raw_Input ("enter data") Info, incrips () Estaiomethod # Statement 1 def incrips (): Info, ips, "times" I = Info () I. getinput () Print I. SystemTime Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.ii. On Executing the above code, Statement 2 is giving an error explain.Answer:i. print Iii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed outside the class.
TOPIC – 5Short Programs
Question 1.Write a program to calculate the area of a rectangle. The program should get the length and breadth ;values from the user and print the area.Answer:
length = input(“Enter length”) breadth = input(“Enter breadth”) print “Area of rectangle =”,length*breadth
Question 2.Write a program to calculate the roots of a quadratic equation.Answer:
import math a = input(“Enter co-efficient of x^2”) b = input(“Enter co-efficient of x”) c = inputfEnter constant term”) d = b*b - 4*a*c if d == 0: print “Roots are real and equal” root1 = root2 = -b / (2*a) elif d > 0: print “Roots are real and distinct” root1 = (- b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) else: print “Roots are imaginary” print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.Write a program to input any number and to print all the factors of that number.Answer:
n = inputfEnter the number") for i in range(2,n): if n%i == 0: print i,“is a factor of’.n
Question 4.Write a program to input ,.any number and to check whether given number is Armstrong or not.(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)Answer:
n = inputfEnter the number”) savedn = n sum=0 while n > 0: a = n%10 sum = sum + a*a*a n = n/10 if savedn == sum: print savedn,“is an Armstrong Number” else: print savedn,”is not an Armstrong Number”
Question 5.Write a program to find all the prime numbers up to a given numberAnswer:
n = input("Enter the number”) i = 2 flag = 0 while (i < n): if (n%i)==0: flag = 1 print n,“is composite” break i = i+ 1 if flag ==0 : print n,“is prime”
Question 6.Write a program to convert decimal number to binary.Answer:
i=1 s=0 dec = int ( raw_input(“Enter the decimal to be converted:”)) while dec>0: rem=dec%2 s=s + (i*rem) dec=dec/2 i=i*10 print “The binary of the given number is:”,s raw_input()
Question 7.Write a program to convert binary to decimalAnswer:
binary = raw_input(“Enter the binary string”) decimal=0 for i in range(len(str(binary))): power=len (str (binary)) - (i+1) decimal+=int(str(binary)[i])*(2**power) print decimal
Question 8.Write a program to input two complex numbers and to find sum of the given complex numbers.Answer:
areal = input("Enter real part of first complex number”) aimg = input("Enter imaginary part of first complex number”) breal = input("Enter real part of second complex number”) bimg = input("Enter imaginary part of second complex number”) totreal = areal + breal totimg = aimg + bimg print “Sum of the complex numbers=",totreal, “+i”, totimg
Question 9.Write a program to input two complex numbers and to implement multiplication of the given complex numbers.Answer:
a = input("Enter real part of first complex number”) b = input("Enter imaginary part of first complex number”) c = input("Enter real part of second complex number”) d = input("Enter imaginary part of second complex number”) real= a*c - b*d img= a*d + b*c print “Product of the complex numbers=",real, “+i”,img
Question 10.Write a program to find the sum of all digits of the given number.Answer:
n = inputfEnter the number”) rev=0 while (n>0): a=n%10 sum = sum + a n=n/10 print “Sum of digits=”,sum
Question 11.Write a program to find the reverse of a number.Answer:
n = input("Enter the number”) rev=0 while (n>0): a=n%10 rev=(rev*10)+a n=n/10 print “Reversed number=”,rev
Question 12.Write a program to print the pyramid.12 23 3 34 4 4 45 5 5 5 5Answer:
for i in range(1,6): for j in range(1,i+1): print i, print
Question 13.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(username.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 14.Write a generator function generatesq () that displays the squareroots of numbers from 100 to nwhere n is passed as an argument.Answer:
import math def generatesq (n) : for i in range (100, n) : yield (math, sqrt (i))
Question 15.Write a method in Python to find and display the prime number between 2 to n.Pass n as argument to the method.Answer:
def prime (N) : for a in range (2, N): for I in range (2, a): if N%i ==0 : break print a OR def prime (N): for a in range (2, N): for I in range (2, a) : if a%1= = 0 : break else : print a
Question 16.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(usemame.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 17.Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str[i])
str.replace(char, newchar)
Question 18.Write a program to input any string and to find the number of words in the string.Answer:
str = “Honesty is the best policy” words = str.split() print len(words)
Question 19.Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input(“Enter no. of values") num=[] for i in range (n): number=input(“Enter the number") num.append(number) newno = input(“Enter the number to be inserted”) pos = input(“Enter position”) num.insert(newno,pos) print num
Question 20.Write a program to input n numbers and to search any number from the list.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) search = input(“Enter number to be searched") for i in range(n): if num[i]==search: print search,“found at position”,i flag=1 if flag==0: print search, “not found in list”
Question 21.Write a program to search input any customer name and display customer phone numberif the customer name is exist in the list.Answer:
def printlist(s): i=0 for i in range(len(s)): print i,s[i] i = 0 phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’] flag=0 number = raw_input(“Enter the phone number to be searched") number = number.strip() try: i = phonenumbers.index(number) if i >= 0: flag=1 except ValueError: pass if(flag <>0): print “\nphone number found in Phonebook at index”, i else: print'\iphonenumbernotfoundin phonebook” print “\nPHONEBOOK” printlist(phonenumbers)
Question 22.Write a program to input n numbers and to reverse the set of numbers without using functions.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j] = num[j],num[i] j=j-1 else: break print num
Question 23.Find and write the output of the following Python code: [CBSE Complementry-2016]
class Client: def init (self, ID = 1, NM=”Noname”) # constructor self.CID = ID self. Name = NM def Allocate (self, changelD, Title) : self.CID = self.CID + Changeld self.Name = Title + self. Name def Display (self) : print (self. CID). "#”, self. Name) C1 = Client () C2 = Client (102) C3 = Client (205, ‘’Fedrick”) C1 . Display () C2 . Display () C3 . Display () C2 . Allocate (4, "Ms.”) C3 .Allocate (2, "Mr.”) C1. Allocate (1, "Mrs.”) C1. Display () C2 . Display () C3 . Display ()
Answer:
CID Name — Fedrick 102 Mr. Fedrick 205 Mrs. Fedrick — Mr. & Mrs. Fedrick
Question 24.What will be the output of the following Python code considering the following set of inputs?
MAYA Your 5 Apples Mine2 412 Also, explain the try and except used in the code. Count = 0 while True : try: Number=int (raw input ("Input a Number :")) break Except valueError : Count=Count + 2 # For later versions of python, raw_input # Should be consider as input
mehtods:– DenCal () # Method to calcualte Density as People/Area– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod– View () # Method to display all the data members also display a message “”High Population”if the Density is more than 8000.Answer:Output is below2 Re Enter Number10 Re Enter Number5 Input = Number3 Input = numberTry and except are used for handling exception in the Pythan code.
Question 25.Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.Answer:
def prime (N) : for a in range (2, N) Prime=1 for I in range (2, a): if a%i= = 0 : Prime = 0 if Prime = = 1: print a OR def prime (N) : for a in range (2, N): for I in range (2, a) : if a%i = = 0: break else : print a OR Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.Aastha wnats to create a program that accepts a string and display the characters in the reversein the same line using a Stack. She has created the following code, help her by completing thedefinitions on the basis of requirements given below:[CBSE SQP 2016]
Class mystack : def inin (self): selfe. mystr= # Accept a string self.mylist= # Convert mystr to a list # Write code to display while removing element from the stack. def display (self) : : :
Answer:
class mystack : def _init_ (self) : self.myster= rawjnput ("Enter the string”) self.mylist = list (self.mystr) def display (self) : x = len (self. mylist) if (x > 0) : for i in range (x) : print self.mylist.pop (), else : print "Stack is empty”
from Blogger http://www.margdarsan.com/2020/09/ncert-class-12-computer-science-chapter_22.html
0 notes