Duplicate entries in the list - python-3.x

Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.
I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.
sorry, i'm new to this i thought i've included code. Hoping it goes through this time.
x=1
mac_list = []
while (x <=8):
MAC1 = input("SCAN MAC"+str(x)+":")
for place in mac_list:
print (mac_list)
if place==MAC1:
print ("place"+place)
print ("Duplicate SCAN, please rescan")
else:
mac_list.append(MAC1)
x+=1

Python's in comparison should do what you need:
values = []
while True:
value = input('Input value: ')
if value in values:
print('Duplicate, please try again')
else:
values.append(value)
if len(values) > 7:
break
print(values)

Would something like this not work?
Sets can only hold unique elements and thus remove any duplicates by default - that should solve a lot of your worries. This should work better for larger datasets over elementwise comparison.
entries = set()
while len(entries)<8:
entries = entries ^ set([input("You do not have enough unique items yet, add another")])
To detect a change you can have an old list and a new one:
entries = set()
new=set()
while True:
latest = input("You do not have enough unique items yet, add another")
new = entries ^ set([latest])
if len(new) == len(entries):
print("you entered a duplicate:",latest, " Please rescan")
else:
entries = new
if len(entries) == 8 : break

Store the entries in a set, check if the set has fewer than 8 elements. If it does not, break the loop.
entries = set()
counter = 0
while len(entries) < 8:
counter += 1
entries.add(input("Enter an item: "))

Related

(Beginner Python assignment help) Search input list

I have just started learning python and i have been given an assignment to create a list of players and stats using different loops.
I cant work out how to create a function that searches the player list and gives an output of the players name and the players stat.
Here is the assignment:
Create an empty list called players
Use two input() statements inside a for loop to collect the name
and performance of each player (the name will be in the form of a
string and the performance as an integer from 0 – 100.) Add both
pieces of information to the list (so in the first iteration of the
loop players[0] will contain the name of the first player and
players[1] will contain their performance.) You are not required to
validate this data.
Use a while loop to display all the player information in the
following form:
Player : Performance
Use a loop type of your choice to copy the performance values from
the players list and store these items in a new list called results
Write a function that accepts the values “max” or “min” and
returns the maximum or minimum values from the results list
Write a function called find_player() that accepts a player name
and displays their name and performance from the players list, or an
error message if the player is not found.
Here is what I have so far:
print ("Enter 11 Player names and stats")
# Create player list
playerlist = []
# Create results list
results = []
# for loop setting amount of players and collecting input/appending list
for i in range(11):
player = (input("Player name: "))
playerlist.append(player)
stats = int(input("Player stats: "))
playerlist.append(stats)
# While loop printing player list
whileLoop = True
while whileLoop == True:
print (playerlist)
break
# for loop append results list, [start:stop:step]
for i in range(11):
results.append(playerlist[1::2])
break
# max in a custom function
def getMax(results):
results = (playerlist[1::2])
return max(results)
print ("Max Stat",getMax(results))
# custom function to find player
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
return (name)
for s in list:
if name in str(s):
return (s)
print (find_player(playerlist))
I have tried many different ways to create the find player function without success.
I think I am having problems because my list consists of strings and integers eg. ['john', 6, 'bill', 8]
I would like it to display the player that was searched for and the stats ['John', 6]
Any help would be greatly appreciated.
PS:
I know there is no need for all these loops but that is what the assignment seems to be asking for.
Thank you
I cut down on the fat and made a "dummy list", but your find_player function seems to work well, once you remove the first return statement! Once you return something, the function just ends.
All it needs is to also display the performance like so:
# Create player list
playerlist = ["a", 1, "b", 2, "c", 3]
# custom function to find player
def find_player(playerlist):
name = str(input("Search keyword: "))
searchIndex = 0
for s in playerlist:
try:
if name == str(s):
return ("Player: '%s' with performance %d" % (name, playerlist[searchIndex+1]))
except Exception as e:
print(e)
searchIndex += 1
print (find_player(playerlist))
>>Search keyword: a
>>Player: 'a' with performance 1
I also added a try/except in case something goes wrong.
Also: NEVER USE "LIST" AS A VARIABLE NAME!
Besides, you already have an internal name for it, so why assign it another name. You can just use playerlist inside the function.
Your code didn't work because you typed a key and immediately returned it. In order for the code to work, you must use the key to find the value. In this task, it is in the format of '' key1 ', value1,' key2 ', value2, ...]. In the function, index is a variable that stores the position of the key. And it finds the position of key through loop. It then returns list [index + 1] to return the value corresponding to the key.
playerlist = []
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
index = 0
for s in list:
if name == str(s):
return ("This keyword's value: %d" % (list[index+1]))
index+=1
print (find_player(playerlist))

How do i fix the 'element not found' in binary search?

