81 results found for ""

• What does // mean in python?

It’s floor division. Python docs has very nice documentation on this. Python3: Mathematical division that rounds down to nearest integer. The floor division operator is //. For example, the expression 11 // 4 evaluates to 2 in contrast to the 2.75 returned by float true division. >>> 11//4 2 >>> 11/4 2.75 Note that (-11) // 4 is -3 because that is -2.75 rounded downward. >>> -11//4 -3 >>> -11/4 -2.75 Python2: True division returns round integer in older version of python. Floor division is same. >>> 11//4 2 >>> 11/4 2 >>> -11//4 -3 >>> -11/4 -3

• What programming language is famous amongst Russians?

According to Google Trends it seems like Javascript. However, I didn’t except Python as least popular language amongst Russians. First of all, it’s little difficult to cover all the programming languages used by Russians (or used in Russia). But we can find what are the most popular programming languages in Russia and then drill down geographically. Javascript, Java, Python, PHP and C++ are the most popular languages according to Google Trends. I didn’t include Swift, Ruby, Rust, Scala, PERL etc because they are comparatively less popular to show on charts. Geographically, it looks like Javascript is most popular programming language across Russia. Did you notice the blue color in above chart? I didn’t expect this for Python. Interesting. Drilling down just for Javascript “Saint Petersburg” is the most popular location with Javascript in Russia. I haven’t heard this place before, sorry my geography is not very good.

• What is the most efficient way to find prime factors of a number (python)?

