Digit of Life in Python - python

I'm trying to create a method that will return a digit of life when receiving input of a date of birth in the following format: YYYYMMDD. The requirements are as follows (see image below):
I have tried the following:
def split(word):
return [char for char in word]
date = input("Enter your date of birth in YYYYMMDD format: > ")
sum_list = []
def digitOfLife(date):
sum = 0
if(len(date) > 8):
print("Input data too long")
return
else:
date_list = []
for char in date:
date_list.append(int(char))
while len(date_list) >= 1:
print(len(date_list))
for num in date_list:
if sum > 9:
sum = 0
sum+=num
date_list.pop()
return sum
print(digitOfLife(date))
However, I am not getting the result that is supposed to be produced with this algorithm. I know it has something to do with my logic which adds the digits of the list after it's been popped, but I'm not sure what it is.
Any insight would be greatly appreciated.

It looks like you would only need to perform modulo 10 on cumulative additions:
def dol(N): return N if N < 10 else dol(N//10+N%10)
date = "19991229"
dol(int(date)) # 6

while len(date_list) >= 1:
print(len(date_list))
# check if it's over 9
if sum > 9:
sum =0
num = date_list.pop()
sum += num
Check the above code maybe this would help you. And also check the documentation of pop() function from here
Pop function removes the last element from the list and returns it. Like this :
L = [1, 2, 3]
x = L.pop()
print(x) # this will return 3
***This afterwards occured me that you can also add them straightforward and apply modulo by ten.

A .pop() inside loop may cause a problem because size of the list is changing during the iterations.
Besides .pop() removes the last element.
I would suggest the following solution:
def digitOfLife(date):
sum_ = 0
if (len(date) > 8):
print("Input data too long")
return
else:
date_list = []
for char in date:
date_list.append(int(char))
sum_ = sum(date_list) # calculate the sum of list of digits
while len(str(sum_)) > 1: # repeat while the sum has more than 1 digit
sum_ = sum(date_list)
date_list = [int(x) for x in str(sum_)]
return sum_
Also "sum" is a reserved word, so I renamed variable to sum_

Starting from your piece of code:
you should use a for loop istead of the while loop with pop .. this will make things easier.
then when sum > 9, you should not reset the sum to 0, but add the digits together.
This gives you the following piece of code:
def split(word):
return [char for char in word]
date = input("Enter your date of birth in YYYYMMDD format: > ")
sum_list = []
def digitOfLife(date):
sum = 0
if(len(date) > 8):
print("Input data too long")
return
else:
date_list = []
for char in date:
date_list.append(int(char))
for num in date_list:
sum+=num
if sum > 9:
sum = sum%10 +sum//10
return sum
print(digitOfLife(date))
This will output what you expect:
Enter your date of birth in YYYYMMDD format: > 19991229
6
Other improvements are still possible, but this shows you the easier change to make in your code.

Short way for digit of life:
def digitoflife(date):
if len(date) > 8:
print("date inputed is long")
else:
num = num2 = 0
for digit in date:
num += int(digit)
for i in str(num):
num2 += int(i)
return num2
date = str(input('Enter the date: '))
print("The digit of life is: ",digitoflife(date))

Code:
def bd_digit(string):
total = 0
for digit in string:
total+=int(digit)
if total >=10:
return bd_digit(str(total))
else:
return total
print(bd_digit('19991229'))
This may help you with recursion

I did the same exercise today like this.
date = '19991229'
list1=[]
for i in date:
list1.append(int(i))
date2 = str(sum(list1))
list2 = []
for i in date2:
list2.append(int(i))
total = sum(list2)
print(total)

def digitsoflife(number):
sum_ = [i for i in str(number)]
sum_ = sum(list(map(int, sum_)))
sum_total = 0
while len(str(sum_)) > 1:
for i in str(sum_):
sum_total += int(i)
sum_ = sum_total
print(sum_total)
break
else:
print(sum_)

Related

Printing largest number from a given input

I created a code to print the largest number from a given input(string) but it is only valid for inputs containing distinct digits and gives an error 'string index out of range' when the input consists of repetitive digits. Why so?
Note: "The concept of list cannot be used"
My code is as follows:
def largest_num(num):
nums = ""
length = len(num)
while length:
max_num = num[0]
for i in num:
if i > max_num:
max_num = i
num = num.replace(max_num,"")
nums = nums + max_num
length-=1
return nums
x = input("Entered number: ")
a = largest_num(x)
print(a)
Output:
Output of above code
#Husnian Mehdi - the original code has error in the line - "num.replace(max_num, ""). You could put print statement after that to see what's happening when you input a number with duplicated digits: such as '454'. I also change some variable names to make it more descriptive. [Hint: that num.replace() statement has removed both duplicated digits....!]
def largest_num(num):
ans = ""
size = len(num)
while size:
max_digit = num[0]
for n in num[1:]:
if n > max_digit:
max_digit = n
ans = ans + max_digit
num = num.replace(max_digit, "")
print(f' num is: {num} now ...')
size -=1
print(f' len: {size}')
return ans
x = input("Entered number: ")
It's more straightforward to take the advantage of the fact that the input is a string, and string can be sorted easily. Please try the code next:
from functools import cmp_to_key
def largestNum(num):
num = [str(n) for n in num]
num.sort(key=cmp_to_key(lambda b, a: ((a+b)>(b+a))-((a+b)<(b+a)) ))
return ''.join(num).lstrip('0') or '0'
x = input("Entered number: ")
#a = largest_num(x)
print(largestNum(x))
Demo:
>>>Entered number: 321895
985321
>>>Entered number: 10957
97510
>>>Entered number: 4576889
9887654
>>>
Or simply do the sorting directly (you can convert this to function):
1. num = list(num). # num is string input of number
2. num = num.sort(reverse=True)
3. largest = int(‘’.join(num)) # answer

Counting the most amount of zeros in a row in a number | Python

I want to create a function that asks for a number and then sees the most amount of zeros in a row and returns its value (ex: 5400687000360045 -> 3 | 03500400004605605600 -> 4).
So far this is all I got but it isn't working:
def zeros():
num = input('Write a number: ')
row = 0
result = 0
for i in num:
if i == '0':
while i == '0':
row += 1
if row > result:
result = row
return result
What's wrong?
EDIT:
This is what the desired output should be:
zeros()
Write a number: 03500400004605605600
4
My current output is nothing, meaning it's not returning anything
This should do it.
def zeros():
num = input('Write a number: ')
row = 0
count = 0
for i in num:
if i == '0':
count += 1
else:
row = max(row, count)
count = 0
row = max(row, count)
return row
Your code is getting stuck in an infinite loop in inner while
To do it your way, you just need to keep track of whether the number is a 0 or not (i.e. to know if it is a row of zeros or if you need to restart the count). Something like this would work:
def zeros():
num = input('Write a number: ')
row = 0
result = 0
for i in num:
if i != '0':
row = 0
else:
row += 1
if row > result:
result = row
return result
Output is as you would expect.
If you know regex, you could achieve this with much less code using:
import re
def zeros():
num = input('Write a number: ')
result = max(map(len, re.findall(r'0+', num)))
return result
Is this helpful to you..? regex (Regular expression operations) is a very handy tool which could make your life easier. Please have look at Regular expression operations
import re
def zeros():
num = input('Write a number: ')
return max(re.findall("(0+0)*", (num)))
output : 000
def zeros():
num = input('Write a number: ')
return len(max(re.findall("(0+0)*", (num))))
output : 3
I think this might work
num = input()
countOfZeros = 0
for i in range(len(num)-1):
curr = 0
if num[i] == num[i+1]:
curr = 0
if curr > countOfZeros:
countOfZeros = curr
else:
countOfZeros += 1
print(countOfZeros - 1 )

Largest Adjacent Numbers- Values Incrementing Incorrectly

I am writing this program to find the 13 adjacent digits in this number that, when added together, have the largest sum. When I run it, however, the b value does not start at 12; it starts at some obscenely high number and I cannot figure out why. Any idea why my a and b values are not incrementing correctly?
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
a = 0
b = 12
greatest = 0
while b != len(str(num)):
num = str(num)
newNum = num[a:b]
total = 0
for num in newNum:
num = int(num)
total += num
if total > greatest:
greatest = total
a+=1
b+=1
print(b)
print(greatest)
The main issue is that you are reusing num in the inner loop, which renders the "original" num wrong after the first run.
Additionally, if you want a 13 digits run-in, you'd better start with b = 13
And furthermore, there is no need for str(num) since it is already a string, and no need to change b along the program. You can also replace the inner loop with a sum upon map.
Here is what it should look like after these changes:
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
index = 0
run_in = 13
greatest = 0
while index + run_in < len(num):
num_slice = num[index: index + run_in]
slice_sum = sum(map(int, num_slice))
if slice_sum > greatest:
greatest = slice_sum
index += 1
print(greatest)
If you are into super functions, you can create the same effect with a list comprehension and a max closure, iterating all possible indexes (until the length of the number minus the run in):
greatest = max(sum(map(int, num[index: index + run_in])) for index in range(len(num) - run_in))
def largest(num, k):
num = str(num)
if len(num) < k: raise ValueError("Need a number with at least {} digits".format(k))
currsum = sum(int(i) for i in num[:k])
answer = currsum, 0
i = k+1
while i < len(num):
currsum -= int(num[i-k])
currsum += int(num[i])
if currsum > answer[0]: answer = currsum, i
i += 1
return answer
total, ind = largest(myNum, 13)
print("The maximum sum of digits is {}, starting at index {}".format(total, ind))

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Beginners python program

Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1

Categories

Resources