How to convert alphabetical input to numbers and add them together - python

i'm trying to convert user input into only alphabets, and convert each alphabet into a number(ex. a=1, b=2), then the numbers together. I've been able to complete the first part, but not sure how to do the second part.
import re
name = input("Name: ")
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
for al in range(len(cleaned_name)):
print(numbers,sep='+')
#if input is jay1joe2, cleaned name will be jayjoe
#after the 'numerology', will print the following below
#10+1+25+10+15+5 = 66

Something like this should work for what you're trying to do.
Note: I'm hardcoding the name here rather than using the user input, so it's easier to test it out if needed.
import string
# name = input("Name: ")
name = 'jay1joe2'
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {char: i for i, char in enumerate(string.ascii_lowercase, start=1)}
result = list(map(numbers.get, cleaned_name))
print(*result, sep='+', end=' ')
print('=', sum(result))
Where the second part (after numbers) could also be written alternatively as follows, using f-strings in 3.6+:
result = [numbers[c] for c in cleaned_name]
print(f"{'+'.join(map(str, result))} = {sum(result)}")
Result:
Your 'cleaned up' name is: jayjoe
10+1+25+10+15+5 = 66

name = input("Name: ")
name = name.lower()
name1 = list(name)
Addition: int = 0
for k in name1:
if ord(k)-96 < 1 or ord(k)-96 > 26:
pass
else:
Addition = Addition + ord(k) - 96
print(Addition)
We can use ascii codes for Numbers and Characters :)

Related

How to ask the user of a program for a random objects corresponding value in a list?

I have a list which looks like this: [1 H 1.0079, 2 He 4.0026, 3 Li 6.941, 4 Be 9.01218, ...]
I want to ask the user of the program for the corresponding atomic number to the atom. So the program will take a random atomic symbol and ask the user what's the atoms atomic number.
Code so far:
class Atom:
def __init__(self, number, weight, atom):
self.number = nummer
self.atom = atom
self.weight = weight
def __str__(self):
return self.atom + " " + str(self.weight)
def __repr__(self):
return str(self.number) + " " + self.atom + " " + str(self.weight)
def atom_listan():
atom_file = open('atomer2.txt', 'r')
atom_lista = []
number = 1
for line in atom_fil:
data = line
weight = float(data.split()[1])
atom = data.split()[0]
new_atom1 = Atom(number, weight, atom)
atom_lista.append(new_atom1)
atom_lista.sort(key=lambda x: x.vikt)
atom_lista[17], atom_lista[18] = atom_lista[18], atom_lista[17]
atom_lista[26], atom_lista[27] = atom_lista[27], atom_lista[26]
atom_lista[51], atom_lista[52] = atom_lista[52], atom_lista[51]
atom_lista[89], atom_lista[90] = atom_lista[90], atom_lista[89]
atom_lista[91], atom_lista[92] = atom_lista[92], atom_lista[91]
atom_fil.close()
for i in range(len(atom_lista)):
atom_lista[i].number = i + 1
return atom_lista
Code so far where I create a list consisting of the elements information. I have tried using the random.choice module but I don't really know how to get only the atomic symbol from the list with random.choice and also have the corresponding atomic number to the random atom be the correct answer.
You can get the atomic symbol like this if you have the list of elements as you mentioned in the question.
import random
a=["1 H 1.0079", "2 He 4.0026", "3 Li 6.941", "4 Be 9.01218"]
random_choice = random.choice(a)
random_atom = random_choice.split(" ")[1]
print(random_atom)
Try this. Clearly you could put it into a loop. I just used a part of your List.
import random
elements = ['1 H 1.0079', '2 He 4.0026', '3 Li 6.941', '4 Be 9.01218']
choose = random.choice(elements)
splitted = choose.split(' ')
print('The element symbol is : ', splitted[1])
attempt = input('Enter the Atomic Number ')
if (attempt == splitted[0]):
print('Correct')
else:
print('Wrong')

Saving the output of a list to a file

