Problem converting decimal to binary in python - python-3.x

The following code is to convert decimal to binary.
My question is: When num becomes less than or equal to 1, python jumps to the last line i.e print(num % 2, end = '') and consequently prints out 1. But after that, why does it move to line 'decimalToBinary(num // 2)'? That line is supposed to execute only when num > 1
def decimalToBinary(num):
if num > 1:
decimalToBinary(num // 2)
print(num % 2, end='')
decimalToBinary(17)

It's because the last function in the stack finished,so it jumps to the call point of the function in the upper stack.If you add a=1 behind the print(num%2,end='') statement, you will see that a=1 gets called before the control returns to the upper function.

import numpy as np
import pandas as pd
# Read the input
s = int(input())
# Write your code below
print(format(s, 'b'))

Related

File operation using numpy

I am trying to delete phrase from text file using numpy.I have tried
num = [] and num1.append(num1)
'a' instead of 'w' to write the file back.
While append doesn't delete the phrase
writes' first run deletes the phrase
second run deletes second line which is not phrase
third run empties the file
import numpy as np
phrase = 'the dog barked'
num = 0
with open("yourfile.txt") as myFile:
for num1, line in enumerate(myFile, 1):
if phrase in line:
num += num1
else:
break
a=np.genfromtxt("yourfile.txt",dtype=None, delimiter="\n", encoding=None )
with open('yourfile.txt','w') as f:
for el in np.delete(a,(num),axis=0):
f.write(str(el)+'\n')
'''
the bird flew
the dog barked
the cat meowed
'''
I think you can still use nums.append(num1) with w mode, the issue I think you're getting is that you used the enumerate function for myFile's lines using 1-index instead of 0-index as expected in numpy array. Changing it from enumerate(myFile, 1) to enumerate(myFile, 0) seems to fix the issue
import numpy as np
phrase = 'the dog barked'
nums = []
with open("yourfile.txt") as myFile:
for num1, line in enumerate(myFile, 0):
if phrase in line:
nums.append(num1)
a=np.genfromtxt("yourfile.txt",dtype=None, delimiter="\n", encoding=None )
with open('yourfile.txt','w') as f:
for el in np.delete(a,nums,axis=0):
f.write(str(el)+'\n')

how to change this code that use xrange to run in python 3?

I'm reading the High-Performance Python book from O'Reilly collection, in the page number 11 I found this code that works for python 2, the point here is to make one instruction that performs(by vectorizing) several at the same time
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = range(2, int(sqrt_number)+1)
for i in xrange(0, len(numbers), 5):
# the following line is not valid Python code
result = (number_float / numbers[i:(i+5)]).is_integer()
if any(result):
return False
return True
but I get this error
TypeError: unsupported operand type(s) for /: 'float' and 'list'
I've tried to change it to work on python 3 here is my try:
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = list(range(2, int(sqrt_number)+1))
for i in range(0, len(numbers), 5):
# the following line is not valid Python code
result = (number_float / numbers[i:(i+5)]).is_integer()
if any(result):
return False
return True
I changed the xrange for range and the range(2, int(sqrt_number)+1) for list(range(2, int(sqrt_number)+1)) but i did not have succeed in this. I suppose there is a special operator for sets or something like that but have no idea. if any of you people can help me I'll be so grateful whit you
I looked at the book and that line is not supposed to actually work as is; you cannot divide by a list in Python. The author uses that code as an example of what vectorization would look like. The # the following line is not valid Python code comment is in the original to indicate that.
The closest in term of functionality and semantics would probably be this code:
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = list(range(2, int(sqrt_number)+1))
for i in range(0, len(numbers), 5):
# the following line is now valid Python code, but not vectorized
result = [(number_float / n).is_integer for n in numbers[i:(i+5)]]
if any(result):
return False
return True
Note that the processing for result in this version is not done in parallel, so it's probably not what the author wanted to demonstrate. As far as I know, vectorization isn't natively available in Python, you would have to use numpy to do it. This article should be useful if you want to try it.
Try this:
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = list(range(2, int(sqrt_number)+1))
for i in range(0, len(numbers), 5):
result = [number_float % num == 0 for num in numbers[i:(i+5)]]
if any(result):
return False
return True

Write a program to take dictionary from the keyboard and print sum of values?

d =dict(input('Enter a dictionary'))
sum = 0
for i in d.values():
sum +=i
print(sum)
outputs: Enter a dictionary{'a': 100, 'b':200, 'c':300}
this is the problem arises:
Traceback (most recent call last):
File "G:/DurgaSoftPython/smath.py", line 2, in <module>
d =dict(input('Enter a dictionary'))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
You can't create a dict from a string using the dict constructor, but you can use ast.literal_eval:
from ast import literal_eval
d = literal_eval(input('Enter a dictionary'))
s = 0 # don't name your variable `sum` (which is a built-in Python function
# you could've used to solve this problem)
for i in d.values():
s +=i
print(s)
Output:
Enter a dictionary{'a': 100, 'b':200, 'c':300}
600
Using sum:
d = literal_eval(input('Enter a dictionary'))
s = sum(d.values())
print(s)
import json
inp = input('Enter a dictionary')
inp = dict(json.loads(inp))
sum = sum(inp.values())
print(sum)
input Enter a dictionary{"a": 100, "b":200, "c":300}
output 600
Actually the return of input function is a string. So, in order to have a valid python dict you need to evaluate the input string and convert it into dict.
One way to do this can be done using literal_eval from ast package.
Here is an example:
from ast import literal_eval as le
d = le(input('Enter a dictionary: '))
_sum = 0
for i in d.values():
_sum +=i
print(_sum)
Demo:
Enter a dictionary: {'a': 100, 'b':200, 'c':300}
600
PS: Another way can be done using eval but it's not recommended.

Can't convert complex to float on python 3

I write this code for uri online judge(problem no.1036)...It is an Bhaskara's formula...
import cmath
A,B,C=input().split()
A = float(A)
B = float(B)
C = float(C)
D = (B*B)-(4*A*C)
if((D== -D)|(A==0)):
print("Impossivel calcular")
else:
T = cmath.sqrt(D)
x1 = (-B+T)/(2*A)
x2 = (-B-T)/(2*A)
print("R1 = %.5f" %x1)
print("R2 = %.5f" %x2)
but when i submit this program...that runtime error occured...
Traceback (most recent call last): File "Main.py", line 14, in
print("R1 = %.5f" %x1)
TypeError: can't convert complex to float
Command exited with non-zero status (1)
please help me to solve this problem.
The problem with using sqrt imported from cmath is that it outputs a complex number, which cannot be converted to float. If you are calculating a sqrt from positive number, use math library (see below).
>>> from cmath import sqrt
>>> sqrt(2)
(1.4142135623730951+0j)
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951
the problem is just that your format string is for floats and not for complex numbers. something like this will work:
print('{:#.3} '.format(5.1234 + 4.123455j))
# (5.12+4.12j)
or - more explicit:
print('{0.real:.3f} + {0.imag:.3f}i'.format(5.123456789 + 4.1234556547643j))
# 5.123 + 4.123i
you may want to have a look at the format specification mini language.
# as format specifier will not work with the old-style % formatting...
then there are more issues with your code:
if((D== -D)|(A==0)):
why not if D==0:? and for that it might be better to use cmath.isclose.
then: | is a bit-wise operator the way you use it; you may want to replace it with or.
your if statement could look like this:
if D == 0 or A == 0:
# or maybe
# if D.isclose(0) or A.isclose():

Pass an array as command line argument to the script

I'd like to experiment codes from command line, so import argv form sys.
from sys import argv
def binary_search(array, item):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2 # round down if not an even
guess = array[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
def main():
script, array, item = argv
binary_search(array, item)
When run it on the command line:
$ python3 binary_search.py [1, 2, 3] 8
Traceback (most recent call last): File "binary_search.py", line 94, in <module>
main() File "binary_search.py", line 89, in main
script, array, item = argvValueError: too many values to unpack (expected 3)
I tested and found that arguments passed from command line are treated as str by argv.
How can pass an array as argument?
There are a couple different ways you can do this...
using re
Using regular expressions may be one of the easiest ways of handling this.
from sys import argv
import re
def binary_search(array, item):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2 # round down if not an even
guess = array[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
def main():
array = re.findall(r"[\w]+", argv[1])
array = [int(i) for i in array]
item = int(argv[2])
binary_search(array,item)
if __name__== "__main__":
main()
using exec()
You can also use exec() which may be more risky and complicated. Here's a simple example:
from sys import argv
command = 'mylist = {0}'.format(argv[1])
exec(command)
for item in mylist:
print(item)
example output:
C:\path>py foo.py [1,2,3]
1
2
3
The arguments on the command line are strings, they're not parsed like literals in the program.
argv construct the strings automatically to a list from command line arguments (as separated by spaces), in short,
sys.argv is a list.
Additionally, module argparse helps
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Resources