Onur
Onur

Reputation: 197

A function in my code is changing the given variable's value

hand = input("Enter your hand :")
handList = hand.split()
for i in range(0, len(handList)):
    handList[i] = int(handList[i])
handList.sort()
backup = handList
print(backup)
backup = simplify(backup)
sNumColor = sameNumber(backup)
print(f'List : {handList}')
print(f'Backup: {backup}')
sStraightNum = straightNumber(handList)
print("Different color but same number :", sNumColor[0])
print("Different number but same color (straight) :", sStraightNum[0], "New array is :", 
sStraightNum[1])

In the line 'sNumColor = sameNumber(backup)' it changes both handList and backup variables and I don't know why it is happening. Here is the functions.

def sameNumber(array):
    array = simplify(array)
    sameN = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, '10': 0, '11': 0, '12': 0, '13': 0}
    result = 0
    for n in range(1, 14):
        for item in array:
            if item == n:
                sameN[f'{n}'] += 1
    for n in range(1, 14):
        if sameN[f'{n}'] >= 3:
            result += 1
        elif 52 in array:
            if sameN[f'{n}'] == 2:
                result += 1
                array.remove(52)
    return result, array

def simplify(array):
    for n in range(len(array)):
        array[n] = int(array[n])
    for n in range(len(array)):
        if 0 <= int(array[n]) <= 12:
            array[n] = int(array[n]) + 1
        elif 13 <= int(array[n]) <= 25:
            array[n] = int(array[n]) - 12
        elif 26 <= int(array[n]) <= 38:
            array[n] = int(array[n]) - 25
        elif 39 <= int(array[n]) <= 51:
            array[n] = int(array[n]) - 38
    return array

In the function simplify it changes the values of the items in the array if its lower than 13 and etc. (Its about a table game which there is 4 different colors of the same 13 pieces. 0-12 is Yellow 0-1-2-3....-13 and the 13-25 is Black 1-2-3....-13) Can someone please tell me why this sameNumber() function is changing 2 variables without me giving one of it to the function.

Upvotes: 0

Views: 41

Answers (1)

AirSquid
AirSquid

Reputation: 11883

Your line of code:

backup=handList

isn't doing what you hoped for. :) This basically assigns a new variable backup to point to the same variable that is handList so now they both refer to the SAME object in memory. What you appear to want is a copy of handList so you should use:

backup=handList[:]

which is a cheap & easy way to create a new data structure (essentially a slice that is the whole list) and return it to your new variable name.

Upvotes: 1

Related Questions