So I'm running in to the string formatting error when trying to pass the arguments num1 and num2 to the function gcd. I'm not sure how to fix this. Please bear with me since I'm new to Python programming. Thanks!
#!/usr/bin/python
import sys
from collections import defaultdict
lines = sys.stdin.read()
lineArray = lines.split()
listLength = len(lineArray)
def gcd(a, b):
c = 0
if a > b:
r = a%b
if r == 0:
return b
else:
return gcd(b, r)
if a < b:
c = b
b = a
a = c
return gcd(a, b)
for x in range(0, listLength):
num1 = lineArray[x]
num2 = lineArray[x+1]
print num1, 'and', num2
print gcd(num1, num2)
print 'end'
It's pretty simple. lineArray is not a list containing integers, but strings.
So when you do this:
r = a%b
It tries to format the string a, instead of calculating a%b.
To solve this, convert a and b to integers:
def gcd(a, b):
a,b = int(a),int(b)
c = 0
if a > b:
r = a%b
if r == 0:
return b
else:
return gcd(b, r)
if a < b:
c = b
b = a
a = c
return gcd(a, b)
Also, in your gcd function, the recursion never ends. Hint: You'll have to check if b is 0.
Hope this helps!
Related
my goal is to sort three numbers into a, b, and c, with a being the largest, b being the middle, and c being the smallest. To do this, I'm required to write a function. However, I've tried multiple ways and haven't found a way to allow it to work.
num1 = int(input("input an integer: "))
num2 = int(input("input another integer: "))
num3 = int(input("input another integer: "))
def simple_sort(a,b,c):
if a > b and a > c:
return a
if b < a and b > c:
return b
if c < a and c < b:
return c
a,b,c=simple_sort(num1,num2,num3)
print(a,b,c)
#for it to be correct, when i do print(a,b,c), it should print num1, num2 and num3
#in ascending order
You're only returning one value (a, b, or c) where you need to return a tuple or list.
def simple_sort(a,b,c):
if a < b:
a,b = b,a
# above guarantees that a > b
if c > a:
return (c,a,b)
elif c > b:
return (a,c,b)
else:
return (a,b,c)
values = list(map(int,input("Input three integers separated by spaces: ").split()))
print(simple_sort(*values))
How does one append the output of a while function into a list? For example:
fib = []
def FIB():
a,b = 0,1
while a < 100:
fib.append(a)
a, b = b, a + b
print(fib)
I am expecting:
[0,1,1,2,3,5,8,13,21,34,55,89]
But I receive:
[]
you need to return fib, so you can print it. You also need to call your function correctly.
fib = []
def FIB():
a,b = 0,1
while a < 100:
fib.append(a)
a, b = b, a + b
return fib
print(FIB())
fib = []
def FIB(fib):
a,b = 0,1
while a < 100:
fib.append(a)
a, b = b, a + b
return fib
print(FIB(fib))
I'm trying to do the following in my code:
A man is trying to shoot some balloons with a rock.
a is the number of balloons in a row.
b is the speed of the rock the man is trying to shoot with.
c is the speed that the rock loses after hitting each balloon.
In the end I want to know how many balloon have been shot by the rock.
The problem is that the code doesn't want to give me any output. Please help!
def Balloons(a, b, c):
d = 0
for i in (0, a):
b - c
d = d+1
if d == int(a):
print(d)
if d > int(a):
d = d-1
print(d)
if int(b) <= 0:
print(d)
x = int(input('give me the number of test cases: '))
for i in range (0, x):
a = int(input())
b = int(input())
c = int(input())
Balloons(a, b, c)
Problems
There is no output because in your definition of your code, it you wrote b - c which does nothing. You need to tell Python what to do with the result of b - c.
What you should do instead is to use to subtraction assignment operator:
b -= c
Which is equivalent to:
b = b - c
This will give you some output but not the right output. Another problem with your code is that you missed out the keyword range in the for loop of your function:
for i in (0, a):
What this means in the loop is that i will be the value of 0 and a then the loop will end. It should be changed to:
for i in range(0, a):
Lastly, you may want to add some break statements which exit the for loop so that you only have one output:
if d == int(a):
print(d)
break
if d > int(a):
d -=1
print(d)
break
if int(b) <= 0:
print(d)
break
Final solution
The resulting code using subtraction assignment and addition assignment operators would be:
def Balloons(a, b, c):
d = 0
for i in range(0, a):
b -= c
d += 1
if d == int(a):
print(d)
break
if d > int(a):
d -=1
print(d)
break
if int(b) <= 0:
print(d)
break
x = int(input('give me the number of test cases: '))
for i in range(0, x):
a = int(input())
b = int(input())
c = int(input())
Balloons(a, b, c)
Alternative method
However, looking at your problem, it could be solved with basic math, math.ceil and the min function.
The number of balloons shot through is equals to the smaller of:
ceil(Initial speed/Speed loss)
Number of balloons
Hence, you can have a much smaller function:
import math
def Balloons(a, b, c):
return min(math.ceil(b/c), a)
b-c
I think you want to write b -= c
This should work
def Balloons(a, b, c):
d = 0
for i in range(0, a):
b=b-c
d=d+1
if d==int(a):
print(d)
if d>int(a):
d=d-1
print(d)
if int(b)<=0:
print(d)
x = int(input('give me the number of test cases: '))
for i in range(0, x):
a=int(input())
b=int(input())
c=int(input())
Balloons(a, b, c)
I am solving this problem in SPOJ and it states that :
Problem statement is simple. Given A and B you need to calculate
S(A,B) .
Here, f(n)=n, if n is square free otherwise 0. Also f(1)=1.
Input
The first line contains one integer T - denoting the number of test
cases.
T lines follow each containing two integers A,B.
Output
For each testcase output the value of S(A,B) mod 1000000007 in a
single line.
Constraints
`T <= 1000
1 <= A,B <= 1000000`
Example
Input:
3
42 18
35 1
20 25
Output:
306395
630
128819
I wrote this code for this problem (if I got the the problem right) :
def gcd(a,b): #gcd(a,b)
if b==0:
return a
else:
return gcd(b,a%b)
# print gcd(42,18)
import math
def issquarefree(n): #sqare free number check
i=2
s=i*i
if (n==1 or n==2) or n==3:
return True
while s<=n:
if n%s==0:
i=-1
break
else:
i+=1
s=i*i
if i==-1:return False
else:
return True
for i in range(int(raw_input())): #main program
a,b=map(int,raw_input().split())
g=gcd(a,b)
sa=(a*(a+1))/2 #see below
sb=(b*(b+1))/2 #see below
gc=issquarefree(g)
s=0
if gc== False:
print 0
elif gc==True:
s+=sa*sb*g
print s%1000000007
here I found that so applying this to the problem # S(A,B) I wrote this as (multiplication of sum of first A and B numbers ) multiplied by f(n) which is gcd(a,b) or 0.
But I am not getting the expected output to this problem so is my code wrong or I got the problem wrong
my output vs expected
3
35 1
42 18
20 25
630 630
926478 306395
341250 128819
Writing out the G(a, b) = f(gcd(a, b)) (so that you can use the cited formula) is incorrect since the function is not constant. The proper solution is this:
for i in range(int(raw_input())):
A, B = map(int, raw_input().split())
# proper algorithm
s = 0
for a in xrange(1, A):
for b in xrange(1, B):
s += a * b * G(a, b)
print s % 1000000007
You obviously have to implement G function properly (as returning 0 or gcd(a, b)).
Careful analysis of G might give some optimization insight but it is definitely not a trivial one if any.
Here is a simple optimization:
import fractions
DIVISOR = 1000000007
def is_not_square_free(a):
counter = 1
factor = 1
while factor < a:
counter += 1
factor = counter * counter
if a % factor == 0:
return True
return factor == a
def F(n):
if n == 1:
return 1
if is_not_square_free(n):
return 0
return n
_CACHE = {}
def G(a, b):
a = a % DIVISOR
b = b % DIVISOR
key = (a, b) if a > b else (b, a)
if key not in _CACHE:
_CACHE[key] = (a * b * F(fractions.gcd(a, b))) % DIVISOR
return _CACHE[key]
def S(A, B):
s = 0
for a in range(1, A+1):
for b in range(1, B+1):
s += G(a, b)
return s
for _ in range(int(raw_input())):
A, B = map(int, raw_input().split())
print(S(A, B) % DIVISOR)
def gcd(a, b):
returns greatest common divisor of a and b'''
return gcd(b % a, a) if a and b else max(a, b)
print test gcd should print 6,5, 7, and 9'''
print gcd(48,18)
print gcd(10,5)
print gcd(14,21)
print gcd (9,0)
Does anyone know how to code the Harmonic Series in python?
H(n) = 1 + 1/2 + 1/3 + ... + 1/n
Note: We're not allowed to import from predefined modules. The output must be the numerator and the denominator of the answer in fraction form (lowest terms).
so here's my code for this harmonic series.
n = input("Enter n:")
def harmonic(n):
a=1
b=1
for d in range(2, n+1):
a = a*d+b
b = b*d
return (a,b)
x == max(a,b)%min(a, b)
if x == 0:
y=min(a,b)
return y
else:
y=min(a,b)/x
return y
a=a/y
b=b/y
return (a,b)
print harmonic(n)
what's wrong? Whatever I input, the output is always (3,2)
I have to check your attempt twice - and inserted a simple gcd (in the middle of the your original code)
n = input("Enter n:")
def harmonic(n): #original harmonic series
a=1
b=1
for d in range(2, n+1):
a = a*d+b
b = b*d
return(a,b)
def harmonic_lt(n): #_lt: harmonic series with lowest terms
#not pythonic, but simple
a=1
b=1
for d in range(2, n+1):
a = a*d+b
b = b*d
y=a
x=b
while x > 0:
re = y % x
y = x
x = re
a=a/y
b=b/y
return(a,b)
print harmonic(n)
print harmonic_lt(n)
As others pointed out, you are returning when d = 2 i.e. (1 + 1/2), it should be outside of the for loop.
Here's a code I wrote for doing the same:
#!Python2.7
def gcd(a, b):
if b: return gcd(b, a%b)
return a
def lcm(a, b):
return a*b/gcd(a, b)
def start():
n = int(raw_input())
ans = reduce(lambda x, y: (x[0]*lcm(x[1],y[1])/x[1]+y[0]*lcm(x[1],y[1])/y[1], lcm(x[1],y[1])),[(1,x) for x in xrange(1,n+1)])
_gcd = gcd(ans[0], ans[1])
print (ans[0]/_gcd, ans[1]/_gcd)
start()
If you want to avoid using reduce, lamda and list comprehensions:
#!Python2.7
def gcd(a, b):
if b: return gcd(b, a%b)
return a
def lcm(a, b):
assert a != 0
assert b != 0
return a*b/gcd(a, b)
def next(x, y):
lcmxy = lcm(x[1], y[1])
return (x[0]*lcmxy/x[1]+y[0]*lcmxy/y[1], lcmxy)
def start():
n = int(raw_input())
curr = (1,1)
for x in xrange(2,n+1):
curr = next(curr, (1,x))
_gcd = gcd(curr[0], curr[1])
print (curr[0]/_gcd, curr[1]/_gcd)
start()
You can find the denominator by finding the lowest common multiple of the numbers 1..n.
The nominator will then be the sum of all values denominator/x with x being all values from 1..n.
Here's some code:
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
def lcmm(args):
"""Return lcm of args."""
return reduce(lcm, args)
def harmonic(n):
lowest_common_multiple = lcmm(range(1,n))
nominator = sum([lowest_common_multiple/i for i in range(1,n)])
greatest_common_denominator = gcd(lowest_common_multiple, nominator)
return nominator/greatest_common_denominator, lowest_common_multiple/greatest_common_denominator
print harmonic(7)
print harmonic(10)
print harmonic(20)
Harmonic series:
1/1 + 1/2 + ... + 1/n == (n!/1 + n!/2 + ... + n!/n)/n!
therefore you can do:
nom = reduce(lambda s, x: s*x, xrange(1, n+1),1) # n!
denom = sum([nom / x for x in xrange(1, n+1)])
Then you need to do gcd-reduction on nom and denom.
Use the version from Thorsten Kranz.
Note that this way only one call to gcd is needed!
Example:
def gcd(a, b):
while b:
a, b = b, a % b
return a
def harmonic(n):
nom = reduce(lambda s, x: s*x, xrange(1,n+1), 1) # n!
denom = sum([nom / x for x in xrange(1, n+1)])
f = gcd(denom, nom)
return (denom / f), (nom / f)
print harmonic(10)
print harmonic(20)
(7381, 2520)
(55835135, 15519504)
You always return (a,b) at the first iteration. – Scharron"
Return always ends a function. If you return (a,b), the rest of the code is unreachable