Hello,
Im currently writing code for a program that translates a line of text from English into German then back again. Its a big loop that needs to be executed the same number of times as words in the text. I'm almost there but there doesn't seem to be anything on big for loops. I know the general idea but I cant get it to work with this one. any help would be great. This code is for the first word in the phrase.

def translate(phrase):
	words = phrase.split()
	position0 = english_to_german.index(words[0])
	position0 = position0 + 1
	german_0 = english_to_german[position0]
	location0 = german_to_english.index(german_0)
	location0 = location0 + 1
	english_0 = german_to_english[location0]
	print english_0

If I understand your code correctly, you have two lists. One list called english_to_german where you store the words in "pairs", i.e. index 0 is the english word, and index 1 is the german translation. And the other way around in german_to_english

The way you can do this with a for loop is:

for word in phrase.split():
    position = english_to_german.index(word) + 1
    german = english_to_german[position]
    location = german_to_english.index(german) + 1
    english = german_to_english[location]
    print(english)

However, this is a quite inefficient way to do it. My choice would be using two dicitonaries instead.

english_to_german = {}
german_to_english = {}
# populate the dicitonaries
# english_to_german['english_word'] = 'deutche_wort'
# and the other way around with the german_to_english

for word in phrase.split():
    german_word = english_to_german[word]
    english_word = german_to_english[german_word]
    print(english_word)

The reason why this is better, is because dictionaries uses O(1) time to look up a value. A list uses O(n) time to look it up. As your lists grow, the code will run slower and slower, but this is not the case with dictionaries :)

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.