2

I'm looking at a challenge to build a Floyd's triangle out of integers using only arithmetic operators and a single for-loop. There are hundreds of tutorials using dual for-loops and string operations, but I haven't seen anything using math.

Example output using repeating integers:

1
22
333
4444

I'm approaching the solution logic like so:

1 * (1) = 1
2 * (1 + 10) = 22
3 * (1 + 10 + 100) = 333

As a newb Python learner I can't construct the logic loop. Any ideas or alternative approaches? No string operations allowed here, just math!

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
NickNaym99
  • 35
  • 5
  • If you use hex, you can go past 9 rows – Mad Physicist Jul 16 '22 at 18:11
  • When you're trying to convert some logic to a loop, think about how you can express the key logic of the loop as a function of the counter. For your example, you've recognized that you need to multiply the loop counter by some factor (1, 11, 111, ...), and you've recognized that 111 = 1 + 10 + 100. Next, note that `1 = 10**0`, `10 = 10**1`, `100 = 10**2`, and so on. This tells you that the `i`th line of your output is going to be `i * sum(10**x)`, where `x` goes from `0` to `i-1` – Pranav Hosangadi Jul 16 '22 at 18:17
  • Thanks for the answers. Using sum(10**x) threw a 'not iterable' error since the input isn't an iterable list. Also, the challenge forbids using more than one for-loop. The solution from Benjamin Merchin does work. But it's still more code than allowed by the challenge. If I missed the concept of sum() let me know. I'm happy to learn. – NickNaym99 Jul 16 '22 at 19:25

1 Answers1

6

this works for me :)

n = 4

val=0
for i in range(n):
    val+=10**i
    print(val*(i+1))

Val is 1, then 11, then 111. I'm not sure if this is what you are expecting.

Benjamin Merchin
  • 1,029
  • 6
  • 11
  • Use base 16 and print `hex(val * (i + 1))` :) – Mad Physicist Jul 16 '22 at 18:13
  • The += approach works with a slight variation by using (i-1) as the power. That results in 1*1 = 1 as the first number in the triangle. A further part of the challenge is to get the code down to two lines, and this is four lines. But it's way better than what I had before. – NickNaym99 Jul 16 '22 at 19:00
  • 1
    Interesting, you can do it in two lines like that: `val=0` `for i in range(n):val+=10**i;print(val*(i+1))` – Benjamin Merchin Jul 16 '22 at 20:29
  • That did it! I wasn't familiar with the semi-colon separator, so I just learned something new for making my code more compact. Thanks, I appreciate that. – NickNaym99 Jul 17 '22 at 01:20