How to interpret numbers with leading zero's as decimal? - decimal

all!
I need to interpret numbers given with leading zeros in python as decimal. ( on input there are numbers, not strings!)
Python2 is used, in python3 there are no more such problem.
I haven't ideas how to do this.
Anybody help me please!!!
example:
id = 0101
print id
# will print 65 and I need 101
id = 65
print id
# will print 65 - ok
possible solution:
id = 0101
id = oct(id).lstrip('0')
print id
# will print 101 - ok
id = 65
id = oct(id).lstrip('0')
print id
# will print 101 - wrong, need 65

It is a normal behaviour for Python2. This kind of numbers are specified in the language:
octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+
"0" octdigit+ - numbers that are started with "0" - are octal by design. You can't change this behaviour.
If you want to interpret 077 as 77, the most you can do is some kind of ugly transformations like it:
int(str(oct(077)).lstrip('0'))

Can you cast it to string?
For example:
def func(rawNumber):
id = str(rawNumber)
if id[0] == '0':
res = oct(id).lstrip('0')
else:
res = id
return int(res)
# then use it like this:
print(func(0101)) # will print 101
print(func(65)) # will print 65

Related

Horizotal print of a complex string block

Once again I'm asking for you advice. I'm trying to print a complex string block, it should look like this:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
I wrote the function arrange_printer() for the characters arrangement in the correct format that could be reutilized for printing the list. This is how my code looks by now:
import operator
import sys
def arithmetic_arranger(problems, boolean: bool):
arranged_problems = []
if len(problems) <= 5:
for num in range(len(problems)):
arranged_problems += arrange_printer(problems[num], boolean)
else:
sys.exit("Error: Too many problems")
return print(*arranged_problems, end=' ')
def arrange_printer(oper: str, boolean: bool):
oper = oper.split()
ops = {"+": operator.add, "-": operator.sub}
a = int(oper[0])
b = int(oper[2])
if len(oper[0]) > len(oper[2]):
size = len(oper[0])
elif len(oper[0]) < len(oper[2]):
size = len(oper[2])
else:
size = len(oper[0])
line = '------'
ope = ' %*i\n%s %*i\n%s' % (size,a,oper[1],size,b,'------'[0:size+2])
try:
res = ops[oper[1]](a,b)
except:
sys.exit("Error: Operator must be '+' or '-'.")
if boolean == True:
ope = '%s\n%*i' % (ope,size+2, res)
return ope
arithmetic_arranger(['20 + 300', '1563 - 465 '], True)
#arrange_printer(' 20 + 334 ', True)
Sadly, I'm getting this format:
2 0
+ 3 0 0
- - - - -
3 2 0 1 5 6 3
- 4 6 5
- - - - - -
1 0 9 8
If you try printing the return of arrange_printer() as in the last commented line the format is the desired.
Any suggestion for improving my code or adopt good coding practices are well received, I'm starting to get a feel for programming in Python.
Thank you by your help!
The first problem I see is that you use += to add an item to the arranged_problems list. Strings are iterable. somelist += someiterable iterates over the someiterable, and appends each element to somelist. To append, use somelist.append()
Now once you fix this, it still won't work like you expect it to, because print() works by printing what you give it at the location of the cursor. Once you're on a new line, you can't go back to a previous line, because your cursor is already on the new line. Anything you print after that will go to the new line at the location of the cursor, so you need to arrange multiple problems such that their first lines all print first, then their second lines, and so on. Just fixing append(), you'd get this output:
20
+ 300
-----
320 1563
- 465
------
1098
You get a string with \n denoting the start of the new line from each call to arrange_printer(). You can split this output into lines, and then process each row separately.
For example:
def arithmetic_arranger(problems, boolean:bool):
arranged_problems = []
if len(problems) > 5:
print("Too many problems")
return
for problem in problems:
# Arrange and split into individual lines
lines = arrange_printer(problem, boolean).split('\n')
# Append the list of lines to our main list
arranged_problems.append(lines)
# Now, arranged_problems contains one list for each problem.
# Each list contains individual lines we want to print
# Use zip() to iterate over all the lists inside arranged_problems simultaneously
for problems_lines in zip(*arranged_problems):
# problems_lines is e.g.
# (' 20', ' 1563')
# ('+ 300', '- 465') etc
# Unpack this tuple and print it, separated by spaces.
print(*problems_lines, sep=" ")
Which gives the output:
20 1563
+ 300 - 465
----- ------
320 1098
If you expect each problem to have a different number of lines, then you can use the itertools.zip_longest() function instead of zip()
To collect all my other comments in one place:
return print(...) is pretty useless. print() doesn't return anything. return print(...) will always cause your function to return None.
Instead of iterating over range(len(problems)) and accessing problems[num], just do for problem in problems and then use problem instead of problems[num]
Debugging is an important skill, and the sooner into your programming career you learn it, the better off you will be.
Stepping through your program with a debugger allows you to see how each statement affects your program and is an invaluable debugging tool

Capitalizing each words with chr and ord

