Layer Python Sum of Digits - python

this is my first question around here.
I've been working on an algorithm that adds the numbers entered until I get a single-digit number, but haven't been able to find a solution for about a week.
for example:
value = 1994
Step = 1+9+9+4 = 23
Step = 2+3 = 5

Try this:
def func(x):
while x >= 10:
x = sum([int(c) for c in str(x)])
return x
print(func(1994))

value = 1994
while len(str(value)) != 1:
value = sum([int(i) for i in str(value)])
print(value)
5
What's going on?
initiate value
loop if the length of the integer is not equal to one (meaning it's done)
get a sum of the list of all sub ints inside the int

Related

Sum of integers in string (7kyu) - Issue in the code

def sum_of_integers_in_string(s):
sum = 0
for x in s:
if x.isdigit() == True: #check if its a digit
if isinstance(x, int) == True: #check if its int and sum
sum += int(x)
if isinstance(x, float) == True: #check if its float and sum
sum += float(x)
else:
sum = 0
return sum
I'm trying to solve this kata, however, it do not passes any test from these:
exampleTests = (
("12.4", 16),
("h3ll0w0rld", 3),
("2 + 3 = ", 5),
("Our company made approximately 1 million in gross revenue last quarter.", 1),
("The Great Depression lasted from 1929 to 1939.", 3868),
("Dogs are our best friends.", 0),
("C4t5 are 4m4z1ng.", 18),
("The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", 3635)
)
I think there is any issue in the part of summing an int or float.
Any help?
It's because you are adding the digits not the entire number. For example, in the first test:
Your program is doing this:
1+2+4 = 7
And it should do:
12+4 = 16
Because 12 it's a unique number not 1 and 2.
And float never must be added.
You should try this:
import re
def sum_of_integers_in_string(s):
s = [int(s) for s in re.findall(r'\d+', s)]
return sum(s)
Using regular expressions it's easier. you split the entire string to get only the digits that are together. and then you can add them with sum function that add every element of a list.
You must keep track of whether of not you are inside of a number, as #Xac said, here is something to put you on the right track:
def sum_of_integers_in_string(s):
sum = 0
inside_number = False
this_num = ""
for x in s:
if x.isdigit() == True: #check if its a digit
inside_number = True
this_num += x
else:
pass # complete this function!
return sum

My Function To Count The Largest Binary Gap Doesn't Work But I Can't Figure Out Why

I'm working through the Codility problems and I have gotten the first one almost correct. The task is to write a function which returns the longest binary gap (a sequence of 0s in between 1s) in a binary number. I have gotten all of the test numbers correct apart from 9, which should be 2 (its binary representation is 1001) but which my function returns as 0. I can't seem to figure out why.
My function is as follows:
def Solution(N):
x = bin(N)[2:]
x_string = str(x)
y = (len(x_string))
count = 0
max = 0
for index, item in enumerate(x_string):
if item == "1":
count = 0
elif item == "0" and x_string[index + 1:y-1] != "0"*(y -1 - (index + 1)):
count = count + 1
if count > max:
max = count
print(max)
The complicated indexing and second condition in the elif statement is so that when a 0 is not contained between two 1s then it isn't recognised as the beginning of a binary gap e.g. when the for loop looks at the second character in bin(16) = 10000, it doesn't set count to 1 because all of the remaining characters in the string are also zero.
Simple solution
x_string[index + 1:y-1] != "0"
this bit wants to take a look at the whole string that's left, but the end argument isn't inclusive,it's exluded, so if string length = 4; string[0:4] is the whole string.
source: https://docs.python.org/3/tutorial/introduction.html
-Sam

Formatting unknown output in a table in Python

Help! I'm a Python beginner given the assignment of displaying the Collatz Sequence from a user-inputted integer, and displaying the contents in columns and rows. As you may know, the results could be 10 numbers, 30, or 100. I'm supposed to use '\t'. I've tried many variations, but at best, only get a single column. e.g.
def sequence(number):
if number % 2 == 0:
return number // 2
else:
result = number * 3 + 1
return result
n = int(input('Enter any positive integer to see Collatz Sequence:\n'))
while sequence != 1:
n = sequence(int(n))
print('%s\t' % n)
if n == 1:
print('\nThank you! The number 1 is the end of the Collatz Sequence')
break
Which yields a single vertical column, rather than the results being displayed horizontally. Ideally, I'd like to display 10 results left to right, and then go to another line. Thanks for any ideas!
Something like this maybe:
def get_collatz(n):
return [n // 2, n * 3 + 1][n % 2]
while True:
user_input = input("Enter a positive integer: ")
try:
n = int(user_input)
assert n > 1
except (ValueError, AssertionError):
continue
else:
break
sequence = [n]
while True:
last_item = sequence[-1]
if last_item == 1:
break
sequence.append(get_collatz(last_item))
print(*sequence, sep="\t")
Output:
Enter a positive integer: 12
12 6 3 10 5 16 8 4 2 1
>>>
EDIT Trying to keep it similar to your code:
I would change your sequence function to something like this:
def get_collatz(n):
if n % 2 == 0:
return n // 2
return n * 3 + 1
I called it get_collatz because I think that is more descriptive than sequence, it's still not a great name though - if you wanted to be super explicit maybe get_collatz_at_n or something.
Notice, I took the else branch out entirely, since it's not required. If n % 2 == 0, then we return from the function, so either you return in the body of the if or you return one line below - no else necessary.
For the rest, maybe:
last_number = int(input("Enter a positive integer: "))
while last_number != 1:
print(last_number, end="\t")
last_number = get_collatz(last_number)
In Python, print has an optional keyword parameter named end, which by default is \n. It signifies which character should be printed at the very end of a print-statement. By simply changing it to \t, you can print all elements of the sequence on one line, separated by tabs (since each number in the sequence invokes a separate print-statement).
With this approach, however, you'll have to make sure to print the trailing 1 after the while loop has ended, since the loop will terminate as soon as last_number becomes 1, which means the loop won't have a chance to print it.
Another way of printing the sequence (with separating tabs), would be to store the sequence in a list, and then use str.join to create a string out of the list, where each element is separated by some string or character. Of course this requires that all elements in the list are strings to begin with - in this case I'm using map to convert the integers to strings:
result = "\t".join(map(str, [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]))
print(result)
Output:
12 6 3 10 5 16 8 4 2 1
>>>

Adjust values in a list by normalizing_zybook

1.7 LAB: Adjust values in a list by normalising
When analysing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalising to values between 0 and 1, or throwing away outliers.
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, adjust each integer in the list by subtracting the smallest value from all the integers.
Ex: If the input is:
5
30
50
10
70
65
the output is:
20
40
0
60
55
The 5 indicates that there are five integers in the list, namely 30, 50, 10, 70, and 65. The smallest value in the list is 10, so the program subtracts 10 from all integers in the list.
Anyone can solve this question in python?
This is my code.
arr1 = []
input = int()
for i in range(0,input):
e = int(intput())
arr1.append(e)
k = min(arr1)
for i in range(0,val):
arr1[i] = arr1[i] - k
for i in range(0,val):
print(arr1[i])
Here is the error.
Traceback (most recent call last):
File "main.py", line 8, in <module>
arr1.append(e)
NameError: name 'e' is not defined
You could use list comprehension:
input = [5,30,50,10,70,65]
input = input[1:]
output = [i - min(input) for i in input]
print(output)
[20, 40, 0, 60, 55]
This is the way I solved it
list = []
values = int(input())
for n in range(values):
number = float(input())
list.append(number)
largest = max(list)
for number in list:
number = number / largest
print(f'{number:.2f}')
def get_minimum_int(nums):
low = min(nums)
return low
if __name__ == '__main__':
num = int(input())
nums = []
while num != -1:
nums.append(num)
num = int(input())
l = get_minimum_int(nums)
for n in nums:
print(n - l)
idk if your question ever got answered but I also had the same type of task.
Mine was:
"For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
5
30.0
50.0
10.0
100.0
65.0
the output is:
0.30
0.50
0.10
1.00
0.65
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0."
So this is how I solved mine:
x = int(input())
dislist = []
i = 1
while i <= x:
y = float(input())
dislist.append(y)
i += 1
q = max(dislist)
for item in dislist:
item = item / q
print('{:.2f}'.format(item))
Tell me what you think :)
A few problems I can see with your code.
input = int()`
input in the name of a function that gets an input string from the user. int() simply returns 0. You are assigning the value 0 to a variable named input, making the input function no longer accessible.
for i in range(0,input):
e = int(intput())
Because input is 0, this is an empty range. The loop never runs. Which is good because it would have no idea what intput is.
Because the loop never runs, e is never defined, which is why you get the error you do.
Another style note: arr1 is a list so using a name that suggests it's an array is misleading.
You likely wanted something like the following tweaked version of your code.
n = int(input())
vals = []
for _ in range(0, n):
e = int(input())
vals.append(e)
k = min(vals)
for i in range(0, n):
arr1[i] = -= k
for i in range(0, n):
print(arr1[i])
Gathering the input numbers could be simplified using a list comprehension.
vals = [int(input()) for _ in range(0, n)]
This may be helpful for your lab:
user_int = []
while True:
user_input = int(input())
user_int.append(int(user_input))
if len(user_int) > (int(user_int[0])):
break
user_int.pop(0)
vals = min(user_int)
for user_vals in user_int:
my_vals = user_vals - vals
print(my_vals)

how do I run a defined function multiple times with a for statement so that the return compounds?

I am pretty new at Python and have a defined function for doubling a number. I want to double the number three times using a for statement. This is from lesson 6.3 in Dan Bader's Python Basics. For some reason, this one has me stumped.
Below, I tried adding:
number = number * 2 after my for statement but my result is
20
40
80
def doubles(number):
"""Takes one number as its input and doubles it."""
double = number * 2
return double
number = 5
for x in range(0, 3):
print(doubles(number))
Actual results are:
10
10
10
Expected results are:
10
20
40
def doubles(number):
"""Takes one number as its input and doubles it."""
double = number * 2
return double
number = 5
for x in range(0, 5):
print(doubles(number))
number=doubles(number)
Sounds like you want number (the global one) to retain the result of calling doubles; so do that explicitly:
for x in range(0,3):
number = doubles(number)
print(number)
you need to add the numbers over each other like this.
'number = number + number' in short "number += number"
best,
i hope its easier to see it when you write it like this.
number = 5
for x in range(0, 3):
double = number * 2
print(double)
number += number
you are incrementing x but not change the value of "number" along the way
def doubles(number):
"""Takes one number as its input and doubles it."""
double = number * 2
return double
number = 5
for x in range(0, 3):
print(doubles(number))
number*=2
Here's the solution with minimum coding.
def double(a):
print(a)
for b in range(1,5):
b = a * 2
a = b
print(a)
double(10)

Categories

Resources