I have been trying to implement this code whose work is to find a particular element using Binary search.Now the code works fine if element is present in the list but it is unable to display the intended block if the search element is not present.I have assumed that the list is sorted in ascending order.Help on this would be appreciated
I have tried giving an else part with the while: but it doesn't help.Its unable to show the error for element not found
def binarysearch(l,item):
low=0
u=len(l)-1
while low<=u:
mid=int((low+u)/2)
if item==l[mid]:
return mid
elif item<l[mid]:
high=mid-1
else:
low=mid+1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
print(item,"found at index",index)
else:
print("Element not found") #i am unable to reach this part
If input is:
Enter the list of elements[8,12,19,23]
Enter search item:10
I expect the result to be "Element not found" .but the program does nothing in this situation
I will give you a tip and later on I will test better this code and try to explain why it is happening.
The tip is to use in to check if the items exist in a list or not. In is more performatic than use a loop.
Exemplo working:
def binarysearch(elem, item):
if item in elem:
return elem.index(item)
else:
return -1 # because your if verifying if the return is equal or greater than 0.
Update 1
When I tried to run your code I got in one infinite loop, it's happening because of the expression mid=int((low+u)/2) - I couldn't understand why you did it. If we run this code happens this:
list [8,12,19,23] and Item 10
u=len(l)-1 u = 3 because 4 - 1
Get in the while because the condition is True
mid=int((low+u)/2) here mid will be (0+3)/2 as you force it to be int the result will be 1
if item==l[mid]: 10 == 12 -- l[mid] - l[1] - False
elif item<l[mid]: 10<12 True
high=mid-1 high will be 1 - 1 = 0
You go to the next iteration starting on the number 3, and that is why you get in an infinite loop
To go through all positions in a list, you could use the low that starts in 0 and increase if the item is not == the value in that position. So you could use the while but in that way:
def binarysearch(l,item):
low=0
u=len(l)-1
while low<=u:
if item==l[low]:
return low
else:
low+=1
return -1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
print(item,"found at index",index)
else:
print("Element not found")
To debug your code you can use [1]: https://docs.python.org/3/library/pdb.html

How to return the result of for loop count using python?

I am using below code to compare each value from the string i have given and if any of the character matches with 4 i need the total matching occurrences for it.
I have tried the below snipped but i am getting only 0, can any one check and advise , where i went wrong?
def wordcount(list):
count=0
values=[]
for i in range (len(list)):
if int(list[i])==4:
print("the value taken from the loop is: ",list[i])
print("comparison result is: ",list[i]==4)
count=count+1
print("match count=",count)
values.append(count)
return values
else:
values.append(count)
return values
# return count
print(wordcount("1452454878594521564"))
expecting 5 as count
The reason why your code doesn't work is because once return statement is executed, the loop will not execute again. The control will be out of the function. Here's how you can fix your code:
def wordcount(l):
count=0
for i in range(len(l)):
if int(l[i])==4:
count=count+1
return count
print(wordcount("1452454878594521564"))
I removed the empty values list because honestly, I didn't see the purpose of it.
Also, if you want to count a particular character in a string just use the count method:
print("1452454878594521564".count('4'))
The result your getting is correct in case you want to find out if an item was repeated 4 times in the string. The below code will demonstrate how many times an item occurred repeatedly 4 times or over:
def wordcount(list):
count=0
values=[]
for item in list:
innercount=0
for initem in list:
if item == initem:
innercount=innercount+1
if innercount >=4:
count=count+1
values.append([item,innercount])
#list = list.replace(item, "")
return values, count
If you want a unique occurrence un-hash the commented line.

Search the nth number of string in side the another list in python

add name, where is a string denoting a contact name. This must store as a new contact in the application.
find partial, where is a string denoting a partial name to search the application for. It must count the number of contacts starting with and print the count on a new line.
Given sequential add and find operations, perform each operation in order.
Input:
4
add hack
add hackerrank
find hac
find hak
Sample Output
2
0
We perform the following sequence of operations:
1.Add a contact named hack.
2.Add a contact named hackerrank.
3.Find and print the number of contact names beginning with hac.
There are currently two contact names in the application
and both of them start with hac, so we print 2 on a new line.
4.Find and print the number of contact names beginning with hak.
There are currently two contact names in the application
but neither of them start with hak, so we print 0 on a new line.
i solved it but it is taking long time for large number of string. my code is
addlist =[]
findlist=[]
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if(op=='add'):
addlist.append(contact)
else:
findlist.append(contact)
for item in findlist:
count=0
count=[count+1 for item2 in addlist if item in item2 if item==item2[0:len(item)]]
print(sum(count))
is there any other way to avoid the long time to computation.
As far as optimizing goes I broke your code apart a bit for readability and removed a redundant if statement. I'm not sure if its possible to optimize any further.
addlist =[]
findlist=[]
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if(op=='add'):
addlist.append(contact)
else:
findlist.append(contact)
for item in findlist:
count = 0
for item2 in addlist:
if item == item2[0:len(item)]:
count += 1
print(count)
I tested 10562 entries at once and it processed instantly so if it lags for you it can be blamed on your processor

Need help using values from one list to find values for another list

Here is my code:
def collectData():
print ("Please use correct spelling\n")
print("Choose what game type this is")
getGameType = input(" FFA: 1\n 1v1: 2\n 2v2: 3\n 3v3: 4\n 4v4: 5\n")
if getGameType == "1":
FFAPlayerList = []
getFFAMaxLen = (int)(input("How Many players were in this FFA?: "))
print("Please enter playername as well as placing, seperated by a comma\n(playerName,placing) One player per entry. \n")
while len(FFAPlayerList) < getFFAMaxLen:
getFFAPlayers = input("format: playerName,Placing::: ").split(',')
FFAPlayerList.append(getFFAPlayers)
with open("C:\\Users\\Twinklenugget\\Documents\\NQGroup\\Databases\\NQMasterDatabase.csv", 'r') as ffaDatabaseExtract:
reader = csv.reader(ffaDatabaseExtract)
ffaDatabaseList = list(reader)
FFAPlayerList.append(ffaDatabaseList)
print (FFAPlayerList)
collectData()
Forgive the formatting, it's actually all correct. I am relativly new to python and coding in general. My goal is to be able to take the values stored in FFAPlayerList (the player names) and use those strings to look for the same strings in ffaDatabaseList. After it finds the same strings from ffaDatabaseList I then need to take values from the second column from ffaDatabaseList and append them into FFAPlayerList. How exactly would I go about doing that? Even a pointer in the right direction would be great.

Resources