简体   繁体   中英

Python3 print statement prints 0 instead of the actual return value of the function

I am doing AOC 2020 and I am seeing something weird with python3 print statement and I don't understand what's going on.

This question is day 6 part 1 and it is suppose to count a bunch of chars in a file and basically find out how many is counted.

This is my code below, and when I run it on my Pycharm 2020.3 in Win 10 with Python 3.5, these two print statements gives wildly different results:

The print(a) line gives me what I expect, the value returned from process_customs_data. The print(process_customs_data(customs_data)) gives me 0 which makes no sense shouldn't it print the return value of the function?

and just as an extra test I changed total_count =total_count + a with total_count =total_count + process_customs_data(customs_data) and both scenarios works. I can see my total count updated correctly.

在此处输入图像描述

import pprint
from aocd.models import Puzzle
from aocd import submit
import time

def process_customs_data(data):
    pprint.pprint(set(data))

    return len(set(data))

puzzle = Puzzle(year=2020, day=6)

raw = puzzle.input_data
data = raw.splitlines()

total_count = 0
customs_data = ""

for line in data:

    if line == '':
        a = process_customs_data(customs_data)
        total_count =total_count + a
        customs_data = ''
        print(a)
        print(process_customs_data(customs_data))
        time.sleep(5)
    else:
        customs_data = customs_data + line.strip()

print(total_count)


#submit(total_count, part="a", day=6, year=2020)

You print(process_customs_data(customs_data)) command prints the actual return value of the expression process_customs_data(customs_data) .

And if you are wondering, why that's different from a , then just see that you updated function argument customs_data = '' before calling your function.

In your function process_customs_data(data) you create a set that will contain all possible different characters from your string. For the call with the empty data it will be the empty set, so the len of the empty set is 0. And print prints this 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM