Is there any way to find the index of everything found after using the count function - python-2.7

first question over here. I'm currently scanning through two lists and what I need to do is use the count function to find how many times a specific word appears and then I'd like to take the index of every one of those words and scan a second list for them. I have a list with a bunch of products and a second list with the corresponding prices so I'd like to be able to take the average of the prices and match them which each product. Any help would be appreciated

I may not fully have understood your data structure, some code and data would be appreciated, but try:
list1 = [1,2,3,4,5]
list2=['a', 'b','c', 'a', 'b']
b=list2.count('a')
print b
print
for i, j in enumerate(list2):
if j == 'a':
print i,": ", list1[i]
Result is:
2
0 : 1
3 : 4

Related

Why won't my list.append() not append despite working in print output

Below is my code for the leet code problem: here
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
tripletsList = []
uniqueNums = set(nums)
uniqueNums = list(nums)
for x in range(len(uniqueNums)):
for y in range(len(uniqueNums)):
for z in range(len(uniqueNums)):
print(uniqueNums[x],uniqueNums[y],uniqueNums[z])
if (uniqueNums[x] + uniqueNums[y] + uniqueNums[z]) == 0:
if [[uniqueNums[x],uniqueNums[y],uniqueNums[z]]] not in tripletsList:
tripletsList.append([uniqueNums[x],uniqueNums[y],uniqueNums[z]])
print(tripletsList)
I realize it isn't the optimal solution but in my print line the output shows the correct combination, yet my final triplets list is not eliminating anything which leads me to believe I am not using the "not in" function of python correctly. Any help is greatly appreciated and I must be missing something that is just trivial
I tried first printing every combination of the unique list (yes tons of overlap), then I tried limiting the triplets that made it pass the == 0 check to only triplets that were not already in the triplets list (failed)

Map Reduce Removing Duplicates

I have been given a large text file and want to find the number of different words that start with each letter. I am trying to understand input and output values for map and reduce functions.
I understand a simpler problem which does not need to deal with duplicate words: determine the frequency with which each letter of the alphabet starts a word in the text using map reduce.
Map input: <0, “everyday i am city in tomorrow easy over school i iterate tomorrow city community”>
Map output: [<e,1>,<i,1>,<a,1>,<c,1>,<i,1>,<t,1>,<e,1>,<o,1>,<s,1>,<i,1>,<i,1>,<t,1>,<c,1>,<c,1>]
Reduce input: <a,[1]>,<c,[1,1,1]>,<e,[1,1]>,<i,[1,1,1,1]>,<o,[1]>,<s,[1]>,<t,[1,1]>
Reduce output: [<a,1>,<c,3>,<e,2>,<i,4>,<o,1>,<s,1>,<t,2>]
For the above problem the words 'i' 'city' and 'tomorrow' appear more than once so my final output should be:
Reduce output: [<a,1>,<c,2>,<e,2>,<i,3>,<o,1>,<s,1>,<t,1>]
I am unsure of how I would ensure duplicate words are remove in the above problem (would it be done in a pre processing phase or could it be implemented on either map or reduce functions). If I could get help understanding the map and reduce outputs of the new problem I would appreciate it.
You can do it in two map-reduce passes:
find all the distinct word by using word as a map output and in reduce outputting each word once
you already solved - find frequency of each initial letter on each unique word.
Alternatively, since there are not many unique words you can cache them in mapper and output each one (or its first letter) only once and the reduce will be identical to your simpler problem. Actually, no, that won't work because same words can appear in different mappers. But you can still cache the words in mapper in the first solution and output each word only once per mapper - a little bit less traffic between map and reduce.
Maybe something like this would help,
let str = "everyday i am city in tomorrow easy over school i iterate tomorrow city community"
let duplicatesRemoved = Set(str.split(separator: " "))
Output:
["city", "community", "tomorrow", "easy", "everyday", "over", "in", "iterate", "i", "am", "school"]
And maybe you don't need those map statements and can achieve something like this,
Code
var varCount = [Character: Int]()
for subStr in duplicatesRemoved {
if let firstChar = subStr.first {
varCount[firstChar] = (varCount[firstChar] ?? 0) + 1
}
}
Output
["i": 3, "t": 1, "e": 2, "c": 2, "s": 1, "a": 1, "o": 1]

Python loop query and issue

