Python Forum
Help on adding two lists recursively
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help on adding two lists recursively
#2
def recursive_sum(l1, l2, idx=0, carryout=0):
    if idx < min(len(l1), len(l2)):
        l1 = l1[::-1]
        l2 = l2[::-1]
        n = int(l1[idx]) + int(l2[idx]) + carryout
        carryout = 0
        if n > 999:
            carryout = int(n/1000)
            n -= 1000*carryout
        return recursive_sum(l1, l2, idx + 1, carryout) + [n]
    else:
        return [carryout] if carryout else []


l1 = ['001', '234', '567']
l2 = ['007', '894', '561']
# l2 = ['999', '166', '568']
print(recursive_sum(l1, l2))
Reply


Messages In This Thread
RE: Help on adding two lists recursively - by gontajones - Sep-16-2018, 04:36 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Modifying a dictionary recursively SpongeB0B 2 352 May-12-2024, 04:09 PM
Last Post: Gribouillis
  How to return the next page from json recursively? sandson 0 1,262 Apr-01-2022, 11:01 PM
Last Post: sandson
  Help Needed | Read Outlook email Recursively & download attachment Vinci141 1 4,248 Jan-07-2022, 07:38 PM
Last Post: cubangt
Star Recursively convert nested dicts to dict subclass Alfalfa 1 3,043 Jan-22-2021, 05:43 AM
Last Post: buran
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,579 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Python script that recursively zips folders WITHOUT nesting the folder inside the zip umkc1 1 3,050 Feb-11-2020, 09:12 PM
Last Post: michael1789
  How to get full path of specified hidden files matching pattern recursively SriRajesh 4 4,142 Jan-18-2020, 07:12 PM
Last Post: SriRajesh
  Adding markers to Folium map only adding last element. tantony 0 2,273 Oct-16-2019, 03:28 PM
Last Post: tantony
  Find a given file recursively inside a directory alinaveed786 1 2,048 Jul-01-2019, 01:53 PM
Last Post: ichabod801
  adding lists to lists? ivinjjunior 5 3,282 Apr-15-2019, 07:41 PM
Last Post: ivinjjunior

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020