Home > Net >  How to sum a list of arrays?
How to sum a list of arrays?

Time:07-24

New to python and got stuck.

I produced the below code to sum the cube of the digits of a given number. i.e. 123 -> 1 8 27 = 36

# split_cube used to seperate digits in number and cube in an array
# i.e 32 -> [27, 8]

def split_cube(n):
    return [int(x)**3 for x in str(n)]

# change n to number and run for sum of digits cubed
n = 123

a = split_cube(n)

def sum_of_digits_cubed(y):
    print(sum(a))

sum_of_digits_cubed(a)

output 36.

I now want to make a code that does this for all 3 digit number.

I've been able to write a code to list all the arrays, however I don't know how to sum them.

# split_cube used to seperate digits from number
# and cube in an array i.e 32 -> [27, 8]
# range is 100 - 999

def list_split_cube(n):
        for n in range(100,1000,1):
                print([int(x)**3 for x in str(n)])

a = list_split_cube(n)

print(a)

first 4 output is, it goes on:

[1, 0, 0]
[1, 0, 1]
[1, 0, 8]
[1, 0, 27]

However I want a list like this where it now sums the array. i.e. 1 2 9 28 etc.

However when I try toadd sum commands it errors because it iterates I believe.

My next aim will then be to only display the list where the sum of there digits cubed is equal to the number. i.e. 153 -> 1 125 27. However cant yet get to the point where it's showing a list of the summed array.

Is there a way to do this?

CodePudding user response:

Use the function you've already defined instead of copying and pasting it into your loop; the whole point of defining a function is that once you've defined it, it becomes a shortcut to do whatever is defined in the body of the function so you don't have to copy and paste that same code everywhere.

You can also apply the sum function to that list just like you did in sum_of_digits_cubed:

def split_cube(n):
    return [int(x)**3 for x in str(n)]

for n in range(100, 1000):
    print(sum(split_cube(n)))

prints:

1
2
9
28
65
126
217
344
513
730
2
...etc

For the next part (only printing the numbers where n is equal to sum(split_cubed(n)), you just need an if:

for n in range(100, 1000):
    if n == sum(split_cube(n)):
        print(n)

prints:

153
370
371
407
  • Related