Use a loop to go through each character of a string

Question:

Write a function named CoinStar that has one argument, a string containing just the characters p, n, d, and q (can be uppercase or lowercase). Each character represents a coin penny nickel dime and quarter

The function should return a float representing the value of the entire string in dollars,

def coinstar(yo):
    for i in (0,len(yo)):
        ye=0
        if i == 'p' or i =='P':
            ye + 0.01
        if i == 'n' or i =='N':
            ye+ 0.05
        if i == 'd' or i == 'D':
            ye + 0.10
        if i == 'q' or i == 'Q':
            ye+ 0.25
    return ye
print(coinstar('qdnp'))

Examples

coinstar('pppp') -> 0.04
coinstar('QdNnpqDqq') -> 1.31
coinstar('dpnx') -> -1
Asked By: Mattx21

||

Answers:

In your code change these

  • ye += 0.01 inteasd of ye + 0.01.
  • if i == 'p' or i =='P': to if i.lower() == 'p':
  • for i in (0,len(yo)): to for i in yo:
  • Declare ye=0 before the for loop

So, your function will be like this,

def coinstar(yo):
    ye = 0
    for i in yo.lower():
        if i == 'p':
            ye += 0.01
        if i == 'n':
            ye += 0.05
        if i == 'd':
            ye += 0.10
        if i == 'q':
            ye += 0.25
    return ye

Here another approach,

def coinstar(s):
    val = {'p':0.01, 'n': 0.05, 'd': 0.10,'q': 0.25}
    return sum(val.get(i) for i in s.lower())

coinstar('pppp')
# 0.04
Answered By: Rahul K P
def coinstar(yo):
    ye = 0
    yi = len(yo)
    for x in range(yi):
        yz = yo[x]
        if (yz == 'p' or yz == 'P'):
            ye = ye + 0.01
        elif (yz == 'n' or yz == 'N'):
            ye = ye + 0.05
        elif (yz == 'd' or yz == 'D'):
            ye = ye + 0.10
        elif (yz == 'q' or yz == 'Q'):
            ye = ye + 0.25
    return ye


print(coinstar('QdNnpqDqq'))
Answered By: kaann.gunerr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.