This is the question,
Write a Python program to find numbers in between 100 and 400 (both inclusive) where each digit of
the numbers is an even number. The numbers obtained should be printed in a comma-separated
sequence. I'm only allowed to use while loops so I'm not sure how.
Edited: It has to in a single line
My current code:
x = 100
while x < 400:
x += 2
str_x = str(x)
if int (str_x[0]) % 2 == 0 and int(str_x[1]) % 2 == 0 and int(str_x[2]) % 2 == 0:
l = [str_x]
print(l)
You need to collect the values in a list, and at the end print them comma-separated
x = 100
keep = []
while x <= 400:
strx = str(x)
if all(int(digit) % 2 == 0 for digit in strx):
keep.append(strx)
x += 2
print(",".join(keep))
# 200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,280,282,284,286,288,400
Here is a solution with only while loops and without converting to string:
i = 100
while i <= 400:
d = i
flag = True
while d > 0:
d,r = divmod(d,10)
if r%2:
flag = False
if flag:
print(i)
i += 2 # optimization as only even numbers are valid
output (as single line):
200 202 204 206 208 220 222 224 226 228 240 242 244 246 248 260 262 264 266 268 280 282 284 286 288 400
This is just some correction to have a list with all the values at the end. With only using a while loop.
x = 100
l = []
while x < 400:
x += 2
str_x = str(x)
if int(str_x[0]) % 2 == 0 and int(str_x[1]) % 2 == 0 and int(str_x[2]) % 2 == 0:
l.append(x)
print(l)
A more pythonic way in doing this:
l = lambda a, b : [
x for x in range(a, b+1)
if all(int(digit) % 2 == 0 for digit in str(x))
]
print(l(200, 401))
Cant you just do :
x= 100 # start number
while x <= 400:
odds = ['1','3','5','7','9'] # odds
t = len(str(x)) # how long string is
v = 0 # a variable
for i in list(str(x)): # a for loop
if i not in odds:# checking if its even or not
v += 1 # adds 1 to v
else:
v += 0
if v == t: #if its all even,
print(x, end = ',') #print it out.
x += 1 # move on to next one
#200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,280,282,284,286,288,400,
Related
a = 0
b = 0
for x in range (100):
a = a + 1
if a == 10:
b = b + 1
print(a)
print(b)
The outcome
99
1
What I want
10
90
IIUC, this should do the trick:
a = 0
b = 0
for x in range (100):
if a < 10:
a = a + 1
else:
b = b + 1
But to simplify further, you can use python's assignment operator, a += 1 syntax, which increments the value of a by 1:
a = 0
b = 0
for x in range (100):
if a < 10:
a += 1
else:
b += 1
Add a conditional check.
a = 0
b = 0
for x in range (100):
if (a % 10 != 0 or a==0):
a = a + 1
else:
b = b + 1
print(a)
print(b)
Just for fun:
a, b = 0, 0
for x in range(100):
add = a % 10 != 0 or a == 0
a += add
b += not add
This uses the fact that a bool is an int although I don’t advise it as it’s not too readable
I mean how can I convert from any number system to decimal system with get rid of number systems that are inside that system!
This code is an example of a triple system:
notice that the number 001 is not counted in the second counter because it is a binary system!
This code can convert between small systems but cannot convert systems with more than 100 numbers
I tried to make him do it but I failed.
Who can help me?
def To_decimal(num_str):
dec_num = 0
f = len(num_str)-1
for num in num_str:
dec_num +=int(num)*(3**f)
f-=1
return dec_num
def Find(i,txt):
for v in txt:
if v == i:
return False
return True
def Number_system_of(num):
txt = ""
for i in num:
if Find(i,txt):
txt += i
return len(txt)
t = 0
r=["0","1","2"]
k=[" "," "," "]
x = 0
while x!= 3:
k[0] = r[x]
x+=1
x1 = 0
while x1 != 3:
k[1] = r[x1]
x1+=1
x2 = 0
while x2 != 3:
k[2] = r[x2]
x2+=1
s=""
s = k[0]+k[1]+k[2]
if Number_system_of(s) == 3:
t+=1
print(s,t,To_decimal(s))
out :
000 0 0
001 0 1
002 0 2
010 0 3
011 0 4
012 1 5
020 1 6
021 2 7
022 2 8
100 2 9
101 2 10
102 3 11
110 3 12
111 3 13
112 3 14
120 4 15
121 4 16
122 4 17
200 4 18
201 5 19
202 5 20
210 6 21
211 6 22
212 6 23
220 6 24
221 6 25
222 6 26
this works ! .. but it very slow :<
def Switch(keyl):
key = keyl
L = key[len(key)-1]
R = key[len(key)-2]
key[len(key)-1] = R
key[len(key)-2] = L
return key
def Zero(y,n,f):
keyf = f
for x in range(y,n):
keyf[x]= 0
return keyf
def inkey(ke,r):
for x in ke:
if x == r:
return False
return True
def Getnum(f,li,n):
nl = []
for x in range(0,f):
nl.append(li[x])
i = li[f]
while i != n-1:
i+=1
if inkey(nl,i):
return i
def clear(f,key1,n):
key0 = key1
key0f =[]
for x in range(0,f):
key0f.append(key0[x])
notinkey =[]
for x in range(n):
if inkey(key0f,x):
notinkey.append(x)
key0 = Zero(f,n,key0)
keyl = []
for x in range(len(key0)-len(notinkey)):
keyl.append(key0[x])
for x in notinkey:
keyl.append(x)
return keyl
def plus(kee,f,n,stop):
if kee == stop:
return kee
if f == 0:
kee[0]+=1
kee = clear(1,kee,n)
return kee
if kee[f] == n-1 :
return plus(kee,f-1,n,stop)
k = Getnum(f,kee,n)
if k == None:
return plus(kee,f-1,n,stop)
kee[f]=k
kee = clear(f+1,kee,n)
return kee
def main(n):
key = []
for x in range(n):
key.append(x)
stop = []
for x in range(n-1,-1,-1):
stop.append(x)
o = 1
t = 0
while key != stop :
st = ""
for x in key:
st+=str(x)
print(st,t)
if o == 1 :
key = Switch(key)
if o == 2 :
key = plus(key,n-3,n,stop)
o = 0
t+=1
o+=1
st = ""
for x in stop:
st+=str(x)
print(st,t)
while True:
main(int(input("base ? : ")))
I would like to double the value of every second digit and then add up the digits that are in their tens. Finally adding all the digits together
E.g: 123456789 -> 1 4 3 8 5 12 7 16 9 -> 1 4 3 8 5 3 7 7 9 -> 47
edit: the user would input any number and the function would still work eg: 5153 -> 5 2 5 6 -> 18
-SORRY first post I'm still getting used to this-
So I would like my function to
1. Reverse the inputted number
2. Double the value of the second digit
3. Sum all the digits together
4. Check if it's divisible by 7
Here is my code so far
my testing
def checksum(num):
#print(rev)
odd_digit = ""
even_digit = ""
even_sum = 0
odd_sum = 0
total_sum = 0
if num < 10 and num != 7:
return False
else:
return True
rev = (num[::-1])
for i in range(len(rev)):
if i % 2 == 0:
odd_digit += rev[i]
else:
even_digit += rev[i]
#print(even_digit)
even_digit = int(even_digit)
while even_digit > 0:
even_digit, even_sum = even_digit//10,even_sum+(even_digit%10)
#print(even_sum)
even_sum_2 = even_sum * 2
#print(even_sum_2)
odd_digit = int(odd_digit)
while odd_digit > 0:
odd_digit, odd_sum = odd_digit//10,odd_sum+(odd_digit%10)
#print(odd_sum)
total_sum = even_sum_2 + odd_sum
#print(total_sum)
if total_sum % 7 == 0:
return True
else:
return False
print(checksum(12345678901))
Try using this sum with a map, and a list comprehension:
>>> sum(map(int,''.join([str(int(v)*2) if i%2 else v for i,v in enumerate(s)])))
47
Or use:
>>> sum([sum(map(int,str(int(v)*2))) if i%2 else int(v) for i,v in enumerate(s)])
47
sum([sum(map(int, str(i * 2))) if i % 2 == 0 else i for i in range(1, 10)])
I wrote a program to check the highest number of steps of the collatz conjecture in a range. However, the number I get is incorrect, it appears that the loop ends far too early. Can anyone tell me what is wrong with my code? I checked multiple times over different ranges and each time it is still wrong.
def collatz_sequence(n):
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n = n // 2
elif n % 2 != 0:
n = 3 * n + 1
return sequence
max_len = 1
for i in range(1, 1000):
if len(collatz_sequence(i)) > max_len:
max_len = i
print(max_len)
You are setting max_len to the index of the longest sequence, not its length. You want to keep track of the length of the longest sequence seen so far (and update it for longer sequences as they are seen), rather than its position in the first 1000 sequences. Try:
def collatz_sequence(n):
sequence = []
while n != 1:
sequence.append(n)
if n % 2 == 0:
n = n // 2
elif n % 2 != 0:
n = 3 * n + 1
return sequence
max_len = 1
for i in range(1, 1000):
seq_len = len(collatz_sequence(i))
if seq_len > max_len:
max_len = seq_len
print(i, max_len)
3 7
6 8
7 16
9 19
18 20
25 23
27 111
54 112
73 115
97 118
129 121
171 124
231 127
313 130
327 143
649 144
703 170
871 178
you want to store len(collatz_sequence(i)) in max_len:
max_len = 1
for i in range(1, 1000):
l = len(collatz_sequence(i))
if l > max_len:
max_len = l
print(i, max_len)
Question 3: Amicable
Implement a function amicable that takes a positive integer n. It returns the smallest amicable number greater than n.
Two different numbers are both amicable if the sum of the proper divisors of each is equal to the other. Any number that's part of such a pair is an amicable number.
def abundant(n):
while n > 0:
a = n
k = n
y = 0
total = 0
while k > y or n == 0:
if n % k == 0:
y = n // k
if k != n:
total = total + k + y
if k == y:
total = total - y
k -=1
total = total + 1
print(total)
def abundant2(n):
b = n
x = n
y = 0
total2 = 0
while x > y or n == 0:
if n % x == 0:
y = n // x
if x != n:
total2 = total2 + x + y
if x == y:
total2 = total2 - y
x -=1
total2 = total2 + 1
print(total2)
if total == b and total2 == a:
print('Amicable!')
amicable_numbers2 = int(total2)
amicable_numbers = int(total)
else:
print('Nope')
return abundant2
n += 1
def amicable(n):
"""Return the smallest amicable number greater than positive integer n.
Every amicable number x has a buddy y different from x, such that
the sum of the proper divisors of x equals y, and
the sum of the proper divisors of y equals x.
For example, 220 and 284 are both amicable because
1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
1 + 2 + 4 + 71 + 142 is 220
>>> amicable(5)
220
>>> amicable(220)
284
>>> amicable(284)
1184
>>> r = amicable(5000)
>>> r
5020
"""
nums = [amicable_numbers2, amicable_numbers]
nums2 = [n for n in nums if n >= amicable_numbers2 and n <= amicable_numbers]
return nums2
# return a value that is less than amicable_numbers2 and less than amicable_numbers???