Printing integers tiled horizontally - Python3 - python-3.x

I'm trying to obtain the following: i want to print a range of integers, but if the integer contains more than 10 digits, the '1' in '10' needs to be printed on top.
e.g.:
6 - > 123456
13 - >...................1111
..........1234567890123
Remark, that if it contains less then 10 digits, there's no 'upper line' printed. And the '.' should be replaced just by spaces, but the editor won't let me do that
I've tried the following:
line10 = ''
line1 = ''
if length > 10:
for i in range(length):
if (i + 1) // 10 == 0:
line10 += ' '
else:
line10 += str((i + 1) // 10)
for i in range(length):
line1 += str((i + 1) % 10)
if length > 10:
print(line10)
print(line1)
And: this works, but how can you make it work for let's say 100 or 1000, without having to copy the lines of code?
Thanks in advance.

There may be a more elegant solution to your problem, but I believe this does what you require:
def number_printer(n):
lines = [[] for m in range(len(str(n)))]
for i in range(1, n+1):
diff = len(str(n))-len(str(i))
if diff > 0:
for z in range(diff):
lines[z].append(" ")
for x, y in enumerate(str(i)):
lines[x+diff].append(y)
else:
for x, y in enumerate(str(i)):
lines[x].append(y)
for line in lines:
print "".join(line)
if __name__ == "__main__":
number_printer(132)
Essentially, it is checking the length of each number it counts through against the lenght of the number you wish to print (in this example 132). Wherever it finds a difference (where diff > 0), it appends the appropriate number of blank spaces so all the numbers align (e.g. for the number 12 it would append 1 blank space, as the difference in length between 12 and 132 is 1).
Hopefully this is what you were after!

Related

Why isn't chr() outputting the correct character?

I'm working on a Caesar Cypher with Python 3 where s is the string input and k is the amount that you shift the letter. I'm currently just trying to work through getting a letter like 'z' to wrap around to equal 'B'(I know the case is wrong, I'll fix it later). However when I run caesarCipher using the the following inputs: s = 'z' and k = 2, the line: s[n] = chr((122-ord(s[n]) + 64 + k)) causes s[n] to equal 'D'. If i adjust it down two(logically on the unicode scale this would equal 'B'), it makes s[n] = #. What am I doing wrong on that line that's causing 'B' not to be the output?
def caesarCipher(s, k):
# Write your code here
n = 0
s = list(s)
while n < len(s):
if s[n].isalpha() == True:
if (ord(s[n].lower())+k) < 123:
s[n] = (chr(ord(s[n])+k))
n += 1
else:
s[n] = chr((122-ord(s[n]) + 64 + k))
else:
n += 1
s = ''.join(s)
return s
You forgot to add 1 to n in the test of (ord(s[n].lower())+k) < 123 so that it would count s[n] twice or more.
Change it to
else:
s[n] = chr((122 - ord(s[n]) + 64 + k))
n += 1
and if you input "z" and 2, you'll get "B"
print(caesarCipher("z", 2))
# B
and if you adjust it down two, you'll get "#", which is the previous previous character of B in ASCII.
...
else:
s[n] = chr((122 - ord(s[n]) + 62 + k))
n += 1
...
print(caesarCipher("z", 2))
# #

Multiplying all the digits of a number in python

If i have a number 101, i want to multiply all the digits of the number (1*0*1) but this result will become Zero. Instead how to split the number into 10 and 1 and multiply(10*1).
Similar examples,
3003033 -> 300*30*3*3 or
2020049 -> 20*200*4*9
You could use a negative look behind to check its not the start of the list and a positive look ahead for nums that are not 0 as your split point.
REGEX: Essentially this says split where the next num is not a 0 and it not the start of the line
/
(?<!^)(?=[^0])
/
gm
Negative Lookbehind (?<!^)
Assert that the Regex below does not match
^ asserts position at start of a line
Positive Lookahead (?=[^0])
Assert that the Regex below matches
Match a single character not present in the list below [^0]
0 matches the character 0 literally (case sensitive)
CODE
import re
from functools import reduce
def sum_split_nums(num):
nums = re.split(r'(?<!^)(?=[^0])', str(num))
total = reduce((lambda x, y: int(x) * int(y)), nums)
return " * ".join(nums), total
nums = [3003033, 2020049, 101, 4040]
for num in nums:
expression, total = sum_split_nums(num)
print(f"{expression} = {total}")
OUTPUT
300 * 30 * 3 * 3 = 81000
20 * 200 * 4 * 9 = 144000
10 * 1 = 10
40 * 40 = 1600
Let a and b be two integer numbers. Let c be a new number made by putting n zeros in the right side of b. Then multiplying a and c is equal to multiplying a and b and 10^n.
Now you can simplify what you want to do to the following: Multiply digits of your number to each other with the agreement that instead of 0, you will put 10. So actually you don't need to split your number.
Here I defined two functions. In both of them the idea is to convert your number to a string, run a for-loop on its digits and by an if condition in the case
1) multiply the previous result to the new digit if it is not 0, otherwise multiply to 10.
def multio1(x):
s = str(x)
ans = 1
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
ans *= 10
return(ans)
2) multiply the previous result to the new digit if it is not 0, otherwise add one unit to the number of zeros. Then at the end put as many as number of zeros, zeros at the right side of your final result.
def multio2(x):
s = str(x)
ans = 1
number_of_zeros = 0
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
number_of_zeros += 1
if number_of_zeros != 0:
ans = str(ans)
for i in range(number_of_zeros):
ans += '0'
ans = int(ans)
return(ans)
Now the multio1(x) and multio2(x) for x=101,3003033,2020049, both gives equal results shown in below.
10,81000,144000
That's kind of odd, but this code will work:
a = '3003033'
num = ''
last_itr = 0
tot=1
for i in range(len(a)-1):
if a[i]=='0' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[last_itr:i+1])
last_itr=i+1
elif a[i]>'0' and a[i]<='9' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[i])
last_itr=i+1
tot*=int(a[last_itr:len(a)])
print(tot)
Just put your number at a