I came across a project geared toward starters like myself - creating a CLI passwordcreator.
I have with the help of a few guides completed the generator and added a few of my own features, however there is one feature I can't seem to figure out how to implement; saving the output to a file.
In the terminal the passwords shows up perfectly fine line by line, however if I try to save the output to a file it only saves the last password, and it seperates each letter by line.
My code is below, together with examples of output from both the terminal and a .txt file.
import string
import random
from os import system, name
letters = list(string.ascii_letters)
digits = list(string.digits)
special_characters = list("!##$%^&*()£")
characters = list(string.ascii_letters + string.digits + '!##$%^&*()£')
def clear():
if name == 'nt':
_ = system('CLS')
else:
_ = system('clear')
def generate_random_password():
clear()
length = int(input("Enter password length: "))
amount = int(input('Enter amount of passwords: '))
letters_count = int(input("Enter letter count: "))
digits_count = int(input("Enter digits count: "))
special_characters_count = int(input("Enter special characters count: "))
character_count = letters_count + digits_count + special_characters_count
if character_count > length -1:
print("Characters total count is greater than desired password length")
exit()
clear()
password = []
print("Following passwords saved to Passwords.txt, please move the file before generating new passords, as a new generation will overwrite existing")
print('\n')
for pwd in range(amount):
password = []
for c in range(digits_count):
password.append(random.choice(digits))
for c in range(letters_count):
password.append(random.choice(letters))
for c in range(special_characters_count):
password.append(random.choice(special_characters))
if character_count < length:
random.shuffle(characters)
for c in range(length - character_count):
password.append(random.choice(characters))
random.shuffle(password)
if str(password) < str(length):
return()
else:
print("".join(password))
with open('Passowrds.txt', 'w') as file:
for line in ("".join(password)):
file.write(line)
file.write('\n')
#file = open('Passwords.txt', 'w')
#str1 = repr(password)
#file.write('\n' + str1 + '\n')
#file.close
#f = open('Passwords.txt', 'r')
#if f .mode == 'r':
# contents=f.read
generate_random_password()
This is what the output from the terminal looks like:
Following passwords saved to Passwords.txt, please move the file
before generating new passords, as a new generation will overwrite
existing
gtBVA3QDcUohDc£TfX(zVt*24
KD8PnMD£)25hvHh#3xj79$qZI
Dx^*2£srcLvRx5g3B3(nq0H&9
&r6^3MEsaV1RuDHzxq*(h3nO)
However what is saved in the .txt file looks like this:
&
r
6
^
3
M
E
s
a
V
1
R
u
D
H
z
x
q
*
(
h
3
n
O
)
The reason why your script is saving only 1 password is because you are opening the file to be written (which clears the contents of the file) for every password you are generating.
You want to do something along the lines of:
passwords = []
for _ in range(num_passwords):
password = ...
passwords.append(password)
with open("password.txt", "w") as f:
f.writelines(passwords)
Although there is nothing terrible about the way you're using the random library, I recommend taking a look at random.sample (without replacement) or random.choices (with replacement).
Also, using shuffling your characters list isn't adding additional randomness to your random.choice.
You don't have to convert the strings to lists in order to run choice:
>>> import random
>>> random.choice("abc")
'b'
A fuller example:
def generate_random_password():
clear()
length = int(input("Enter password length: "))
amount = int(input("Enter amount of passwords: "))
letters_count = int(input("Enter letter count: "))
digits_count = int(input("Enter digits count: "))
special_characters_count = int(input("Enter special characters count: "))
character_count = letters_count + digits_count + special_characters_count
if character_count > length - 1:
print("Characters total count is greater than desired password length")
exit()
clear()
passwords = []
for _ in range(amount):
chosen_digits = random.choices(digits, k=digits_count)
chosen_letters = random.choices(letters, k=letters_count)
chosen_special_characters = random.choices(
special_characters, k=special_characters_count
)
extra_characters_count = length - character_count
extra_characters = random.choices(characters, k=extra_characters_count)
password = (
chosen_digits
+ chosen_letters
+ chosen_special_characters
+ extra_characters
)
random.shuffle(password)
passwords.append("".join(password))
with open("Passwords.txt", "w") as f:
f.writelines(passwords)

Need help in python dictionaries

This code saves a number of key and value pair from the user but I want to go further and enter keys to be searched in phone book .Can someone tell me what's wrong with my code
phonebook = {}
n = int(input())
for x in range (n):
name , phoneno = input().split()
phonebook[ name ] = int(phoneno)
for y in phonebook:
name = input().split()
if name in phonebook:
print("Found")
else:
print('Not Found')
phonebook = {}
n = int(input())
for x in range (n):
name , phoneno = input().split()
phonebook[ name ] = int(phoneno)
name = input().split()
out = phonebook.get(name,None)
if out == None:
print('Not found')
else:
print('found')
You don't need a loop to check for a key in a dictionary
In name , phoneno = input().split() the .split() needs an argument on what to split it on, so lets say you did thisGuy 69420, if you did .split(' ') space being the argument name & phoneno would both be a list, which at index [0] would be thisGuy and at index[1] would be 69420
Hopefully, that helps :)

