Trying to make a phone book using python - python-3.x

I am trying to make a phone book using these instructions
Write a program that creates 2 lists: one of names and one of phone numbers. Give these variables appropriate names (for example names and numbers). Using a for loop, have the user enter 3 names and 3 numbers of people for the phone book. Next: display the entries from the phone book, name and then number. Use a for loop. Next, ask the user to enter a name. Store their input in a variable. Use a search to see if the name is entered in the name list. If the name is in the name list, print the number. If not have the program respond, “Name not found.
Your output should look like:
Name Number
sally 11
bob 22
carl 33  
Number you are looking for is: 11
All I want to know is how do you make a simple list out of user inputed data. so I can do this question.
Pseudocode is
#LOOP THREE TIMES
# names = GET INPUT name
# numbers = GET INPUT number
#END LOOP
#LOOP THREE TIMES
# PRINT (name) in names, (number) in numbers
#END LOOP
# searchName = GET INPUT "Enter a name for Search"
#IF searchName IN names THEN
# PRINT matching number
# LOOP names
# IF searchName == name THEN
# foundIndex = name(index)
# searchPhoneNumber = phoneNumber[foundIndex]
# END IF
# END LOOP
# PRINT searchPhoneNumber
#ELSE
# PRINT "Name Not Found"
#END IF

use this:
names = []
phone_numbers = []
num = 3
for i in range(num):
name = input("Name: ")
phone_number = input("Phone Number: ") # for convert to int => int(input("Phone Number: "))
names.append(name)
phone_numbers.append(phone_number)
print("\nName\t\t\tPhone Number\n")
for i in range(num):
print("{}\t\t\t{}".format(names[i], phone_numbers[i]))
search_term = input("\nEnter search term: ")
print("Search result:")
if search_term in names:
index = names.index(search_term)
phone_number = phone_numbers[index]
print("Name: {}, Phone Number: {}".format(search_term, phone_number))
else:
print("Name Not Found")

To add a name or number to the appropriate list, use the append function i.e.
numberlist.append(number_that_was_input)
or
namelist.append(name_that_was_input)
and as #cricket007 so eloquently states, we do like to see that you at least try to do things for yourself.

To receive input from the user, use the input() function.
Example:
name = input('type in name')
print(name)
#Outputs the name you typed.
To add that value into a list use the append.
Example:
my_list = [] #Initialize list first.
my_list.append(name) # this will add the contents of variable name to your list.
# my_list now looks like this: ["user817205"]
Since you have to do this 3 times, it's smart to use a for loop to do that,
you can iterate 3 times through a block of code using the following:
for _ in range(3):
#type the code you want to repeat 3 times here!
PS.: Remember you only need to initialize your list once, so keep the my_list = [] out of the for loop.

Related

How to get elements from a text file and searching them in another text file in python 3?

