Again firstly I am sorry because keep asking the same question.I am new to python programming. I am now trying to build a program which convert every element in a list of numbers of base 10 into its base 4. For example here, say i have numbers from 0 to 20 or more, I want to convert every number starting from 0 to numbers of base 4. The result should be like this
[[0,0],[0,1],...[1,1,0]
for numbers starting from 0 to 20. For the code,here is what I wrote so far
for n in range(21):
def base(n,b):
result = []
while n > 0:
result.insert(0, n % b)
n = n // b
return result
print(base(n, 4))
For the result I got only for number 20 which is
[1,1,0]
Did I missed something here or there is another option to make it work?
Thank you for the answer
The issue is that you are defining the function inside the loop body, and only call it once. The structure you actually need is
<define the function>
for n in range(21):
print(base(n, 4))
The results will print out, but each one on a separate line. To create a list of the results you should replace the two lines of the loop with a single line that prints a list of all results, like
print([base(n, 4) for n in range(21)])
The problem is that you're defining the function inside the loop. What you want to do is define the function first, then construct your desired list:
def base(n,b):
result = []
while n > 0:
result.insert(0, n % b)
n = n // b
return result
print [base(n, 4) for n in range(21)]
(See this article if you're new to list comprehensions.)
If you want all the numbers, then indent your print statement, so that it's part of the loop.
If you want these as strings, then convert the digits to characters and concatenate them.
I've done both here:
def base(n, b):
result = []
while n > 0:
result.insert(0, n % b)
n = n / b
return result
for decimal in range(21):
print(''.join(str(digit) for digit in base(decimal, 4)))
You can manually compute the base of a number by doing something like this:
from math import log
from math import floor
def n_to_base(n, b):
num = n
lead_idx = floor(log(num, b))
b_rep = int(10**lead_idx)
b_rep = str(b_rep)
rep = 0
for i in range(len(b_rep)-1, -1, -1):
coeff = floor(num/(b**i))
rep += int(coeff*(10**i))
num -= int(coeff*(b**i))
return rep
Related
I am writing a program that looks for keith numbers in different bases. Is there a way to iterate through numbers in a certain base? I have a program that can convert decimal to any base, but I'm not sure how to proceed.
This is my code so far.
def is_keith_number(n,base):
# Find sum of digits by first getting an array of all digits then adding them
c = str(n)
a = list(map(int, c))
b = sum(a)
# Now check if the number is a keith number
while b < n:
a = a[1:] + [b]
b = sum(a)
return (b == n) & (len(c) > 1)
I also have a function,
convert()
which converts a number from one base to another. Its unneccesary to show that code, but it does work. Any help?
The code is to find the largest possible product of 13 consecutive digits of a 1000 digit number. When I tried to run it on IDLE, it just gave RESTART and the directory where I saved the .py file. When I tried this on Pycharm(I know its not the IDE's problem, but I just had to try), no output. Am I doing something wrong?
n=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
s=[]
j=13
def product(j):
p = 1
for i in range(j,j+13):
p=p*s[i]
return(p)
for i in range(0,1000):
s=s+[n%10]
n=n//10
k = product(0)
c=k
while j<1000:
if s[j]==0:
j=j+1
c=product(j)
while c==0:
j=j+13
c=product(j)
else:
c=(c*s[j+13])/s[j]
if c>k:
k=c
print(k)
Try this:
>>> n=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
>>> digits = str(n)
>>> from numpy import prod
>>> products = [prod( map( int, digits[i:i+13])) for i in range(len(digits)-13)]
>>> max(products)
23514624000
Here's the quick explanation. First line -- this is your number. Second line -- I convert the number (like, 123) into the string "123", so I can take it digit by digit, hence the name of the variable digits.
I'm lazy to write multiplication routine, so I use a ready-made from numpy package, it's called prod and computes a product of the list, for example, prod( [1,2,3] ) = 6.
The next line is kind of complicated, but all it does -- going over your digits, selecting 13 of them at at time (digits[i:i+13]) and multiply them, saving the results in products.
Finally, the last line finds the maximum number in the products.
Your original code can be simplified to the following.
n=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
def product(j):
p = 1
for i in range(j,j+13):
p=p*s[i]
return(p)
s=[]
for i in range(0,1000):
s=s+[n%10]
n=n//10
k = 0
N = len(s)
j = 0
while j<N-13: #need to 13 elements before end
c = product(j)
if c>k:
k=c
j = j + 1
print(k)
Result: 23514624000
This can be generated more easily even without resorting to Numpy by:
digits = str(n) # generates digits of number
products = [product(j) for j in range(1000-13)] # list comprehension
# uses you product function
print(max(products))
I want to find multiples of 3 or 5 below 1000 using the code below:
a=[]
b=[]
def multiples_of_3():
i=1
for i in range(330):
m=i*3
if(m<1000):
a.append(m)
def multiples_of_5():
j=1
for j in range(330):
k=j*5
if(k<1000):
b.append(k)
if __name__ == "__main__":
multiples_of_3()
multiples_of_5()
print sum(a) + sum(b)
Result- 262355
Result is not right. It should be 233168 . How am I going wrong with the logic here?
You are looping over the wrong ranges and adding multiples of 15 twice.
I believe that this is the smallest change to your program that makes it work:
a=[]
b=[]
def multiples_of_3():
i=1
for i in range(334): # stops at 1 less than the value passed to `range`
m=i*3
if(m<1000):
a.append(m)
def multiples_of_5():
j=1
for j in range(330): # could change to 201 and still work
k=j*5
if(k<1000):
b.append(k)
if __name__ == "__main__":
multiples_of_3()
multiples_of_5()
print sum(set(a+b))
But you should probably rethink your approach. Using global variables is generally a bad idea - looking at the call multiples_of_3(), there is no way to know what the subroutine is doing with those multiples; the variable a is not referenced anywhere, yet before the line and after the line it has two different values. So for starters, I would turn the subroutines into pure functions - have them return the arrays instead of modifying globals.
As minor stylistic points, you also don't need to use different variable names inside the two functions, since they're all local. You don't need to assign anything to i before the loops (the loop will create the variable for you), and you don't need parentheses around the condition in Python's if statement (the colon takes care of delimiting it):
def multiples_of_3():
a = []
for i in range(334):
m = i * 3
if m < 1000:
a.append(m)
return a
def multiples_of_5():
a = []
for i in range(201):
m = i * 5
if m < 1000:
a.append(m)
return a
if __name__ == "__main__":
a = multiples_of_3()
b = multiples_of_5()
print sum(set(a+b))
You could also combine the two multiples_of functions into a single generic one that takes a parameter telling it what to return multiples of:
def multiples_of(k):
result = []
for i in range(1000/k+1):
multiple = i * k
if multiple < 1000:
result.append(multiple)
return result
You could even turn the maximum value into an optional parameter:
def multiples_of(k, under=1000):
result = []
for i in range(under/k+1):
multiple = i * k
if multiple < under:
result.append(multiple)
return result
Either way, your main part becomes this:
a = multiples_of(3)
b = multiples_of(5)
print sum(set(a+b))
Finally, just as a point of reference, it is possible to do the whole thing as a one-liner. Here I've switched from building up the list of multiples by actually doing the multiplication, to just looping over all the numbers under 1000 and testing them for divisibility by either 3 or 5:
print sum([n for n in range(1000) if n%3==0 or n%5==0])
Shouldn't for j in range(330): be for j in range(200): since you're using multiples of 5?
def fact(n):
fac = 1
while (n>1):
fac = fac*n
n -= 1
return fac
z = 0
t = int(raw_input())
nz = []
for i in range(0,t):
c = 0
n = int(raw_input())
z = fact(n)
z = list(str(z))
for j in range(len(z)-1,1,-1):
if z[j] != '0':
break
else:
c +=1
nz[i].append(c)
for k in range(0,t):
print nz[k]
Hello I am getting
Indexerror : index out of range at " nz[i].append(c)
This program should calculate trailing zeros in the factorial of N.
Can you also please help me optimize my code, so it can run also for large values of N?
nz is empty list. It doesn't have any elements, so nz[i] would always raise IndexError. Perhaps you meant nz.append(c) ie. add c at the end of nz.
This is how does append() work:
list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
so you may want to change nz[i].append(c) to nz.append(c), since your i index is already handled by the append function. You're actually assuming you have an i element in your list, which is false, since you are using an empty list
About optimizing, your problem is probably due to your recursion limit. Try import sys; sys.getrecursionlimit() in your python shell, you should see something like 1000 as result.
Swapping for an iterative version of the factorial function could be a start
def fact(n):
r = 1
for x in range (n):
r = r * (x+1)
return r
I would like to write a recursive function in Python. I have written one but it doesn't work correctly.
I have a range of numbers from 1 to 1000 and I want cut it into two parts 1 to 500 and 501 to 1000. Then I want to do this recursively until there are only 20 numbers in each part.
Here is my attempt:
mw = range(1,1000)
def cuter(mw):
if len(mw)<20:
return False
else:
cut=int(len(mw)/2)
number.append(mw[0])
number.append(cut)
number.append(mw[-1])
return cuter(mw)
cuter(mw)
Try something like this, where seq is a list with the range of numbers:
def cutter(seq):
n = len(seq)
if n <= 20:
# here the recursion stops, do your stuff with the sequence
return
a = cutter(seq[:n/2])
b = cutter(seq[n/2:])
# combine the answer from both subsequences
return