In Python how do I make a space between a list and string?

I need to put a space between the list (a cat's name) and the index.
Right now it comes out like this:
Pussy0
Pinky1
Fats2
I want it to print out like this:
Pussy 0
Pinky 1
Fats 2
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(catNames[i] + str(i))
Just do this:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(catNames[i] + " " + str(i))
Though its always better to use f-strings or format:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(f"{catNames[i]} {str(i)}")
Using f-strings makes the code much cleaner, and simpler to understand. Look here for more details. Note that f-strings are only for python 3.6 or above. If you have a version of python below 3.6, check my previous answer to see how you can use f-strings in below python 3.6.
Try string formatting:
catnames = ['Fuzzy', 'Pinky', 'Fats']
for i, cname in enumerate(catnames):
print('{} {}'.format(cname, str(i)))
I would suggest using string interpolation for this:
for i in range(len(catNames)):
print(f"{catNames[i]} {i}")
I with the help of "Demolution Brother" showed me how to write a list in a string followed by an index.
print(str(i),":",catNames[I])
print function
Turn the interfere into a string - (str(
After the str( we now have the interfere (str(I)
Important to use the , to separate the string to put in " : ". It has to be done with
double-quotes.
Now after the comma , we can continue with catNames[I]) (The List)
List item now prints after the index.
Answer - print(catNames[i], " : ", str(I))
Some of the other ways to it was tried out:
#print(str(i),":",catNames[i])
#print(catNames[i], i, end=' ')
#print(catNames[i],end=' ' + str(i))
The code -cat_names
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(str(i),":",catNames[i])
#print(catNames[i], " : ", str(i))

Logic Error (Pythons): Not getting write output but function works?

Inputted:
Akash Das
Expected return:
Das Akash
My code is outputting:
Da Akash
Here's my code:
#a
def firstWord(string):
space = string.find(" ")
first = string[:space]
return first
#b
def removeFirst(string):
space = string.find(" ")
word = string[space + 1:]
return word
print(removeFirst("Akash Das"))
#c
def reversePhrase(string):
reverse = []
numSpace = string.count(" ")
reverse.append(firstWord(string))
while numSpace > 0:
string = removeFirst(string)
reverse.insert(0, firstWord(string))
numSpace -= 1
return reverse
def printReverse(string):
for i in reversePhrase(string):
print (i, end = " ")
#d
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ") #call reverse
printReverse(string)
main()
And here's the output:
>>>
Das
Enter a phrase. Akash Das
Your reversed phrase is Da Akash
>>>
CSZ is right, that is simpler. But your problem is in firstWord. If the string has no spaces, then find will return -1. So space will be -1, and string[:space] will be string[:-1] which is all characters except the last. You just need to check whether you actually found a space:
def firstWord(string):
space = string.find(" ")
first = string[:space] if space >= 0 else string
return first
There is simplier way:
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ")
print(' '.join(reversed(string.split())))
main()
output
Enter a phrase. Akash Das
Your reversed phrase is Das Akash
You are not taking care of the case when find returns -1, it happens when it does not find " ".
Try:
#a
def firstWord(string):
space = string.find(" ")
if space >=0:
first = string[:space]
else:
first = string
return first
Try this :
>>> import re
>>> name = 'Harsha Biyani'
>>> s = re.split('\W',s)
>>> s.reverse()
>>> ' '.join(s)
'Biyani Harsha'

Categories