1

This simple while loop that stops at a sentinel value and otherwise continuously asks for user input.
How would I use the incrementing line count variable to display after on what line the user inputted certain things? I would guess use of a dictionary is needed?

lineCount = 1
d = {} #is this needed?
q = raw_input("enter something")
while q != "no":
    lineCount += 1
    q = raw_input("enter something")
#code here that stores each new input with its respective line and prints what the user inputted on each corresponding line when the loop ends

Many thanks in advance

Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94
user7222454
  • 67
  • 1
  • 7

2 Answers2

1

Using array:

lines = []
def add_line(line):
    lines.append(line)

def print_lines():
    for i in range(len(lines)):
        print "%d: %s" % (i, lines[i])

lineCount = 1
q = raw_input("enter something")
add_line(q)
while q != "no":
    lineCount += 1
    q = raw_input("enter something")
    if q != "no":
        add_line(q)

print_lines()
Marek Nowaczyk
  • 257
  • 1
  • 5
0

Exactly like you said, using a dictionary:

d = {}
lineCount = 1
q = raw_input("enter something: ")
while q != "no":
    lineCount += 1
    q = raw_input("enter something: ")
    d[lineCount] = q

Then you could just query your dictionary if you want to know what the user input at a desired line as d[desired_line].

Assuming you have a simple dictionary, such as:

d = {2: 'b', 3: 'c', 4: 'd', 5: 'no', 6: 'c'}

Then if you'd like to print out the lines where a desired word appear you could define a function like so:

def print_lines(my_dict, word):
    lines = [line for line, ww in my_dict.iteritems() if ww == word]
    return lines

You could call this function with your dictionary (d) and the word your looking for, let's say 'c':

print_lines(d, 'c')

Finally, could iterate over the set of words (unique_words using set) you have and print the lines they appear on by calling the previous function:

def print_words(my_dict):
    unique_words = set([word for word in my_dict.itervalues() if word != 'no'])    
    for word in sorted(unique_words):
        print("'{0}' occurs in lines {1}".format(word, print_lines(my_dict, word)))

UPDATE (for sentences instead of single words):

In case you want to work with sentences, rather than single words per line, you'll need to modify your code as follows:

First, you could define a function to handle the user input and build the dictionary:

def build_dict():
    d = {}
    lineCount = 1
    q = raw_input("enter something: ")
    while q != "no":
        d[lineCount] = q        
        lineCount += 1
        q = raw_input("enter something: ")        
    return d

Let's say you build a dictionary like such:

d = {1: 'a x', 2: 'a y', 3: 'b x'}

Then you can define a helper function that tells you at which line a particular word occurs:

def occurs_at(my_dict, word):
    lines = [line for line, words in my_dict.iteritems() if word in words]
    return lines

Finally, you can query this function to see where all your words occur at (and you can decide which words to ignore, e.g. 'a').

def print_words(my_dict, ignored=['a']):
    sentences = [sentences.split(' ') for sentences in my_dict.itervalues()]
    unique_words = set([word for sentence in sentences for word in sentence])
    for word in sorted(unique_words):
        if word not in ignored:
            print("'{0}' occurs in lines {1}".format(word, occurs_at(my_dict, word)))
José Sánchez
  • 1,126
  • 2
  • 11
  • 20
  • 2
    Why not use a `list` and simply append the lines? Then you don't need the line counter. The only downside is that the line numbers start at zero. – Wombatz Dec 01 '16 at 13:47
  • Thanks José. Just a quick follow up, if the same word is inputted on more than one line, could you explain how would I get it so that when the loop ends, it just prints this word once from the dictionary, but then will show all the line numbers it appeared on? I'm not too good with dictionary formatting (as you can probably tell). – user7222454 Dec 01 '16 at 14:01
  • @Wombatz I agree. I guess I focused on the answer and didn't see the [gorilla](http://www.michaelchimenti.com/2015/05/spot-the-dancing-gorilla-to-code-better-python/) :). – José Sánchez Dec 01 '16 at 14:02
  • @user7222454, I updated my answer to show how to print the number of lines where the word appears. Is this what you had on mind? Let me know if I didn't understand your comment. – José Sánchez Dec 01 '16 at 14:11
  • Thanks again :). Returning multiple line numbers bit works fine, but if I just wanted to print all the words once without their duplicates, what would I have to pass in as the second parameter in the print_lines call? Or would this involve changes to the function itself? I.e. if inputs were 'a' 'b' 'c' 'c' 'd' 'no', how would it print something along the lines of: " 'a' 1" " 'b' 2 " " 'c' 3, 4 " " 'd' 5 " – user7222454 Dec 01 '16 at 14:27
  • @user7222454 Could you try the last function I added to the answer and see if it works for you? – José Sánchez Dec 01 '16 at 14:43
  • 1
    This works perfectly, had to alter the original loop slightly to put the dictionary appending before the line increment and new input, as this wasn't appending the first input to the dictionary. Thanks so much :) – user7222454 Dec 01 '16 at 15:05
  • Just one final query, if it isn't too much of a bother; how would I get it so that if the user types in "my x" on line 1 and "my y" on line 2, it prints that 'my' appears on both lines, and 'x' and 'y' appear on different lines? Right now it takes in everything on the same input line as one string and appends that to the dictionary. I imported string and tried a .split() function but this makes the input into a list, so it can't be appended to the dictionary – user7222454 Dec 01 '16 at 16:57
  • I'm not sure I get what you mean. Would you mind updating your question with a sample input and the expected output? – José Sánchez Dec 01 '16 at 19:08
  • Sure. So if the input is "a x" on line 1 and "a y" on line 2, how would the code need to be altered so that the final print is "a occurs on lines 1 and 2, " "x occurs on line 1" "y occurs on line 2" – user7222454 Dec 01 '16 at 19:13
  • I've updated the answer, let me know if it works as expected. – José Sánchez Dec 01 '16 at 21:31
  • Unfortunately it's throwing up an error about 'sentence' and 'sentences' in the print_words function being referenced before assignment. Where would these need to be defined? – user7222454 Dec 01 '16 at 22:44
  • My bad, I forgot to add that sentence. Good catch! Now it's updated. – José Sánchez Dec 01 '16 at 23:02
  • Thanks very much, this works now. Could you explain if there is a different way to write the final subroutine without using the set/sorted functions? As these are concepts that I am not too familiar with, so even if the code is longer it would be easier for me to understand what you are explaining – user7222454 Dec 02 '16 at 15:57
  • Dictionaries in Python are unordered (that's why I used the `sorted` function). You could use a `OrderedDict` from the `collections` library instead. I used `set`, since this ensures that the elements are unique (e.g. if you try to add an element that is already on the set it would ignore it, unlike if you use a list or a tuple). This [answer](http://stackoverflow.com/a/3489100/4788274) provides a nice and succinct explanation of list, sets and dicts; and their differences. Hope this helps. – José Sánchez Dec 02 '16 at 16:13