One of the best method is to use Sieve of Eratosthenes Create a list of prime flags with their indices representing corresponding numbers. 0 → False 1 → False 2 → True and so on.. Flag → False for each multiples of index if it’s prime. Python program is shown below, def primes(n): flag = [True] * n flag[0] = flag[1] = False for (index, prime) in enumerate(flag): if prime: yield index for i in range(index*index, n, index): flag[i] = False Print the last item from generator, p = None for p in is_prime(1000000): pass print(p) >>> 999983 Regular way To make the program efficient you need to: Cross out 1 as it's not prime. Cross out all of the multiples of 2 if input number is odd. Cross out all of the multiples of 3 if input number is even. Most importantly, for number N, you only need to test until you get to a prime till √N. If a number N has a prime factor larger than √N , then it surely has a prime factor smaller than √N. So it's sufficient to search for prime factors in the range [1,√N]. If no prime factors exist in the range [1,√N], then N itself is prime and there is no need to continue searching beyond that range. You can do it like this, def is_prime(num): if num<2: return False else: return all(num%i for i in range(2, int(num ** 0.5)+1)) Checking if 1471 is prime, is_prime(1471) True Let's say you want to check all the prime numbers up-to 2 million, prime_list = [i for i in range(2000000) if is_prime(i)] I have seen similar type of problems in project Euler like sum of primes or total number of primes below (a very large number). If the number is small you can simply divide by all the numbers till (n-1) and check if it’s prime or not, but that program (shown below) performs very bad if the number is big. def is_prime(num): if num < 2: return False for i in range(2, num): if num%i==0: return False else: return True For example: is_prime(47) True >>> %timeit ("is_prime(47)") 10.9 ns ± 0.0779 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each) Above program performs very bad if the number is big. Better solution is, instead of dividing by all the numbers up-to (n-1), you just need to check if number is divisible till sqrt(num). def is_prime(x): '''Checking if number is prime, run until sqrt(number)''' sqrt = round(x ** 0.5) if x < 2: return False else: for i in range(2, sqrt + 1): if x%i == 0: return False else: return True OR, def is_prime(num): if num<2: return False else: return all(num%i for i in range(2, int(num ** 0.5)+1)) That’s it, now use list comprehension to get prime_list and print whatever you need. >>> prime_list=[i for i in range(3000000) if is_prime(i)] >>> print(f"Number of primes below 3 million: {len(prime_list)}") >>> print(f"Sum of primes below 3 million: {sum(prime_list)}") >>> print(prime_list) Number of primes below 3 million: 216816 Sum of primes below 3 million: 312471072265 [2, 3, 5, 7, 11, 13, 17, 19....... ]

• What is the difference between Python 2 and Python 3?

Below are the key differences which I have observed and encountered frequently while working on Python 2 and Python 3. Integer division Python2 : The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are. >>> 3/2 1 >>> -3/2 -2 >>> 3//2 1 >>> -3//2 -2 Python3 : Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you need to use // operator. >>> 3/2 1.5 >>> -3/2 -1.5 >>> 3//21 >>> -3//2-2 Input function Python2 : When you use input() function, Python dynamically converts the data type based on your input. So input() function can return anything int, str, float, bool, list etc based on your input. For instance, >>> val = input("Enter any value: ") Enter any value: 7 >>> type(val) int >>> val = input("Enter any value: ") Enter any value: 7.0 >>> type(val) float >>> val = input("Enter any value: ") Enter any value: 'abc' >>> type(val) str >>> val = input("Enter any value: ") Enter any value: True >>> type(val) bool >>> val = input("Enter any value: ") Enter any value: [1,2,3,4,5] >>> type(val) list When you use raw_input(), Python will simply return string irrespective of your input value data type. >>> val = raw_input("Enter any value: ") Enter any value: 7 >>> type(val) str >>> val = raw_input("Enter any value: ") Enter any value: 7.0 >>> type(val) str >>> val = raw_input("Enter any value: ") Enter any value: 'abc' >>> type(val) str and so on.. Python3 : In Python 3, input() function returns string type (acts like raw_input()). It’s confusing sometimes when you are transiting from Python 2 to Python 3. >>> val = input("Enter any value: ") Enter any value: 7 >>> type(val) str Note when you are using input() in Python 3 : If you are using Python 2.7, it’s good idea to use raw_input() when you are getting user inputs. In Python 3, you would use input(). Both the functions interprets all input as a string based on which version of Python you are using. Sometimes, I feel instead of Python doing type change dynamically it’s always safe to handle it manually. In Python 3, when you use the input() func, every input will be interpreted as string and sometimes it creates unexpected results. Consider the below example, >>> a = input("Enter first number: ") Enter first number: 3.4 >>> b = input("Enter second number: ") Enter second number: 5.7 >>> print a + b 3.45.7 # It's because >>> type(a), type(b) (str, str) # In order to fix this you need to apply float() function when user is prompted for input. Round function Python2 : Return the floating point value number rounded to n digits after the decimal point. If n digits is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n digits; if two multiples are equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0). >>> round(3.5) 4.0 Python3 : Return number rounded to n digits precision after the decimal point. If n digits is omitted or is None, it returns the nearest integer to its input. >>> round(3.5) 4 Print function Python2 : Extra pair of parenthesis was not mandatory. >>> print "Hello" Hello >>> print 'Hello' Hello >>> print ("Hello") Hello >>> print ('Hello') Hello Python3 : Extra pair of parenthesis is now mandatory. >>> print "Hello" SyntaxError: Missing parentheses in call to 'print'. >>> print 'Hello' SyntaxError: Missing parentheses in call to 'print'. >>> print ("Hello") Hello >>> print ('Hello') Hello ASCII, Unicode and Byte types (Please ignore below question if you already have this understanding) What is ASCII, Unicode and Byte type in simple english? ASCII defines 128 characters, which map to the numbers 0–127. ASCII uses 7 bits to represent a character. By using 7 bits, we can have a maximum of 2^7 (= 128) distinct combinations. Which means that we can represent 128 characters maximum. The last bit (8th) is used for avoiding errors as parity bit. Most ASCII characters are printable characters of the alphabet such as a, b, c, A, B, C, 1, 2, 3, ?, &, ! etc. ASCII was meant for English only. The others are control characters such as carriage return, line feed, tab, etc. Binary representation of a few characters will be like: 1000001 -> A (ASCII code - 65) or 0001101 -> Carriage Return (ASCII code - 13) ASCII (including ASCII extended 2^8=256 characters) solves the problem for languages that are based on the Latin alphabet. But what about the others needing a completely different alphabet? Russian? Hindi? Chinese? We would have needed an entirely new character set, that's the rational behind Unicode. Unicode defines (less than) 2^21 characters, which, similarly, map to numbers 0–2^21 (though not all numbers are currently assigned, and some are reserved). Unicode is a superset of ASCII, and the numbers 0–127 have the same meaning in ASCII as they have in Unicode. For example, the number 65 means "Latin capital 'A' ". Because Unicode characters don't generally fit into one 8-bit byte, there are numerous ways of storing Unicode characters in byte sequences, such as UTF-32 and UTF-8. Python2 : It has ASCII string type, a separate unicode type, but there is no byte type. >>> type(unicode('a')) unicode >>> type(u'a') unicode >>> type(b'a') str Python3 : We have unicode strings, and byte type. >>> type(unicode('a')) NameError: name 'unicode' is not defined >>> type(u'a') str >>> type(b'a') bytes Range function Python2 : It has range and a separate xrange function. When you need actual list use range and when you need to iterate one object at a time use xrange like a generator which will be faster and save memory. >>> %timeit [i for i in range(1000)] The slowest run took 4.72 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 45.3 µs per loop >>> %timeit [i for i in xrange(1000)] 10000 loops, best of 3: 40.1 µs per loop Python3 : Here, range does what xrange used to do and xrange does not exist separately. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange. >>> %timeit [i for i in range(1000)] 42.6 µs ± 1.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) >>> %timeit [i for i in xrange(1000)] NameError: name 'xrange' is not defined Exception handling Python2 : Syntax is little different for Python3. You need to include as keyword. try: BlahBlah except NameError, error: print error, " => ERROR IS HERE!" # output name 'BlahBlah' is not defined => ERROR IS HERE! try: BlahBlah except NameError as error: print error, " => ERROR IS HERE!" # output name 'BlahBlah' is not defined => ERROR IS HERE! Python3 : You need to include “as” keyword. try: BlahBlah except NameError as error: print (error, " => ERROR IS HERE!") # output name 'BlahBlah' is not defined => ERROR IS HERE! Global Namespace Leak Python2 : Consider below example, how global variable changes. num = 7 print (num) mylist = [num for num in range(100)] print (num) # output 7 99 Python3 : It’s fixed now, there is no namespace leak. num = 7 print (num) mylist = [num for num in range(100)] print (num) # output 7 7 Functions and methods that don’t return lists anymore in Python3 zip() map() filter() dictionary’s .keys() method dictionary’s .values() method dictionary’s .items() method List Comprehensions Python2 [item for item in 1,2,3,4,5] [1, 2, 3, 4, 5] Python3 : You need to use extra pair of parenthesis [item for item in (1,2,3,4,5)] [1, 2, 3, 4, 5] I just mentioned 10 differences. Please add in comments if you can recall other differences.

• Mutable vs Immutable Objects in Python example

Everything in Python is an object and all objects in Python can be either mutable or immutable. Immutable objects: An object with a fixed value. Immutable objects include numbers, bool, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary. Consider an integer → 1 assigned to variable “a”, >>> a=1 >>> b=a >>> id(a) 4547990592 >>> id(b) 4547990592 >>> id(1) 4547990592 Notice id() for all of them them is same. id() basically returns an integer which corresponds to the object’s memory location. b → a → 1 → 4547990592 Now, let’s increment the value of “a” by 1 so that we have new integer object → 2. >>> a=a+1 >>> id(a) 4547990624 >>> id(b) 4547990592 >>> id(2) 4547990624 Notice how id() of variable “a” changed, “b” and “1” are still same. b → 1 → 4547990592 a → 2 → 4547990624 The location to which “a” was pointing has changed ( from 4547990592 → 4547990624). Object “1” was never modified. Immutable objects doesn’t allow modification after creation. If you create n different integer values, each will have a different constant hash value. Mutable objects can change their value but keep their id() like list, dictionary, set. >>> x=[1,2,3] >>> y=x >>> id(x) 4583258952 >>> id(y) 4583258952 y → x → [1,2,3] → 4583258952 Now, lets change the list >>> x.pop() >>> x[1,2] >>> id(x) 4583258952 >>> id(y) 4583258952 y → x → [1,2] → 4583258952 x and y are still pointing to the same memory location even after actual list is changed.

• What is "is" in Python?

The operators is and is not test for object identity. x is y is true if and only if x and y are the same object (object location in memory is same). Object identity is determined using the id() function. x is not y yields the inverse truth value. It’s easy to understand if I compare this operator with equality operator. is and is not compares the object reference. Check for identity. == and != compares the object value. Check for equality. For example, if you consider integer objects (excluding integers from -5 to 256), >>> A=9999 >>> B=9999 >>> A == B, A is B (True, False) >>> A, B (9999, 9999) >>> id(A), id(B) (4452685328, 4452686992) Python stores integer objects as single object between range -5 to 256 so the identity is same. >>> A=99 >>> B=99 >>> A == B, A is B (True, True) >>> A, B (99, 99) >>> id(A), id(B) (4404392064, 4404392064) Lets see behavior of other immutable objects like int & float, string, tuples and boolean: >>> 1 == 1.0, 1 is 1.0 (True, False) >>> 1 == 1, 1 is 1 (True, True) >>> 'A' == 'A', 'A' is 'A' (True, True) >>> (1,2) == (1,2), (1,2) is (1,2) (True, True) >>> True == True, True is True (True, True) What about mutable objects - list, set, dict? Behavior is totally different. >>> [1,2] == [1,2], [1,2] is [1,2] (True, False) >>> {1,2} == {1,2}, {1,2} is {1,2} (True, False) >>> {'k1':1} == {'k1':1}, {'k1':1} is {'k1':1} (True, False) is operator is used only when you want to compare the object identity, for regular comparison equality operator is used.

• Interesting and Unknown facts about Python programming

• Spaghetti with Potatoes (Indian Style)

This spaghetti with Indian spices brings back childhood memories. It is a quick, simple, tasty recipe which everyone can enjoy as a meal anytime of the day! Preparation time: 20 min, Serves: 3-4 Ingredients : Spaghetti Onions : 2 Green Chillies : 2 Ginger : 1/2 inch Potato : 1 (medium sized) Cilantro/Coriander Tomato Ketchup : 1 cup Shredded Cheese Turmeric Powder : 1/2 tsp Red Chilli Powder : 1/2 tsp Dhania Powder ( Coriander Seed Powder) : 1 tsp Salt to taste Preparation Steps : Cook spaghetti as per the instructions mentioned on the packet. While the spaghetti is cooking heat oil in a pan. Add finely chopped ginger, green chilies. Saute for a minute and add the chopped onions. Once the onions are translucent , add the potatoes (finely chopped into small cubes). Saute for 3-4 minutes. Add Turmeric powder, red chili powder, dhania powder. Mix well. Cover the pan and let the potatoes cook. Once the potatoes are cooked, add the cooked spaghetti, tomato ketchup, cilantro and salt. Garnish with cheese and cover the lid so it melts. Serve hot! Hope you all enjoy this recipe!

• Quick & Easy Punjabi Palak Paneer Recipe

My love for Palak Paneer never ends. Each time I cook Palak Paneer, I try a new variation and love to see how it turns out. Here I am going to share one of the versions which is easy and quick. Preparation time: 20 min, Serves: 3-4 Ingredients : Spinach : 1 bunch Onion : 1 medium size Tomato : 2 small Ginger : 1/2 inch or less Garlic : 3-4 cloves Cardamom : 2 (whole) Green Chili : 3 Coriander/Dhania Powder : 1 tsp Kitchen King masala powder : 1.5 tsp Cumin/Jeera seeds : 1/2 tsp Paneer/Cottage cheese cubes : 200 grams Milk : 1 cup Preparation Steps : Heat some oil in a pan. Once hot, add cardamom, diced onions, ginger, garlic and green chilies. Saute these for 4-5 minutes till onions are golden brown. Next add the tomatoes and salt. Saute till the tomatoes are soft . Next add roughly chopped spinach (baby spinach need not be chopped). Once the spinach is soft. Blend this mix to a smooth paste. In the same pan add 1 tsp of oil. Add Cumin/Jeera seeds and wait till they crackle. Add the spinach paste into the pan. Next add Dhania(coriander seeds) powder and kitchen king masala powder, salt to taste. Stir the mix for few minutes and add hot water to adjust the consistency of the gravy. Bring it to a boil. Add paneer/cottage cheese cubes and one cup milk. Let this simmer for 5-6 minutes. Serve hot! Hope you all enjoy this version of Palak Paneer :)

• Tangy Creamy Tomato Carrot Soup Recipe

When it's cold outside, nothing hits the spot quite like a creamy tomato carrot soup. This healthy, quick and easy recipe makes use of real cream, for a thick and satisfying soup with fabulous flavor that's ready in less than an hour. What could be better for dinner that a nice hot bowl of soup along with your favorite salad. Well this is what I was craving for one evening and turned out I had no vegetables in my refrigerator except for 3 carrots and few tomatoes. So a mashup of the left over ingredients in my fridge turned into a nice soothing bowl of carrot tomato soup topped with croutons and dollops of cottage cheese (current favorite at my place). Below are the details of the recipe. Do try it out and I would love to hear how it turned out. Let me know if anyone comes up with interesting variations as well. Preparation time: 30-40 min, Serves: 3-4 Ingredients 3 Carrots 2 Tomatoes 1/2 inch Ginger 3-4 Garlic Cloves 1 Onion 2-3 Green Chilies (as per spice preference) 1-2 tsp of cottage cheese ( as per preference) Salt to taste Pepper Oregano/Cilantro/Parsley ( as per preference) Heavy cream ( optional) Preparation Steps Heat Oil in a pan. Add chopped onions, garlic, ginger, green chilies. Saute till the onions are translucent. Next, add chopped carrots and saute for another 3 minutes. Next add the chopped tomatoes and continue to saute till the tomatoes are mushy and carrots are soft. I prefer to saute till the veggies are nicely roasted and the tomatoes have dissolved. Now blend this to a smooth paste. Pour the paste into the same pan and add 2 cups of hot water while stirring continuously. Add Salt per taste. Cook till it boils rapidly. Adjust the consistency as per your preference. Finally add salt to taste , fresh cracked pepper and some oregano or any herb of your choice. Add 2 teaspoons of cottage cheese to each serving and top it with some croutons. Hope you all like this recipe and can enjoy it on a cozy winter evening!