input error in Python3.6

t = int(input())
while t:
qu , pt = input().split(' ')
qu = int(qu)
pt = int(pt)
sd = []
for i in range(0,qu):
x = int(input()) # I think I am getting problem in this part of
sd.append(x)
hd , cw = 0 , 0
diff = pt / 10
cwk = pt / 2
for i in range(0,qu):
if sd[i] <= diff:
hd += 1
else:
if sd[i] >= cwk:
cw += 1
if hd == 2 and cw == 1:
print ('yes')
else:
print('no')
t -= 1
When I try to give input like '1 2 3' I get an an error like this
Traceback (most recent call last):
File "C:/Users/Matrix/Desktop/test.py", line 8, in <module>
x = int(input())
ValueError: invalid literal for int() with base 10: '1 2 3'
Why am I seeing this problem ? How do I rectify this ?
The issue is that you're passing it a string rather than an integer. When you typed "1 2 3," you left spaces, which are considered characters. Spaces cannot be cast as integers. If your set on having the input as number space number space number space, then I suggest you split the sentence at the whitespace into a list.
def setence_splitter(user_input):
# splits the input
words = text.split()
Now you have the list, words, which will have each individual number. You can call each individual number using its index in words. The first number will be words[0] and so on.

Slicing strings and adding the integers, Loop trouble

My assignment is to chop apart sequences of numbers with dashes and add each piece together (ex: 1-1-1 = 3, 2-2 = 4). I don't know why my loop terminates after the first run through though. The output right now is
3
456
456
56-234
0
456
Here is the function:
def SSN(str):
total = 0
y = -1
dash = 0
while dash >= 0:
dash = str.find("-")
print(dash)
if dash > -1:
section = str[0:dash]
str = str[dash+1:]
section = int(section)
print(section)
total += section
print(total)
print(str)
else:
total = str
y+=1
print(y)
return total
print(SSN("456-56-234"))

Could someone please go through this code line by line and explain it in Pseudocode or English

while True:
try:
number = input('Enter') #Asks user to input 7 digit number
if len(str(number)) != 7:
print('Incorrect')
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
for index, digit in enumerate(list(str(number))):
total = total + int(digit)*multiplier[index%2]
times = times+str(int(digit)*multiplier[index%2])+', '
mof10 = total + (10 - total%10)
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print (times[:-1])
print(total)
print(mof10)
print(checkdigit)
print(final)
break
except ValueError:
print('Not a number')
My task is to 'Calculate the GTIN-8 product code from a seven digit number'
I need a line by line explanation of the code above, please.
Some info on enumerate by typing help(enumerate)
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list:
The % operator returns the remainder of x / y eg
10 / 5 = 2 r 0 | 10 % 5 = 0
7 / 2 = 3 r 1 | 7 % 2 = 1
Here is the code explained with comments
while True: # Loop will continue until break is called
try:
number = input('Enter') #Asks user to input 7 digit number
# Checks if the length of the input
# If not 7 characters long
# Will then ask for input again due to while loop
if len(str(number)) != 7:
print('Incorrect')
# If is 7 chacters long
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
# example input for number '1234567'
# list(str(number))
# '1234567' -> ['1', '2', '3', '4', '5', '6', '7']
for index, digit in enumerate(list(str(number))):
# index%2 returns either 0 or 1
# this is used to get 3 or 1 from multiplier
# depending on if the index is odd or even
# for first index and digit from example
# index = 0, digit = '1'
# total = total + 1 * 3
total = total + int(digit)*multiplier[index%2]
# adds the multiplier value from digit * multiplier[index%2]
# to times as a string. First value is
# times = times + str(1 * 3) which is 3
times = times+str(int(digit)*multiplier[index%2])+', '
# essentially rounds up to nearest 10
mof10 = total + (10 - total%10)
# gets the number it was rounded up by
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print(times[:-1]) # slice the string to return everything except the last value
print(total)
print(mof10)
print(checkdigit)
print(final)
break # exit while loop
# If the convertion from string to int returns an error
# meaning a non-number was entered into input eg. !##$
# print the following, while loop will continue and prompt again
except ValueError:
print('Not a number')

Resources