0

I just want to do something for transformation my string into view like: (2 ** 5)(5)(7 ** 2)(11), but my code works wrong. tell me please, where are my mistakes?!

values = [(2, 5), (5, 1), (7, 2), (11, 1)]
result = str(f'({i[0]}**{i[1]})' for i in values if i[1] != 1 else f'({i[0]})')
print(result) # (2 ** 5)(5)(7 ** 2)(11)

3 Answers 3

2

this is a variant:

values = [(2, 5), (5, 1), (7, 2), (11, 1)]
result =  ''.join(f'({base} ** {exp})' if exp != 1 else f'({base})' 
                  for base, exp in values)
print(result) # (2 **  5)(5)(7 ** 2)(11)

where i use tuple unpacking to assign base and exp to the items of your list and then str.join (in the form ''.join(...)) to join the individual terms.

so in the first iteration you get base=2, exp=5 which will be converted to the string '(2 ** 5)'; on the second iteration you get base=5, exp=1which will be converted to the string '(5)' (and so on); then these strings will be joined with '' (i.e. an empty string) in between.

Sign up to request clarification or add additional context in comments.

Comments

1

Place your ternary operator before the list comprehension part:

result = "".join([
    f'({i[0]} ** {i[1]})' if i[1] != 1 else f'({i[0]})'
    for i in values 
])
print(result) # (2 ** 5)(5)(7 ** 2)(11)```

1 Comment

you create an unnecessary list in your join; a generator expression would do there.
0

that is my decision. thank to all!

result =  ''.join('({} ** {})'.format(i[0], i[1]) if i[1] != 1 else '({})'.format(i[0]) for i in values)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.