Skip to content Skip to sidebar Skip to footer

Python: How To Track Two Or More Equal Variables In A While Loop

I am trying to count the amount of names that follow the first name in a line of a .txt file to determine who has the most names after them using python using the following code: l

Solution 1:

Not giving a direct answer to homework, but a technique you can use to solve this and future problems you may face: add print statements to your code to understand what is happening. For example, if we add the 2 print statements below:

for word in follows:
    lines += 1
    f1=word.split()
    wordCount=wordCount+len(f1)
    print("f1 = {}, mostWordsInLine = {}".format(f1, mostWordsInLine))
    if len(f1) > mostWordsInLine:
        mostWordsInLine = len(f1)
        mostWordsInLine = word[: word.find(' ')]
    print("    after comparison: mostWordsInLine = {}".format(mostWordsInLine))

It will print the following output:

f1 = ['andrew', 'fred'], mostWordsInLine = 0
    after comparison: mostWordsInLine = andrewf1= ['fred'], mostWordsInLine = andrew
    after comparison: mostWordsInLine = andrewf1= ['judy', 'andrew', 'fred'], mostWordsInLine = andrew
    after comparison: mostWordsInLine = andrewf1= ['george', 'judy', 'andrew'], mostWordsInLine = andrew
    after comparison: mostWordsInLine = andrewf1= ['john', 'george'], mostWordsInLine = andrew
    after comparison: mostWordsInLine = andrewf1= [], mostWordsInLine = andrew
    after comparison: mostWordsInLine = andrew
Most social user: andrew

The first time one of the output lines does not make sense, see if you can figure out why.

Solution 2:

wordCount=0
mostWordsInLine = 0
follows = open("follows.txt", "r")
mostFollows = []


for word in follows:
    f1=word.split()
    wordCount += len(f1)
    iflen(f1) > mostWordsInLine:
        mostWordsInLine = len(f1)
        mostFollows = [f1[0]]
    eliflen(f1) == mostWordsInLine:
        mostFollows.append(f1[0])


print ("Most social user: " + ''.join(mostFollows))

Solution 3:

The string library has a .count('name') function. So you could count each element in the for loop and compare them all. You need to clarify the problem because andrew and fred occur three times.

"Makes sense....First have a list of unique names [names]. Then use a dictionary to store them. {name:[list_names] then len(string) . Write a function that iterates the dictionary and retrieves the dictionary with the most speakers."

Post a Comment for "Python: How To Track Two Or More Equal Variables In A While Loop"