I'm new to Python so patience may be required on your behalf :) If this is not the right area for this then please let me know. I'm having trouble with a for loop navigating through a list. The idea here is to print "True" when a consecutive set of numbers are found in the list however it shouldn't print true if the sequence contains less than 3 consecutive iterations.
For example:
Ideally the program would say "You have 3 sequences in your list". In this case it would be (1,2,3), (10,11,12) and (22,23,24). Notice there are 2 other consecutive sets of numbers in the list (7,8) and (15,16) however the program should ignore them because it's less than 3 (as mentioned above). Please find code below however I'm at a slight road block. Appreciate any pointers you may have.
list1=[1,2,3,7,8,10,11,12,15,16,22,23,24]
for i in range(len(list1)-1):
if (list1[i] + 1 == list1[i+1]):
count+=1
if count >=3:
print("True")
else:
continue
continue
print(count)
I'm sure I have read the answer in similar posts but I would like to understand the code I'm missing rather than inserting code that doesn't make sense to me.
Thanks
As the query is to have only unique numbers in the sequences .. so below code will just work fine...
list1=[1,2,3,4,5,6,7,8,9,10]
count=0
i=0
while i < (len(list1)-3):
if list1[i]+1 == list1[i+1]:
if list1[i+1]+1 == list1[i+2]:
print(list1[i], list1[i+1], list1[i+2])
i=i+2
count=count+1
i=i+1
print(count)

print sum of duplicate numbers and product of non duplicate numbers from the list

I am new to python. I am trying to print sum of all duplicates nos and products of non-duplicates nos from the python list. for examples
list = [2,2,4,4,5,7,8,9,9]. what i want is sum= 2+2+4+4+9+9 and product=5*7*8.
There are pythonic one liners that can do this but here is an explicit way you might find easier to understand.
num_list = [2,2,4,4,5,7,8,9,9]
sum_dup = 0
product = 1
for n in num_list:
if num_list.count(n) == 1:
product *= n
else:
sum_dup += n
Also side note, don't call your list the name "list", it interferes with the builtin name of the list type.
count is useful for this. Sum is built in, but there is no built in "product", so using reduce is the easiest way to do this.
from functools import reduce
import operator
the_sum = sum([x for x in list if list.count(x)>1])
the_product = reduce(operator.mul, [x for x in lst if lst.count(x)==1])
Use a for loop to read a number from the list. create a variable and assign the number to it, read another number and compare them using an if statement. If they are the same sum them like sameNumSum+=sameNumSum else multiply them. Before for loop create these two variables and initialize them. I just gave you the algorithm to it, you can change it into your code. Hope that help though.

sorting elements in the list in python

suppose the list is like this
l = [("Texas","city1"), ("Texas","city2"), ("Texas","city3"), ("Texas","city4"), ("Texas","city5"),
("Georgia","city6"), ("Georgia","city9"), ("Georgia","city10"),
("Alabama","city7"), ("Alabama","city8")]
This list will have a unique state names.
Now what i need two things to be done with this list.
1) sorting based on states first and cities second. say after sorting based on states first and cities second the list looks like this
l = [("Georgia","city6"),("Georgia","city9"),("Georgia","city10"),("Texas","city1"), ("Texas","city2"), ("Texas","city3"), ("Texas","city4"), ("Texas","city5"),("Alabama","city7"), ("Alabama","city8")]
2) after this step i need the states to be alphabetized with their corresponding cities. Say i need like below format finally.
l = [("Alabama","city7"), ("Alabama","city8"),("Georgia","city6"),("Georgia","city9"),("Georgia","city10"),("Texas","city1"), ("Texas","city2"), ("Texas","city3"), ("Texas","city4"), ("Texas","city5")]
sorted(lsNearCities, key=operator.itemgetter(0,1)) --> I assume this would sort based on states first and then cities second. And after that how should i accomplish the list which i needed using python. Please help would be appreciated.
How about this:
l = [("Texas","city1"), ("Texas","city2"), ("Texas","city3"), ("Texas","city4"), ("Texas","city5"),("Georgia","city6"), ("Georgia","city9"), ("Georgia","city10"),("Alabama","city7"), ("Alabama","city8")]
def cmp(x,y):
if x[0]<y[0]:
return -1
elif x[0]>y[0]:
return 1
elif x[1]<y[1]:
return -1
elif x[1]>y[1]:
return 1
else:
return 0
l.sort(cmp)
print l
By the way, this is the default sorting so if you don't want to do a different sort then you can just simply do:
l.sort()
You can change the cmp function for different sort modes. I'm not sure what you mean by "alphabetizing"?