I have players.txt It is like:
Iteration: 1
Lloris
Kounde
Varane
Upamecano
Hernandez
Tchoumeni
Rabiot
Dembele
Griezman
Mbappe
Giroud
Iteration:2
Martinez
Molina
Otamendi
Romero
Tagliafico
Mac Allister
De Paul
Fernandez
Alvarez
Messi
Lautaro
Iteration 3:
xxxxx
yyyyy
zzzzz
namenamename
name
name
name
And I have superstarplayers.txt like:
Messi
Modric
Ronaldo
Mbappe
playername
playername
playername
playername
It goes like this, a lot of player name
No blank line in superstarplayer.txt
But in players.txt there is a blank line afterward the name of a player line. It is like 1st row is player 2nd row blank 3rd row is player 4th row is blank. One player one blank.
For each iteration, I want to get number of how many players in my iteration. And also I want to get the number of how many players is also exist in superstarplayers.txt
How can I do that in python3. I am learning python file operations.
(in players.txt in every iteration there are not always 11 players the numbers might different)
I'm learning how to read from a txt file, how to write to a txt file. I have no idea about how to get elements from a text file and searching them in another text file in python 3. How can I do that?
You can do what you are asking with this
def fix_data(lst):
""" Fixes any blank lines or empty strings"""
#remove the newline character from the strings if there
remove_newline = [x.replace("\n","") for x in lst]
#remove empty strings (your example has them) - also remove whitespace
remove_empty = [x.strip() for x in remove_newline]
#return data
return remove_empty
#open a text file for reading like this - its wrapped in a fix_data function
with open('/home/lewis/players.txt', 'r') as f:
lines = fix_data(f.readlines())
#open superstar players - also wrapped
with open('/home/lewis/superstar.txt', 'r') as f:
superstar_lines = fix_data(f.readlines())
#create a iteration dictionary.
iteration_store = {}
#create a variable to store the iteration no
iteration = 0
#create a variable to store the iteration start no
iteration_start = 0
#create a variable to store unknown player no
unknown_player = 1
#loop each line and and to dict on each iteration
for line in lines:
#check if an iteration line
iteration_start += 1
if "Iteration" in line:
# get the iteration number from the string by splitting the string on 'Iteration:' and taking the last value, then removing white space
iteration = line.split("Iteration:")[-1].strip()
#store this value in the dict as a list
iteration_store[iteration] = []
#set to zero
iteration_start = 0
# after the interation line is found then find the player name in every other space
elif iteration_start % 2 != 0:
#check if the player is unknown and rename the line
if line == "" or line is None:
#set the line
line = f"Unknown Player {unknown_player}"
#increment the player number
unknown_player += 1
#if not an iteration line then store the player name in the dict[list]
iteration_store[iteration].append(line)
#print the information
print(iteration_store)
#print a new line to seperate the data
print("\n\n")
#loop the newly create dict and print each iteration number and count of players
for k,v in iteration_store.items():
# check the superstar list for matches
superstars = [x for x in v if x in superstar_lines]
#print the information
print(f"Iteration: {k} - No Players {len(v)} - No Superstars {len(superstars)}")
EDIT:
Changed the code to take the player name from every other line after the "Iteration" line has been found. This will only work if it follows the following format ALWAYS
iteration line
player name (empty or not)
empty string
player name (empty or not)
ALSO
If the superstar player is not found, then there must be something that doesnt match like its written messi and Messi as they are different. The code is sound.
Read the codes, research and play with it. Google is your friend.

My Five - stores five names and five numbers before being promoted for a number need input

For class I need to create a code that stores five names of your friends and five numbers in two separate arrays and then outputs the list of your five friends. The user would then be prompted for a number between 1 and 5, and the program will determine the person and the number to dial.
it should look something like -
1. Jack Black
2. Robert Downey Jr.
3. Chris Evens
4. Scarlett Johansson
5. Harry Potter
Please enter a number (1-5): *4*
Calling Scarlett Johansson at 416-568-8765
right now I have:
name = ["Paige"]
number = ["519-453-4839"]
#populate with a while loop
while True:
#add an element or q for quit
addname = input("Enter a name, or q to quit ").lower()
if addname == "q":
break
else:
theirnumber = input("Enter their number ")
#adds to the end of the list
name.append(addname)
number.append(theirnumber)
#when they break the loop
#print the lists side by side
print()
print("Name \t\t\t Number")
print("----------------------------------")
for x in range(len(name)):
print(f"{name[x]} \t\t\t {number[x]}")
#search for a gift and who gave it
searchItem = input("What name are you looking for? ")
if searchItem in name:
nameNumber = name.index(searchItem)
print(f"{name[nameNumber]} is the number {number[nameNumber]}")
else:
print("that is not a saved name, please enter a different name")
I'm not sure how to do it without asking for the numbers, if anyone has any ideas I would love to hear them.
#Mitzy33 - try to this and see if you follow, or have any other questions:
# two array for names, and the numbers
names = []
numbers = []
#populate with a while loop
while True:
# get the name and numbers:
name = input("Enter a name, or q to quit ")
if name == "q":
break
else:
number = input("Enter his/her number ")
#adds to the end of the list
names.append(name)
numbers.append(number)
#when they break the loop
#print the lists side by side
print(names)
print(numbers)
searchPerson = input("What name are you looking for? ").strip()
#print(searchPerson)
index = names.index(searchPerson)
print(f' {searchPerson} at {numbers[index]} ')
Output:
Enter a name, or q to quit John
Enter his/her number 9081234567
Enter a name, or q to quit Mary
Enter his/her number 2121234567
Enter a name, or q to quit Ben
Enter his/her number 8181234567
Enter a name, or q to quit Harry
Enter his/her number 2129891234
Enter a name, or q to quit q
['John', 'Mary', 'Ben', 'Harry']
['9081234567', '2121234567', '8181234567', '2129891234']
What name are you looking for? Harry
Harry at 2129891234
Instead of using two arrays you can do it using Python Dictionaries.
Use the name as the key and the number as the corresponding value.
peoples = {"Paige": "519-453-4839"}
You can add an item like that:
poeples["newName"] = "111-111-1111"
Then you can access the number like that:
peoples["Paige"]
So you can ask the name and return the number:
searchName = input("What name are you looking for? ")
print(f"{searchName} is the number {peoples[searchName]}")
If you have to use only arrays then you can find the index from the name:
searchName = input("What name are you looking for? ")
index = name.index(searchName)
print(f"{name[index]} is the number {number[index]}")

