Nicole Foster
Nicole Foster

Reputation: 381

Python issue with return statement

The code takes a list as input for example:

[1995, 1750, 2018] 

and I am expecting it to give back Basically, this code searches for the closest leap year for each year in a list of years

1996
1948
2016 

all in a separate line.

The output I get back with the return statement is:

1996 1748 2016

But the thing is I must use return because I use a map thing to write it to file, but I get

map argument #1 must support iteration

Is there a solution to my problem?

#!/bin/python3

import math
import os
import random
import re
import sys

def is_leap(year):
    leap = False

    if year % 4 == 0:
        if year % 100 != 0 or year % 400 == 0:
            leap = True

    return leap

forward_list = {}
back_list = {}
newLst = []

def year_forward(yearBounds):
    for item in yearBounds:
        counter = 0
        # forwad list
        while not is_leap(item):
            item = item + 1
            counter += 1
        #forward_list.append(item)
        forward_list[item] = counter
    return forward_list


def year_backward(yearBounds):
    # back_list
    for item in yearBounds:
        counter = 0
        while not is_leap(item):
            item = item - 1
            counter -= 1
        #back_list.append(item)
        back_list[item] = counter
    return back_list

def findLastLeapYears(yearBounds):

    forward =  (year_forward(yearBounds))
    backward = (year_backward(yearBounds))
    tuple_forward = list(forward.items())
    tuple_backward = list(backward.items())

    counter = 0
    for item in tuple_forward:
        if abs(item[1]) < abs(tuple_backward[counter][1]):
            newLst.append (item[0])
            counter+=1
        elif abs(item[1]) == abs(tuple_backward[counter][1]):
            if item[0] < tuple_backward[counter][0]:
                newLst.append (item[0])
                counter += 1
            else:
                newLst.append (tuple_backward[counter][0])
                counter += 1

        else:
            newLst.append (tuple_backward[counter][0])
            counter+=1

    return newLst

The call:

leapYears = findLastLeapYears(years)

fptr.write(' '.join(map(str, leapYears)))
fptr.write('\n')

fptr.close()

Upvotes: 0

Views: 127

Answers (2)

Ricky Kim
Ricky Kim

Reputation: 2022

For me, using your code, I can't reproduce the error and everything works fine.

The error map argument #1 must support iteration suggests that you're using str as a variable or function that overwrites the default str.

Upvotes: 0

tungd
tungd

Reputation: 14907

Your code runs fine, if you want it to be on separate line use '\n'.join(...) instead.

Upvotes: 1

Related Questions