-5

Okay, editing for clarity, sorry about the confusion.

I need to count the number of occurrences of a number (we'll say 2) between 1 and n (user inputted positive number). That includes each time given number can go into each number between 1 and n.

So every instance of 2 in each number up to n. so 10 would be 5 in ten, plus 4 in 9, 4 in 8, 3 in 7, 3 in 6, 2 in 5, 2 in 4, 1 in 3, and 1 in 2. Remainders don't matter, I just need to count the 2s.

so a user inputting 10 should print 25, if my math is right.

I'm new and totally clueless.

As of right now, I basically have asking the user to input a number.

n = int (input("Enter a positive number between 1 and 1000"))

I had successfully gotten my code to divide by nine, but that isn't really what I'm trying to do. I think I need to convert everything between 1 and n to a string? Would that use a range like so 1:n? Is that even possible?

Then I could count how many of a certain number?

Thanks!

1 Answers1

1

Do you mean something along these lines?

def count(n):
    occurrences = 0
    for i in range(n, 0, -1):  # i -> n, n-1, n-2, ... 3, 2, 1
        occurrences += i//2    # add whole number of 2's in this value of i
    return occurrences

print(count(10))  # 25
print(count(9))   # 20

If what that does is correct, it can be optimized and shorted to just:

def count(n):
    return sum(i//2 for i in range(n, 0, -1))

Which applies the built-insum()function to agenerator expression.

Therange(n, 0, -1)is an iterator that produces all the numbers fromnto1backwards -- which I used since that's how you described what you wanted. Since doing it in that order doesn't really matter, it would probably be better (simpler) to just userange(1, n+1)which produces the sequence in ascending order (1, 2, 3, ... n-2, n-1, n).

martineau
  • 119,623
  • 25
  • 170
  • 301