making a dictionary of student from space separated single line user input where name will be key and list of exam numbers will be value

Suppose I take one line space separated input as by using a string as : john 100 89 90
now from this string a dictionary is to be made as : d={'john':[100,89,90]}. Here, the numbers are to be collected in a list as integers. Basically from that input string line I want to make a student info dictionary where the name will be the key and the numbers will be exam numbers collected in a list as integers.
st=input()
value=st[1:]
c=list(map(int, value.split()))
print(c)
key=st[0]
d={}
d[key]=c
print(d)
I was writing this but mistakenly written key=st[0].. but this will only take the first character j as name and rest as values so I eventually got error: invalid literal for int() with base 10: 'ohn'
So, how can I correct it and get the exact result that I mentioned above?? I also want to know alternative method for taking space separated input like john 100 89 90 other than strings.
Your approach is correct in a way , the only addition I would like to make is , have a preset delimiter string for student input info
student_dict = {}
loop_flag = True
loop_input = "Y"
delimit = "," #### You preset delimiter
while loop_flag:
key = input("Input Student Name : ")
if key in student_dict:
print("Student already in Dictionary, continuing...."
continue
else:
info_str = input("Input Student Information: ")
info_list = info_str.split(delimit)
student_dict[key] = info_list
loop_input = input("Do you wish to add another student (Y/N)"
if loop_input == "N":
loop_flag = False
You can even use the space delimiter as well , but a more intuitive delimiter is suggested

Forming a target string using minimal substrings of words from a word list

I have a text file with first names but there are new names added every year.
I need a program in Python that takes parts of names from the text file and finds some combination of substrings of these names that can be concatenated to create a string that matches a user's input.
The program should do this using the fewest possible available names from the text file.
For example, if the text file contains this:
Joppe
Fien
Katrijn
Sven
Kobe
The program asks for a name that isn't already in the text file. For example:
Please fill in a name: Katrien
Then it should print this:
Katri => Katrijn
ien => Fien
Not like this--it builds the name correctly, but there is a better solution that uses fewer words:
K => Kobe
a => Katrijn
tr => Katrijn
ien => Fien
If the text file contains this:
Joppe
Fien
Makatrijn
Sven
Kobe
It could also print this:
Katr => Makatrijn
ien => Fien
I tried this but with no result:
name_input = input('Fill in a name: ')
with open('namen.txt', 'r') as file:
for name in file.readlines():
for letter_name_input in name_input:
for letter in name:
if letter == letter_name_input:
print(letter)
You can use a function that takes a target name and a set of names as input, tries matching a prefix of the target name with each name in the set of names, from the longest to the shortest, and for each matching name, recursively finds the names that would form the target name with the prefix removed, from the set of names with the matching name removed, and yields each of the returning combinations with the current prefix and name prepended as a tuple:
def form_name(target, names):
if target:
for i in range(len(target), 0, -1):
prefix = target[:i]
matching_names = [name for name in names if prefix.lower() in name.lower()]
if matching_names:
for name in matching_names:
for fragments in form_name(target[i:], names - {name}):
yield [(prefix, name), *fragments]
else:
yield []
so that you can use the min function with len as the key function to obtain the combination with the fewest names:
from io import StringIO
file = StringIO('''Joppe
Fien
Katrijn
Sven
Kobe''')
for fragment, name in min(form_name('Katrien', set(file.read().split())), key=len):
print(fragment, '=>', name)
outputs:
Katri => Katrijn
en => Fien
Demo: https://repl.it/repls/IllustriousTrustingIntegrationtesting
Note that both Fien and Sven in your example input would match the en fragment and make for valid answers with the fewest names, so the min function would arbitrarily return one of them (which is fine per your requirement). Also note that you shouldn't expect the fragments of the target name to overlap, so instead of ien the second fragment should be en after the first fragment Katri is removed from the target name Katrien.
If you're interested in seeing all the valid answers, you can calculate the minimum length of all the combinations first and then output all the combinations with the minimum length:
combinations = list(form_name('Katrien', set(file.read().split())))
min_len = min(map(len, combinations))
for combination in combinations:
if len(combination) == min_len:
for fragment, name in combination:
print(fragment, '=>', name)
print()
This outputs:
Katri => Katrijn
en => Sven
Katri => Katrijn
en => Fien
Katr => Katrijn
ien => Fien
Assuming you'd want to stop searching as soon as you find a shortest answer, here's my solution:
First you need a function to break the word into all possible parts starting from the biggest possible set:
def breakWord(word, n):
list = []
for k in range(len(word)):
subword = word[k:]
out = [(subword[i:i+n]) for i in range(0, len(subword), n)]
if(k > 0):
out.append(word[:k])
list.append(out)
return list
Notice that if you use:
breakWord(yourWord, len(yourWord)-1)
It will break the word into all possible sets of two parts.
Then a function to check if a given string is in the list of names:
def isInNames(word):
for name in name_list:
if(word in name):
return true
return false
Finally iterate over the whole possible combination of characters:
def findWordCombination(word):
resultSet = []
resultSize = 50 #Something large to ensure it gets changed
for i in range(len(word)-1, 0, -1): #Will go from max to minimum
testSet = breakWord(word, i)
for set in testSet:
isValid = true #assumes true at first
for part in set:
if(not isInNames(part)):
isValid = false
#Once all parts of the set are checked we find
#If the set is valid. i.e. it is a valid combination.
if(isValid and len(set) < resultSize):
resultSize = len(set)
resultList = set
return resultList
This will return the first set that finds with the minimum possible combination of subwords from your search query. You can tweak it to have it store the words names from the list that yielded the resulting set.
Yet another approach (I upvoted #blhsing's recursive solution already, very elegant, I love it)
import itertools as it
from collections import defaultdict
def get_all_substrings(input_string):
length = len(input_string)
return [input_string[i:j+1] for i in range(length) for j in range(i,length)]
names = ['Joppe', 'Fien', 'Katrijn', 'Sven', 'Kobe']
d = defaultdict(list) # each key is a substring of any of the names and the value is the list of names that contain it
for name in names:
for subname in get_all_substrings(name):
d[subname].append(name)
input_name = 'Katrien'
input_subs = get_all_substrings(input_name)
sub_combs = [it.combinations(input_subs, n) for n in range(1,len(input_name))]
whole_combs = [el for co in sub_combs for el in co if ''.join(el) == input_name] # those combs that can form the input name
saved = [wc for wc in whole_combs if all((c in d for c in wc))] # those whole combinations that actually appear
shortest_comb = min(saved, key=len)
shortest_sub_and_name = [(s, d[s]) for s in shortest_comb]
for s, ns in shortest_sub_and_name:
print(f"{s} => {ns}")
produces
Katr => ['Katrijn']
ien => ['Fien']
Note: as you can see, the output shows all the names that can contribute to each specific substring
you could try:
import difflib
name = input('Please fill in a name: ')
with open('namen.txt', 'r') as file:
file_data = file.readlines()
# either you are looking for
print([i for i in file_data if difflib.SequenceMatcher(a = i,b = name).ratio() >= 0.5])
#or you are looking for
print(difflib.get_close_matches(name,file_data,len(file_data),0.5))
['Katrijn\n', 'Fien\n']

trying to create a program in python 3.4 but not having any luck with it

I am trying to create a program in python 3.4 that uses a list to store the names of some notable celebrities. I want to use a loop to prompt the user for the names and to add them to the list. When the user enters "done" the loop should stop. The program should then output the number of celebrities entered. Finally, the program should use another loop to display the celebrity names, each on its own line, and "done" should NOT be in the celebrities list
def main():
with open("celeb1.txt", "w") as Celeb:
def Celebrites():
Celeb = ["Johnny Depp', 'Gary Busey', 'Tommy Lee Jones"]:
#file for saving names.
#write the list to the file
.writelines(Celeb1.txt)
#close file
outfile.close()
main()
Given below is the code you have asked for. If you can post your code we can look for errors in it.
lst = []
while(1):
name = input("enter celebrity name:") # read name of celebrity
if name == "done":
break;
else:
lst.append(name) # add name to list
# len(list) to find length of list
print(len(lst))
# print names in loop
for item in lst:
print(item)

Resources