So for homework we were asked to write a function that takes 2 lists as an input and use a sequential/linear search to go through them and if any name appeared in both lists to append that name to a new list. For the actual assignment two classes are specified as VoterList and VoterName, thus not allowing us to use 'in' and only VoterNames can be appended to a VoterList. (This task is going to be developed into finding people who voted twice in two different voting booths for an election).
So I have written a function that seems to work when I pass in 3-4 person long lists but I'm not sure that it is actually a sequential search working how it should be. Would be awesome for some advice. Cheers
def fraud_detect_seq(first_booth_voters, second_booth_voters):
fraud = []
length_first = len(first_booth_voters)
length_second = len(second_booth_voters)
first_booth_position = 0
second_booth_position = 0
while first_booth_position < length_first:
name_comparison = first_booth_voters[first_booth_position]
if second_booth_position == length_second:
first_booth_position += 1
second_booth_position = 0
elif second_booth_voters[second_booth_position] == name_comparison:
fraud.append(second_booth_voters[second_booth_position])
first_booth_position += 1
second_booth_position += 1
elif second_booth_voters[second_booth_position] != name_comparison:
second_booth_position += 1
print(fraud)
fraud_detect_seq(['Jackson', 'Dylan', 'Alice'],['Jackson', 'ylan', 'Alice'])
Gets the output:
['Jackson', 'Alice']
Which is correct. But I feel like I'm not doing it right.
def fraud_detect_seq(first_booth_voters, second_booth_voters):
fraud = []
for voter in first_booth_voters:
if voter in second_booth_voters:
fraud.append(voter)
This is a really simple way of checking if they are in both lists. There isn't a wrong way to write the program but since you're using python you might as well us the most "pythonic". For loops are incredibly useful in python for checking membership in lists.
Related
I'm writing a script that scrapes all of the data from my works ticketing site and the end goal is to have it send a text when a new ticket enters the bucket with all of the important info of the ticket.
Python 3.10
So far, it pulls from a scattered list and combines all of the elements into an appropriate group ie. ticket numbers,titles and priorities.
tn = rawTickets[0::14]
title = rawTickets[5::14]
priority = rawTickets[9::14]
With this I can say
num = x
wholeticket = tn[num], title[num], priority[num],
print(wholeticket)
and get x ticket in the list
# Results: "tn0, title0, priority0"
I want it to print all of the available tickets in the list based on a range
totaltickets = 0
for lines in rawTickets:
if lines == '':
totaltickets += 1
numrange = range(totaltickets)
so lets say there are only 3 tickets in the queue,
I want it to print
tn0, title0, priority0,
tn1, title1, priority1,
tn2, title2, priority2,
But I want to avoid doing this;
ticket1 = tn[0], title[0], priority[0],
ticket2 = tn[1], title[1], priority[1],
ticket3 = tn[2], title[2], priority[2],
flowchart to help explain
You could use zip:
tickets = list(zip(rawTickets[0::14], rawTickets[5::14], rawTickets[9::14]))
This will give you a list of 3-tuples.
You could do something like that:
l1 = [*range(0,5)]
l2 = [*range(5,10)]
l3 = [*range(10,15)]
all_lst = [(l1[i], l2[i], l3[i]) for i in range(len(l1))]
Or you could use zip as trincot offered.
Note that on large scales, zip is much faster.
I want to figure out how to identify any case of identical items in a list.
Currently, there is a list of people and I want to first identify their surnames and put their surnames in a separate list called list_surnames.
Then I want to loop through that list and figure out whether there are instances of people having the same surname and if so I would add that to the amount value.
this code currently does not identify cases of duplication in that list.
Should be said I am brand new to learning programming, I apologize if code is horrible
group = ["Jonas Hansen", "Bo Klaus Nilsen", "Ida Kari Lund Toftegaard", "Ole Hansen"]
amount = 0
list_surnames = []
for names in group:
new_list = names.split(" ")
extract_surname = new_list[-1:]
for i in extract_surname:
list_surnames.append(i)
for x in list_surnames:
if x == list_surnames:
amount += 1
print(list_surnames)
print(amount)
You can use the Counter to count
from collections import Counter
l = ["Jonas Hansen", "Bo Klaus Nilsen", "Ida Kari Lund Toftegaard", "Ole Hansen"]
last = [names.split()[-1] for names in l]
print(last)
c = Counter(last)
print(c)
How do I store the value of an index and then use that value in a formatted exec function to print me the second results of each list under class Animal(): Dog list, which is what I expect to print. A simplified version of the essence of my problem along with further clarification below:
class Global():
str_list = []
current_word = ""
adj_word = 'poofy'
adj_int = 0
size = 0
pounds = 0
dog_years = 0
class Animal():
##### Formatted like so:[[visual size],[pounds],[age in dog years],[almost dead]] #####
dog = [['small', 'poofy'],[7, 45],[18, 101],[0, 1]]
input = 'dog'
def done():
print(Global.adj_int)
print(str(Global.size), str(Global.pounds), str(Global.dog_years))
def split_str():
Global.str_list = input.split()
split_str()
def analyze():
Global.current_word = Global.str_list.pop(0)
exec(f"""if Global.adj_word in Animal.{Global.current_word}[0]:
Global.adj_int = Animal.{Global.current_word}[0].index('{Global.adj_word}')
Global.size = Animal.{Global.current_word}[1][{Global.adj_int}]
Global.pounds = Animal.{Global.current_word}[2][{Global.adj_int}]
Global.dog_years = Animal.{Global.current_word}[3][{Global.adj_int}]""")
if len(Global.str_list) == 0:
done()
analyze()
it returns:
1
7 18 0
When I expect it to return "45 101 1" for size, pounds, dog_years because I am storing the .index value of 'poofy' for Animal.dog list in Global.adj_int. which in this case is '1'. Then I try to format the code so it uses that value to print the second values of each list but for some reason it will not print the expected results(under def analyze():... exec(f""".... Does anyone have an answer to this question?? This is a much more simple version of what I originally have but produces the exact same result. when I try to use the formatted code it acts as if adj_int = 0 when really it's adj_int = 1 (and I know it is stored as 1 like it should be because I print adj_int at the end to check) or I am not able to format the code in this way? But I need a work around regardless.
The problem is that the string argument to exec is being evaluated before it is executed. So, when you are calling exec this is what is called:
exec(f"""if Global.adj_word in Animal.dog[0]:
Global.adj_int = Animal.{dog}[0].index('poofy')
Global.size = Animal.dog[1][0]
Global.pounds = Animal.dog[2][0]
Global.dog_years = Animal.dog[3][0]""")
And after this, Global.adj_int becomes 1. The control flow and the structure of your code is incredibly complex comparing to its simplicity so I would carefully rethink its design, but for a quick fix, you probably want to first execute the part that sets the adj_int and then the rest, like this:
exec(f"""if Global.adj_word in Animal.{Global.current_word}[0]:
Global.adj_int = Animal.{Global.current_word}[0].index('{Global.adj_word}'"""))
exec(f"""if Global.adj_word in Animal.{Global.current_word}[0]:
Global.size = Animal.{Global.current_word}[1][{Global.adj_int}]
Global.pounds = Animal.{Global.current_word}[2][{Global.adj_int}]
Global.dog_years = Animal.{Global.current_word}[3][{Global.adj_int}]""")
Even after stating that your program is unnecessarily complex, let me additionally point out that using a global, mutable state is a really really bad practice, which makes your programs hard to follow, maintain & debug. The same concern relates to using exec.
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
I am trying to create a function, getStocks, that gets from the user two lists, one containing the list of stock names and the second containing the list of stock prices. This should be done in a loop such that it keeps on getting a stock name and price until the user enters the string 'done' as a stock name. The function should return both lists. My main issues are figuring out what my parameters are, how to continuously take in the name and price, and what type of loop I should be using. I am very new to programming so any help would be appreciated. I believe I'm close but I am unsure where my errors are.
def getStocks(name,price):
stockNames = []
stockPrices = []
i = 0
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while i < len(stockNames):
stockNames.append(name)
stockPrices.append(price)
i += 1
else:
if name = done
return stockNames
return stockPrices
Your question is a bit unclear but some things off the bat, you cant have two return lines, once you hit the first, it leaves the function. Instead you'do write something like
return (stockNames, stockPrices)
Secondly while loops dont have an else, so you'd actually set up your while loop, then setup an if statement at the beginning to check if the string is 'done', then act accordingly. Break will get you out of your last while loop, even though it looks like it's associated with the if. So something like this:
while i < len(stockNames):
if name.upper() == 'DONE':
break
else:
stockNames.append(name)
stockPrices.append(price)
i += 1
Also you have to use == (comparison) instead of = (assignment) when you check your name = done. And dont forget done is a string, so it needs to be in quotations, and I used .upper() to make the input all caps to cover if its lower case or uppercase.
If you can clear up your question a little bit, I can update this answer to include everything put together. I'm not quite understanding why you want to input a list and then also take user input, unless you're appending to that list, at which point you'd want to put the whole thing in a while loop maybe.
Update:
Based on your comment, you could do something like this and enclose the whole thing in a while loop. This takes the incoming two lists (assuming you made a master list somewhere) and sends them both into the getStocks function, where someone can keep appending to the pre-existing list, and then when they type done or DONE or DoNe (doesn't matter since you use .upper() to make the input capitalized) you break out of your while loop and return the updated lists:
def getStocks(name, price):
stockNames = name
stockPrices = price
while 1:
inputName = str(input("What is the name of the stock?"))
inputPrice = int(input("what is the price of that stock?"))
if name.upper() != 'DONE':
stockNames.append(inputName)
stockPrices.append(inputPrice)
else:
break
return (stockNames, stockPrices)
But really, depending on the rest of the structure, you might want to make a dictionary instead of having 2 separate lists, that way everything stays in key:value pairs, so instead of having to check index 0 on both and hoping they didn't get shifted by some rogue function, you'd have the key:value pair of "stock_x":48 always together.