python - adding each digit that is greater than 4 - python

Given an integer. for each individual digit that is greater than 4, i need to add it to all the next digits that greater than 4.
For example: a = 4567; the result should be 0 + (5) + (5+6) + (5+6+7) = 34
So far in my code, I was able to get the sum for single digit only. If the integer is greater 10, it will only give the sum of the very first digit. Any idea why this happening?
def morethanfour(number):
num = 0
num = [int(d) for d in str(number)] #seperate into individual digit
total = 0
for i in range (len(num)):
if num[i] > 4:
total = sum(x for x in range(5, num[i]+1)) #adding the sum
return total
num = 9
print(morethanfour(num))
the result when num = 9 is 35 (5+6+7+8+9)
However, when num = 178, it gave me 0

Try this:
>>> def morethanfour(number):
return sum(sum(range(5,x+1)) for x in map(int,str(number)) if x>4)
>>> morethanfour(9)
35
>>> morethanfour(4567)
34
>>> morethanfour(178)
44

>>> sum(sum(num[j] for j in range(0, i+1) if num[j] > 4) for i in range(len(num)))
34

Related

Compacting Number values into shorter string

I have 1296 random values ranging 0-31. I want to represent this information so let’s say I just concatenate all 1296 values into a string. If I were to do that the string would be about 2500 characters long. How can I store this information in a shorter string so I can still know all 1296 values in the correct order but not have such a long string? (I managed to get it to 648, but wanted to see if someone has an even better way)
This will work when the range of numbers in the input list are 0-31 (inclusive) and when the list length is a multiple of 3
import random
numbers = [random.randint(0, 31) for _ in range(1296)]
def pack(n):
result = []
for i in range(0, len(n), 3):
result.append(n[i] << 10 | n[i+1] << 5 | n[i+2])
return ''.join(map(chr, result))
def unpack(s):
result = []
for o in map(ord, s):
for shift in 10, 5, 0:
result.append(o >> shift & 0x1F)
return result
packed = pack(numbers)
print(len(packed))
result = unpack(packed)
assert result == numbers
Output:
432
Note:
If the range of numbers was 1-31 then this technique (with a minor modification) could be used for any list length because zero could be used as a padding indicator as follows:
import random
numbers = [random.randint(1, 31) for _ in range(1295)]
def pack(n):
result = []
a = None
for i, x in enumerate(n):
match i % 3:
case 0:
a = x << 10
case 1:
a |= x << 5
case _:
result.append(a|x)
a = None
if a is not None:
result.append(a)
return ''.join(map(chr, result))
def unpack(s):
result = []
for o in map(ord, s):
for shift in 10, 5, 0:
if (n := o >> shift & 0x1F) == 0:
break
result.append(n)
return result
packed = pack(numbers)
print(len(packed))
result = unpack(packed)
assert result == numbers
You can easily store 32 unique values in one character, which means your 1296 numbers can fit in a string of 1296 characters.
For example:
import random
numbers = [random.randint(0, 31) for i in range(1296)]
def numbers_to_string(numbers):
return "".join(chr(ord("0") + number) for number in numbers)
def numbers_from_string(string):
return [ord(char) - ord("0") for char in string]
numbers_str = numbers_to_string(numbers)
numbers_roundtrip = numbers_from_string(numbers_str)
print(numbers_roundtrip == numbers)
Output:
True
These are the numbers and the characters used to represent them:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 :
11 ;
12 <
13 =
14 >
15 ?
16 #
17 A
18 B
19 C
20 D
21 E
22 F
23 G
24 H
25 I
26 J
27 K
28 L
29 M
30 N
31 O

Finding the n-th number that consists of only 2 or 3