First I have to receive a string from the user. The function would be capitalizing the introduced string object. It would make the words start with uppercased characters and all remaining characters have lower case. Here is what I did:
ssplit = s.split()
for z in s.split():
if ord(z[0]) < 65 or ord(z[0])>90:
l=(chr(ord(z[0])-32))
new = l + ssplit[1:]
print(new)
else:
print(s)
I can't see what I am doing wrong.
Using str.title() as suggested by #Pyer is nice. If you need to use chr and ord you should get your variables right - see comments in code:
s = "this is a demo text"
ssplit = s.split()
# I dislike magic numbers, simply get them here:
small_a = ord("a") # 97
small_z = ord("z")
cap_a = ord("A") # 65
delta = small_a - cap_a
for z in ssplit : # use ssplit here - you created it explicitly
if small_a <= ord(z[0]) <= small_z:
l = chr(ord(z[0])-delta)
new = l + z[1:] # need z here - not ssplit[1:]
print(new)
else:
print(s)
Output:
This
Is
A
Demo
Text
There are many python methods that could solve this easily for you. For example, the str.title() will capitalize the start of every word in the given string. If you wanted to ensure that all others were lowercase, you could first do str.lower() and then str.title().
s = 'helLO how ARE YoU'
s.lower()
s.capitalize()
# s = 'Hello How Are You'

printing the same line without repeating

I know that this topic was discussed here in many variations but I didn't find the solution to my problem. for example sample code like this
ages = {}
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45
for key in ages:
if ages[key] >30:
print("names",key, end = " ")
Output is : names Andrew names Karren,
how to do: names Andrew Karren
Your snippet:
for key in ages:
if ages[key] >30:
print("names",key, end = " ")
will print "names <the-name>" for all names such that ages[key] > 30. So, if you have more than one name, "names" will be printed more than once. That's what for loops are for and what they do: they execute code repeatedly.
Therefore, it stands to reason that if you don't want the literal "names" to be printed repeatedly, then you should likely move the code that prints "names" outside of the loop.
ages = {}
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45
print("names", end=" ") # Take this line out of the loop
for key in ages:
if ages[key] > 30:
print(key, end = " ")
Output:
names Andrew Karren

password checker. Something is wrong with where it checks uppercase and lowercase letters

I have this password checker that gives you one point each time you use a captital letter or a lowercase letter. here is the code.
def write_password():
points = 0
askpassword = input("enter in a password. only use the chasricters")
#char = "qwertyuiopasdfghjklzxcvbnmQERTYUIOPASDFGHJKLZXCVBNM"#
#askpassword = "qwe"#testing askpassword
chars = ["qwertyuiop","asdfghjkl",
"zxcvbnm","QWERTYUIOP","ASDFGHJKL","ZXCVBNM",]
#counts consectutive numbers
triples = []
for char in chars:
for i in range(len(char)-2):
triples.append(char[i:i+3])
input_string = askpassword.strip().lower()
for triple in triples:
if triple in input_string:
points += -5
# checks to see wather or not password has more than 8 charicters
for char in askpassword:
if char in askpassword:
if len (askpassword) >= 8:
points += 1
#checks to see if password has a capital letter
for chars in askpassword:
if (askpassword.isupper()):
points = points + 1
# checks to see if password has any lowercase letters
if (askpassword.islower()):
points = points + 1
else:
print("no points")
print("this password is worth",points,"points")
write_password()
each time I put a lowercase in or a upper case in or booth, i get as an output. how many inputs i put in, squared. (e.g. input = As. my output is 4 points)
Is this what you're looking for? Python has a library called "string" with all the lower/upper case letters. You can define your own but why not just use it while it's already there.
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> def checkpassword (passwd):
... points = 0
... if len (passwd) >= 8:
... points += 1
... for char in passwd:
... if char in string.ascii_letters:
... points += 1
...
... print ('Your password has a score of: ', points)
...
>>>
>>> checkpassword('Abdzf')
Your password has a score of: 0
>>> checkpassword('Abdzf2fdadf')
Your password has a score of: 11
>>> len ('Abdzf2fdadf')
11
If you want user's input, you can do it like so:
>>> def checkpassword ():
... points = 0
... passwd = input ('Enter a password: ')
... [...] # Rest of the code goes here
Don't forget! Even though I only have 10 characters excluding the digits, but my score is 11. The extra point was from the length of the password being greater or equal to 8 assuming this is what you wanted.

convert input to string

How to convert numbers to the first letters of the alphabet? . I want to use this code for me. But I need alphabets for 10,11,12,13 etc. for example if the user will enter 10 , the program will print j for 11 -->"k" . How cam I do this.
My code is same in the link above
You can use this BASH function:
cnvt() { printf "\x$(printf '%x' $((97 + $1 -1)))\n"; }
Test it:
cnvt 10
j
cnvt 11
k
cnvt 26
z
You can use ASCII table for this.
If user inputs 10 you can add 87 and get "a" = 97.
This way input 11 will get a value of "b" = 98.

Resources