Get the number of same string in a list - python

I want to get the no. of same string in a list
Example
list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
Output
2
I have tried this so far
def getnumber(string_var,list):
if any(string_var in s for s in list):
print("This user exits !")

There's a built-in method count that does this.
number_of_jeen = list.count('jeen')

Use Counter from collections:
list = ['jack','jeen','jeen']
count = Counter(list)
print(count['jeen'])

Try just using a simple counter function. The idea is to loop through the list you have. In each iteration you are checking whether or not the name you are looking at is equal to 'jeen' in this case. If it is increment your counter, otherwise just move onto the next name. Below is an example:
listNames = ['jack','jeen','jeen']
occurrences = 0
for i in listNames:
if(i == 'jeen'):
occurrences += 1
print(occurrences)

Related

Counting how many of a certain character there are in a string with one while and one for loop in python

I was given a question with a random string such as
example = ‘asdkfkebansmvajandnrnndklqjjsustjwnwn’
and was asked to find the number of a’s in this string with a while and with a for loop
So simply using the count() function like this is not allowed:
print('# of a:’, example.count(‘a’))
We were given one example: (and were told to find a different way)
counter = 0
for letter in example:
if letter == ‘a’:
counter = counter + 1
print(counter)
I’m very new to python and I really can’t find a way. I thought of converting this string into a list that contains every character as a different object like this:
example_list = list(example)
but then I still couldn't find a way.
We were given two starting points, so the end code has to be in a somewhat similar format and we're not really allowed to use more advanced functions (simple string or list functions and if-statements are allowed as far as I know).
For while-loop:
counter = 0
while counter < 4:
print(example_list[counter])
counter += 1
And for for-loop:
for counter in range(0, len(example_list)):
print(counter, example[counter])
I either end up printing every single character with its position, or I end up printing the number without actually using the loop.
I think the advises tell you that you have to iterate through array using a counter.
Here is the example for while loop:
example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
counter = 0
a_count = 0
while counter < len(example):
if example[counter] == 'a':
a_count += 1
counter += 1
print(a_count)
And for for-loop it might look like this:
for counter in range(len(example)):
if example[counter] == 'a':
a_count += 1
Note that converting to a list isn't necessary, since you can iterate over a string exactly the same way that you'd iterate over a string that's been converted into a list.
For your first starting point, I think the idea is to iterate by index:
index = 0
counter = 0
while index < len(example):
if example[index] == 'a':
counter += 1
index += 1
And the for-loop version would be:
counter = 0
for index in range(len(example)):
if example[index] == 'a':
counter += 1
Note: iterating by index like this is actually considered bad practice in Python (because it's basically just adding unnecessary work), and the preferred method is to iterate by value, as in the example you were given and then told not to use.
Two functions, while_count and for_count, to achieve what you need:
def while_count(s):
counter, i = 0, 0
while i < len(s):
if s[i] == "a":
counter += 1
i += 1
return counter
def for_count(s):
counter = 0
for i in range(len(s)):
if s[i] == "a":
counter += 1
return counter
You can make the for case much simpler using a list comprehension:
def for_count2(s):
return sum([x=="a" for x in s])
Here is the solution for your question
1.Using for loop
example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
count=0
for i in example:
if i.lower()=='a':
count+=1
print(count)
2. Using While loop:
example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
loop_count=0
a_counter=0
lis=list(example)
while loop_count<len(example):
if lis[loop_count]=='a':
a_counter+=1
loop_count+=1
print(a_counter)
Might it help if it does vote my ans up

In a function ,How can I assign the value to a set?

I'm trying to make a program that finds the perfect number.(Perfect number=The sum of its divisors except itself is a number equal to itself.)And I want to add one more thing. Firstly I want to define an empty list and put the perfect numbers in it.But When I run the programm I didn't take the right throughput.How can I solve this problem.
My cods
def perfect(number):
total = 0
for i in range(1,number):
if number % i == 0:
total += i
return total
perfect_number_set = []
for i in range(1,1001)
if perfect(i):
perfect_number_set += [perfect(i)]
print(perfect_number_set)
print(i)
The output of the codes I wrote
[True]
6
[True,True]
28
[True,True,True]
You have following issues in your code:
Your implementation of perfect method is incorrect. You need to return True/False if a number is perfect. You are returning the total which is not correct.
Missing colon : in the for loop
def perfect(number):
total = 0
for i in range(1,number):
if number % i == 0:
total += i
return total == number
perfect_number_list = []
for i in range(1,1001):
if perfect(i):
print(i)
perfect_number_list.append(i)
print(perfect_number_list)
There is a difference between set and a list in python. You have used a list.
Set contains only unique entries.
Best practice tip:
defining a list use :
list_name = list()
Better way of adding items to as list by using it's method
list_name.append(list_item_to_add)
Another thing is that returning a number and checking it in if without any condition is not readable. Change it to:
if perfect(i) != 0:
(Altho Yours implementation work, because python if treats 0 like False and any other value as True)

how to count values inside of an array and convert them into a dictionary

I have a program that returns a set of ages inside of an array and I want to count them and put them inside of a dictionary, I have tried the following but no results. Please help!
let's say I have an array as follows:
ages = [20,20,11,12,10,11,15]
# count ages inside of array, I tried this
for i in set(ages):
if i in ages:
print (ages.count(i))
# result returns the following
1
2
1
1
2
this makes perfect sense as if we look at the set(ages) it equals = {10,11,12,15,20}
so the returning count actually equals to the count of each value in ages
When I try to put in a variable though, it only appends the first number or it says it is not iterable!
How can I store it into a list, even better how can I make dictionary containing the set(ages) and the count for each of the set(ages)
Thank you
try this!
ages = [20,20,11,12,10,11,15]
dic = {x:ages.count(x) for x in ages}
print dic
There are a lot of different ways to achieve this. The first, and likely easiest, is to import the Counter class from collections.
from collections import Counter
ages = [20,20,11,12,10,11,15]
counts = Counter(ages)
# Counter({10: 1, 11: 2, 12: 1, 15: 1, 20: 2})
# if you want to strictly be a dictionary you can do the following
counts = dict(Counter(ages))
The other way is to do it in a loop:
counts = {}
for a in ages:
# if the age is already in the dicitonary, increment it,
# otherwise, set it to 1 (first time we are seeing it)
counts[a] = counts[a] + 1 if a in counts else 1
And finally, dict comprehension. It has really no advantage over the loop other than the fact that it's a single line. You still end up iterating over each variable in the list:
counts = {a:ages.count(a) for a in ages}
Since you asked more about the ternary operator, that loop is equivalent to saying:
counts = {}
for a in ages:
# if the age is already in the dicitonary, increment it,
# otherwise, set it to 1 (first time we are seeing the number)
if a in counts:
counts[a] = counts[a] + 1
print("Already seen", a, " -- ", counts[a])
else:
counts[a] = 1
print("First time seeing", a, " -- ", counts[a])
The ternary operator allows us to complete this pattern in a single line. Lots of languages have it:
C/C++/C#
JavaScript
If you need to store counts, better you use Python dicts.
ages = [20,20,11,12,10,11,15]
age_counts={} #define dict
for i in ages:
#if age_counts does not have i, set its count to 1
#increment otherwise
if not age_counts.has_key(i):
age_counts[i]=1
else:
age_counts[i]+=1
#you can now have counts stored
for i in age_counts:
print i, age_counts[i]

Intro to Python - Lists questions

we've started doing Lists in our class and I'm a bit confused thus coming here since previous questions/answers have helped me in the past.
The first question was to sum up all negative numbers in a list, I think I got it right but just want to double check.
import random
def sumNegative(lst):
sum = 0
for e in lst:
if e < 0:
sum = sum + e
return sum
lst = []
for i in range(100):
lst.append(random.randrange(-1000, 1000))
print(sumNegative(lst))
For the 2nd question, I'm a bit stuck on how to write it. The question was:
Count how many words occur in a list up to and including the first occurrence of the word “sap”. I'm assuming it's a random list but wasn't given much info so just going off that.
I know the ending would be similar but no idea how the initial part would be since it's string opposed to numbers.
I wrote a code for a in-class problem which was to count how many odd numbers are on a list(It was random list here, so assuming it's random for that question as well) and got:
import random
def countOdd(lst):
odd = 0
for e in lst:
if e % 2 = 0:
odd = odd + 1
return odd
lst = []
for i in range(100):
lst.append(random.randint(0, 1000))
print(countOdd(lst))
How exactly would I change this to fit the criteria for the 2nd question? I'm just confused on that part. Thanks.
The code to sum -ve numbers looks fine! I might suggest testing it on a list that you can manually check, such as:
print(sumNegative([1, -1, -2]))
The same logic would apply to your random list.
A note about your countOdd function, it appears that you are missing an = (== checks for equality, = is for assignment) and the code seems to count even numbers, not odd. The code should be:
def countOdd(lst):
odd = 0
for e in lst:
if e%2 == 1: # Odd%2 == 1
odd = odd + 1
return odd
As for your second question, you can use a very similar function:
def countWordsBeforeSap(inputList):
numWords = 0
for word in inputList:
if word.lower() != "sap":
numWords = numWords + 1
else:
return numWords
inputList = ["trees", "produce", "sap"]
print(countWordsBeforeSap(inputList))
To explain the above, the countWordsBeforeSap function:
Starts iterating through the words.
If the word is anything other than "sap" it increments the counter and continues
If the word IS "sap" then it returns early from the function
The function could be more general by passing in the word that you wanted to check for:
def countWordsBefore(inputList, wordToCheckFor):
numWords = 0
for word in inputList:
if word.lower() != wordToCheckFor:
numWords = numWords + 1
else:
return numWords
inputList = ["trees", "produce", "sap"]
print(countWordsBeforeSap(inputList, "sap"))
If the words that you are checking come from a single string then you would initially need to split the string into individual words like so:
inputString = "Trees produce sap"
inputList = inputString.split(" ")
Which splits the initial string into words that are separated by spaces.
Hope this helps!
Tom
def count_words(lst, end="sap"):
"""Note that I added an extra input parameter.
This input parameter has a default value of "sap" which is the actual question.
However you can change this input parameter to any other word if you want to by
just doing "count_words(lst, "another_word".
"""
words = []
# First we need to loop through each item in the list.
for item in lst:
# We append the item to our "words" list first thing in this loop,
# as this will make sure we will count up to and INCLUDING.
words.append(item)
# Now check if we have reached the 'end' word.
if item == end:
# Break out of the loop prematurely, as we have reached the end.
break
# Our 'words' list now has all the words up to and including the 'end' variable.
# 'len' will return how many items there are in the list.
return len(words)
lst = ["something", "another", "woo", "sap", "this_wont_be_counted"]
print(count_words(lst))
Hope this helps you understand lists better!
You can make effective use of list/generator comprehensions. Below are fast and memory efficient.
1. Sum of negatives:
print(sum( i<0 for i in lst))
2. Count of words before sap: Like you sample list, it assumes no numbers are there in list.
print(lst.index('sap'))
If it's a random list. Filter strings. Find Index for sap
l = ['a','b',1,2,'sap',3,'d']
l = filter(lambda x: type(x)==str, l)
print(l.index('sap'))
3. Count of odd numbers:
print(sum(i%2 != 0 for i in lst))

Python number to word converter needs a space detector

I have been working on a sort of encryption tool in python. This bit of code is for the decryption feature.
The point is to take the given numbers and insert them into a list from where they will be divided by the given keys.
My idea for code is below but I keep getting the out of list index range whenever I try it out. Any suggestions? Keep in mind I'm a beginner:
need = []
detr = raw_input('What would you like decrypted?')
count = 0
for d in detr:
if (d == '.' or d == '!') or (d.isalpha() or d== " "):
count +=1
else:
need[count].append(d)
The problem is you are attempting to overwrite list values that don't exist.
list.append(item) adds item to the end of list. list[index] = item inserts item into list at position index.
list = [0,0,0]
list.append(0) # = [0,0,0,0]
list[0] = 1 # [1,0,0,0]
list[99] = 1 # ERROR: out of list index range
You should get rid of the count variable entirely. You could append None in the case of d==' ' etc. or just ignore them.
The way I understood your description you want to extract the numbers in a string and append them to a list using a for-loop to iterate over each character.
I think it would be easier doing it with regular expressions (something like r'([\d]+)').
But the way joconner said: "get rid of the count variable":
need = []
detr = input('What would you like decrypted?\n')
i = iter(detr) # get an iterator
# iterate over the input-string
for d in i:
numberstr = ""
try:
# as long as there are digits
while d.isdigit():
# append them to a cache-string
numberstr+= d
d = next(i)
except StopIteration:
# occurs when there are no more characters in detr
pass
if numberstr != "":
# convert the cache-string to an int
# and append the int to the need-array
need.append( int(numberstr) )
# print the need-array to see what is inside
print(need)

Categories