Max and Min Characters - python

I'm new to python. I am trying to make a generator that requires 3 letters from an input. I need it to only accept 3 letters no more no less. The if len i put does not work
import random
usernames = int(input("How Many Usernames Are To Be Generated?"))
names = []
for item in range(0,usernames):
names.append(input("What Is The First Three Letters of The Pupils Name?"))
if len(names) == 3:
suffixes = ["ing", "end", "axe", "gex", "goh"]
for name in names:
final = name + random.choice(suffixes)
print(final)
else (names):
print("Error! Must Be 3 Characters")

else requires no condition
import random
usernames = int(input("How Many Usernames Are To Be Generated?"))
names = []
for item in range(0,usernames):
names.append(input("What Is The First Three Letters of The Pupils Name?"))
if len(names) == 3:
suffixes = ["ing", "end", "axe", "gex", "goh"]
for name in names:
final = name + random.choice(suffixes)
print(final)
else :
print("Error! Must Be 3 Characters")

Why is names a list?
You have an empty list, name = [] .
Then you add one item to it .
names.append(input("What ..
This is why it fails, because the len of names is 1.
Either get rid of the list or check the len of the first item .
if len(names[0]) == 3

Related

how to iterate through a string and change a character in it in python

I want to capitalize a char in a string, specifically using a for loop. Can someone show how this is done using the code below. or something simpler but still using for loop iterations
name = input("Enter name")
name_list = list(name)
for i in range(len(name_list)):
if i == name_list[3]:
name_list = name_list[3].upper
else:
name_list += i
print(name_list)
Assuming this is Python, you can it by assigning the newly uppercase letter to the list at the lowercase letter's index. For example, if we want to make every third letter upper case in the string enter name, then:
name = "enter name"
name_list = list(name)
for i in range(len(name_list)):
if i % 3 == 0:
name_list[i] = name_list[i].upper()
print(''.join(name_list))
Output:
EntEr NamE

python dictionary mydt problems

Write a Python program that will take N names from the user. Create a dictionary from the N names that will hold First_name, Middle_name, and Last_name in separate keys. The inputs will take N at first and then take N names. You can assume that the names will contain less than or equal to 3 words.
Sample Input:
4
Zubayer Ahmed
Sadia Nur Amin
Mehedi Hasan Shawon
Nafis
Sample Output:
{ "Fname" : [“Zubayer”, “Sadia”, “Mehedi”, “Nafis”] , "Mname" : [“Nur”, “Hasan”], "Lname" : [“Ahmed”, “Amin”, “Shawon”] }
This problem requires you to first find the number of names needed, this can be done using a simple input() call.
numNames = int(input("> "))
we can also prepare the dictionary like so
nameDict = {"Fname":[],"Mname":[],"Lname":[]}
Then we need to iterate depending on the number the user has entered
for i in range(numNames):
During each iteration of the above for loop, you need to ask the user for a name, then split it into a list of each names names = input("name {i+1} > ").split(" ")
You can then add them to the dictionary as the problem requires using basic selection
if len(names) >= 1:
nameDict["Fname"].append(names[0])
if len(names) == 2:
nameDict["Lname"].append(names[1])
elif len(names) == 3:
nameDict["Mname"].append(names[1])
nameDict["Lname"].append(names[2])
This solution could be made more efficient if you can find a better way to sort the names into the dictionary.
Although StackOverflow isn't for your entire problems, more so questions about specific areas. Next time have a go at the problem and post if you get suck with details about your attempt.
But anyway, here is my full solution
numNames = int(input('names >'))
nameDict = {'Fname':[],'Mname':[],'Lname':[]}
for i in range(numNames):
names = input(f'name {i+1} > ').split(' ')
if len(names) >= 1:
nameDict["Fname"].append(names[0])
if len(names) == 2:
nameDict["Lname"].append(names[1])
elif len(names) == 3:
nameDict["Mname"].append(names[1])
nameDict["Lname"].append(names[2])
print(nameDict)
Here's my solution:
number_of_entries = int(input("How many entries would you like? "))
first_names = []
middle_names = []
last_names = []
i = 0
while i < number_of_entries:
full_name = input(": ")
names_array = full_name.split(' ')
if len(names_array) >= 1:
first_names.append(names_array[0])
if len(names_array) >= 2:
middle_names.append(names_array[1])
if len(names_array) >= 3:
last_names.append(names_array[2])
i += 1
names_dictionary = { "Fname" : first_names, "Mname" : middle_names, "Lname" : last_names}
print(names_dictionary)
It works by storing every category of name into an array first then adding that to the dictionary in the end.
In this homework, you must handle the initial 4 and read correctly the following input lines.
After that you will have a list of names, I think the best approach is the following
from itertools import zip_longest
names = ["Zubayer Ahmed","Sadia Nur Amin","Mehedi Hasan Shawon","Nafis"]
# split into single words
names = [x.split() for x in names]
# do a zip of the triads and remove None values
filtered = [ list(filter(None,_)) for _ in zip_longest(*names)]
#do the dict:
dict(zip( ("Fname","Mname", "Lname"), filtered))
the output:
{'Fname': ['Zubayer', 'Sadia', 'Mehedi', 'Nafis'],
'Mname': ['Ahmed', 'Nur', 'Hasan'],
'Lname': ['Amin', 'Shawon']}

How to detect the duplicate letters in a inputted string in python and print the letters that are duplicated in a list?

How do I detect a duplicated letter in an input string?
FirstName = input("Enter your First Name: ")
LastName = input("Enter your Last Name: ")
FullName = FirstName + " " * 1 + LastName
Also I wanted to know how to display the letters that are duplicated using if-else, or other methods:
like if there are duplicated letters, it will print "The duplicate letters in your First and Last Names:" and those duplicated letters in a list and if there are no letters duplicated, it will print "There are no duplicate letters in your First and Last Names."
You could use a collections.Counter to count the occurrences of each letter in the names, and then show those with more than one letter.
from collections import Counter
counts = Counter(FullName.lower())
duplicates = [c for c in counts if counts[c] > 1]
if duplicates:
print(f'The duplicate letters in your First and Last Names: {", ".join(duplicates)}')
else:
print('There are no duplicate letters in your First and Last Names.')
Note that the input is converted to lowercase so that upper and lower case letters are equivalent.
Also note that this does nothing to ignore any punctuation or whitespace that might be in the names. You could consider letters only by:
duplicates = [c for c in counts if counts[c] > 1 and c.isalpha()]

How can I remove two or more objects of a list from a single input in Python?

This is my sample database:
In my script now, I am adding elements to the list with the following code:
import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
list1.append(name[incoming_msg[0]])
So now if type "2 JO" my list will have two new elements "John" and "John".
Now I want to do exactly the same but for eliminating objects of a list. I tried to replace the current operator "+=" for "-=" but surprisingly it is not working. Any ideas on how I could solve this?
PS. I need to do it all out of the same input. I cannot ask separately for key and quantity. I want to make a replication of the above code but for removing the objects.
You could use list.remove():
Remove the first item from the list whose value is equal to x. It
raises a ValueError if there is no such item.
import pandas as pd
data = pd.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"], data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
list1.append(name[incoming_msg[0]])
print('\n'.join(list1))
incoming_msg = input('Please type what you want to delete: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
num_to_remove = int(incoming_msg[0])
while name[incoming_msg[1]] in list1 and num_to_remove > 0:
list1.remove(name[incoming_msg[1]])
num_to_remove -= 1
else:
if name[incoming_msg[0]] in list1:
list1.remove(name[incoming_msg[0]])
print('\n'.join(list1))
Example Usage:
Please type what you want to add: 4 JO
John
John
John
John
Please type what you want to delete: 2 JO
John
John

In Python, I can't get all the return values but the last, what mistake did I do here?

This is my code. I'm trying to take an input from the user, put it in a list, then check every elements if it is less than 5 characters.
It's supposed to print all the names under such condition but it only returns the last element that fits the condition.
My code:
#function to check the length of the characters
def test(names):
for x in names:
if len(x) <= 5:
print(x)
return x
#ask input from the user
names = input("Enter names: ").split()
#convert to a list
lst = list(names)
#container
viewList = test(names)
#print names under 5 characters
print("Names under five characters: ", viewList)
#just to test the elements in the list
print(names)
The Output:
Enter names: kent monique jeff ban
kent
jeff
ban
Names under five characters: ban
['kent', 'monique', 'jeff', 'ban']
As you can see, it only prints the last element. What mistake am I doing here?
Use this
#function to check the length of the characters
def test(names):
a = []
for x in names:
if len(x) <= 5:
print(x)
a.append(x)
return a
#ask input from the user
names`enter code here` = input("Enter names: ").split()
#convert to a list
lst = list(names)
#container
viewList = test(names)
#print names under 5 characters
print("Names under five characters: ", viewList)
#just to test the elements in the list
print(names)
Using a generator instead you could use:
# function to check the length of the characters
def test(names):
for x in names:
if len(x) <= 5:
yield x
# ask input from the user
names = input("Enter names: ").split()
# container
viewList = [name for name in test(names)]
# print names under 5 characters
print("Names under five characters: ", viewList)
# just to test the elements in the list
print(names)
Note that after using split() your result is already a list, so converting it to a list is redundant.
An often used method is filter(...) as in
viewList = list(filter(lambda x: len(x) <= 5, names))

Categories