text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Mon Oct 29 21:09:19 2018 @author: 程甜甜 """ def merge_sort(array): if len(array) <= 1: return array num = int(len(array)//2) left = merge_sort(array[:num]) right = merge_sort(array[num:]) return merge(left,right) def merge(left,right): l,r = 0,0 result = [] while l<len(left) and r<len(right): if left[l] < right[r]: result.append(left[l]) l += 1 else: result.append(right[r]) r += 1 result += left[l:] result += right[r:] return result array = [23,3,18,4,65,0,9] print (merge_sort(array))
def binSearch(lst, item): mid = len(lst) //2 found = False if lst[mid] == item: found = True return found if mid == 0: #mid0ҵһԪˡ found = False return found else: if item > lst[mid]: #Һ벿 #print(lst[mid:]) return binSearch(lst[mid:], item) else: return binSearch(lst[:mid], item) #ǰ벿
def merge(left, right): res = [] while left and right: if left[0] < right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) res = res + left + right return res def mergesort(lists): if len(lists) <= 1: return lists mid = len(lists)//2 left = mergesort(lists[:mid]) right = mergesort(lists[mid:]) return merge(left,right)
def selection_sort(alist): for i in range(0, len (alist)): min = i for j in range(i + 1, len(alist)): if alist[j] < alist[min]: min = j alist[i], alist[min] = alist[min], alist[i] return alist alist = [4,2,5,7,21,3,14,35,23] print(selection_sort(alist))
#QuickSort by Alvin def QuickSort(myList,start,end): #判断low是否小于high,如果为false,直接返回 if start < end: i,j = start,end #设置基准数 base = myList[i] while i < j: #如果列表后边的数,比基准数大或相等,则前移一位直到有比基准数小的数出现 while (i < j) and (myList[j] >= base): j = j - 1 #如找到,则把第j个元素赋值给第个元素i,此时表中i,j个元素相等 myList[i] = myList[j] #同样的方式比较前半区 while (i < j) and (myList[i] <= base): i = i + 1 myList[j] = myList[i] #做完第一轮比较之后,列表被分成了两个半区,并且i=j,需要将这个数设置回base myList[i] = base #递归前后半区 QuickSort(myList, start, i - 1) QuickSort(myList, j + 1, end) return myList myList = [49,38,65,97,76,13,27,49] print("Quick Sort: ") QuickSort(myList,0,len(myList)-1) print(myList)
def QuickSort(myList,low,high): i,j = low,high if i >= j: return base = myList[i] while( i<j ): while (i < j) and (myList[j] >= base): j = j - 1 myList[i] = myList[j] while (i < j) and (myList[i] <= base): i = i + 1 myList[j] = myList[i] myList[i] = base QuickSort(myList, low, i - 1) QuickSort(myList, i + 1, high) myList = [] print("请输入需要6个需要排序的数:") x=0 while x<6: myList.append(input()) x=x+1 print(myList) print("Quick Sort:")
even_numbers = [x for x in range(1,101) if x % 2 ==0] print (even_numbers) odd_numbers = [x for x in range(1,101) if x % 2 != 0] print (odd_numbers)
#list l1=[12,4,12,45,223,7,"a","s",True] print (l1) print (type(l1)) print (l1[4]) print (l1[-1]) name = l1[-2] print (name) #list[start:end:step] print (l1[0:3]) l2 = [1,2,3,4,[5,6,7,],8,9,0] print (l2) print (l2[4]) print (l2[4][1])# it print the inner list 1 st position print (l2[4][1:])# it print the inner list 1st position ansd rest l3=[ [1,2,3], [4,5,6], [7,8,9]] print (l3) print (l3[2]) print (l3[2][0]) print (l3[2][0:2:1])
#input from user name = input("enter your name: ") age = int(input("enter your age :")) loc = input("enter your location :") pin = input("enter your pin code :") data ="your name is {} , your age is {} , your location is {} , your pincode is {}" output=data.format(name,age,loc,pin) print (output) # below example firm udemy # First, create a variable called start, and set it equal to "I am ". # Remember the space after the word "am" ! start ="I am " # Next, create a variable called age and set it equal to your age in years. # This must be a number age = 32 # Next, create a variable called end, and set it equal to " years old". # Remember the space before the word "years" end =" years old" # Next, create a variable called output, and use the format() function to add # together the start, age and end variables. output=start+str(age)+end # An example output string would be "I am 15 years old" print(output) # Finally, print the output to the screen using the print() function.
import random from kivy.app import App from action import Action NONE = 0 S = 1 O = 2 class Turn: """ The class for turns """ def __init__(self, num): """ The constructor :param num: Turn number in the game """ self.choice = NONE self.done = False self.num = num def s(self): """ :return: Changes the choice to S """ self.choice = S def o(self): """ :return: Changes the choice to O """ self.choice = O def put(self): """ :return: Used to mark that the player has finished his turn """ self.done = True class AITurn(Turn): """ The class for the turns that are fons by the computer """ def __init__(self, num): """ The constructor :param num: the number of the turn in the game """ Turn.__init__(self,num) self.defends = dict() self.defendo = dict() self.attacks = dict() self.attacko = dict() def doPriorityMove(self): """ :return: finds the preferred move, if there are some 'best' possible moves it chooses randomally """ grid = App.get_running_app().game.board.grid for r in range(9): for c in range(9): if grid[r][c].text == '': self.attacks[(r, c)] = 0 self.attacko[(r, c)] = 0 self.defends[(r, c)] = 0 self.defendo[(r, c)] = 0 for row in range(9): for col in range(9): if row == 0: if col == 0: if grid[row][col].text == '': if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col + 1] == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 if grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 1: if grid[row][col].text == '': if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif 1 < col < 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col] == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 7: if grid[row][col].text == '': if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 8: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 else: pass elif row == 1: if col == 0: if grid[row][col].text == '': if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 if grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass if col == 1: if grid[row][col].text == '': if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif 1 < col < 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 if grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 7: if grid[row][col].text == '': if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S' and grid[row + 1][col - 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col - 2].text == 'S' and grid[row][col - 2].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 if grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 8: if grid[row][col].text == '': if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[row, col] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 if grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 else: pass elif 1 < row < 7: if col == 0: if grid[row][col].text == '': if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 # relevant for all if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 # relevant also from 7 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 # relevant only here if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col + 2].text == '' and grid[row - 1][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 1: if grid[row][col].text == '': if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S' and grid[row + 1][col - 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == '': if grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 # relevant for all if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 # relevant also from 7 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col - 1].text == '' and grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col + 1].text == 'S' and grid[row + 1][col - 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col + 1].text == '' and grid[row + 1][col - 1].text == 'S': self.defendo[(row, col)] -= 1 # relevant only here if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col + 2].text == '' and grid[row - 1][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif 1 < col < 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S' and grid[row + 1][col - 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col + 1].text == '': if grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col + 1].text == '': if grid[row + 2][col + 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col].text == '': if grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 # relevant for all if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 2][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col + 2].text == '' and grid[row - 1][col + 1].text == 'O': self.defends[(row, col)] -= 1 # relevant also for 7 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col - 1].text == '' and grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row - 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 # relevant only here if grid[row + 1][col - 1].text == '' and grid[row + 2][col - 2].text == 'S': self.defends[(row, col)] -= 1 elif grid[row + 1][col - 1].text == 'O' and grid[row + 2][col - 2].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col].text == '' and grid[row + 2][col].text == 'S': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == 'O' and grid[row + 2][col].text == '': self.defends[(row, col)] -= 1 if grid[row + 1][col + 1].text == '' and grid[row + 2][col + 2].text == 'S': self.defends[(row, col)] -= 1 elif grid[row + 1][col + 1].text == 'O' and grid[row + 2][col + 2].text == '': self.defends[(row, col)] -= 1 else: pass elif col == 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col].text == 'O' and grid[row + 2][col].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 2][col - 2].text == 'S' and grid[row + 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col].text == '': if grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 # relevant for all if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 # relevant also for 7 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col - 1].text == '' and grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row - 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 # relevant only here if grid[row + 2][col].text == 'S' and grid[row + 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 2][col].text == '' and grid[row + 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row + 2][col - 2].text == 'S' and grid[row + 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row + 2][col - 2].text == '' and grid[row + 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 else: pass elif col == 8: if grid[row][col] == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 elif grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row + 2][col - 2].text == 'S' and grid[row + 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col].text == '': if grid[row + 2][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col].text == 'S': self.defendo[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row + 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row + 1][col - 1].text == '': if grid[row + 2][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row + 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 elif grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 # relevant for all if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 # relevant also for 7 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 # relevant only here if grid[row + 2][col].text == 'S' and grid[row + 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row + 2][col].text == '' and grid[row + 1][col].text == 'O': self.defends[(row, col)] -= 1 else: pass elif row == 7: if col == 0: if grid[row][col].text == '': if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'O': self.defends[(row, col)] += 1 # relevant for all if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 # relevant also from 7 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 else: pass elif col == 1: if grid[row][col].text == '': if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 # relevant for all if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row + 1][col].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 # relevant also from 7 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col - 1].text == '' and grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col + 1].text == 'S' and grid[row + 1][col - 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col + 1].text == '' and grid[row + 1][col - 1].text == 'S': self.defendo[(row, col)] -= 1 else: pass elif 1 < col < 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 # relevant for all if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 2][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col + 2].text == '' and grid[row - 1][col + 1].text == 'O': self.defends[(row, col)] -= 1 # relevant also for 7 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col - 1].text == '' and grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row - 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 else: pass elif col == 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col + 1].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 # relevant for all if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 # relevant also for 7 if grid[row - 1][col - 1].text == 'S' and grid[row + 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col - 1].text == '' and grid[row + 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 if grid[row + 1][col - 1].text == 'S' and grid[row - 1][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row + 1][col - 1].text == '' and grid[row - 1][col + 1].text == 'S': self.defendo[(row, col)] -= 1 else: pass elif col == 8: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row + 1][col].text == 'S': self.defends[(row, col)] += 1 if grid[row + 1][col - 1].text == 'S': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 # relevant for all if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 # relevant also for 7 if grid[row - 1][col].text == 'S' and grid[row + 1][col].text == '': self.defendo[(row, col)] -= 1 elif grid[row - 1][col].text == '' and grid[row + 1][col].text == 'S': self.defendo[(row, col)] -= 1 else: pass elif row == 8: if col == 0: if grid[row][col].text == '': if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif col == 1: if grid[row][col].text == '': if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 elif grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col + 1].text == 'O' and grid[row - 2][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'S': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 else: pass elif 1 < col < 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == 'S': self.attacks[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col -2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col + 1].text == '': if grid[row - 2][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col + 1].text == '': if grid[row][col + 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col + 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col + 1].text == 'O' and grid[row][col + 2].text == '': self.defends[(row, col)] -= 1 elif grid[row][col + 1].text == '' and grid[row][col + 2].text == 'S': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 2][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col + 2].text == 'S' and grid[row - 1][col + 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col + 2].text == '' and grid[row - 1][col + 1].text == 'O': self.defends[(row, col)] -= 1 else: pass elif col == 7: if grid[row][col].text == '': if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == 'S': self.attacko[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col].text == '': if grid[row - 2][col].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col + 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col + 1].text == 'O': self.defendo[(row, col)] += 1 if grid[row][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row][col - 1].text == 'S' and grid[row][col + 1].text == '': self.defendo[(row, col)] -= 1 elif grid[row][col - 1].text == '' and grid[row][col + 1].text == 'S': self.defendo[(row, col)] -= 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 else: pass elif col == 8: if grid[row][col].text == '': if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == 'O': self.attacks[(row, col)] += 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == 'O': self.attacks[(row, col)] += 1 if grid[row - 1][col - 1].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col - 1].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 1][col].text == 'S': self.defends[(row, col)] += 1 elif grid[row - 1][col].text == 'O': self.defendo[(row, col)] += 1 elif grid[row - 1][col - 1].text == '': if grid[row - 2][col - 2].text == 'S': self.defendo[(row, col)] += 1 elif grid[row - 2][col - 2].text == 'O': self.defends[(row, col)] += 1 if grid[row - 2][col].text == 'S' and grid[row - 1][col].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col].text == '' and grid[row - 1][col].text == 'O': self.defends[(row, col)] -= 1 if grid[row - 2][col - 2].text == 'S' and grid[row - 1][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row - 2][col - 2].text == '' and grid[row - 1][col - 1].text == 'O': self.defends[(row, col)] -= 1 if grid[row][col - 2].text == 'S' and grid[row][col - 1].text == '': self.defends[(row, col)] -= 1 elif grid[row][col - 2].text == '' and grid[row][col - 1].text == 'O': self.defends[(row, col)] -= 1 else: pass maxatt = 0 maxattlist = list() maxdef = 0 maxdeflist = list() defaultlist = list() for current in self.attacks: if self.attacks[current] > maxatt: maxatt = self.attacks[current] for current in self.attacko: if self.attacko[current] > maxatt: maxatt = self.attacko[current] for i in self.attacks: if self.attacks[i] == maxatt: maxattlist.append(Action(S, i, App.get_running_app().game.board.grid[i[0]][i[1]])) for i in self.attacko: if self.attacko[i] == maxatt: maxattlist.append(Action(O, i, App.get_running_app().game.board.grid[i[0]][i[1]])) for current in self.defends: if self.defends[current] > maxdef: maxdef = self.defends[current] for current in self.defendo: if self.defendo[current] > maxdef: maxdef = self.defendo[current] for i in self.defends: if self.defends[i] == maxdef: maxdeflist.append(Action(S, i, App.get_running_app().game.board.grid[i[0]][i[1]])) for i in self.defendo: if self.defendo[i] == maxdef: maxdeflist.append(Action(O, i, App.get_running_app().game.board.grid[i[0]][i[1]])) if len(maxattlist) != 0: num = random.randint(1, len(maxattlist)) - 1 chosen1 = maxattlist[num] elif len(maxattlist) == 0 and len(maxdeflist) != 0: num = random.randint(1, len(maxdeflist)) - 1 chosen1 = maxdeflist[num] else: for i in range(9): for j in range(9): if grid[i][j].text == '': defaultlist.append(Action(S, i, App.get_running_app().game.board.grid[i][j])) defaultlist.append(Action(O, i, App.get_running_app().game.board.grid[i][j])) num = random.randint(1, len(defaultlist)) - 1 chosen1 = defaultlist[num] chosen1.take()
from scipy.stats import norm import matplotlib.pyplot as plt import numpy as np variable = norm.rvs(size=1000) # Fit a normal distribution to the data: mu, std = norm.fit(variable) # Plot the histogram. plt.hist(variable, bins=25, normed=True, color='g') # Plot the PDF. xmin, xmax = plt.xlim() x = np.linspace(xmin, xmax, 100) print x p = norm.pdf(x, mu, std) plt.plot(x, p, 'k', linewidth=2) title = "Fit results: mu = %.2f, std = %.2f" % (mu, std) plt.title(title) plt.show()
# Write a Python program to print the even numbers from a given list. Go to the editor def even(list): i=0 while i<len(list): if list[i]%2==0: print("EVEN NUMBER - ", list[i]) i+=1 even([2,3,4,5,6,7])
from functools import * def anymap(func, l, x): """ check if func(x, y) for any y in l is true """ return any(map(partial(func, x), l)) def allmap(func, l, x): """ check if func(x, y) for all y in l is true """ return all(map(partial(func, x), l)) def filteranymap(func, l1, l2): """ Select all x from l2 for which func(x, y) for any y in l1 is true """ return filter(partial(anymap, func, l1), l2) def filterallmap(func, l1, l2): """ Select all x from l2 for which func(x, y) for all y in l1 is true """ return filter(partial(allmap, func, l1), l2) def contains(x, y): return y in x def startswith(x, y): return x.startswith(y) def endswith(x, y): return x.endswith(y)
def hadron_collider_mt2(p1, p2): """Computes the transverse mass in two-particle system. Parameters ---------- p1 : TLorentzVector The first particle p2 : TLorentzVector The second particle Returns ------- The transverse mass of the two-particle system as defined in [1]. Notes ----- * ``p1`` and ``p2`` can also be arrays Warning ------- This is the definition of transverse mass as hadron collider physicists use it! Check Wikipedia [1] for more details. References ---------- [1] https://en.wikipedia.org/wiki/Transverse_mass """ return (p1.mt + p2.mt) ** 2 - (p1 + p2).pt2
""" Napišite program koji s tipkovnice učitava tri cijela broja: redni broj dana u mjesecu, redni broj mjeseca u godini i redni broj godine. Prekontrolirajte jesu li učitane vrijednosti ispravne (ispravne vrijednosti su: dan - [1, 31], mjesec - [1, 12], godina - [0, 2020]). Za ulazne podatke 19, 2, 2017, ispišite datum u sljedećem formatu: 19. veljače, 2017. """ print("Unesi brojčane vrijednosti datuma u formatu DD-MM-YY") dan = input("Dan: ") mjesec = input("Mjesec: ") godina = input("Godina: ") dan = int(dan) mjesec = int(mjesec) godina = int(godina) if dan < 1 or dan > 31 or mjesec < 1 or mjesec > 12 or godina < 1900 or godina > 2018: print("Greška") else: print(dan, ". ", sep="", end="") if mjesec == 1: print("siječnja, ", end="") elif mjesec == 2: print("veljače, ", end="") elif mjesec == 3: print("ožujka, ", end="") elif mjesec == 4: print("travnja, ", end="") elif mjesec == 5: print("svibnja, ", end="") elif mjesec == 6: print("lipnja, ", end="") elif mjesec == 7: print("srpnja, ", end="") elif mjesec == 8: print("kolovoza, ", end="") elif mjesec == 9: print("rujna, ", end="") elif mjesec == 10: print("listopada, ", end="") elif mjesec == 11: print("studenog, ", end="") elif mjesec == 12: print("prosinca, ", end="") print(godina, ".", sep="")
""" Napišite program koji sadrži varijablu u kojoj je upisan proizvoljni niz znakova i varijablu n. Provjerite da li je vrijednost varijable n manja od broja znakova u nizu. Ako je vrijednost varijable n veća ispišite informaciju o grešci. Ispišite iz niza znakova svako n-to slovo. Na primjer, ulazni niz je "ABCDEFGH", n je 2, tada je izlaz "ACEG". """ rijec = input("Unesi neki text: ") broj = input("Unesi neki broj: ") fbroj = float(broj) brojSlova = len(rijec) fbrojslova = float(brojSlova) if fbrojslova > fbroj : index = 0 for slovo in rijec: if index % fbroj == 0 : print (slovo, end="") index += 1 else: print("Greška!")
""" Napišite program koji će inicijalizirati u varijablu proizvoljnog imena, proizvoljnu vrijednost temperature izražene u stupnjevima Celzijevim. Na ekran ispisati vrijednost temperature u farenhajtima. Formula: ( 𝑥 × 9/5) + 32 , x je vrijednost izražena u stupnjevima Celzijevim. """ celz = input("Unesi temperaturu u Celzijusima: ") temp = float(celz) #pretvaranje unesene vrijednosti u numerički tip podatka fahrenhait = (((temp)*(9/5))+32) print (fahrenhait) #jednostavniji oblik zapisa celz = 24 fahr = (celz * 9/4) + 32 print(fahr)
""" U službenoj Python 3 dokumentaciji pronađite ime funkcije za potenciranje (zamjena za aritmetički operator **). S tipkovnice učitajte cjelobrojne vrijednosti i spremite ih u varijable a i b. Nije potrebno provjeravati ispravnost učitanih brojeva. Na temelju tih vrijednosti izračunajte kvadrat zbroja (𝑎 + 𝑏)**2. Formula za kvadrat zbroja je (𝑎 + 𝑏)**2 = 𝑎**2 + 2𝑎𝑏 + 𝑏**2. Funkcije koje ćete koristiti u ovom zadatku uključite u program """ import math a = input("Unesi neki broj: ") a = float(a) b = input("Unesi neki broj: ") b = float(b) rezultat = pow(a,2) + 2*a*b + pow(b,2) print(rezultat)
""" Napišite program koji će inicijalizirati u varijable a i b dva broja proizvoljnih vrijednosti. Ako je vrijednost varijable a bar za 50 veća od vrijednosti varijable b, a uz to je vrijednost varijable b parna, tada ispišite poruku "Uvjeti su zadovoljeni.", u suprotnom ispišite poruku "Uvjeti nisu zadovoljeni. """ a = input("Unesi neki broj: ") fa = float(a) b = input("Unesi neki broj: ") fb = float(b) if (fa > fb) and ( fb % 2 == 0 ) and (fa - fb >= 50): print("Uvjeti su zadovoljeni.") else: print("Uvjeti nisu zadovoljeni.") #isti se zadatak moze i napraviti na sljedeci nacin if fa > ( fb+50 ) and (fb % 2 == 0) : print("Uvjeti su zadovoljeni.") else: print("Uvjeti nisu zadovoljeni.")
""" 给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向)。 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 返回: 3 解释:和为 22 的路径有:[5,4,11,2], [5,8,4,5], [4,11,7] 提示: 节点总数 <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/paths-with-sum-lcci """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def __init__(self): self.count = 0 def check_sum(self, root, sum): if not root: return 0 if root.val == sum: self.count += 1 self.check_sum(root.right, sum - root.val) self.check_sum(root.left, sum - root.val) def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ if not root: return 0 self.check_sum(root, sum) self.pathSum(root.right, sum) self.pathSum(root.left, sum) return self.count class Solution2: def pathSum(self, root: TreeNode, sum: int) -> int: def f(r, s): if r: s = [i + r.val for i in s] + [r.val] return s.count(sum) + f(r.left, s) + f(r.right, s) return 0 return f(root, [])
# 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下: # # F(0) = 0,   F(1) = 1 # F(N) = F(N - 1) + F(N - 2), 其中 N > 1. # # 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。 # # 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 # # # # 示例 1: # # 输入:n = 2 # 输出:1 # # # 示例 2: # # 输入:n = 5 # 输出:5 # # # # # 提示: # # # 0 <= n <= 100 # # # 注意:本题与主站 509 题相同:https://leetcode-cn.com/problems/fibonacci-number/ # Related Topics 递归 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def fib(self, n): """ :type n: int :rtype: int """ for i in range(n): self._fib(i) return self._fib(n) import functools @functools.lru_cache(None) def _fib(self, n): if n == 0: return 0 elif n == 1: return 1 else: return self._fib(n - 1) + self._fib(n - 2) # leetcode submit region end(Prohibit modification and deletion)
""" You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.   Example: Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295. Output: 2 -> 1 -> 9. That is, 912. Follow Up: Suppose the digits are stored in forward order. Repeat the above problem. Example: Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295. Output: 9 -> 1 -> 2. That is, 912. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-lists-lcci """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = cur_node = ListNode(-1) head.next = cur_node overflow = 0 while l1 or l2 or overflow: if not l1: l1 = ListNode(0) if not l2: l2 = ListNode(0) node_num = (l1.val + l2.val + overflow) % 10 overflow = (l1.val + l2.val + overflow) // 10 cur_node.next = ListNode(node_num) cur_node = cur_node.next l1 = l1.next l2 = l2.next return head.next l1 = ListNode(7) l1.next = ListNode(1) l1.next.next = ListNode(6) l2 = ListNode(5) l2.next = ListNode(9) l2.next.next = ListNode(2) s = Solution() print(s.addTwoNumbers(l1, l2).val)
# 森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。 # # 返回森林中兔子的最少数量。 # # # 示例: # 输入: answers = [1, 1, 2] # 输出: 5 # 解释: # 两只回答了 "1" 的兔子可能有相同的颜色,设为红色。 # 之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。 # 设回答了 "2" 的兔子为蓝色。 # 此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。 # 因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。 # # 输入: answers = [10, 10, 10] # 输出: 11 # # 输入: answers = [] # 输出: 0 # # # 说明: # # # answers 的长度最大为1000。 # answers[i] 是在 [0, 999] 范围内的整数。 # # Related Topics 哈希表 数学 # leetcode submit region begin(Prohibit modification and deletion) from collections import Counter class Solution: def numRabbits(self, answers): res, dct = 0, {} for i in answers: if dct.get(i, 0): dct[i] -= 1 else: dct[i] = i res += i + 1 return res class Solution2: def numRabbits(self, answers): count = Counter(answers) pass
# 冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。 # # 现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。 # # 所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。 # # 说明: # # # 给出的房屋和供暖器的数目是非负数且不会超过 25000。 # 给出的房屋和供暖器的位置均是非负数且不会超过10^9。 # 只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。 # 所有供暖器都遵循你的半径标准,加热的半径也一样。 # # # 示例 1: # # # 输入: [1,2,3],[2] # 输出: 1 # 解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。 # # # 示例 2: # # # 输入: [1,2,3,4],[1,4] # 输出: 1 # 解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。 # # Related Topics 二分查找 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ res = [] heaters = [float('-inf')] + sorted(heaters) + [float('inf')] for c in houses: left, right = 0, len(heaters) - 1 while left < right: mid = left + (right - left) // 2 if heaters[mid] < c: left = mid + 1 else: right = mid res.append(min(heaters[left] - c, c - heaters[left - 1])) return max(res) # leetcode submit region end(Prohibit modification and deletion)
# 给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。 # # 进阶: # 如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现? # # 示例: # # # // 初始化一个单链表 [1,2,3]. # ListNode head = new ListNode(1); # head.next = new ListNode(2); # head.next.next = new ListNode(3); # Solution solution = new Solution(head); # # // getRandom()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。 # solution.getRandom(); # # Related Topics 蓄水池抽样 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None import random class Solution(object): def __init__(self, head): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode """ self.value_list = [] while head: self.value_list.append(head.val) head = head.next def getRandom(self): """ Returns a random node's value. :rtype: int """ return random.choice(self.value_list) class Solution2(object): """ 蓄水池算法 """ def __init__(self, head): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode """ self.head = head def getRandom(self,m=1): """ Returns a random node's value. :param m 随机选出M个 :rtype: int """ if not self.head: return count = 0 cur = self.head ans = None while cur: count += 1 if count == random.randint(1, count): ans = cur.val cur = cur.next return ans # reservoir = []; # # for (int i = 0; i < reservoir.length; i++) # { # reservoir[i] = dataStream[i]; # } # # for (int i = m; i < dataStream.length; i++) # { # // 随机获得一个[0, i]内的随机整数 # int d = rand.nextInt(i + 1); # // 如果随机整数落在[0, m-1]范围内,则替换蓄水池中的元素 # if (d < m) # { # reservoir[d] = dataStream[i]; # } # }
# 给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。 # # 请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。 # # 请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。 # # # # 示例 1: # # 输入:s = "a0b1c2" # 输出:"0a1b2c" # 解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。 # # # 示例 2: # # 输入:s = "leetcode" # 输出:"" # 解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。 # # # 示例 3: # # 输入:s = "1229857369" # 输出:"" # 解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。 # # # 示例 4: # # 输入:s = "covid2019" # 输出:"c2o0v1i9d" # # # 示例 5: # # 输入:s = "ab123" # 输出:"1a2b3" # # # # # 提示: # # # 1 <= s.length <= 500 # s 仅由小写英文字母和/或数字组成。 # # Related Topics 字符串 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def reformat(self, s: str) -> str: numbers=[] letters=[] for i in s: if i.isalpha(): letters.append(i) else: numbers.append(i) n,l=len(numbers),len(letters) if abs(n-l)>1: return '' res=[] if n>=l: while numbers: res.append(numbers.pop()) if letters: res.append(letters.pop()) else: while letters: res.append(letters.pop()) if numbers: res.append(numbers.pop()) return "".join(res)
# 给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。 # # 请你返回字符串的能量。 # # # # 示例 1: # # 输入:s = "leetcode" # 输出:2 # 解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。 # # # 示例 2: # # 输入:s = "abbcccddddeeeeedcba" # 输出:5 # 解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。 # # # 示例 3: # # 输入:s = "triplepillooooow" # 输出:5 # # # 示例 4: # # 输入:s = "hooraaaaaaaaaaay" # 输出:11 # # # 示例 5: # # 输入:s = "tourist" # 输出:1 # # # # # 提示: # # # 1 <= s.length <= 500 # s 只包含小写英文字母。 # # Related Topics 字符串 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def maxPower(self, s): """ :type s: str :rtype: int """ if not s: return 0 ans = 1 last_cur_char = s[0] cur_char_count = 1 for c in s[1:]: cur_char = c if last_cur_char == cur_char: cur_char_count += 1 ans = max(ans, cur_char_count) else: cur_char_count = 1 last_cur_char = c return ans s = "leetcode" print(Solution().maxPower(s))
# 搜索旋转数组。给定一个排序后的数组,包含n个整数,但这个数组已被旋转过很多次了,次数不详。请编写代码找出数组中的某个元素,假设数组元素原先是按升序排列的。若 # 有多个相同元素,返回索引值最小的一个。 # # 示例1: # # 输入: arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 5 # 输出: 8(元素5在该数组中的索引) # # # 示例2: # # 输入:arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 11 # 输出:-1 (没有找到) # # # 提示: # # # arr 长度范围在[1, 1000000]之间 # # Related Topics 数组 二分查找 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def search(self, arr, target): """ :type arr: List[int] :type target: int :rtype: int """ try: return arr.index(target) except: return -1 # leetcode submit region end(Prohibit modification and deletion)
# 给定两个字符串 s 和 t,它们只包含小写字母。 # # 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 # # 请找出在 t 中被添加的字母。 # # # # 示例: # # 输入: # s = "abcd" # t = "abcde" # # 输出: # e # # 解释: # 'e' 是那个被添加的字母。 # # Related Topics 位运算 哈希表 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ return chr(sum(map(ord, t)) - sum(map(ord, s))) s=Solution() s.findTheDifference("aa","a") # leetcode submit region end(Prohibit modification and deletion)
# 括号。设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。 # # 说明:解集不能包含重复的子集。 # # 例如,给出 n = 3,生成结果为: # # # [ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" # ] # # Related Topics 字符串 回溯算法 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ ans = [] def f(l, r, s): l == r == n and ans.append(s) l < n and f(l + 1, r, s + '(') r < l and f(l, r + 1, s + ')') f(0, 0, '') return ans # leetcode submit region end(Prohibit modification and deletion)
""" Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 (e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another? Example 1: Input: s1 = "waterbottle", s2 = "erbottlewat" Output: True Example 2: Input: s1 = "aa", "aba" Output: False 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/string-rotation-lcci """ class Solution(object): def isFlipedString(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ if len(s1) != len(s2): return False find = (s2 + s2).rfind(s1) if find < 0: return False flip_count = len(s1) - find if s1[:flip_count] == s2[find:] and s1[flip_count:] == s2[:find]: return True return False class Solution2: def isFlipedString(self, s1: str, s2: str) -> bool: return len(s1) == len(s2) and s1 in s2 * 2 s = Solution() print(s.isFlipedString("waterbottle", "erbottlewat"))
# 给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。 # # 如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False # 。 # # 一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。 # # # # 示例 1: # # # # 输入:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null # ,1,3] # 输出:true # 解释:树中蓝色的节点构成了与链表对应的子路径。 # # # 示例 2: # # # # 输入:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,nu # ll,1,3] # 输出:true # # # 示例 3: # # 输入:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null, # null,1,3] # 输出:false # 解释:二叉树中不存在一一对应链表的路径。 # # # # # 提示: # # # 二叉树和链表中的每个节点的值都满足 1 <= node.val <= 100 。 # 链表包含的节点数目在 1 到 100 之间。 # 二叉树包含的节点数目在 1 到 2500 之间。 # # Related Topics 树 链表 动态规划 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSubPath(self, head, root): """ :type head: ListNode :type root: TreeNode :rtype: bool """ if not root: return False return self.dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) def dfs(self, head, root): if not head: return True if not root: return False if head.val == root.val: return self.dfs(head.next, root.left) or self.dfs(head.next, root.right) else: return False
import textwrap a = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ' b = 'ABCDCDC' def count_substring(string, sub_string): count = 0 sub_len = len(sub_string) for i in range(len(string)): if i+sub_len <= len(string): if (string[i:i+sub_len])==sub_string: count+=1 return count def abcc(a,b): leng=4 j=0 lists=[] for i in range(len(a)): if j <= len(a): print(a[j:j+leng]) j=j+leng return #print(abcc(a,4)) print(textwrap.fill(a,4))
""" 银行系统 """ import random import time # 存储卡信息 class Card(object): def __init__(self, cardId, cardPasswd, cardMoney): self.cardId = cardId self.cardPasswd = cardPasswd self.cardMony = cardMoney self.cardLock = False # 后面到了锁卡的时候需要有个卡的状态 # 存储用户信息 class User(object): def __init__(self, name, idCard, phone, card): self.name = name self.idCard = idCard self.phone = phone self.card = card # 界面操作类 class Bank_View(object): def __init__(self): # 把逻辑处理类传进来,变成属性 self.controller = Bank_Controller() # 管理员登录界面 def Admin_login(self): account = input("请输入后台管理账号:") password = input("请输入密码:") # 使用a对象去调用内部逻辑,传入账号和密码 a = self.controller.judge_Admin(account, password) # 如果内部返回值是1,则登录成功 if a == 1: print("登录成功,请稍后.....") time.sleep(2) self.__Bank_menu() self.__select__menu() return else: print("登录失败") return # 界面操作列表 def __Bank_menu(self): print( """ * * * * * * * * * * * * * * * * * * * * * * * * * * * 开户【0】 销户【1】 查询余额【2】 存款【3】 取款【4】 转账【5】 冻结【6】 解冻【7】 查询信息【8】退出【9】 * * * * * * * * * * * * * * * * * * * * * * * * * * * """ ) # 操作调用 def __select__menu(self): cmd = input("请输入选项ID:") # 开户 if cmd == 0: self.controller.Open_card() # 销户 elif cmd == 1: self.controller.Pin_card() # 查询余额 elif cmd == 2: self.controller.Select_money() # 存款 elif cmd == 3: self.controller.Save_money() # 取款 elif cmd == 4: self.controller.Take_money() # 转账 elif cmd == 5: self.controller.Shift_money() # 冻结 elif cmd == 6: self.controller.Freeze_card() # 解冻 elif cmd == 7: self.controller.Thaw_card() # 查询信息 elif cmd == 8: self.controller.Select_message() # 退出 elif cmd == 9: self.controller.Exit() # 兜底 else: print("请输入正确的选项ID") # 启动程序 def main(self): while True: self.__Bank_menu() self.__select__menu() # 内部逻辑处理类 class Bank_Controller(object): # object指这是一个可实例化的类 # 管理员登录 def judge_Admin(self, account, password): right_account = "1" right_password = "1" # 如果 用户输入值=默认值 则返回1 if account == right_account and password == right_password: return 1 else: return -1 # 开户 def Open_card(self): name = input("请输入您的名字:") idCard = input("请输入您的身份证号:") phone = input("请输入您的电话号码:") # 销户 def Pin_card(self): pass # 查询余额 def Select_money(self): pass # 存钱 def Save_money(self): pass # 取钱 def Take_money(self): pass # 转账 def Shift_money(self): pass # 冻结 def Freeze_card(self): pass # 解冻 def Thaw_card(self): pass # 查询信息 def Select_message(self): pass # 退出 def Exit(self): pass user_yang = Bank_View() user_yang.Admin_login() # user_yang.main()
""" a) 每次增加pay值时,根据用户的付费渠道信息,计算real_pay增加值=pay增加值×渠道系数(渠道系数可配置) b) 用户价值=real_pay+(outcome- income)-(exchangeincome)-cpl奖励(cpl_reward) """ # 计算充值后的real_pay def calculate_real_pay(): pay = float(input("请输入充值数:")) proportion = float(input("请输入渠道系数:")) now_real_pay = float(input("请输入现在real_pay的值:")) add_real_pay = pay * proportion end_real_pay = now_real_pay + add_real_pay print("最终的real_pay应是:", end_real_pay) # 计算用户价值 def user_vlaue(): real_pay = float(input("请输入real_pay值:")) outcome = float(input("请输入outcome值:")) income = float(input("请输入income值:")) exchangeincome = float(input("请输入exchangeincome值:")) cpl_reward = float(input("请输入cpl_reward值:")) user_vlaue = real_pay + (outcome - income) - (exchangeincome) - cpl_reward print("用户价值为:", user_vlaue) # 计算垃圾用户剩余价值 def garbage_user_value(): real_pay = float(input("请输入real_pay值:")) outcome = float(input("请输入outcome值:")) income = float(input("请输入income值:")) exchange_income = float(input("请输入exchange_income值:")) cpl_reward = float(input("请输入cpl_reward值:")) most_pure_pay = float(input("请输入most_pure_pay值:")) garbage_user_value = (real_pay + outcome - income - exchange_income - cpl_reward) / most_pure_pay print("垃圾用户剩余价值更新为:", garbage_user_value) # 判断椰子积分用户是否满足兑换条件 # 下列参与计算的数值均在tb_game_user_pay表中 def user_coco_vlaue(): real_pay = float(input("请输入real_pay值:")) outcome = float(input("请输入outcome值:")) income = float(input("请输入income值:")) exchange_income = float(input("请输入exchange_income值:")) cpl_reward = float(input("请输入cpl_reward值:")) most_pure_pay = float(input("请输入most_pure_pay值:")) user_vlaue = (real_pay + outcome - income - exchange_income - cpl_reward)/most_pure_pay print("结果为:", user_vlaue) # 如果用户价值小于0.2(配置值)不可以兑换 if user_vlaue < 0.2: print("不可以兑换") else: print("可以兑换") if __name__ == '__main__': # calculate_real_pay() # user_vlaue() # garbage_user_value() user_coco_vlaue()
def gen_matrix(d): # 用二维数组来代表矩阵 hh = int(d) matrix = [[0 for col in range(hh)] for row in range(hh)] return matrix def get_rota_matrix(d): mat = gen_matrix(d) # 初始矩阵,所有元素都为0 x = y = 0 total = mat[x][y] = 1 # 将数组第一个元素设为1,即mat[0][0] = 1 while total != d * d: while y + 1 < d and not mat[x][y + 1]: # 从左至右 y += 1 total += 1 mat[x][y] = total while x + 1 < d and not mat[x + 1][y]: # 从上之下 x += 1 total += 1 mat[x][y] = total while y - 1 >= 0 and not mat[x][y - 1]: # 从右至左 y -= 1 total += 1 mat[x][y] = total while x - 1 >= 0 and not mat[x - 1][y]: # 从下至上 x -= 1 total += 1 mat[x][y] = total return mat
a=input() cnt = 0 board = [[0]*9 for i in range(9)] for j in range(9): for k in range(9): x = j//3*3 + k//3 y = j%3*3 + k%3 # print(j,k,x,y) board[x][y] = cnt cnt += 1 for j in range(9): for k in range(9): print("%2d"%board[j][k], end=' ') print()
# 소수체크 import math def isPrime(N): for i in range(2, N): if N % i == 0: return False # if i >= math.sqrt(N): # 시간 복잡도를 O(N) > O(루트N) if i*i > N: break return True assert isPrime(331) assert isPrime(19) # 소인수분해 (조금 까다롭..) def prime_factorization(N): p, fac = 2, [] # while p < math.sqrt(N): # 시간 복잡도를 O(N) > O(루트N) while p**2 <= N: if N%p == 0: N //= p fac.append(p) else: p += 1 if N > 1: fac.append(N) return fac print(prime_factorization(12345)) print(prime_factorization(16)) # 실전 코테에서는 소수리스트를 미리 만들어놓아야 하는 경우가 있다 # 이때 만약 위의 isPrime(N)을 이용한다면, O(N*루트N)이 되므로 # 안전한 선택지가 아니다. # 이때, 에라토스테네스의 체를 이용하자. O(N*로그로그N)이기때문이다! def getPrimeList(N): # N보다 작은 소수리스트 구하기 A, plist = [0 for _ in range(N+1)], [] for i in range(2, N): if A[i] == 0: # 소수인 경우... plist.append(i) else: continue for j in range(i*2, N, i): A[j] = 1 return plist print(getPrimeList(100)) def prime_factorization_2(N, p): # 에라토스테네스의 체 원리를 사용... fac = [] for i in p: if N==1 or N < i*i : break while N%i == 0: fac.append(i) N //= i if N > 1: fac.append(N) return fac assert prime_factorization_2(12345, getPrimeList(12345)) == prime_factorization(12345) assert prime_factorization(16) == prime_factorization_2(16, getPrimeList(16)) print("========") print(prime_factorization(12345)) print(prime_factorization_2(12345, getPrimeList(12345))) print(prime_factorization(16)) print(prime_factorization_2(16, getPrimeList(16))) # 활용 3종 # 1 소인수의 개수 def era_factor_count(N): # O(NlogN) 정도... A = [0 for _ in range(N+1)] for i in range(2, N): # 해답에는 2가 아닌 1로 되어있네?... for j in range(i, N, i): A[j] += 1 # 배수가 존재한다면 +1 return A # 2 소인수의 합 def era_factor_sum(N): A = [0 for _ in range(N+1)] for i in range(2, N): for j in range(i, N, i): A[j] += i # 배수가 존재한다면 +1 return A # 3 소인수분해 def era_factorization(N): A = [0 for _ in range(N+1)] for i in range(2, N): if A[i] : continue for j in range(i, N, i): A[j] = i # 결국 A[x]에는 x의 가장큰 소인수가 저장되어 있겠다. return A print(era_factor_count(7)) print(era_factor_sum(7)) print(era_factorization(100)) # 예) 에라토스테네스의 체를 이용한 소인수 분해 방법... # A[x] = x의 가장 큰 소인수 A = era_factorization(100) N = 84 while A[N] != 0: print(A[N]) N //= A[N]
import termcolor2 m = int(input()) n = int(input()) for _ in range(0 , n): if _ % 2 == 0: for _ in range(0 , m): if _ % 2 == 0: print(termcolor2.colored("$", color="yellow") , end=' ') elif _ % 2 == 1: print(termcolor2.colored("@", color="red") , end =' ') print() if _ % 2 == 1: for _ in range(0 , m): if _ % 2 == 1: print(termcolor2.colored("$", color="yellow") , end=' ') elif _ % 2 == 0: print(termcolor2.colored("@", color="red") , end =' ') print()
num1 = int(input()) num2 = int(input()) print('PROD = {:d}'.format((num1*num2)))
#June Jeongwon Seo #2016-05-31 #Homework3 #LISTS #1 countries = ['South Korea', 'North Korea', 'Australia', 'Greece', 'Costa Rica', 'Mexico', 'Japan'] #2 for lala in countries: print (lala) #3 countries = ['South Korea', 'North Korea', 'Australia', 'Greece', 'Costa Rica', 'Mexico', 'Japan'] print('-----------SORTED----------') print(countries.sort()) #4 print(countries[0]) #5 print(countries[len(countries)-1]) #6 print ('-----DELETE ONE COUNTRY-----') countries.remove('South Korea') print (countries) #7 for lalala in countries: print (lalala) #DICTIONARIES #1 tree = {}
def part_1(): numSteps = 0 instructions = [] #load instructions input = open("inputs/day5.txt", "r") for line in input: instructions.append(int(line.strip())) input.close() i = 0 while True: j = instructions[i] instructions[i] += 1 i += j numSteps += 1 if i < 0 or i >= len(instructions): break print(numSteps) part_1() def part_2(): numSteps = 0 instructions = [] #load instructions input = open("inputs/day5.txt", "r") for line in input: instructions.append(int(line.strip())) input.close() i = 0 while True: j = instructions[i] if j >= 3: instructions[i] -= 1 else: instructions[i] += 1 i += j numSteps += 1 if i < 0 or i >= len(instructions): break print(numSteps) part_2()
from collections import Counter def noDuplicates(phrase): words = phrase.split() counts = list(Counter(words)) return len(words) == len(counts) def noAnagrams(phrase): words = phrase.split() counts = [Counter(w) for w in words] unique = [c for n, c in enumerate(counts) if c not in counts[n+1:]] return len(words) == len(unique) def part_1(): validPasses = 0 input = open("inputs/day4.txt", "r") for line in input: if noDuplicates(line.strip()): validPasses += 1 input.close() print(validPasses) def part_2(): validPasses = 0 input = open("inputs/day4.txt", "r") for line in input: if noAnagrams(line.strip()): validPasses += 1 input.close() print(validPasses) part_1() part_2()
# Robot Programming # breadth first search # by Dr. Qin Chen # May, 2016 import sys import Tkinter as tk ############## # This class supports display of a grid graph. The node location on canvas # is included as a data field of the graph, graph.node_display_locations. ############## class GridGraphDisplay(object): def __init__(self, frame, graph, behaviors): self.node_dist = 60 self.node_size = 20 self.behaviors = behaviors self.gui_root = frame self.canvas = tk.Canvas(self.gui_root, width = 500, height = 500) self.graph = graph self.nodes_location = graph.node_display_locations self.start_node = graph.startNode self.goal_node = graph.goalNode return # draws nodes and edges in a graph def display_graph(self, path, startNode, endNode): self.canvas.pack() for key in self.nodes_location: for adj_node in self.graph.nodes[key]: self.draw_edge(key, adj_node, "blue") for key in self.nodes_location: self.draw_node(key, "blue") self.highlight_path(path) self.highlight_start_and_end(startNode, endNode) b1 = tk.Button(self.gui_root, text='Go') b1.pack() b1.bind('<Button-1>', self.startProg) b2 = tk.Button(self.gui_root, text='Exit') b2.pack() b2.bind('<Button-1>', self.stopProg) self.gui_root.mainloop() # path is a list of nodes ordered from start to goal node def highlight_path(self, path): for node in path: location = self.nodes_location[node] self.canvas.create_oval(location[0] + self.node_size, location[1] + self.node_size, location[0] - self.node_size, location[1] - self.node_size, fill="gold") self.canvas.create_text(location[0], location[1], fill="white", text=node) def highlight_start_and_end(self, startNode, endNode): startLocation = self.nodes_location[startNode] endLocation = self.nodes_location[endNode] self.canvas.create_oval(startLocation[0] + self.node_size, startLocation[1] + self.node_size, startLocation[0] - self.node_size, startLocation[1] - self.node_size, fill="green") self.canvas.create_oval(endLocation[0] + self.node_size, endLocation[1] + self.node_size, endLocation[0] - self.node_size, endLocation[1] - self.node_size, fill="red") self.canvas.create_text(startLocation[0], startLocation[1], fill="white", text=startNode) self.canvas.create_text(endLocation[0], endLocation[1], fill="white", text=endNode) # draws a node in given color. The node location info is in passed-in node object def draw_node(self, node, n_color): location = self.nodes_location[node] self.canvas.create_oval(location[0] + self.node_size, location[1] + self.node_size, location[0] - self.node_size, location[1] - self.node_size, fill=n_color) self.canvas.create_text(location[0], location[1], fill="white", text=node) # draws an line segment, between two given nodes, in given color def draw_edge(self, node1, node2, e_color): location1 = self.nodes_location[node1] location2 = self.nodes_location[node2] self.canvas.create_line(location1[0], location1[1], location2[0], location2[1], fill=e_color) def startProg(self, event=None): print "startProg" self.behaviors.go = True print self.behaviors.go def stopProg(self, event=None): self.behaviors.done = True self.gui_root.quit() # close window return
def count_consonants(str): str_lower=str.lower() consonants="bcdfghjklmnpqrstvwxz" count=0 for x in str_lower: for y in consonants: if x == y: count+=1 else: pass return count print(count_consonants("A nice day to code!"))
from bill import Bill class BillBatch: def __init__(self, batch): if type(batch) != list: raise TypeError('Invalid argument given, argument needs to be of type list!') else: for bill in batch: if type(bill) != Bill: raise TypeError('Invalid element of list given, argument needs to be list of elements of type Bill!') self.batch = batch def __len__(self): return len(self.batch) def __getitem__(self, index): if index in range(len(self)): return self.batch[index] else: raise IndexError('Index out of boundary!') def total(self): return sum(self.batch) if __name__ == '__main__': values = [10, 20, 50, 100] bills = [Bill(value) for value in values] batch = BillBatch(bills) for bill in batch: print(bill) print(sum(batch)) # A 10$ bill # A 20$ bill # A 50$ bill # A 100$ bill
import constants class Pond(): def __init__(self, leftside_frogs_number, rightside_frogs_number): assert leftside_frogs_number >= 0 and rightside_frogs_number >= 0, 'Enter non-negative number of frogs per side' self.leftside_frogs_number = leftside_frogs_number self.rightside_frogs_number = rightside_frogs_number self.pond_size = leftside_frogs_number + rightside_frogs_number + 1 self.steps_count = 0 self.free_lilly_position = leftside_frogs_number self.leftside_frogs_final_position = self.pond_size - 1 self.rightside_frogs_final_position = 0 def set_pond_string(self): pond = '' for pos in range(0, self.free_lilly_position): pond += constants.LEFT_FROG_SYMMBOL pond += constants.FREE_LILLY_SYMBOL for pos in range(0, self.rightside_frogs_number): pond += constants.RIGHT_FROG_SYMBOL self.pond_string = pond self.pond_arranged = pond[::-1] def is_arranged(self): return self.pond_string == self.pond_arranged def __repr__(self): return f'Step {self.steps_count}: {self.pond_string}' def convert_pond_string_to_array(self): return list(self.pond_string) def move_leftside_frog(self): result_from_move = False pond_as_array = self.convert_pond_string_to_array() if self.free_lilly_position == self.leftside_frogs_final_position: pond_as_array[self.free_lilly_position] = constants.LEFT_FROG_SYMMBOL position_of_leftside_frog = self.free_lilly_position - 1 if pond_as_array[position_of_leftside_frog] != constants.LEFT_FROG_SYMMBOL: position_of_leftside_frog -= 1 pond_as_array[position_of_leftside_frog] = constants.FREE_LILLY_SYMBOL self.pond_string = ''.join(pond_as_array) self.leftside_frogs_final_position -= 1 self.free_lilly_position = position_of_leftside_frog result_from_move = True elif self.free_lilly_position == 1: matching_value = constants.LEFT_FROG_SYMMBOL + constants.FREE_LILLY_SYMBOL + constants.RIGHT_FROG_SYMBOL cuurrent_condition_for_moving_leftside_frog = self.pond_string[0:3] == matching_value if cuurrent_condition_for_moving_leftside_frog: pond_as_array[self.free_lilly_position] = constants.LEFT_FROG_SYMMBOL pond_as_array[self.free_lilly_position - 1] = constants.FREE_LILLY_SYMBOL self.pond_string = ''.join(pond_as_array) self.free_lilly_position -= 1 result_from_move = True elif self.free_lilly_position >= 2: first_matching_value = constants.LEFT_FROG_SYMMBOL + constants.LEFT_FROG_SYMMBOL + constants.FREE_LILLY_SYMBOL + constants.RIGHT_FROG_SYMBOL second_matching_value = constants.LEFT_FROG_SYMMBOL + constants.RIGHT_FROG_SYMBOL + constants.FREE_LILLY_SYMBOL + constants.RIGHT_FROG_SYMBOL pond_range_to_check = self.pond_string[self.free_lilly_position - 2: self.free_lilly_position + 2] first_condition_for_moving_leftside_frog = pond_range_to_check == first_matching_value second_condition_for_moving_leftside_frog = pond_range_to_check == second_matching_value if first_condition_for_moving_leftside_frog: pond_as_array[self.free_lilly_position] = constants.LEFT_FROG_SYMMBOL pond_as_array[self.free_lilly_position - 1] = constants.FREE_LILLY_SYMBOL self.pond_string = ''.join(pond_as_array) self.free_lilly_position -= 1 result_from_move = True elif second_condition_for_moving_leftside_frog: pond_as_array[self.free_lilly_position] = constants.LEFT_FROG_SYMMBOL pond_as_array[self.free_lilly_position - 2] = constants.FREE_LILLY_SYMBOL self.pond_string = ''.join(pond_as_array) self.free_lilly_position -= 2 result_from_move = True if result_from_move: self.steps_count += 1 return result_from_move def move_rightside_frog(self): pond_as_array = self.convert_pond_string_to_array() position_of_rightside_frog = self.free_lilly_position + 1 if pond_as_array[position_of_rightside_frog] != constants.RIGHT_FROG_SYMBOL: position_of_rightside_frog += 1 pond_as_array[position_of_rightside_frog] = constants.FREE_LILLY_SYMBOL pond_as_array[self.free_lilly_position] = constants.RIGHT_FROG_SYMBOL self.pond_string = ''.join(pond_as_array) self.free_lilly_position = position_of_rightside_frog self.steps_count += 1 def move_frog(self): if not self.move_leftside_frog(): self.move_rightside_frog()
import unittest from sort_array_of_fractions import sort_fractions class TestSortFractions(unittest.TestCase): def test_with_given_non_list_of_fractions_should_raise_exception(self): fractions = None exc = None try: result = sort_fractions(fractions) except Exception as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Invalid fractions given!') def test_with_given_empty_list_of_fractions_should_raise_exception(self): fractions = [] exc = None try: result = sort_fractions(fractions) except Exception as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Invalid fractions given!') def test_with_given_list_of_fractions_with_non_integer_element_of_fraction_should_raise_exception(self): fractions = [('str', 2), (5, 25)] exc = None try: result = sort_fractions(fractions) except Exception as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Invalid fractions given!') def test_with_given_list_of_fractions_with_zero_denominator_of_fraciton_should_raise_exception(self): fractions = [(24, 2), (5, 0)] exc = None try: result = sort_fractions(fractions) except Exception as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Invalid fractions given!') def test_with_given_list_of_fractions_with_non_bool_order_should_raise_exception(self): fractions = [(24, 2), (5, 2)] exc = None try: result = sort_fractions(fractions, 5) except Exception as e: exc = e self.assertIsNotNone(exc) self.assertEqual(str(exc), 'Invalid order given, needs to be bool!') def test_with_given_list_of_one_fraciton_and_ascending_default_should_return_given_fraction(self): fractions = [(4, 8)] result = sort_fractions(fractions) expected = [(4, 8)] self.assertEqual(result, expected) def test_with_given_list_of_one_fraciton_and_ascending_false_should_return_given_fraction(self): fractions = [(4, 8)] result = sort_fractions(fractions, False) expected = [(4, 8)] self.assertEqual(result, expected) def test_with_given_list_of_two_fracitons_and_ascending_default_should_return_sorted__fractions_in_ascending_order(self): fractions = [(1, 7), (2, 6)] result = sort_fractions(fractions) expected = [(1, 7), (2, 6)] self.assertEqual(result, expected) def test_with_given_list_of_two_fracitons_and_ascending_false_should_return_sorted_fractions_in_descending_order(self): fractions = [(1, 7), (2, 6)] result = sort_fractions(fractions, False) expected = [(2, 6), (1, 7)] self.assertEqual(result, expected) def test_with_given_list_of_more_than_two_fracitons_and_ascending_default_should_return_sorted_fractions_in_ascending_order(self): fractions = [(5, 3), (2, 5), (3, 6)] result = sort_fractions(fractions) expected = [(2, 5), (3, 6), (5, 3)] self.assertEqual(result, expected) def test_with_given_list_of_more_than_two_fracitons_and_ascending_true_should_return_sorted_fractions_in_ascending_order(self): fractions = [(5, 3), (2, 5), (3, 6)] result = sort_fractions(fractions, True) expected = [(2, 5), (3, 6), (5, 3)] self.assertEqual(result, expected) def test_with_given_list_of_more_than_two_fracitons_and_ascending_false_should_return_sorted_fractions_in_ascending_order(self): fractions = [(5, 3), (2, 5), (3, 6)] result = sort_fractions(fractions, False) expected = [(5, 3), (3, 6), (2, 5)] self.assertEqual(result, expected) if __name__ == '__main__': unittest.main()
from players import Player, Computer from random import shuffle def game(): player_name = input('Enter your name to start the game: ').strip() while len(player_name) == 0: player_name = input('Enter your name to start the game, please: ').strip() player = Player(player_name) computer = Computer() score = {player.name: 0, computer.name: 0} game_condition = True while game_condition: # This while loop is for the re-opportunity to play (game score) print(f' Welcome to the console game, {player.name}! '.center(70, '*'), end='\n\n') users_deck = [player, computer] if player.health < 100 or computer.health < 100: for user in users_deck: user.health = 100 shuffle(users_deck) # Random sequence of players moves move_counter = 0 while player.health > 0 and computer.health > 0: move_counter += 1 for user in users_deck: print(f' Player [{user.name}] move ({move_counter}) '.center(70, '*')) if isinstance(user, Computer): user.make_some_decision(player) else: actions = ['mid_damage_the_enemy', 'high_damage_the_enemy', 'heal_yourself'] print('Choose some action:', '1. Inflict middle damage(18-25hp) to the enemy', '2. Inflict high damage(10-35hp) to the enemy', '3. Heal yourself(18-25hp)', sep='\n') action_choice = actions[int(input('Enter a number: '))-1] if action_choice == 'heal_yourself': getattr(user, action_choice)() else: getattr(user, action_choice)(computer) print(' Players health data '.center(70, '-')) for user_hp in users_deck: # Print the health data of players after the move. print(user_hp) print('-' * 70, end='\n\n') if player.health <= 0: score[computer.name] += 1 print(f'{player.name}, you Lose!') break elif computer.health <= 0: score[player.name] += 1 print(f'Congratulations! {player.name}, you Won!') break print(' SCORE '.center(70, '*')) for key, value in score.items(): print(f'{key}: {value}') print('*' * 70) print('Play again?', '1. No', '2. Yes', sep='\n') game_condition = [False, True][int(input('Enter a number: '))-1]
def shellsort(data, length): gap = length//2 while gap > 0: for index in range(gap, length): temp = data[index] index2 = index while index2 >= gap and data[index2 - gap] > temp: data[index2] = data[index2 - gap] index2 -= gap data[index2] = temp gap //=2 arr = [3,6,5,1,3,6,7,8,9,6,5,6,4,4,3,4,2,2,4,8,8,5,3,5] shellsort(arr, len(arr)) print(arr)
height = float(input("input height: ")) wieght = float(input("input wieght: ")) def bmi(wieght,height): work_bmi = wieght/(height**2) opt_weight = optimalweight(height) print(f"your optimal weight is {opt_weight}") check_overweight(work_bmi) return work_bmi def check_overweight(bmi): if bmi < 18.5: print("underweight") elif bmi > 24.9: print("overweight") else: print("your ok") def optimalweight(height): optimal_weight = 21.7 * (height**2) return optimal_weight bmi(wieght,height)
print("What's your name") name = input () if name == "Zach": print("Welcome back!") else: print("Hello " + name) print("What's your favorite sport?") sport = input () if sport == "Football": print("That's my favorite too!") elif sport == "soccer": print("I love playing soccer too.") elif sport == "Tennis": print("meh, I'm not that good at doubles.") else: print(sport + " is also fun.")
#! /usr/bin/env python # -*- coding=utf8 -*- ''' 处理快递单号 ''' def readCSV1(filename): f = open(filename, 'r') deliver_nos = [] deliver_info = {} for line in f.read().split('\n')[:-1]: items = line.split(',') #print items[7],"宅急送" if items[7] == '宅急送': #print items[7] deliver_nos.append(items[1]) deliver_info[items[1]] = items[2] return deliver_nos[1:],deliver_info def readCSV2(filename): f = open(filename, 'r') deliver_nos = [] deliver_info = {} for line in f.read().split('\n')[:-1]: #import pdb; pdb.set_trace() items = line.split(',') deliver_nos.append(items[0]) deliver_info[items[0]] = items[15] #pdb.set_trace() return deliver_nos[1:],deliver_info def deliverHandler(list1, list2): answer1, answer2 = [],[] for item in list1: if item not in list2: answer1.append(item) for item in list2: if item not in list1: answer2.append(item) return answer1,answer2 def deliver_fee_compare(dict1,dict2): f = open('compare_fee.txt','w') for key in dict1.keys(): try: if float(dict1[key]) - float(dict2[key]) > 1.0: f.write(key + ',' + dict1[key] + ',' + dict2[key] + '\n') except(KeyError): f.write('wrong number:' + key + '\n') f.close() def testReadCSV(): filename = 'in.csv' deliver_nos = readCSV(filename) print len(deliver_nos) print deliver_nos[:10],deliver_nos[-10:] if __name__ == '__main__': list1,dict1 = readCSV1('in.csv') list2,dict2 = readCSV2('out.csv') answer1, answer2 = deliverHandler(list1,list2) f = open('in.txt','w') for item in answer1: f.write(item + '\n') f.close() f = open('out.txt','w') for item in answer2: f.write(item + '\n') f.close() deliver_fee_compare(dict1,dict2)
import re def check(s): s = s.lower() str = re.findall("[a-zA-Z0-9]", s) rstr = str[::-1] print(str) print(rstr) if str == rstr: return True else: return False print (check("ab2a"))
import unittest import application.validator as validator class ValidatorTestCase(unittest.TestCase): def test_date_formatting(self): # date should be changed to format 'YYYY-MM-DD' provided = '2010-2-1' expected = '2010-02-01' self.assertEqual(validator.get_string_date_from_date(provided), expected) def test_date_formatting_wrong_date(self): # with wrong date '' is returnd provided = '2010-02-30' expected = '' self.assertEqual(validator.get_string_date_from_date(provided), expected) def test_register_json_mail_without_at_sign(self): # mail does not contain '@' sign register_json_without_at_sign = {'mail': 'NoAtSign', 'haslo': 'password', 'imie': 'name', 'nazwisko': 'lastName', 'data_urodzenia': '2000-01-01'} self.assertFalse(validator.is_register_json_valid(register_json_without_at_sign)) def test_register_json_mail_wrong_format(self): # mail does not contain .com (or other domain) register_json_without_at_sign = {'mail': 'abcd@gmail', 'haslo': 'password', 'imie': 'name', 'nazwisko': 'lastName', 'data_urodzenia': '2000-01-01'} self.assertFalse(validator.is_register_json_valid(register_json_without_at_sign)) def test_register_json_proper_mail(self): register_json_without_at_sign = {'mail': 'abcd@gmail.com', 'haslo': 'password', 'imie': 'name', 'nazwisko': 'lastName', 'data_urodzenia': '2000-01-01'} self.assertTrue(validator.is_register_json_valid(register_json_without_at_sign)) def test_add_path_zero_points_both_ways(self): # 'punktacja' and 'punktacja_odwrotnie' can't be zero at the same time add_path_both_ways_zero = {'mail': 'abcd@gmail.com', 'haslo': 'password', 'grupa_gorska': 1, 'punktacja': 0, 'punktacja_odwrotnie': 0, 'punkt_startowy': 1, 'punkt_koncowy': 2} self.assertFalse(validator.is_add_path_json_valid(add_path_both_ways_zero)) def test_add_path_zero_one_way(self): # 'punktacja' and 'punktacja_odwrotnie' - one zero is acceptable add_path_one_way_zero = {'mail': 'abcd@gmail.com', 'haslo': 'password', 'grupa_gorska': 1, 'punktacja': 0, 'punktacja_odwrotnie': 5, 'punkt_startowy': 1, 'punkt_koncowy': 2} self.assertTrue(validator.is_add_path_json_valid(add_path_one_way_zero)) def test_add_path_positive_points(self): # 'punktacja' and 'punktacja_odwrotnie' can both be positive add_path_both_positive = {'mail': 'abcd@gmail.com', 'haslo': 'password', 'grupa_gorska': 1, 'punktacja': 4, 'punktacja_odwrotnie': 5, 'punkt_startowy': 1, 'punkt_koncowy': 2} self.assertTrue(validator.is_add_path_json_valid(add_path_both_positive)) def test_add_path_negative_points(self): # 'punktacja' and 'punktacja_odwrotnie' - neither should be negative add_path_negative = {'mail': 'abcd@gmail.com', 'haslo': 'password', 'grupa_gorska': 1, 'punktacja': -4, 'punktacja_odwrotnie': 5, 'punkt_startowy': 1, 'punkt_koncowy': 2} self.assertFalse(validator.is_add_path_json_valid(add_path_negative)) def test_login_ok(self): # proper login json login = {'mail': 'abcd@gmail.com', 'haslo': 'password'} self.assertTrue(validator.is_login_json_valid(login)) def test_login_no_password(self): # empty password login = {'mail': 'abcd@gmail.com', 'haslo': ''} self.assertFalse(validator.is_login_json_valid(login)) def test_login_no_password_field(self): # missing password field login = {'mail': 'abcd@gmail.com'} self.assertFalse(validator.is_login_json_valid(login)) if __name__ == '__main__': unittest.main()
from __future__ import annotations from abc import ABC, abstractmethod from typing import Any class Handler(ABC): """ Represents an interface that declares a method for building a chain of handlers, otherwise known as the chain of responsibility pattern. It also declares a method for executing a request using the chain of handlers. """ @abstractmethod def set_next(self, handler: Handler) -> Handler: """ Sets the next handler in the chain. Args: handler(Handler): The next handler in the chain. """ pass @abstractmethod def handle(self, request: Any) -> Any: """ Handles the given request by executing the chain of registered handlers. All concrete Handlers either handle the request or pass it to the next handler in the chain. Args: request: The request to be handled by the chain. """ pass class ObjectFactory(ABC): """ Represents a general purpose Object Factory that can be used to create all kinds of objects. Provides a method to register a Builder based on a key value and a method to create the concrete object instances based on the key. """ def __init__(self): self._builders = {} def register_builder(self, key, builder): self._builders[key] = builder def create(self, key, **kwargs) -> Any: builder = self._builders.get(key) if not builder: raise ValueError(key) return builder(**kwargs)
#This program was designed by Adam Cox on 7/4/2019 it has two turtles race on screen. import random import turtle def cords(x,y): #Needs to run multiple times as they might collide at various points a,b=x.pos() c,d=y.pos() style = ("Arial", 15) equal=False if(a==c) and (c==d): x.write("Draw, due to collision of turtles.",font=style) print(a,b,c,d) equal=True return equal def isInScreen(win,turt):#This keeps track of if the turtles are on the screen. leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2 topBound = win.window_height() / 2 bottomBound = -win.window_height() / 2 turtleX = turt.xcor() turtleY = turt.ycor() stillIn = True if turtleX > rightBound or turtleX < leftBound: stillIn = False if turtleY > topBound or turtleY < bottomBound: stillIn = False return stillIn def coin(x):#This flips the coin to determine the direction of the turtles movement. coin = random.randrange(0, 2) if coin == 0: x.left(90) else: x.right(90) x.forward(50) def setup(x,y): #Allow the writing to be a bit easier to setup. x.shape('turtle') x.speed(10) x.penup() x.forward(y) x.pendown() def finish(x,y): print("The winner is turtle number:", y) style = ("Arial", 15) x.penup() x.goto(0, 0) x.pendown() x.hideturtle() x.write("The winner is turtle number:"+y, font=style) def main(): wn = turtle.Screen() # Define your turtles here june = turtle.Turtle() setup(june, 0) july = turtle.Turtle() july.pencolor("blue") setup(july, 50) while isInScreen(wn,june) and isInScreen(wn,july): #Runs as long as one turtle is on screen dice= random.randrange(0, 20) #rolls a dice that is from 0-19 if cords(june, july):# This has to run 3 times as turtles might collide at various points. break if dice != 9: coin(june) #1st coin flip and move black turtle if cords(june, july): #Collision check 2 break if dice != 5: coin(july) #2nd coin flip and move blue turtle if cords(june, july): #Collision check 3 break if not isInScreen(wn, july): finish(july, "two") #reports when elif not isInScreen(wn, june): finish(june, "one") else: #For the rare tie. print("Error running software.") wn.exitonclick() main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import random rand_num = random.randrange(10) for i in range(3): guess_num = int(raw_input('请猜猜数字: ')) if guess_num == rand_num: print '太棒了,猜对了' break elif guess_num > rand_num: print '你猜测的数字有对大了,请尝试小点的数字' else: print '你猜测的数字有对小了,请尝试大点的数字' else: print '不要灰心,下次尝试' print '真正的数字是:%d' % rand_num
from ConvexPolygon import ConvexPolygon import Descryptors as desc import math class Triangle(ConvexPolygon): fill_colour = desc.ColorV() outline_colour = desc.ColorV() length_of_a = desc.SideV() length_of_b = desc.SideV() length_of_c = desc.SideV() def __init__(self, fill_colour, outline_colour): super().__init__(fill_colour, outline_colour) self.set_parameters() def set_parameters(self): self.length_of_a = input("Podaj długość boku: ") self.length_of_b = input("Podaj długość boku: ") self.length_of_c = input("Podaj długość boku: ") def scale(self): if self.length_of_a <= 15 and self.length_of_b <= 15 and self.length_of_c <= 15: return 50 else: return 20 def area(self): a = self.length_of_a b = self.length_of_b c = self.length_of_c p = (a + b + c) / 2 return math.sqrt(p * (p - a) * (p - b) * (p - c)) def perimeter(self): return self.length_of_a + self.length_of_b + self.length_of_c def draw(self): a = self.length_of_a b = self.length_of_b c = self.length_of_c A = (0, 0) B = (c, 0) hc = (2 * (a ** 2 * b ** 2 + b ** 2 * c ** 2 + c ** 2 * a ** 2) - (a ** 4 + b ** 4 + c ** 4)) ** 0.5 / (2. * c) dx = (b ** 2 - hc ** 2) ** 0.5 if abs((c - dx) ** 2 + hc ** 2 - a ** 2) > 0.01: dx = -dx C = (dx, hc) coords = [int((x + 1) * self.scale()) for x in A + B + C] return coords class IsoscelesTriangle(Triangle): def __init__(self, fill_colour, outline_colour): super().__init__(fill_colour, outline_colour) def set_parameters(self): self.length_of_a = input("Podaj długość boku: ") self.length_of_b = input("Podaj długość boku: ") self.length_of_c = self.length_of_b class EquilateralTriangle(Triangle): def __init__(self, fill_colour, outline_colour): super().__init__(fill_colour, outline_colour) def set_parameters(self): self.length_of_a = input("Podaj długość boku: ") self.length_of_b = self.length_of_a self.length_of_c = self.length_of_a
# Compute the lowest common ancestor for a binary tree for two given nodes ###### CONDITION ########: # Assuming that both the ndoes are present in the tree def lca(root, n1, n2): # Recursive approach # The function tries to return the pointer to the lca # Base case: if root == None: return None # When a TreeNode gets invoked, it first checks whether its value matches any of the two given nodes # If the TreeNode is one of the nodes itself, then it has to be the ancestor of the other (Assuming itself as the root) if root.val == n1 or root.val == n2: return root # Otherwise, it delegates the work to figure out the lca to its children left_output = lca(root.left, n1, n2) right_output = lca(root.right, n1, n2) # If both the children return some pointer, the node knows that the lca is the node itself so it returns itself if left_output and right_output: return root # Or else it passes on the pointer returned by one of its children or else returns None if left_output: return left_output elif right_output: return right_output else: return None
# LinkedIn Phone Interview # Given a binary search tree and a target value, find k values in the binary search tree (BST) that are closest to the target. # # Given the following Binary Search Tree: # 10 # / \ # 5 20 # /\ /\ # 1 6 15 30 # \ # 7 # Given target=8, and k=3, it should return 6,7,10 # def closest(root,target, k): val = all_values(root, []) # create a queue # insert the first 3 in the queue que = [0, 1, 2] for 3 in range(len(val)): if abs(get(que) - target) > abs(val[i] - target): dequeue() enqueue(val[i]) return que def all_values(root, val): # Base case: if root == None: return all_values(root.left, val) val.append(root.data) all_values(root.right, val) return val
books = "title,autor,1,r" book = books.split(",") print(book) print(book[0]) print(len(book)) string = "new book" books.insert(0, string) print(books)
#!/usr/bin/env python # -*- coding:utf-8 -*- import numpy as np #下标 0,1,2 li = [1,2,3] print(li[1]) print('------------------------------------') #数组索引 #一维数组索引 arr = np.array([1,2,3]) print(arr[1]) #二维的索引 arr = np.array([np.arange(1,4),np.arange(4,7)]) print(arr) #筛选二维数组时,下标[行,列] print(arr[0,1]) print(arr[1,2]) print(arr[1][2]) print('*'*30) #三维的索引 ''' 三维数组的结构:2,2,3 [1,2,3 4,5,6] [2,2,2 3,3,3] ''' data = [[[1,2,3],[4,5,6]], [[2,2,2],[3,3,3]]] arr = np.array(data) print(arr) print(arr.shape) #三维数组的筛选,[表(二维数组),行,列] print(arr[0,1,2]) print(arr[1,1,1]) #第二种索引筛选方式 print(arr[0,1,2]) print(arr[0][1][2]) print('--------------数组切片--------------') li = [1,2,3] print(li[1:]) #[(起始位置):(终止位置):(步长)] #注:所有参数都为默认值时,则不需要写两个:,只需要写一个就可以 arr = np.arange(8) print(arr) #数组的切片运算也是左包含,右不包含 print(arr[3:8]) print(arr[3:]) print(arr[:3]) print(arr[0:3]) print(arr[::2]) print(arr[3::2]) #切片时,起始位置,终止位置,步长都要是整数 #print(arr[1.3::]) #二维数组的切片 arr = np.array([np.arange(1,5),[5,6,7,8],[9,10,11,12]]) print(arr) print(arr[1]) print(arr[:,2]) print(arr[:,0]) print(arr[1,2:]) print(arr[1:,2]) print(arr[0::2,3]) print(arr[1,::3]) print(arr[::2,1:3]) print('----------三维数组----------') #三维数组切片 arr = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) print(arr) #[先筛表,行,列] print(arr[:,1,1:]) #[2,8] print(arr[:,0,1]) print(arr[:]) #数组元素重新赋值,语法,先筛选,再赋值 print('----------------------------------------') arr = np.array([[1,2,3],[4,5,6]]) print(arr) arr[0,1] = 20 print(arr) arr[0,1:] = 30 print(arr) arr_30 = arr[0,1:] print(arr_30) #此时相当于,把31这个整数赋值给变量arr_30 # arr_30 = 31 # print(arr_30) #整个数组都重新赋值,需要将数组内数字全部筛选出来 arr_30[:]=31 #在数组进行赋值时,直接将数组地址复制给新的数组,而不是直接把数给了数组 print(arr_30) print(arr) print('----------------------------------') arr_31 = arr[0,1:].copy() print(arr_31) arr_31[:]=22 print(arr_31) print(arr) #布尔索引,筛选时,[布尔数组],True所对应的位置为所选,False则淘汰 #布尔类型,True,False #布尔数组[True,False] arr = np.ones((4,4)) for i in range(4): arr[i] = i print(arr) bo = np.array([True,True,True,False]) print(bo) print(arr[bo]) print(arr[:,bo]) names = np.array(['Bob','Jame','Bob','Jack']) print("(((((") print(names =='Bob') print(arr[:,names =='Bob']) print(arr[2:,names =='Bob']) print(names!='Bob') print(arr[names!='Bob']) print((names=='Bob')|(names=='Jack')) print(arr[(names=='Bob')|(names=='Jack')]) print('--------------------------------------') print(arr) print(arr>2) arr[arr>2]=11 print(arr) print("asdfasdfadsfffffffffffffffffffffffffff") #花式索引,就是把所需要的行或列放在一个列表内 arr = np.ones((4,4)) for i in range(4): arr[i] = i print(arr[[1,2]]) print(arr[:,[1,2]]) arr = np.array([[1,2,3],[4,5,6]]) print(arr) print('----------------------------------') #(0,1),(1,0) print(arr[[0,1],[1,0]]) print(arr[[0,1,1],[0,1,2]]) print('----------------------------------') #负号,代表从下向上数,起始是从-1开始的 print(arr[-1]) print(arr[[-1,-2],2]) print('----------------------------------') arr = np.ones((4,4)) for i in range(4): arr[i] = i print(arr) #两重花式索引 改变列的顺序 arr[:,0]=0; print(arr[[0,2,3]][:,[1,0,2,3]]) #[0,1,2,3] print('*'*30) ###两个数组进行矢量计算,就是对应位数字分别进行计算。+-*/%, # 如果是两个数组进行计算的话,形状要保持一致 arr = np.array([[1,2,3],[4,5,6]]) arr_1= np.array([[2,2,2],[3,4,4]]) print(arr+arr_1) print(arr*arr_1) print(arr*3) print(1/arr) # arr_2 = np.array([[1,1,1,1],[2,2,2,2]]) # print(arr+arr_2) #特殊形式,广播 print('*'*30) arr = np.array([[1,2,3],[4,5,6]]) print(arr) arr_index = np.array([1,1,1]) print(arr+arr_index) arr_columns = np.array([[2],[2]]) print(arr+arr_columns)
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import walk import icons import objects import print_types def choose_level(): level = [] while not is_valid_level(level): levels = load_levels_from_files() print_levels(levels[:]) player_input = input("Choose: ") if player_input in ["exit", "q"]: return None, None, None, None level_name = get_level_name(player_input, levels) level, player, enemies = get_level(level_name) if not is_valid_level(level): print_types.print_warning("Not a valid input, please enter the number next to the level name") return level, level_name, player, enemies def is_valid_level(level): if len(level) > 0: return True return False def print_levels(levels): levels = clean_names(levels) for i in range(len(levels)): if "_" in levels[i]: levels[i] = levels[i].split("_") levels[i] = " ".join(levels[i]) levels[i] = levels[i].title() print(str(i+1) + ". " + levels[i]) def clean_names(lst): for file_name in lst: if not file_name.endswith(".surv_hor"): lst.remove(file_name) for i in range(len(lst)): lst[i] = lst[i][:-9] if "_" in lst[i]: lst[i] = lst[i].split("_") lst[i] = " ".join(lst[i]) return lst def load_levels_from_files(): levels = [] for (root, dirs, files) in walk("./levels"): levels.extend(files) break return levels def get_level_name(player_input, levels): try: player_input = int(player_input) level = levels[player_input-1] level = "./levels/" + level return level except Exception: return "" def get_level(level_dir): try: with open(level_dir) as open_file: level = open_file.readlines() level = convert_level(level) player = get_objects(level, objects.Player)[0] enemies = get_objects(level, objects.Enemy) return level, player, enemies except Exception: return [], None, [] def convert_level(level): return_list = [] for x in range(len(level)): for y in range(len(level[x])): icon_dict = {icons.get_player_icon(): objects.Player(x, y), icons.get_enemy_icon(): objects.Enemy(x, y), icons.get_wall_icon(): objects.Wall(x, y), icons.get_key_icon(): objects.Key(x, y), icons.get_door_icon(): objects.Door(x, y), icons.get_win_icon(): objects.Win_area(x, y), icons.get_secret_door_icon(): objects.Secret_door(x, y)} add_icon = icon_dict.get(level[x][y], "") if not add_icon == "": return_list.append(add_icon) return return_list def render_level(input_level, player): level = input_level[:] largest_x = get_largest_pos(level, "x") largest_y = get_largest_pos(level, "y") for x in range(largest_x): for y in range(largest_y): if player.get_loc()["x"] == x and player.get_loc()["y"] == y: if player.isdead(): print(icons.get_icon("dead"), end='') elif player.has_given_up(): print(icons.get_icon(objects.Enemy(0, 0)), end='') else: print(icons.get_icon(player), end='') else: found_icon = False for icon in level: if icon.get_loc()["x"] == x and icon.get_loc()["y"] == y: found_icon = True print(icons.get_icon(icon), end='') level.remove(icon) break if not found_icon: print(icons.get_icon(" "), end='') print() def get_largest_pos(level, index): current_largest = level[0].get_loc()[index] for icon in level: if icon.get_loc()[index] > current_largest: current_largest = icon.get_loc()[index] current_largest += 1 return current_largest def get_objects(level, obj_type): return_list = [] for icon in level: if isinstance(icon, obj_type): return_list.append(icon) return return_list def get_icon_at_loc(level, x, y, taboo=[]): for icon in level: if icon.get_loc()["x"] == x and icon.get_loc()["y"] == y: if not type(icon) in taboo: return icon return None def update_level(level, enemies): for icon in level: if isinstance(icon, objects.Enemy): level.remove(icon) elif isinstance(icon, objects.Door): if icon.is_unlocked(): level.remove(icon) elif isinstance(icon, objects.Key): if icon.is_picked_up(): level.remove(icon) elif isinstance(icon, objects.Secret_door): if icon.is_discovered(): level.remove(icon) for enemy in enemies: level.append(enemy) return level
#!/usr/bin/env python # -*- coding: utf-8 -*- def dbsearch(db, key_value, search_value): return_list = [] for person in db: if search_value in person[key_value]: return_list.append(person) return return_list def TEST(): return [ {'name': 'Jakob', 'position': 'assistant'}, {'name': 'Åke', 'position': 'assistant'}, {'name': 'Ola', 'position': 'examiner'}, {'name': 'Henrik', 'position': 'assistant'} ] print(dbsearch(TEST(), 'position', 'examiner')) print(dbsearch(TEST(), 'name', 'Åke')) print(dbsearch(TEST(), 'position', 'assistant'))
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import reduce def uppg_1_2(num): add_val = lambda x, y: x + y mult_val = lambda x, y: x * y function_list = [add_val, mult_val] return_list = [] for function in function_list: return_list.append(reduce(function, range(1, num+1))) return return_list print(uppg_1_2(512))
### Copyright Fabian Blank ### In this chapter we will build a math trainer import random from decimal import Decimal, getcontext getcontext().prec = 2 def trainMath (iterations, min, max, isTest): ### You will get the following variables ### iterations - number of questions ### min - minimum number ### max - maximum number # You will need some randomness and then find numbers numbers = [] # print (numbers) ### output numbers ### Return numbers as an 2D array of form ### [[number 1, operation, number 2, Solution] ...] ### + 0 ### - 1 ### * 3 ### / 4 trainMath(5,1,100, False)
### Copyright Fabian Blank from functions import doubleNumber, rootDouble def testDoubleNumber0(): assert doubleNumber(0) == 0, 'Learn maths' def testDoubleNumber1(): assert doubleNumber(15) == 30, 'Learn maths' def testDoubleNumber2(): assert doubleNumber(8888888888) == 17777777776, 'Are you sure this is calculated right? Or are you overflowing?' def testDoubleNumberWithString(): assert doubleNumber('HAHA') == None , "Check your input" ### Def test square root of number and then double def testSquareDoule1(): assert rootDouble(81) == 18, 'Check your maths' def testSquareDoule2(): assert rootDouble(57392094123049) == 15151514.0, 'Check your function for errors' def testNumberLikeAnAsshole(): assert rootDouble('hjfajkldsfakljödsfakljödsfajkldsfjklsfdgjklfdgjklfdgjklg') == None, 'I know you hate me now, but check the users input'
class myClass: def __init__(self, inp): self.inp=inp def getString(self): self.inp=input("Give input\n") def printString(self): print("\nThis is printString Function's output") print(self.inp) # Test Function def main(): obj = myClass("salman") obj.getString() obj.printString() if __name__ == "__main__": main()
# Test Function def main(): words = input("please give the list\n") words=words.split(',') # words=words.sort() words=sorted(list(words)) print(', '.join(words)) if __name__ == "__main__": main()
#!/usr/bin/python3 import math import polynom def diff1_calculate(values, h): res = [] y = [y for x,y in values] for i in range(2): r = (-3*y[i] + 4*y[i+1] - y[i+2]) / (2*h) res.append(r) for i in range(2, len(values)): #print("3 * {:.4f} - 4 * {:.4f} + {:.4f}".format(y[i], y[i-1], y[i-2])) r = ( 3*y[i] - 4*y[i-1] + y[i-2]) / (2*h) res.append(r) return res def diff2_calculate(values, h): res = [None,] y = [y for x,y in values] for i in range(1, len(values)-1): r = (y[i+1] - 2*y[i] + y[i-1]) / h**2 res.append(r) res.append(None) return res def main(): a, b = (float(x) for x in input('Введите a и b (a < b): ').split(' ')) #a, b = 0.0, 1.0 if a >= b: print('a должно быть строго меньше b') return m = int(input('Введите m (количество отрезков между a и b): ')) #m = 10 h = (b - a) / m func = lambda x: 1 - math.exp(-x) + x**2 diff1 = lambda x: math.exp(-x) + 2*x diff2 = lambda x: -math.exp(-x) + 2 values = polynom.get_values(a, b, m, f=func) diff1_values = diff1_calculate(values, h) diff2_values = diff2_calculate(values, h) print('{:>15} | {:>15} | {:>15} | {:>20} | {:>15} | {:>20}'.format('x', 'f(x)', 'f\'(x)чд', '|f\'(x)т - f\'(x)чд|', 'f\'\'(x)чд', '|f\'\'(x)т - f\'\'(x)чд|')) print('-'*(15*4+20*2+5*3+3)) for i in range(len(values)): x, y = values[i] fx = diff1_values[i] fxx = diff2_values[i] d1 = abs(diff1(x) - fx) if fxx is not None: d2 = abs(diff2(x) - fxx) print('{:> 15.6} | {:> 15.6f} | {:> 15.6f} | {:> 20.6f} | {:> 15.10f} | {:> 20.15f}'.format(x, y, fx, d1, fxx, d2)) else: print('{:> 15.6} | {:> 15.6f} | {:> 15.6f} | {:> 20.6f} | {:>15.6} | {:>20.6}'.format(x, y, fx, d1, '', '')) if __name__ == '__main__': main()
# output the length of the longest substring without repeating characters class Solution: def lengthOfLongestSubstring(self, s: str):
def read_input_file(): with open("./input.txt") as file: for row in file: yield row.rstrip("\n") def sum_group_everyone_yes(): total = 0 first_in_group = True yes_per_group = set() for line in read_input_file(): # group delimiter if line == "": total += len(yes_per_group) first_in_group = True yes_per_group = set() else: # calculate intersection from person to person in each group intersection = set() for char in line: if char in yes_per_group or first_in_group: intersection.add(char) yes_per_group = intersection first_in_group = False # no newline at EOF means checking final record total += len(yes_per_group) print(total) return total sum_group_everyone_yes()
import heapq def read_input_file(): with open("./input.txt") as file: for row in file: yield int(row.rstrip("\n")) def construct_heap(): h = [] for num in read_input_file(): heapq.heappush(h, num) return h def joltage_diff(): diffs = {1: 0, 3: 0} h = construct_heap() start = 0 while len(h) > 0: el = heapq.heappop(h) diffs[el - start] += 1 start = el print(diffs[1] * (diffs[3] + 1)) return diffs[1] * (diffs[3] + 1) joltage_diff()
def read_input_file(): with open("./input.txt") as file: for row in file: yield row.strip() def count_trees(): num_trees = 0 x_coord = 0 for line in read_input_file(): x_coord = x_coord % len(line) if line[x_coord] == "#": num_trees += 1 x_coord += 3 print(num_trees) return num_trees count_trees()
#Type List def typeList(list): intsum = 0; strconcat = "String: "; for value in list: if type(value) == int: intsum += value if type(value) == float: intsum += value if type(value) == str: strconcat += value + " " if intsum > 0 and len(strconcat) > 8: print "The array you entered is of mixed type" elif intsum > 0: print "The array you entered is of integer type" elif len(strconcat) > 8: print "The array you entered is of string type" if intsum > 0: print "Sum: " + str(intsum) if len(strconcat) > 8: print strconcat typeList(['magical','unicorns']) # good.
# Find Characters def findCharacters(list, letter): newList = [] for value in list: if value.find(letter) >= 0: newList.append(value) print newList findCharacters(['hello','world','my','name','is','Anna'], 'o')
"""class Node: def __init__(self,data): self.data=data self.next=None class sing: def __init__(self): self.head=None def be(self,newda): newnode=Node(newda) newnode.next=self.head self.head=newnode def dd(self): val=self.head while val is not None: print(val.data) val=val.next def end(self,newdata): newnode=Node(newdata) if self.head is None: self.head=newnode return last=self.head while last.next: last=last.next last.next=newnode ll=sing() ll.be("3") ll.be("2") ll.be("1") #ll.dell("2") ll.end("last") ll.dd()""" """class Node: def __init__(self,data): self.data=data self.next=None class Sing: def __init__(self): self.head=None def beg(self,newdata): newnode=Node(newdata) newnode.next=self.head self.head=newnode def pri(self): val=self.head while val is not None: print(val.data) val=val.next def dele(self,key): temp=self.head if temp is not None: if temp.data==key: self.head=temp.next temp=None return while temp is not None: if temp.data==key: break prev=temp temp=temp.next if temp ==None: return prev.next=temp.next temp=None list=Sing() list.beg(3) list.beg(2) list.beg(1) list.dele(2) list.pri()""" class Node: def __init__(self,data): self.data=data self.next=None class delete: def __init__(self): self.head=None def beg(self,data): newnode=Node(data) newnode.next=self.head self.head=newnode def de(self,key): temp=self.head if temp is not None: if temp.data==key: self.head=temp.next temp=None return while temp is not None: if temp.data==key: break prev=temp temp=temp.next if temp==None: return prev.next=temp.next temp=None def trav(self): val=self.head while val is not None: print(val.data) val=val.next ll=delete() ll.beg(4) ll.beg(3) ll.beg(2) ll.beg(1) ll.trav() print() ll.de(2) ll.trav()
# 3 1 5 7 # class Solution(object): # def maxArea(self, array): def maxArea(array): water = 0 i, j = 0, len(array) - 1 while i < j: print i, j high = min(array[i], array[j]) water = max(water, (j - i) * high) while array[i] <= high and i < j: i += 1 while array[j] <= high and i < j: j -= 1 return water array1 = [2, 3, 4, 5, 18, 17, 6] # 17 # array2 = [3, 1, 2, 3] # 9 # array3 = [2, 1] # 1 # array4 = [1, 1] # 1 water1 = maxArea(array1) # water2 = maxArea(array2) # water3 = maxArea(array3) # water4 = maxArea(array4) print water1 # , water2, water3, water4
#author zyzMarshall from datetime import datetime def birth_before_parents_death(indi,childname,childID,childbirthday,parentsdeathdate,death_bool): """The birth of a child should within 9 month after the death of their father(if the death date exist.),and can't born after their mother's death""" if (datetime.strptime(childbirthday,'%d%b%Y'))>(datetime.strptime(parentsdeathdate,'%d%b%Y')) and death_bool == False: birthdate = datetime.strptime(childbirthday,'%d%b%Y') parentsdeath = datetime.strptime(parentsdeathdate,'%d%b%Y') interval = ((birthdate - parentsdeath).days/365)*12 #timedelta between child birth and parents death if interval>9: error = "ERROR Us09 at line%s: Birthday of child %s%s is longer than 9 months after father's death\n"%(indi[childID]['BIRT_rec'],childID,childname) print(error) return error elif ((datetime.strptime(childbirthday,'%d%b%Y'))>(datetime.strptime(parentsdeathdate,'%d%b%Y'))): error ="ERROR Us09 at line%s: Birthday of child %s %s is after their mother's death.\n"%(indi[childID]['BIRT_rec'],childID,childname) print(error) return error
from datetime import datetime def age_cal(birthday): # calculate individual's age birthdate = datetime.strptime(birthday, '%d%b%Y') current = datetime.today() return current.year - birthdate.year - ((current.month, current.day) < (birthdate.month, birthdate.day))
with open('./input.txt') as fp: result = 0 for line in fp: mass = int(line) fuel = mass // 3 - 2 result += fuel print(result)
import random from tkinter import * while 1: tk = Tk() tk.resizable(0,0) tk.title('呵呵') canvas = Canvas(tk, width=500, height=500, bg='black', highlightthickness=0) canvas.pack() canvas.create_text(250, 250, text='呵呵', font=('Arial', random.randint(50, 300)),fill='green') tk.update()
""" Sungmin Kim ball_puzzle.py """ from ball_puzzle_animate import * from stack import * def first_balls(ball_colors): """ takes a string of R G B characters and adds them to the red can stack """ red_can = make_empty_stack() for color in ball_colors: push(red_can, color) return red_can def solve(red_can, blue_can, green_can): """ solves the ball puzzle, each parameter is an empty stack except for red can which is filled. takes balls from a can and puts a ball of a target color into the right can. The other colors go into the other can as a throwaway. This is repeated until cans are sorted. """ counter = 0 can_list = [red_can, green_can, blue_can] while not is_empty(red_can): top_ball = pop(red_can) if top_ball == "B": push(blue_can, top_ball) animate_move(can_list, 0, 2) else: push(green_can, top_ball) animate_move(can_list, 0, 1) counter += 1 while not is_empty(green_can): top_ball = pop(green_can) if top_ball == "R": push(red_can, top_ball) animate_move(can_list, 1, 0) else: push(blue_can, top_ball) animate_move(can_list, 1, 2) counter += 1 while not is_empty(blue_can): top_ball = pop(blue_can) if top_ball == "G": push(green_can, top_ball) animate_move(can_list, 2, 1) counter += 1 return counter def main(): """ calls functions to animate the solving of the puzzle """ balls = input("Enter the color of the balls starting in the red can:") animate_init(balls) print(solve(first_balls(balls), make_empty_stack(), make_empty_stack())) print("Close the window to quit") animate_finish() main()
''' This program's goal is to allow the user to guess a number between 0 and 1023 inclusive. The program picks the number and if the user picks the correct number, they will get a message. This code was made by Julian. ''' ''' This block shows the maximum number of the candy that the machine can hold and tells the computer to pick a number between 0 and 1023 inclusive. ''' import random candyGuess = 1024 numberOfCandy = random.randint(0, 1023) ''' This block of code shows that while the user's guess is not equal to to the computers pick, run the program again. ''' while candyGuess != numberOfCandy: while True: try: candyGuess = int(input("Guess how many candies are in the machine!")) if candyGuess < 0: ''' If the user puts an input that is invalid (negative numbers or symbols), the code will reprompt the user. ''' print("Please put a positive number.") continue break except ValueError: print("That's not a valid input") if candyGuess < numberOfCandy: print("That guess is too low! Guess again!") elif candyGuess > numberOfCandy: print("That guess is too high! Guess again!") ''' When the user's guess is equal to the computer's pick, the program will print this: ''' print("That's it! You got it!")
# Momento 1 programa = sistemas and finanzas alumno_count = 0 count_sexM = 0 count_sexF = 0 total = 0.0 while true: alumno = int(input("ingrese nombre de Alumno: ")) average = float(input("Ingrese notas: ")) alumno = alumno_count+1 nota = notas + nota for i in range (alumno): print "Escriba la nota de las 5 clases" nota1 = float(input('Nota1: ')) nota2 = float(input('Nota2: ')) nota3 = float(input('Nota3: ')) nota4 = float(input('Nota4: ')) nota5 = float(input('Nota5: ')) total=nota1+nota2+nota3+nota4+nota5 total=total/5 # Parte II gender=input("Sexo del alumno: ") count_sexM == "m" count_sexF == "f" for i in range (alumno): gender = input("Ingrese genero del alumno: ") if gender == "m": count_sexM+=1 else gender =="f": count_sexF+=1 for i in range (alumno): promedad = input("Ingrese edad del alumno: ") print "Cantidad de alumnos matriculados es: " ,alumno_count print "Promedio de edad " ,promedad print "El total de sus 5 calificaciones es: ",total close_program= input ("Desea continuar: Si-No") if close_program != 'Si': break
import logging def f(a, *args): print(locals()) def f0(): """ a function no args """ print('f0') d = dict(locals()) for x in d: print('\t', x, d[x]) def f1(a, b=1): """ another function, lots of args """ print('f1') d = dict(locals()) for x in d: print('\t', x, d[x]) def f2(c, a=1, b=1, **kwargs): """ yet another function """ print('f2') d = dict(locals()) for x in d: print('\t', x, d[x]) def f3(a: 'first arg', aa: 'second arg', *args: 'other args', b: 'b variable'=3, **kwargs): """ one last one """ print('f3') d = dict(locals()) for x in d: print('\t', x, d[x])
#Programa que calcula tu masa corporal weight = input("Inserta tu peso en kg: ") height = input("Inserta tu estatura en metros: ") bmi = round(float(weight)/float(height)**2,2) print ("Tu indice de masa corporal es: "+str(bmi))
#impuestos sobre la renta income = float(input("Cual es tu renta anual: ")) if income < 10000: tax = 5 elif income < 20000: tax = 15 elif income < 35000: tax = 20 elif income < 60000: tax = 30 else: tax=45 print("Tus impuestos son: "+str(tax)+"%")
def solution (number): acum=0 for i in range (number): if i%3==0 or i%5==0: acum=acum+i return acum if __name__=="__main__": res=solution(500) print (res)
import Special_Random class WaterGun(object): def __init__(self, capacity, distance=30, stock=False): # These are things that a WaterGun has. # All of these should be relevant to our program. self.capacity = capacity self.range = distance self.trigger = True # Someone's triggered? self.stock = stock self.duration_of_pressure = 5 def shoot(self, time): if self.trigger: if self.duration_of_pressure <= 0: print("There's no pressure") elif self.duration_of_pressure < time: print("You run out of pressure after firing for %s seconds", self.duration_of_pressure) self.duration_of_pressure = 0 else: print("You shoot for %s seconds" % time) self.duration_of_pressure -= time else: print("There's no trigger!") def pump_it_up(self): self.duration_of_pressure = 5 print("You pump the tank back to full pressure") # Initialize the object my_water_gun = WaterGun(5.2, 40, True) your_water_gun = WaterGun(1.0, 1, False) wiebe_water_gun = WaterGun(9999999999, 9999999999999999999999999999, True) yahir_water_gun = WaterGun(0, 1) # Do stuff with the objects my_water_gun.shoot(5) my_water_gun.pump_it_up() my_water_gun.shoot(1) print(Special_Random.RandomWiebe.special_random())
# ### Problem 3 # Given 2 lists of claim numbers, write the code to merge the 2 lists provided to produce a new list by alternating values between the 2 lists. Once the merge has been completed, print the new list of claim numbers (DO NOT just print the array variable!) # ``` # # Start with these lists list_of_claim_nums_1 = [2, 4, 6, 8, 10] list_of_claim_nums_2 = [1, 3, 5, 7, 9] # ``` # Example Output:list_of_claim_nums_2[each] # ``` # The newly created list contains: 2 1 4 3 6 5 8 7 10 9 # ``` # Create empty variable array newclaimList = [] # for each in range(len(list_of_claim_nums_1)): # # newclaimList = str(list_of_claim_nums_1[each]) + str(list_of_claim_nums_2[each) # print(newclaimList) # append claim list to new list and print newclaimList.append(list_of_claim_nums_1) newclaimList.append(list_of_claim_nums_2) print(newclaimList) # created for loop to print each index in list for each in newclaimList: print(newclaimList[::1]) # newclaimList.append(list_of_claim_nums_2) # print(newclaimList[each])
#!/bin/python3 """ Given an array (its values as a space separated list), perform d left rotations taking into account that the array is circular. """ import copy def rot_left(a, d): # Maybe better like return a[d:] + a[:d] orig = copy.copy(a) # shallow copy for i in range(len(a)): a[i-d] = orig[i] return a if __name__ == '__main__': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) print(rot_left(a, d))
#!/bin/python3 """ Given two sentences, the first representing the available words on a magazine and the second the words needed to write a ransom note. Check if said note can be writte. Take into account that words are case sensitive. """ from collections import Counter def check_magazine(magazine, note): can_wrinte = "Yes" if Counter(note) - Counter(magazine) == {} else "No" print(can_wrinte) if __name__ == '__main__': mn = input().split() m = int(mn[0]) n = int(mn[1]) magazine = input().rstrip().split() note = input().rstrip().split() check_magazine(magazine, note)
#!/bin/python3 """ Given an array of integer, count the number of triplets (x, y, z) which follow a geometric progression of a given ratio (r); e.g. for r=5, (5, 25, 125) would be a triplet. Triplets do not have to be consecutive, e.g. the can be in positions (0, 4, 10). """ from collections import defaultdict, Counter def count_triplets(arr, r): appearances = Counter(arr) # could be understood as right hand vals seen = defaultdict(int) # could be understood as left hand vals num_triplets = 0 for val in arr: first_val = val // r second_val = val third_val = second_val * r appearances[val] -= 1 # not second_val % r because we only want exact multiples of the ratio if seen[first_val] and appearances[third_val] and not second_val % r: num_triplets += seen[first_val] * appearances[third_val] seen[second_val] += 1 return num_triplets if __name__ == '__main__': nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) print(count_triplets(arr, r))
#!/bin/python3 """ Given an array of integers representing the places where a leaf falls, calculate the time when there are leaves in positions 1 to X (included). Return -1 if not possible. """ # Checking if the sum of the elements is equal to what it should # (i.e. n*(n+1)//2) would not work because numbers can be compensated. # It needs to check for exact existance. def perm_check(A, X): nums = set() for i in range(1, len(A)+1): nums.add(i) for num in A: try: nums.remove(num) except KeyError: pass # Repeated or out of range numbers return 1 if not len(nums) else 0 # Example execution # (4, 3, 1, 2) --> 1 # (4, 1, 3) --> 0 (Should not contain 4, but contain 2)
#!/bin/python3 """ Two strings are anagrams when they contain the same characters with the same frequency. Calculate the minimum number of characters to remove from them so they are anagrams. """ from collections import Counter def make_anagram(a, b): chars_a = Counter(a) chars_b = Counter(b) to_remove = 0 for char, amount_a in chars_a.items(): amount_b = chars_b.get(char) if not amount_b : to_remove += amount_a else: to_remove += abs(amount_a - amount_b) chars_b.pop(char) for char, amount_b in chars_b.items(): to_remove += amount_b return to_remove if __name__ == '__main__': a = input() b = input() print(make_anagram(a, b))
#!/bin/python3 """ Given a list of operations defined as (start index, end index, value) sum up the value to all index positions between the start and end index. Note that those indexes start in 1. Return the maximum value of the resulting array. """ import itertools # Trivial but requires more resources than allocated. # def array_manipulation(n, queries): # array = [0] * n # Create 0-filled array or length n # max_val = 0 # Cuz max() is O(n) # for query in queries: # for i in range(query[0]-1, query[1]): # array[i] += query[2] # if array[i] > max_val: # max_val = array[i] # return max_val def array_manipulation(n, queries): array = [0] * n # Create 0-filled array or length n for query in queries: array[query[0] - 1] += query[2] if query[1] < n: array[query[1]] -= query[2] # To compensate on accumulate # Could do a manual loop and do O(n) instead of O(n*n) return max(itertools.accumulate(array)) if __name__ == '__main__': nm = input().split() n = int(nm[0]) m = int(nm[1]) queries = [] for _ in range(m): queries.append(list(map(int, input().rstrip().split()))) print(array_manipulation(n, queries))
class Spot: ''' Coordinate object Contains overloaded functions for comparison, hashing, and addition ''' def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if self.x == other.x and self.y == other.y: return True else: return False def __add__(self, other): x = self.x + other.x y = self.y + other.y return Spot(x, y) def __hash__(self): return hash((self.x, self.y)) def __str__(self): return str(self.x) + ', ' + str(self.y) def double(self): ''' Used for checking past the box to see what's behind it ''' return Spot(self.x * 2, self.y * 2)
from stop_watch import start_watch, stop_watch_print def knapsack(n, m, weights): if n == 0: return 0 if m == -1: return 0 if weights[m] <= n: return max(weights[m] + knapsack(n - weights[m], m - 1, weights), knapsack(n, m - 1, weights)) else: return knapsack(n, m - 1, weights) def knapsack_memo(n, m, weights, dp): if n == 0 or m == -1: return 0 if dp[n][m] != -1: return dp[n][m] if weights[m] <= n: res = max(weights[m] + knapsack_memo(n - weights[m], m - 1, weights, dp), knapsack_memo(n, m - 1, weights, dp)) dp[n][m] = res return res else: res = knapsack_memo(n, m - 1, weights, dp) dp[n][m] = res return res def knapsack_DP(m,n, weights): dp = [[0 for i in range(0, m + 1)] for j in range(0, n + 1)] dp[n][0] = 0 for i in range(1, m + 1): for j in range(0, n + 1): if weights[i - 1] <= j: dp[j][i] = max(dp[j][i - 1], dp[j - weights[i - 1]][i - 1] + weights[i - 1]) else: dp[j][i] = dp[j][i - 1] return dp[n][m] def knapsack_DP_reconstruct(W, weights): dp = [[0 for i in range(0, len(weights) + 1)] for j in range(0, W + 1)] n = len(weights) decisions = [[False for i in range(0, len(weights) + 1)] for j in range(0, W + 1)] dp[W][0] = 0 for i in range(1, n + 1): for w in range(0, W + 1): if weights[i - 1] <= w: if dp[w - weights[i - 1]][i - 1] + weights[i - 1] > dp[w][i - 1]: # We record the decision here that its beneficial to pick the ith item decisions[w][i] = True dp[w][i] = dp[w - weights[i - 1]][i - 1] + weights[i - 1] else: dp[w][i] = dp[w][i - 1] else: dp[w][i] = dp[w][i - 1] i = n w = W while i > 0 and w > 0: if decisions[w][i]: print("Picked up {} , Weight {}".format(i - 1, weights[i - 1])) w -= weights[i - 1] i -= 1; else: i -= 1 return dp[W][n] weights = [3, 6, 10, 6] W = 20 N = len(weights) # Recursive solution start_watch() print(knapsack(W, N - 1, weights)) stop_watch_print("Recursive solution {} millis") # Memoization dp = [[-1 for i in range(0, len(weights) + 1)] for j in range(0, W + 1)] start_watch() print(knapsack_memo(W, N - 1, weights, dp)) stop_watch_print("Memoization solution {} millis") \ \ # Bottom up start_watch() print(knapsack_DP(W, weights)) stop_watch_print("Bottom up solution {} millis") # Bottom up with solution reconstruction print(knapsack_DP_reconstruct(W, weights))