I am really struggling with this program. I would appreciate any kind of help.
For a natural number we say that it is strange if it is completely composed of digits 2 and 3. The user enters a natural number. The program prints the n-th strange number.
Numbers that are considered strange are 2, 3, 22, 23, 33...
n = int(input())
current_number = 1
counter_strange = 0
counter = 0
while counter_strange < n:
x = current_number
while x < n:
k = x % 10
if k != 2 or k != 3:
counter += 1
else:
break
if counter >= 1:
counter_strange += 1
current_number += 1
print(current_number-1)
Strange numbers come in blocks. A block of 2 1-digit numbers, followed by a block of 4 2-digit numbers, then 8 3-digit numbers. You can do the math and determine which block of k-digit numbers a given index n is, and how far into that block it lies. Convert that distance into a base-2 number, zero-filled to k digits, then replace 0 by 2 and 1 by 3. Convert the result back to an int:
from math import log2, ceil
def strange(n):
"""returns the nth strange number"""
#first determine number of digits:
k = ceil(log2(n+2)) - 1
#determine how far is in the block of strange k-digit numbers
d = n - (2**k - 1)
#convert to base 2, zfilling to k digits:
s = bin(d)[2:].zfill(k)
#swap 2,3 for 0,1:
s = s.replace('0','2').replace('1','3')
#finally:
return int(s)
for n in range(1,10): print(n,strange(n))
Output:
1 2
2 3
3 22
4 23
5 32
6 33
7 222
8 223
9 232
You can use a while loop with itertools.product in a generator function. Using a generator will allow you to create a stream from which you can access strange numbers on the fly:
import itertools
def strange():
c = 0
while True:
yield from map(''.join, itertools.product(*([['2', '3']]*(c:=c+1))))
s = strange()
for _ in range(10):
print(int(next(s)))
Output:
2
3
22
23
32
33
222
223
232
233

The sum of the digits is incorrect. Why?

i can't understand why the output of my code concatnates the digits instead of showing their sum:
#Get a number, and show the number of digits and the sum of the digits.
num = int(input('Enter a number: '))
j = 0
i = 1
k = 0
while i < num:
i = i*10
j += 1
k += (num - k)%i
print (f' The number has {j} digit(s), and the sum is: {k}')
Follow the code. Let's say num = 432:
i = 1 * 10 = 10
j = 0 + 1 = 1
k = 0 + (432 - 0)%10 = 2
---
i = 10 * 10 = 100
j = 1 + 1 = 2
k = 2 + (432 - 2)%100 = 2 + 32 = 34
---
i = 100 * 10 = 1000
j = 2 + 1 = 3
k = 34 + (432 - 34)%1000 = 34 + 398 = 432
This algorithm is most definitely not adding every digit. There are several ways to do what you intend in python. One way is inputting the number as a string and summing every digit casting them as integers inside a generator:
num = input('Enter a number: ')
total = sum(int(digit) for digit in num)
print(total)
If you want the number to be an integer since the beginning, you can also do this:
num = int(input('Enter a number: '))
total = 0
while num > 0:
digit = num%10
total += digit
num /= 10 # num //= 10 in python 3
print(total)

how does result = k + tri_recursion(k-1) give me an output of triangular numbers?

I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion

Python While loop to calculate smallest common multiple

This is meant to calculate the smallest common multiple of 1-20.
I can't seem to figure out why the while loop won't end. Can anyone help me out?
i = 1
j = 1
factors = 0
allfactor = False
while allfactor == False:
while j < 21:
if i % j == 0:
factors = factors + 1
j = j + 1
else:
break
if factors == 20:
allfactor = True
break
else:
i = i + 1
j = 1
factors = 0
The least common multiple of the numbers 1..20 is 232792560.
To get to that number you just need to look at the numbers 1 to 20. You need at least all prime numbers: 2, 3, 5, 7, 11, 13, 17 and 19.
In addition, you need another 2 to calculate 4, and two more 2s for 16. To get a 9 you also need another 3.
So you end up with:
2 * 2 * 2 * 2 * 3 * 3 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560
And you can easily confirm that using Python:
>>> all(map(lambda x: 232792560 % x == 0, range(1, 21)))
True
I.e. all numbers are divisors of said number; and per the proof above (its construction) there is no smaller number.

Categories

Resources