I have a dictionary like this:
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2,3]}.
I need to do for example: In the key 1 I have the list [2,3,4]. I have to count the number of connections between the element of the list as value in all the keys.
So I have to verify if in key 2 there are as elements 3or 4 and also the key 3with the element 4.
This research has to continue for all the key of the dictionary d.
At the end of searching in all the keys, I had to count the number of the couples found. In the example I have only count=2 because key 2 is connected with 3 and 4, but 3 isn't connected to 4. Repetitions aren't required. So I'm not interested in the couple 4-2 if I had already found (and counted) the couple 2-4.
I tried to implement for the first key:
`
d={}
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2,3]}
values=[]
count = 0
#for key in d:
values = d[1]
for value in values:
for i in (d[value]):
print "i: ",i
if i in values:
count += 1
print " count: ", count
print ".........."
print(count)
`
But, in this way count=5 because it count also the reversed couples. I have to specify something so count will be count=3. How can do that?
d={}
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2]}
print d
values=[]
for key in d:
count = 0
values = d[key]
for value in values:
for i in (d[value]):
if i in values:
count += 1
print "count: ",count/2, " key: ", key
Related
I wish to create a program in Python that prompts the user to enter a number of integer values. The
program stores the integers, counts the frequency of each integer and displays the frequency
as per the below image.
I have the following code but I don't know how to execute the final step (i.e. print "1 occurs 2 times" and below that "2 occurs 3 times" etc)
selection = int(input("Input the number of elements to be stored in the list: "))
counter = 1
valuesList = []
while counter <= selection:
value = input("Element - " + str(counter) + ": ")
valuesList.append(value)
counter +=1
#count number occurrences of each value
import collections
counter=collections.Counter(valuesList)
#create a list for the values occurring and a list for the corresponding frequencies
keys = counter.keys()
values2 = counter.values()
print("The frequency of all elements in the list: ")
Below the last print should be a series of print commands: keys[0] + "occurs" + values2[0] + "times" and continue for the all values within 'keys'. But I don't know how to print for all values in the list if the length of the list changes depending on the original 'selection' input.
Something like this is a compact solution for what you need using list comprehension and the count function of lists
print('The frequency of all elements of the list :')
print('\n'.join({f'{i} occurs {valuesList.count(i)} times' for i in valuesList}))
You can use itertools library. This should work for you.
import itertools
print("The frequency of all elements in the list: ")
for key, vals in itertools.zip_longest(keys, values2):
print("{0} occurs {1} times".format(key, vals))
For a current research project, I am planning to measure the relative occurrence of a unique word within a JSON file. Currently, I have an indicator for the number of unique words within the file and their corresponding number of occurrences (e.g. "technology":"325") but am still lacking a method for a full word count.
The code as I am using for a full word count (total = sum(d[key])) yields the following notification. I have checked some solutions for similar problems but not found an applicable answer yet. Is there any smart way to get this solved?
total = sum(d[key]) - TypeError: 'int' object is not iterable
The corresponding code section looks like this:
# Create an empty dictionary
d = dict()
# processing:
for row in data:
line = row['Text Main']
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Remove the punctuation marks from the line
line = line.translate(line.maketrans("", "", string.punctuation))
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
# Count the total number of words
total = sum(d[key])
print(total)
https://docs.python.org/3/library/functions.html#sum
You are trying to sum(iterable, /, start=0) an integer. This doesn't make sense, because sum is meant to be called on an iterable. A brief explanation of an iterable is that it's something that you could use a for loop on. For example, a list.
You could either modify your # Print the contents of dictionary loop in one of the two following ways:
# Print the contents of dictionary
total = 0
for key in list(d.keys()):
print(key, ":", d[key])
# Count the total number of words
total += d[key]
print(total)
print("Actual total: ," total)
Or, more condensed:
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
# Get the total word count
total = sum(d.values())
python's built-in sum function takes iterable as argument, but you trying to pass an single number to it. your code is equivalent to
total = sum(1)
but sum function need add something iterable to compute sum from. e.g.
sum([1,2,3,4,5,6,7])
if you want to compute total number of words you can try:
sum(d.values())
d=dict()
d['A']=1
d['B']=2
d['C']=3
total = sum(d.values())
print total
for key in list(d.keys()):
print(key, ":", d[key], float(d[key])/total)
#Count the total number of words
d[key] is a single int
d.values() is a list
There is dictionary in python.key and value spelling is compared.if the mistake is greater than or equal to 2 than print incorrect
input={"their":"thuyr"}
output=incorrect(because t=t,h=h but e!=u,i!=y).
My problem is that i was unable to compare t==t,h==h,e==u,i==y.
The below code shows count value 22 but count value must be 2 because only two words mismatches with their
def find_correct(words_dict):
count=0
for key,value in words_dict.items():
for val in value:
for ky in key:
if(val!=ky):
count+=1
return count
print(find_correct({"their":"thuor"}))
It's because you're using nested loops. It's comparing each letter of "t" in "their" with each 5 letters in "thuor". Instead, just use a single loop like this:
def find_correct(words_dict):
count=0
for key,value in words_dict.items():
for val, ky in zip(value, key):
if(val!=ky):
count+=1
return count
the question was actually like
Write a program that says the number of terms to be replaced to get all the numbers same in the list
ex
a=[1,1,2,1,1,4,1,1]
then the expected output is 2
I guess you are looking for the minimum number of numbers to be replaced so that all numbers are the same.
# store occurrences of each number in a dictionary
d = {}
for i in a:
if i not in d:
d[i] = 1
else:
d[i] += 1
# get key with max value: i.e. most frequent number in initial list
max_k = max(d, key=d.get)
# delete element that appears most often in the initial list
del d[max_k]
# count rest of the numbers => numbers to be replaced
nums_to_replaces = sum([d[k] for k in d])
Your wording is a bit strange.
If you want the number of items that are not one:
len([i for i in a if i!=1])
or
len(a)-a.count(1)
if you want the unique set of numbers that are not repeated as the question says:
len([i for i in set(a) if a.count(i)==1])
You could iterate over the list and make a dictionary of the occurrence:
occurrences = {}
for x in range(len(a)):
if a[x] not in occurences:
occurrences[x] = 1
else:
occurrences[x] += 1
Now you could have a dict of the occurrences and you could do this to get the number of terms to be replaced:
nums = list(occurrences.values()).sort(reverse=True) # Sort I descending order with num of repetitions
print(sum(nums[1:])) # Add occurrences of all but the element with max occurrences
#Or just subtract the max occurrence from the length of list
print(len(a) - max(list(occurrences.values())))
This will give you the least number of changes need to be made. In this way you cannot specify which element you want the whole list to contain
mik=[]
def(example):
for i in range(count):
for j in range(count):
"function etc."
a = str(mar)
b = str(chi)
c = float(dist)
d = float(dost)
mylist=[a,b,c,d]
if c>0:
if d>c:
mik.append(a)
print a
Now i get the output for example
AB01
AB02
AB02
AB04
BH22
I'm trying to find the most common word (yes even if there is 2 or 3 etc. that occur that amount of times) in this (list? array? set?) and print the times it occurs (yes even if there is 2 or 3 etc.) and print the number of times that element occurs as well. Do I need to define another function? I tried that and the mik was out of range. I've tried min and max and im realazing that dosent work on strings, at least mine,these in this case. Would sorting do something?
From this im trying to output
Minimum Occurrence Number: 1
Codes that Occur this much: ABO1 ABO4 BH22
Maximum Occurrence Number: 2
Codes that Occur this much: ABO2
Use the collections module and Counter.
What you are trying to do can be done by:
from collections import Counter
common = Counter(yourList).most_common()
min = common[0][1]
print "Minimum Occurrence Number: {0}".format(min)
print "Codes that Occur this much:"
for item in common:
if item[1] != min:
break
print item[0]
max = common[-1][1]
print "Maximum Occurrence Number: {0}".format(max)
print "Codes that Occur this much:"
for item in reversed(common):
if item[1] != max:
break
print item[0]