blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
7824f37abb2647b29d5ff1e43ac88692ac613c94
JXY3511088jxy/pythonprictise
/python基础知识/python基础/元组.py
1,177
3.640625
4
#coding:utf-8 ''' Python 的元组与列表类似,不同之处在于元组的元素不能修改。 元组使用小括号,列表使用方括号。 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。 ''' '''创建空元组''' tup1 = () '''元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用''' tup1 = (50) print(type(tup1)) # 不加逗号,类型为整型 tup1 = (50,) print(type(tup1)) # 加上逗号,类型为元组 '''访问元组''' tup1 = ('Google', 'Runoob', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7) print("tup1[0]: ", tup1[0]) print("tup2[1:5]: ", tup2[1:5]) '''修改元组:元组中的元素值是不允许修改的,但我们可以对元组进行连接组合''' tup1 = (12, 34.56); tup2 = ('abc', 'xyz') # 以下修改元组元素操作是非法的。 # tup1[0] = 100 # 创建一个新的元组 tup3 = tup1 + tup2; print(tup3) '''删除元组:元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组''' tup = ('Google', 'Runoob', 1997, 2000) print(tup) del tup; print("删除后的元组 tup : ") print(tup)
4fe8c1da543d1a0a351ec88b0d2c43235ea0dd4b
vadimr/tttoe
/tttoe/boxwalker.py
4,008
4.09375
4
''' This module defines `BoxWalker` class. See its documentation. ''' class BoxWalker: """This class allows to iterate through adjacent elements in two-dimensional arrays of data, in horizontal, vertical or diagonal directions. It can help to detect sequences of identical elements in 2d arrays. For example: we have a 2d array of tictactoe game state (with "x" and "o" elemenets), and we know that the last move was made by the "x" player to the (0, 0) cell. So we can check if the user is a winner, without checking all vertical, horizontal and diagonal sequences. We can walk from the cell (0, 0) to the right, down, and diagonally to the right-down. It's cheaper than go through all the cells. This is especially beneficial for large arrays, and can be uses as a good optimization. Example usage: ary - 2d array of chars (" ", "x" or "o") field_width = 3 field_height = 3 last_step_x = 1 last_step_y = 1 walker = BoxWalker(field_width, field_height, last_step_x, last_step_y) # checking horizontal cells count = 0 # This method will iterate us on all available steps in the specified # direction, within the specified borders. # It iterates only on adjacent cells, so we can count the continuous # sequence. for x, y in walker.steps_in_direction(1, 0): if ary[x][y] == "x": count += 1 if count == 3: # We found a continuous sequence of three "x" chars. # So we found the winner. break else: # Here we decide that further sequence is broken (we found chars # other than "x") and we want to try the opposite direction. # This walker.turn_around_or_stop() """ def __init__(self, width, height, pos_x, pos_y): self._width = width self._height = height self._pos_x = pos_x self._pos_y = pos_y self._stopped = False if self._is_out_of_the_box(self._pos_x, self._pos_y): raise ValueError("pos_x and pos_y should be inside the box " \ "(width: %d, height: %d, x: %d, y: %d)" % \ (self._width, self._height, self._pos_x, self._pos_y)) def _is_out_of_the_box(self, pos_x, pos_y): """Checks if provided x,y coordinats belongs to the area inside the box""" if pos_x < 0 or pos_x >= self._width: return True if pos_y < 0 or pos_y >= self._height: return True return False def steps_in_direction(self, dir_x, dir_y): """Returns generator. Iterates on all available steps within the specified box. dir_x and dir_y arguments can indicate only vertical, horizontal or diagonal direction. So their values can be only -1, 0 or 1. """ for direction in [dir_x, dir_y]: if direction not in (-1, 0, 1): raise ValueError("dir_x and dir_y can be only -1, 0, 1, " \ "but %d provided" % direction) if dir_x == 0 and dir_y == 0: raise ValueError("dir_x and dir_y can't be 0 at the same time") yield self._pos_x, self._pos_y for positive_or_negative in [1, -1]: self._stopped = False dir_x *= positive_or_negative dir_y *= positive_or_negative inc_x = dir_x inc_y = dir_y while True: if self._stopped: break pos_x = self._pos_x + inc_x pos_y = self._pos_y + inc_y if self._is_out_of_the_box(pos_x, pos_y): break yield pos_x, pos_y inc_x += dir_x inc_y += dir_y def turn_around_or_stop(self): """Indicates that we should turn around and iterate in reverse direction. """ self._stopped = True
6d2eac8177c7e4d33e62018a9696ca273b88f67b
Chaozs/Clean-Messenger
/WordChecker.py
1,069
3.953125
4
# Read file with english words, return list of all words seperated by newline def get_words_from_file(filename): fileWords = open(filename, "r") words = fileWords.read().splitlines() fileWords.close() return words # check if a string exists in a list of words that are passed in def check_word_exists_in(words, stringToCheck): #Check if word exists in list of english words #check lowercase of filter word, as all strings in englishWords are lowercase return (stringToCheck.lower() in words) # append a word to end of file def add_word_to_file(filename, stringToAdd): file = open(filename, "a+") file.write(stringToAdd) file.write("\n") file.close() # remove a word from a file def remove_string_from_file(filename, stringToCheck): filter = open(filename, "r+") filterWords = filter.readlines() filter.seek(0) for word in filterWords: if word.strip() != stringToCheck.strip(): filter.write(word) else: pass filter.truncate() filter.close() return False
4730cc1d9940f01c473d74a35eb847dc1752cc0c
codin-eric/herencia-y-polimorfismo
/animales.py
635
3.53125
4
class Mascota: def __init__(self, nombre): self.nombre = nombre def saludar(self): print(f"Hola mi nombre es {self.nombre}") class Perro(Mascota): def saludar(self): print(f"Hola mi nombre es {self.nombre} y soy un perro") class Gato(Mascota): def saludar(self): print(f"Hola mi nombre es {self.nombre} y soy un gato") class Pajaro(Mascota): def saludar(self): print(f"Hola mi nombre es {self.nombre} y soy un pajaro") if __name__ == '__main__': p1 = Perro("Framir") g1 = Gato("Keo") b1 = Pajaro("Jorge") p1.saludar() g1.saludar() b1.saludar()
e87c923ce1937778fcc547cd8e6c77cffeed353a
KoliosterNikolayIliev/Softuni_education
/Fundamentals2020/Text Processing - Exercise/01. Valid Usernames.py
148
3.75
4
users = input().split(", ") for user in users: if 3 <= len(user) <= 16 and (user.isalnum() or "_" in user or "-" in user): print(user)
4508a276d9986ec9c172459239658fde8b9b5424
NikitaFedyanin/python_tests
/other/text_version_control.py
1,542
3.578125
4
""" Своеобразная система контроля версий для текстового редактора """ class TextEditor: text = '' style = None def write(self, text): self.text += text def set_font(self, font): self.style = '[{}]'.format(font) def show(self): if self.style: return '{0}{1}{0}'.format(self.style, self.text) return self.text def restore(self, version): self.text = version[0] self.style = version[1] class SavedText: versions = {0: ['', None], 1: ['', None], 2: ['', None], 3: ['', None], 4: ['', None], 5: ['', None], 6: ['', None], 7: ['', None], 8: ['', None], 9: ['', None]} text_editor = TextEditor() state = -1 def save_text(self, current_text): self.state += 1 self.versions[self.state] = [current_text.text, current_text.style] def get_version(self, ver_number): return self.versions[ver_number] if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing text = TextEditor() saver = SavedText() text.write("At the very beginning ") saver.save_text(text) text.set_font("Arial") saver.save_text(text) text.write("there was nothing.") assert text.show() == "[Arial]At the very beginning there was nothing.[Arial]" text.restore(saver.get_version(0)) assert text.show() == "At the very beginning " print("Coding complete? Let's try tests!")
ec2b8d4bc7c34e3b710c4f0d8631b293dbb65585
Jaceyli/COMP9021-17S2
/Lab/Lab_4/characters_triangle.py
557
3.625
4
import sys # print(ord('Z')) # print(chr(90)) def triangle(n): for e in range(1, n+1): L = [i for i in range(sum(list(range(e)))+1, sum(list(range(e+1)))+1)] L1 = L[:-1] L1 = L1[::-1] L.extend(L1) y = n - e print(' '*y, end="") print(''.join(chr((x-1) % 26+65) for x in L)) height = input('Enter strictly positive number: ') try: height = int(height) if height < 0: raise ValueError except ValueError: print('Incorrect input, giving up.') sys.exit() triangle(height)
6dbcb0771e77e861273555e96e770def499b3218
LiKevin/python
/working_relative/random_study_wk43.py
1,923
4.03125
4
# -*- coding: utf-8 -*- __author__ = 'k22li' import random def testFunction10Times(func ='', *arg): for i in range(10): print 'The %d \'s result of %s calling is:'%(i, func) print func(*arg) """ random.random random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0 """ tFunc = random.random testFunction10Times(tFunc) """ random.uniform random.uniform的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。 如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= a。""" tFunc = random.uniform testFunction10Times(tFunc, 2, 3) """ random.randint random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b""" tFunc = random.randint testFunction10Times(tFunc, 2, 10) """ random.randrange random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。 如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。 random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。""" tFunc = random.randrange testFunction10Times(tFunc, 10, 100, 2) """ random.shuffle random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱。""" tFunc = random.shuffle tList = ['this', 'is', 'an', 'random', 'shuffle', 'function', 'test'] #testFunction10Times(tFunc, tList) #print tList """ random.sample random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。""" tFunc = random.sample testFunction10Times(tFunc, tList, 3)
d5e81645ab051a7e3f58d518ec515151fcd5406e
Sashagrande/Faculty-of-AI
/Lesson_6/task_4.py
5,657
4.125
4
class Car: yes = ('да', 'Да') def __init__(self, name, color, speed, is_police): self.Name = name self.Color = color self.Speed = speed self.Is_police = True if is_police in self.yes else False print(f'Автомобиль - {self.Name}, цвет - {self.Color}, скорость - {self.Speed} добавлен.', 'Автомобиль является полицейским' if self.Is_police else '') self.show_speed() def go(self, speed): self.Speed = speed print(f'Машина {self.Name} изменила скорость и теперь она движется со скоростью - {self.Speed}') self.show_speed() def stop(self): self.Speed = 0 print(f'Машина {self.Name} остановилась') def turn(self, direction): print(f'Машина {self.Name} повернула {direction}') def show_speed(self): print(f'Текущая скорость автомобиля - {self.Speed}') class TownCar(Car): def show_speed(self): if int(self.Speed) > 60: print(f'У автомобиля {self.Name} превышена скорость!!!') print( f'Внимание!!! Сработала система безопасности, дальнейшее движение со сокростью {self.Speed} запрещено!') self.Speed = 60 # и скорость автоматически снизилась до максимально допустимой class SportCar(Car): pass class WorkCar(Car): def show_speed(self): print(f'У автомобиля {self.Name} превышена скорость!!!') print( f'Внимание!!! Сработала система безопасности, дальнейшее движение со сокростью {self.Speed} запрещено!') self.Speed = 40 # и скорость автоматически снизилась до максимально допустимой class PoliceCar(Car): def turn_on_the_flashes(self): if self.Is_police: print('Мигалки включены') def turn_off_the_flashes(self): if self.Is_police: print('Мигалки выключены') # Катаемся на личном авто и мониторим показания спидометра my_own_car = TownCar(name=input('Введите название машины: '), color=input('Введите цвет машины: '), speed=input('Введите скорость: '), is_police=input('Это полицейская машина? \nда или нет: ')) print() my_own_car.go(100) print('Текущая скорость -', my_own_car.Speed) my_own_car.turn('Налево') my_own_car.go(120) print('Текущая скорость -', my_own_car.Speed) my_own_car.stop() print('Текущая скорость -', my_own_car.Speed) print('*' * 40) # Катаемся на корпоративном автомобиле и мониторим показания спидометра corporate_car = WorkCar(name=input('Введите название машины: '), color=input('Введите цвет машины: '), speed=input('Введите скорость: '), is_police=input('Это полицейская машина? \nда или нет: ')) print() corporate_car.go(100) print('Текущая скорость -', corporate_car.Speed) corporate_car.turn('Направо') corporate_car.go(120) print('Текущая скорость -', corporate_car.Speed) corporate_car.stop() print('Текущая скорость -', corporate_car.Speed) print('*' * 40) # Катаемся на спорткаре и мониторим показания спидометра sport_car = SportCar(name=input('Введите название машины: '), color=input('Введите цвет машины: '), speed=input('Введите скорость: '), is_police=input('Это полицейская машина? \nда или нет: ')) print() sport_car.go(100) print('Текущая скорость -', sport_car.Speed) sport_car.turn('Налево') sport_car.go(200) print('Текущая скорость -', sport_car.Speed) sport_car.turn('Налево') sport_car.stop() print('Текущая скорость -', sport_car.Speed) print('*' * 40) # Катаемся на полицейской тачке, мониторим показания спидометра и гонимся за нарушителем на спорткаре police_car = PoliceCar(name=input('Введите название машины: '), color=input('Введите цвет машины: '), speed=input('Введите скорость: '), is_police=input('Это полицейская машина? \nда или нет: ')) print() police_car.go(100) print('Текущая скорость -', police_car.Speed) police_car.turn('Направо') print(f'Полицейская машина погналась за {sport_car}') police_car.turn_on_the_flashes() police_car.go(120) print('Текущая скорость -', police_car.Speed) police_car.stop() print('Текущая скорость -', police_car.Speed) police_car.turn_off_the_flashes()
2ebd342c0031e8ad549cee8e5a98448d07d79c53
rafaelgama/Curso_Python
/CursoEmVideo/Mundo3/Aulas/aula18.py
1,168
4.09375
4
# Nessa aula, vamos aprender o que são LISTAS e como utilizar listas em Python. # As listas são variáveis compostas que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais. teste = list() teste.append('Rafael') teste.append(40) galera = list() galera.append(teste[:]) # é necessário sempre fazer uma cópia, se não colocar o [:], ele apenas vai referenciar. teste[0] = 'Gama' teste[1] = 42 galera.append(teste[:]) print(galera) print('-=-'*10) # Mostrando como imprimir os dados pessoas = [['João',23],['Maria',24],['Joaquim',30],['Paulo',18]] for g in pessoas: print(f'{g[0]} tem {g[1]} anos de idade.') print('-=-'*10) # Mostrando outra fomra de manipular os dados galera = list() dado = list() totmai = totmen = 0 for c in range(0,3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera.append(dado[:]) dado.clear() for d in galera: if d[1] >= 21: print(f'{d[0]} é maior de idade.') totmai += 1 else: print(f'{d[0]} é menor de idade.') totmen += 1 print(f'Temos {totmai} maiores e {totmen} menores de idade.') print('-=-'*10)
32b6f79e273e39802b2156db64f4cf93be86cadf
jacob3015/SWExpertAcademy
/D1_1933_SimpleNDivisor.py
700
3.546875
4
""" Problem : 간단한 N 의 약수(Simple N Divisor) 입력으로 1개의 정수 N 이 주어진다. 정수 N 의 약수를 오름차순으로 출력하는 프로그램을 작성하라. N은 1이상 1,000이하의 정수이다. (1 <= N <= 1,000) 입력으로 정수 N이 주어진다. 정수 N의 모든 약수를 오름차순으로 출력한다. """ def solution(): # 정수 N N = int(input()) # N의 모든 약수를 저장할 result result = [] # N의 모든 약수를 구해 result 에 append 한다. for n in range(1, N+1): if N % n == 0: result.append(n) # 결과를 출력한다. for r in result: print(r, end=' ') solution()
03d74721ed17719704f310ae60308d885701185a
gjewstic/GA-Python
/homework/hw-3_pig_game.py
2,586
4.15625
4
import random turn = 1 player_one_total = 0 player_two_total = 0 max_score = 50 selection = int(input('Who will be rolling first? Enter a 1 or 2: ')) turn = selection while True: choice = input(f'Player {turn}, do you choose to roll (r) or pass (p)? ') if choice == 'r': score = random.randint(1, 15) if score is not 1: if turn is 1: player_one_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_one_total}') else: player_two_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_two_total}') else: if turn is 1: print( f'Player {turn}, your score is {score}. You lose your turn.') player_one_total = 0 turn = 2 else: print( f'Player {turn}, your score is {score}. You lose your turn.') player_two_total = 0 turn = 1 # else: if turn == 1: turn = 2 print(f'Player {turn}, your score is {score}.') else: turn = 1 choice = input( f'Player {turn}, do you choose to roll (r) or pass (p)? ') score = random.randint(1, 15) # if score is not 1: if turn is 1: player_one_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_one_total}') else: player_two_total += score print( f'Player {turn}, you scored {score}. Your current total is: {player_two_total}') else: if turn is 1: print( f'Player {turn}, your score is {score}. You lose your turn.') player_one_total = 0 turn = 2 else: print( f'Player {turn}, your score is {score}. You lose your turn.') player_two_total = 0 turn = 1 # if player_one_total >= max_score or player_two_total >= max_score: if player_one_total > max_score: print(f'Player 1 is the winner!! Score = {player_one_total}') else: print(f'Player 2 is the winner!! Score = {player_two_total}') break
a7d9dbe6b473d6bdfa94d905a4413df4ef87a423
newbieeashish/LeetCode_Algo
/3rd_30_questions/LongestHarmoniousSubsequence.py
1,122
4.09375
4
''' We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of Example 1: Input: nums = [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. Example 2: Input: nums = [1,2,3,4] Output: 2 Example 3: Input: nums = [1,1,1,1] Output: 0 ''' def LongestHarmonious(nums): nums = sorted(nums) n = {} for i in nums : if i not in n : n[i] = 1 else: n[i] += 1 #print(n) l = list(n.keys()) m = 0 for i in range(len(l)-1): if l[i+1] -l[i] == 1: c = n[l[i]]+n[l[i+1]] if c >= m: m = c #print(n[i]) #print(n.sort()) return m print(LongestHarmonious([1,1,1,1]))
14a58a2c6917b36a7583cdb8602f93b94621028d
rifanarasheed/PythonDjangoLuminar
/REGULAR_EXPRESSION/program5.py
316
4.0625
4
from re import * mobile_no = input("enter the mobile number") rule="(91)?\d{10}" # checks for 91 is present or not, both are valid and 10 digits mandatory matcher = fullmatch(rule,mobile_no) if matcher == None: print(":invalid mobile number") else: print("valid mobile number")
d1141a8e4aa079515d80ec04d02f2f0ae4fff284
littlecodersh/Apprentices
/Wu/2.py
478
3.734375
4
def sum_fib(number,odd=True): a = 0 b = 1 L = [] single=[] double=[] for i in range(number): L.append(b) a = b b = a+b if b >= number: break for each in L: if each %2==0: double.append(each) elif each %2 !=0: single.append(each) if odd==True: return (sum(single)-1) else: return sum(double) print (sum_fib(4000000,False))
b29a74a294a57435decff48735cc592def2a1a63
fujimaki3968/meister-serverless-IoT
/ch01/tutorial01.py
2,105
4.1875
4
# python 基本文法 tutorial # print コンソールに出力 print("Hello, World!") # titleという変数に文字列(string)を代入 title = "serverless IoT" # title: str = "serverless IoT" <- このように型を定義して代入も可能 # chapterという変数に整数(integer)を代入 chapter = 1 # chapter: int = 1 # chapter変数は文字ではないのでstr(変数)で文字列に変換 print(title + " chapter: " + str(chapter)) # input() で文字列の入力を取得 text = input("適当に文字を入力してください: ") print("入力内容: " + text) # len()で文字列の長さを取得 text_length = len(text) print("文字列の長さ: " + str(text_length)) # if文 text_lengthが10だったら if text_length == 10: print("この文字列は10文字です!") # text_lengthが10ではなく、10より大きかったら elif text_length > 10: print("この文字列の長さは10より大きいです") # text_lengthが10でも10以上でもなかったら else: print("この文字列の長さは10より小さいです") print("-----------------------------") print("1 + 1 = ", 1+1) print("4 - 1 = ", 4-1) print("2 x 2 = ", 2*2) print("6 ÷ 3 = ", 6/3) # わったあまりを求める print("7を3で割ったあまり =", 7%3) print("-----------------------------") # 1から10を足す sum_num = 0 for i in range(1, 11): sum_num += i print("sum_num +", i) print("sum_num ->", sum_num) print("-----------------------------") # 配列(リスト)を作成 今回は文字列の配列 array = ['python', 'IoT', 'serverless', 'aws', 'cloud'] # arrayに入っている文字列の長さの合計を求める sum_array_text_length = 0 for string in array: print("文字列: ", string) print(" 長さ: ", str(len(string))) sum_array_text_length += len(string) print("文字列合計:", sum_array_text_length) # 辞書型変数 print("----------------------------") makiart = { "name": "藤巻晴葵", "belongs": "4J32", "age": 18 } print(makiart["name"]) print(makiart["belongs"]) print(makiart["age"])
c22ad5ce93110f8e13093914607ca8dec8cc1a18
eric496/leetcode.py
/tree/272.closest_binary_search_tree_value_II.py
1,398
3.796875
4
""" Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. Note: Given target value is a floating point. You may assume k is always valid, that is: k ≤ total nodes. You are guaranteed to have only one unique set of k values in the BST that are closest to the target. Example: Input: root = [4,2,5,1,3], target = 3.714286, and k = 2 4 / \ 2 5 / \ 1 3 Output: [4,3] Follow up: Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)? """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Solution 1: O(n) time complexity - a variation of inorder traversal from collections import deque class Solution: def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]: res = deque([]) self.dfs(root, target, k, res) return res def dfs(self, node: TreeNode, target: float, k: int, res: deque) -> None: if not node: return self.dfs(node.left, target, k, res) if len(res) == k: if abs(node.val - target) < abs(res[0] - target): res.popleft() else: return res.append(node.val) self.dfs(node.right, target, k, res)
41d2803ce4ce76b1761bf0ea64a510a9bf2aafa3
gva-jjoyce/gva_data
/gva/flows/operators/filter_operator.py
961
3.90625
4
""" Filter Operator Filters records, returns the record for matching records and returns 'None' for non-matching records. The Filter Operator takes one configuration item at creation - a Callable (function) which takes the data as a dictionary as it's only parameter and returns 'true' to retain the record, or 'false' to not pass the record through to the next operator. Example Instantiation: filter_ = FilterOperator(condition=lambda r: r.get('severity') == 'high') The condition does not need to be lambda, it can be any Callable including methods. """ from .internals.base_operator import BaseOperator def match_all(data): return True class FilterOperator(BaseOperator): def __init__(self, condition=match_all): self.condition = condition super().__init__() def execute(self, data={}, context={}): if self.condition(data): return data, context return None
55f310641d0d42fbe2c1f5fe6fca06c6a4382fdd
daksh105/CipherSchool
/Assignment4/PowerSubset.py
392
3.578125
4
def PowerSet(s): sets = [] __SetGenerator__(s, 0, [], sets) print(sets) def __SetGenerator__(s, cur, cur_set, sets): if cur == len(s): sets.append("".join(cur_set)) return cur_set.append(s[cur]) __SetGenerator__(s, cur + 1, cur_set, sets) cur_set.pop() __SetGenerator__(s, cur + 1, cur_set, sets) s = list(input().split()) PowerSet(s)
454488ee8896e4986633b21e9f4ebf86026c580f
hvaltchev/UCSC
/python1/notes/Module 3/Module 3 Sample Files/OrderedRectangle.py
1,260
4.3125
4
# Determine if the four side lengths represent a Rectangle or not: # Function to determine if four sides represent a Rectangle # Is a rectangle if left is the same as the right # and top is the same as the bottom def isRectangle(left, top, right, bottom): if left == right: if top == bottom: return True return False #Test cases if isRectangle(2, 8, 2, 8): print('2, 8, 2, 8 is a Rectangle') else: print('2, 8, 2, 8 is not a Rectangle') if isRectangle(2, 7, 2, 9): print('2, 7, 2, 9 is a Rectangle') else: print('2, 7, 2, 9 is not a Rectangle') # Get user input and call the function. userLeft = input('Enter the left: ') userLeft = int(userLeft) userTop = input('Enter the top: ') userTop = int(userTop) userRight = input('Enter the right: ') userRight = int(userRight) userBottom = input('Enter the bottom: ') userBottom = int(userBottom) # Let's assign the result of calling the funtion to a boolean variable, # then check the variable in the if statement userRectangle = isRectangle(userLeft, userTop, userRight, userBottom) if userRectangle: print(userLeft, userTop, userRight, userBottom, 'is a Rectangle') else: print(userLeft, userTop, userRight, userBottom, 'is not a Rectangle')
54e1920c5477e246793e0a06a5ec039c68cd4adf
oliverschwartz/leet
/flatten_binary_tree_ll/flatten_binary_tree_ll.py
405
3.53125
4
if not root: return None head = TreeNode(None) cur = head stack = [root] while stack: v = stack.pop() if v.right: stack.append(v.right) if v.left: stack.append(v.left) cur.left = None cur.right = v cur = cur.right return head.right
5c7697f763ef3b439f4269c708585180bd5a4bb3
gschen/where2go-python-test
/1300-蓝桥杯/year-2016/JAVA-C/test01.py
125
3.515625
4
result='vxvxvxvxvxvxvvx' money=777 for i in result: if i=='v': money*=2 else: money-=555 print(money)
deacfacf0bad427646a5bea6c4c4e498cc92b95d
OgnyanPenkov/Programming0-1
/week2/3-Simple-Algorithms/solutions/prime_digit.py
701
3.90625
4
# Тази задача я решаваме по следния начин: # Превръщаме n в списък от цифри # Проверяваме за всяка цифра, ако е 2, 3, 5 или 7 - значи е просто цифра # Използваме похвата с флаговата променлива n = input("Enter n: ") n = int(n) digits = [] while n != 0: digit = n % 10 digits = [digit] + digits n = n // 10 has_prime_digit = False for digit in digits: if digit in [2, 3, 5, 7]: has_prime_digit = True break if has_prime_digit: print("At least one prime digit found") else: print("No prime digits found")
0c6efcddfbadfac03af6945f6acd4af848c8d6c2
xiaoke321/pywinbot
/pywinbot/memory_reader/address.py
1,587
4.28125
4
from typing import Union class Address: """A class used to easier represent memory addresses. To use: >>> addr = Address("10BC4AF0") <Address hex=10BC4AF0 decimal=280775408> Calculating: >>> addr += 4 <Address hex=10BC4AF4 decimal=280775412> >>> addr += "A" <Address hex=10BC4AFE decimal=280775422> >>> addr += Address("10BA0170") <Address hex=21764C6E decimal=561400942> """ def __init__(self, address: Union[int, str]): """Initalizes Address class. Args: address (Union[int, str]): the address either as a string or as an integer. """ if isinstance(address, str): self.address_string = address self.address_decimal = int(address, 16) elif isinstance(address, int): self.address_string = hex(address) self.address_decimal = address def __repr__(self) -> str: # Formats 0x10bc4af0 to 10BC4AF0 string = self.address_string.replace("0x", "").upper() return f"<Address hex={string} decimal={self.address_decimal}>" def __add__(self, other: Union["Address", str, int]) -> "Address": if isinstance(other, str): return Address(self.address_decimal + int(other, 16)) elif isinstance(other, int): return Address(self.address_decimal + other) elif isinstance(other, Address): return Address(self.address_decimal + other.address_decimal) def __mul__(self, other: int): return Address(self.address_decimal * other)
a4761ba3e6dabe1a42dcbbb76af0b7e5c94725c6
roca12/gpccodes
/Codigos estudiantes por lenguaje/PY/Cristian Maldonado/MaxMin_Search.py
491
3.609375
4
def calcular (arr,n): max = 0 min = 0 if(n == 1): max = arr[0] min = arr[0] if(arr[0] > arr[1]): max = arr[0] min = arr[1] else: max = arr[1] min = arr[0] for i in range (2 ,n,1): if(arr[i] > max): max = arr[i] elif(arr[i] < min): min = arr[i] print("El minimo es:", min) print("El maximo es:", max) arr = [4000, 11, 445, -11, 330, 3000] n = len(arr) calcular(arr, n)
469e36fa745e2ae399a86b9f0c20d436686ccab5
pchen12567/Leetcode
/Algorithm_Sort/CountingSort/counting_sort.py
758
3.734375
4
def countingSort(nums): # 桶的个数 bucket = [0] * (max(nums) + 1) # 将元素值作为键值存储在桶中,记录其出现的次数 for num in nums: bucket[num] += 1 # nums 的索引 i = 0 # 遍历一次所有的"桶" for j in range(len(bucket)): # 遍历当前"桶",当"桶"中有数值的时候 while bucket[j] > 0: # 取出当前值 nums[i] = j bucket[j] -= 1 i += 1 return nums if __name__ == '__main__': import time print('Start test...') start = time.clock() nums = [3, 1, 5, 7, 8, 9, 6] re = countingSort(nums) end = time.clock() print(re) print('Running time:', end - start) print('Test end!')
3b4964e139e66ccd6ae23a95246fe33f2c13fc62
liuhu0514/py1901_0114WORK
/练习项目/练习/data/数据类型转换和eval练习.py
614
3.5
4
''' 程序中的数据,存储到文件中 ''' # 基本数据类型、组合数据类型 # 1. 将程序中的字典数据,转换成字符串存储到文件中 # users = {'admin': {'username': 'admin', 'password': '123', 'nickname': '老刘'}} # # 转换成字符串类型 # users = str(users) # print(users, type(users)) # with open("./data/1.1.text", "w") as file: # file.write(users) with open("./data/1.1.text", "r") as file: users = file.read() print(users, type(users)) # 转换成字典 users = eval(users) print(users, type(users)) print(users.get("admin").get("username"))
f5120f2cb4a1efc94d07de191144e9e8f156e588
01658836515/python-co-ban
/BTVN Buoi4.py
2,146
3.875
4
#Bài 1 : Viết chương trình thay thế tất cả các ký tự giống ký tự đầu tiên của một Chuỗi thành $. print('-'*20,"Bài 1",'-'*20) chuoi=input("nhap chuoi:") def manual_replace(s, char, index): return s[:index] + char + s[index +1:] print(manual_replace(chuoi,"$", 0)) print('*'*100) print(" ") #Bài 02: Viết chương trình để xóa bỏ ký tự thứ m trong chuỗi không rỗng, với m là số không âm, nhập từ bàn phím. print('-'*20,"Bài 2",'-'*20) chuoi=input("nhap chuoi:") def remove_char_m(str, n): phan_dau=str[:n] phan_cuoi=str[n+1:] return phan_dau + phan_cuoi print(remove_char_m(chuoi,int(input("thu tu muon xoa:")))) print('*'*100) print(" ") #Bài 03: Viết chương trình để xóa bỏ các ký tự có chỉ số là số lẻ trong một chuỗi. print('-'*20,"Bài 3",'-'*20) chuoi = input("nhap chuoi:") def even_values_string(str): ketqua = "" for i in range(len(str)): if i % 2 != 0: ketqua = ketqua + str[i] return ketqua print(even_values_string(chuoi)) print('*'*100) print(" ") #Bài 04: Viết chương trình sinh ra một chuỗi từ 2 ký tự đầu và 2 ký tự cuối trong chuỗi được nhập vào ___ nếu độ dài chuỗi nhỏ hơn 2 thì in ra chuỗi rỗng. print('-'*20,"Bài 4",'-'*20) chuoi = input("nhap chuoi:") def dau_va_duoi(str): if len(str) < 2: return "chuoi rong" return str[0:2] + str[-2:] print(dau_va_duoi(chuoi)) print('*'*100) print(" ") #Bài 05: Viết chương trình tìm ra ký tự lớn nhất và ký tự nhỏ nhất của một chuỗi nhập từ bán phím. print('-'*20,"Bài 5",'-'*20) chuoi = input("nhap chuoi:") print("ki tu lon nhat cua chuoi:", max(chuoi)) print("ki tu nho nhat cua chuoi:", min(chuoi)) print('*'*100) print(" ") #Bài 06: Viết chương trình đảo ngược từ ký tự thường sang ký tự hoa và từ ký tự hoa sang ký tự thường trong một chuỗi. print('-'*20,"Bài 6",'-'*20) chuoi = input("nhap chuoi:") print(chuoi.swapcase()) print('*'*100) print(" ")
c5e43473c8a618faf4df368b1dc20a5db2ad3c9c
gauravshremayee/PythonDayThree
/dayThree.py
2,345
4.28125
4
#!/usr/bin/python #tuples #Empty Tuples tup1=() #Create tuple with one element tup2=(2,) print tup1 print tup2 tup3=(1,2,3,4,5,"hello",5) #to find the count of 5 #Everything in python is treated as object . object.function() count=tup3.count(5) print ("occurence of 5 is:") print count #find index of 5 loc=tup3.index(5) print("index of 5 is") print loc #for i,j print upto i to j-1 tupSlice=tup3.__getslice__(2,5) print("Tuple Element between 2 to 5") print(tupSlice) #del(tup3) #tuple already deleted ,hence cant be accessed print(tup3) #merge two tuples tup4=tup2+tup3 print("After merging tup2 and tup3") print tup4 #will overwrite the element in list but not in tuples #tup4[4]="11" #print tup4 #accessing all elements in tuples #iterator is tup4 here for t1 in tup4: if t1==5: print "element found",t1 #2nd wayof accessing using index tupLen=len(tup4) i=0 while i<tupLen: print tup4[i] i=i+1 #dictionary #key value dict1={} dict1['ip1']="192.168.1.0" dict1['ip2']="192.168.1.1" dict1['ip3']="192.168.1.2" print dict1 for keys in sorted(dict1.iterkeys()): print dict1.get(keys) print("2nd way of dict print") print dict1['ip3'] #Sets #Unordered Collection #doesnt allow duplicate element set1={"area1","area1","area3"} print len(set1) set1.add("area4") print set1 #doesnt support indexing #print set1[0] #union and intersection of sets set2={"area4","area6","area7","area8"} set3=set1.union(set2) print set3 #intersection set4=set1.intersection(set2) print("intersection result") print set4 #1 Enter two numbers from argument and multiply them and print result #2 Enter two strings from console and concatenate them and print result #3 Enter 5 elements from argument and store in a list list1 and append a new value and print result #4 From the above list find the element between 2nd and 5th index #5 Check whether 2 is present orr not in the list #6 Check whether tuple can add a new element #7 Using for loop create a new dictionary of 10 elements which contains number as keys and its square as values i.e dict[2]=4 #8 Using a set create a union of 2 sets first set containing area and second set containing Zip code #9 Convert from binary to decimal using Python literals i.e 1010 = 10 #10 Concatenate a number and a string i.e Hello and 9 result hello9
ee33d68a2a69c43dfe1db0e23a76d4e3e8d20978
shreyajarsania/python_training
/git_ass_py_2/question10.py
1,684
4.5
4
############################################################################################### # # Write a program in Python to calculate and print the Electricity bill of a given customer. # The customer id., name and unit consumed by the user should be taken from the keyboard and # display the total amount to pay to the customer. The charge are as follow : # Unit Charge/unit # upto 199 @1.20 # 200 and above but less than 400 @1.50 # 400 and above but less than 600 @1.80 # 600 and above @2.00 # If bill exceeds Rs. 400 then a surcharge of 15% will be charged and the minimum bill should # be of Rs. 100/- # ############################################################################################## #take input from user cus_id = input ("Enter customer id ") cus_name = input ("Enter customer name ") cus_unit = input ("Enter total units consumed by the customer") #convert units string to int cus_unit = int(cus_unit, 10) # check units range and calculte money accordingly if cus_unit <= 199: money = cus_unit * 1.2 elif 200 <= cus_unit < 400: money = 199 * 1.2 + (cus_unit - 199) * 1.5 elif 400 <= cus_unit < 600: money = 199 * 1.2 + 200 * 1.5 + (cus_unit - 399) * 1.8 elif cus_unit >= 600: money = 199 * 1.2 + 200 * 1.5 + 200 * 1.8 + (cus_unit - 599) * 2 # overwrite money if amount is less then 100, and add 15% more charges if greater than 400 if money < 100: money = 100 # minimum amount must be 100 elif money > 400: money += 0.15 * money # 15% = 0.15 surplus charges if amount is more than 400 print("Customer details : \nid: \t\t{} \nname: \t\t{} \nbill amount: \t{}". format(cus_id, cus_name, money))
fe6cd626a31c24dbd26f3a8b33abed70c3e2b858
nobregagui/Guicodigo1
/aula10ex31.py
179
3.59375
4
n1 = float(input('Quantos Km tem a sua viagem? ')) if n1 <=200: print('Sua viagem ira custar R${}'.format(n1*0.50)) else: print('Sua viagem custará R${}'.format(n1*0.45))
cd7ceb71625197a574c769e10fc8814165801fd5
ISINth/Labs-HW
/ex_3.py
305
3.875
4
#!/usr/bin/env python3 def f(data): for i in range(len(data)): data[i] = abs(data[i]) return sorted(data) data = [4, -30, 100, -100, 123, 1, 0, -1, -4] # Реализация задания 3 print(data) print(sorted(data, key = lambda key: abs(key))) print(sorted(data, key = abs ))
d0caaea76b7f6dfd10264ebb600b4dd7faf19062
briannaf/aoc-2019
/day6p2.py
1,916
3.5625
4
#AOC 2019 Brianna Frye #Day 6 import re def parse_to_array(base_file): data_left = True output_array = [] try: file = open(base_file) while data_left == True: temp = file.readline() if temp == '': data_left = False else: output_array.append(temp) file.close() return output_array except IOError: print('File does not exist!') finally: print('Parsing complete!') def list_bodies(inp): list_of_bodies = [] orbit_dict = {} map_reg = re.compile(r'(\w{3})\)(\w{3})') for entry in inp: results = map_reg.search(entry) orbiter = results.group(2) orbitee = results.group(1) orbit_dict[orbiter] = orbitee if orbiter not in list_of_bodies: list_of_bodies.append(orbiter) return list_of_bodies, orbit_dict def determine_orbits(body, orbit_dict): if str(orbit_dict[body]) == 'COM': return ['COM'] else: return determine_orbits(orbit_dict[body], orbit_dict) + [body] def count_jumps(start_body, end_body, orbit_dict): if str(orbit_dict[start_body]) == end_body: return 0 else: return 1 + count_jumps(orbit_dict[start_body], end_body, orbit_dict) data = parse_to_array('day6input.txt') list_of_bodies, orbit_dict = list_bodies(data) my_map = determine_orbits('YOU', orbit_dict) santas_map = determine_orbits('SAN', orbit_dict) common_points = list(set(my_map) & set(santas_map)) lowest_combo = len(my_map) + len(santas_map) common_point = '' for i in common_points: my_dist = count_jumps('YOU', i, orbit_dict) santas_dist = count_jumps('SAN', i, orbit_dict) if my_dist + santas_dist < lowest_combo: lowest_combo = my_dist + santas_dist common_point = i print(str(my_dist) + str(santas_dist)) print(lowest_combo) print(common_point)
15967a89883a22e6e9e2bd77bce9ce43c5dbcf5f
jmmedel/Python3-Data-Structure-References
/Python3_Data_Structure/12_Python_Queue/02_Queue.py
813
4.28125
4
""" Removing Element from a Queue In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method. """ class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): if len(self.queue)>0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.removefromq()) print(TheQueue.removefromq()) """ When the above code is executed, it produces the following result − Mon Tue """
aa76e5ce18d1aebdfe6f189a379001bb29cb07e7
oursoul/python-demo
/第7章/7-14.py
349
3.75
4
total = 0 #全局变量total def sum( arg1, arg2 ): #返回2个参数的和 total = arg1 + arg2 #局部变量total print ("函数内是局部变量 : ", total) #输出局部变量total的值 return total sum(10, 20) #调用sum函数 print ("函数外是全局变量 : ", total) #输出全局变量total的值
365ad59bf3677eb9febe04101d29202d25533419
polyccon/algorithm-challenges
/intermediate-python/2_diff_two_arrays.py
1,323
3.78125
4
def filt(array1, array2): arr = [] for item in array1: if item not in array2: arr.append(item) return arr def diffArray(arr1, arr2): return filt(arr1, arr2) + filt(arr2, arr1) #TESTS print (diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])) #should return an array. print (diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])) #should return ["pink wool"]. print (diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])) #should return ["pink wool"]. print (diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])) #should return ["diorite", "pink wool"]. print (diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"])) #should return []. print (diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])) #should return [4]. print (diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4])) #should return ["piglet", 4]. print (diffArray([], ["snuffleupagus", "cookie monster", "elmo"])) #should return ["snuffleupagus", "cookie monster", "elmo"]. print (diffArray([1, "calf", 3, "piglet"], [7, "filly"])) #should return [1, "calf", 3, "piglet", 7, "filly"].
2bc8545361f1510dd37d80d557ec65d0f8d08e79
jshields/python_academic_examples
/examples/search/binary.py
1,083
4.25
4
#!/usr/bin/python """Binary search algorithm""" import logging logging.basicConfig( filename='binary_search.log', format='%(asctime)s %(message)s', level=logging.DEBUG ) def binary_search(item, lst): """ Binary search for an item in an ordered list. Returns an index in the list or False if not found. :param item int: number to search for in the list. :param lst list: sorted list of ints, in ascending order. :return: index of item, or False if not found """ bottom = 0 top = len(lst) - 1 while bottom <= top: middle = (bottom + top) // 2 # middle, greater half or lesser half? if lst[middle] == item: # we found it return middle elif lst[middle] < item: # the item is greater than where we are looking # move the search bracket up bottom = middle + 1 elif lst[middle] > item: # the item is less than where we are looking # move the search bracket down top = middle - 1 return False
15953429d7831780e19cd8b4ecfbb61e3bbbe58f
vshypko/coding_challenges
/problems/misc/fib.py
651
3.953125
4
import time def nthfib(n): if n <= 0: return if n == 1 or n == 2: return 1 return nthfib(n-1) + nthfib(n-2) def memoizedNthfib(n, mem=list()): if not mem: mem = [0] * (n + 1) if mem and mem[n]: return mem[n] if n == 1 or n == 2: result = 1 else: result = memoizedNthfib(n-1, mem) + memoizedNthfib(n-2, mem) mem[n] = result return result n = 33 start = time.time() print("Regular fib:", nthfib(n)) print("Took %f seconds.\n" % (time.time() - start)) start = time.time() print("Memoized fib:", memoizedNthfib(n)) print("Took %f seconds." % (time.time() - start))
23ad8afdbdbbd3bc968ac84a3f9da4fcb6143215
mohamad97mj/PYTHON-a_bit_more_practice
/intro-exceptions.py
482
3.8125
4
import requests from json import JSONDecodeError number = input("Enter a number") try: print(int(number) * 2) except ValueError: print("you did not enter a base 10 number! try again!") r = requests.post("http://someexampleurl.com/users", data={'text': "hello world"}) try: label = r.json()['label'] except JSONDecoderError: print("we could not decode the json response") except KeyError: print("we get json back from server but it did not hva a key 'label'")
a4fcc34643a6f12ff5b460390764379cebf31e70
cki86201/swppgitpractice
/prime5to50.py
242
3.78125
4
is_prime = [0] * 51 for i in range(2, 51): is_prime[i] = 1 for i in range(2, 51): if is_prime[i]: j = i * i while j <= 50: is_prime[j] = 0 j += i for i in range(5, 51): if is_prime[i]: print str(i) + " is a prime number"
c5ab559f945778a1fe91b4a4b26353824f9d8a60
Shinkei/matchaHimbeere
/RaspberryCode/Pygame/HelloWoldPyGame.py
404
3.578125
4
import pygame width = 640 height = 480 radius = 100 fill = 1 pygame.init() window = pygame.display.set_mode((width, height)) window.fill(pygame.Color(255, 255, 255)) while True: pygame.draw.circle(window, pygame.Color(255 ,0 ,0), (width/2, height/2), radius, fill) pygame.display.update() if pygame.QUIT in [e.type for e in pygame.event.get()]: # listen for the close button of the window break
549486ddb829995ec8ab0ce3c9af5fb7477a7208
gidj/pyBSTree
/bstree.py
2,237
3.765625
4
import collections class BSTree: def __init__(self, *args, **kwargs): self.head = None if args: print args for item in args: self.insert(item) if kwargs: print kwargs for item in kwargs.items(): self.insert(*item) def insert(self, key, value=None): if not self.head: self.head = Node(key, value) return self.head.payload cursor = self.head while cursor: if cursor.key > key: if cursor.left: cursor = cursor.left else: cursor.left = Node(key, value) return cursor.left.payload else: if cursor.right: cursor = cursor.right else: cursor.right = Node(key, value) return cursor.right.payload def search(self, key): cursor = self.head while cursor: if cursor.key == key: return cursor.payload elif cursor.key > key: cursor = cursor.left else: cursor = cursor.right return None def delete(self, key): """ Takes a key, finds the node associated with that key and returns the value of the deleted key after deleting the node and maintaining the search structure of the tree""" pass def print_in_order(self): if self.head is None: return [] else: return self.head.print_in_order() class Node: def __init__(self, key, value, left=None, right=None): self.key = key # Sometimes the key is the value; if so, payload is just the key if value is None: self.payload = self.key else: self.payload = value self.left = left self.right = right def print_in_order(self): sublist = [] if self.left: sublist.extend(self.left.print_in_order()) sublist.append(self.payload) if self.right: sublist.extend(self.right.print_in_order()) return sublist
39bc7386f26335ca30d90875b41aa4970ec25d23
Shubhammehta2012/Tree
/Tree.py
1,202
3.96875
4
class Node(object): def __init__(self, data = None): self.left = None self.right = None self.data = data def setLeft(self, node): self.left = node def setRight(self, node): self.right = node def getLeft(self): return self.left def getRight(self): return self.right def setData(self, data): self.data = data def getData(self): return self.data def inorder(Tree): if Tree: inorder(Tree.getLeft()) print(Tree.getData(), end = ' ') inorder(Tree.getRight()) return def preorder(Tree): if Tree: print(Tree.getData(), end = ' ') preorder(Tree.getLeft()) preorder(Tree.getRight()) return def postorder(Tree): if Tree: postorder(Tree.getLeft()) postorder(Tree.getRight()) print(Tree.getData(), end = ' ') return if __name__ == '__main__': root = Node(1) root.setLeft(Node(2)) root.setRight(Node(3)) root.left.setLeft(Node(4)) print('Inorder Traversal:') inorder(root) print('\nPreorder Traversal:') preorder(root) print('\nPostorder Traversal:') postorder(root)
2d86f1827a8d728e7a5a426189a1f973f52cd218
EOppenrieder/HW070172
/Homework5/Exercise6_3.py
386
4.21875
4
# Functions for the volume and area of the surface of a sphere import math def sphereArea(r): area = 4*math.pi*r**2 return area def sphereVolume(r): Volume = 4/3*math.pi*r**3 return Volume def main(): r = float(input("Enter the radius: ")) print("The area of a sphere with the radius", r, "is", sphereArea(r), ", and the volume is", sphereVolume(r), ".") main()
5d4506e5682a85ce77855c97c27133473f9a34e3
Liberhaim/courseGeekBrains
/Python/Lesson_2/les2_2.py
540
3.84375
4
count_index_list_t = int(input("Введите размерность желаемого списка: ")) list_t = [] for i in range(0, count_index_list_t, 1): new_element = input("Введите элемент списка: ") list_t.append(new_element) print(f"Начальный список: {list_t}") for index in range(0, len(list_t), 2): temp = list_t[index] if index + 1 != len(list_t): list_t[index] = list_t[index + 1] list_t[index + 1] = temp print(f"Конечный список: {list_t}")
16ebe6e5eabdb3fcd5249997ddeab58450d1a8c3
tleonhardt/CodingPlayground
/python/shlex/shlex_split.py
327
4.0625
4
#!/usr/bin/env python """ Example of using the shlex module to split a string by spaces, but preserver quoted substrings. """ import shlex orig_string = 'this is "a test"' shlex_split = shlex.split('this is "a test"') print("original string = '{}'".format(orig_string)) print("shlex.split(original) = {}".format(shlex_split))
134046545f54acf3ca553888572be8064e2ea877
fwangboulder/DataStructureAndAlgorithms
/#80RemoveDuplicatesFromSortedArrayII.py
950
3.84375
4
""" 80. Remove Duplicates from Sorted Array II Description Submission Solutions Add to List Total Accepted: 104190 Total Submissions: 297373 Difficulty: Medium Contributors: Admin Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. Hide Company Tags Facebook Hide Tags Array Two Pointers """ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 3: return len(nums) tail = 1 for i in range(2, len(nums)): if nums[tail] != nums[i] or nums[tail] != nums[tail - 1]: tail = tail + 1 nums[tail] = nums[i] return tail + 1
e022a8a88928a2ea7d9efeac9be15cafe37e85a8
Sleeither1234/t08_huatay.chunga
/huatay/busqueda.py
1,337
4.0625
4
#asignacion de una variable y declarar valor y a partir de eso desarrollar busqueda presentacion="HOLA MI NOMBRE ES LAURA Y SOY POSTULANTE A LA UNIVERSIDAD PEDRO RUIZ GALLO QUE QUEDA EN LAMBAYEQUE TENGO 16 AÑOS Y QUIERO ESTUDIAR DERECHO" #ejercicio 01 print(presentacion.index("HOLA")) #se imprime unabusqueda #ejercicio 02 print(presentacion.find("MI")) #se imprime unabusqueda #ejercicio 03 print(presentacion.index("NOMBRE ")) #se imprime unabusqueda #ejercicio 04 print(presentacion.find("LAURA")) #se imprime unabusqueda #ejercicio 05 print(presentacion.index("BAYEQUE")) #se imprime unabusqueda #ejercicio 06 print(presentacion.find("RUIZ ")) #se imprime unabusqueda #ejercicio 07 print(presentacion.find("POSTULANTE")) #se imprime unabusqueda #ejercicio 08 print(presentacion.index("A")) #se imprime unabusqueda #ejercicio 09 print(presentacion.index(" ")) #se imprime unabusqueda #ejercicio 10 print(presentacion.find(" N")) #se imprime unabusqueda #ejercicio 11 print(presentacion.index("QUE ")) #se imprime unabusqueda #ejercicio 12 print(presentacion.find("N ")) #se imprime unabusqueda #ejercicio 13 print(presentacion.index(" A ")) #se imprime unabusqueda #ejercicio 14 print(presentacion.find("G A")) #se imprime unabusqueda #ejercicio 15 print(presentacion.index("P E D RO")) #se imprime un error de busqueda
10009b0dbbedc38795f9f8a9fa14f6f6b60e4474
TonikaHristova/Loops
/NOD.py
248
3.890625
4
a = int(input()) b = int(input()) if a > b: while b !=0: oldB= b b = a % b a = oldB print(a) elif a == b: print(a) elif a < b: while a!=0: oldA = a a = b % a b = oldA print(b)
5f5432e183ea6e7d09092e75d83b79479c5738ed
sunitakunwar/test_feb_19
/q2.py
497
3.96875
4
'''Create a class Circle which has a class variable PI with value=22/7. Make two methods getArea and getCircumference inside this Circle class. Which when invoked returns area and circumference of each ciecle instances.''' class Circle: PI = 22/7 def __init__(self,radius): self.radius = radius def getArea(self): return self.radius*self.radius*2*Circle.PI def getCircumference(self): return self.radius*2*Circle.PI c1=Circle(2) print(c1.getArea()) print(c1.getCircumference())
64c6215423537390e9d7ff3bbe1d1bdf5de8378e
Destr1zzj/D_C_R
/python_study/类 2.py
343
3.6875
4
class Rec: length = float(input("long:")) width = float(input("wide:")) def setrect(self): print('enter:') def getrect(self): print(self.length,self.width) def geta(self): #return self.width * self.length print(self.width * self.length) new = Rec() new.getrect() new.setrect() new.geta()
669864b6b61834e1b3440e7c23e807f36276eea6
congsonzero/Python-1
/hoc.py
451
3.703125
4
#Tạo dữ liệu nam có dấu hiêu dạng chuổi nam="Son" print(nam) diem=5.5 print(type(diem)) hoten="Công " Hoten="Sơn" print("Tên tôi là",hoten+Hoten) print(5>=5.0) a=5 a+=1 a+=5 print(a) days ={ 0: "sunday", 1: "monday", 2: "tuesday", 3: "wednesday", 4: "thursday", 5: "friday", 6: "sartuday", "cuoituan":"weekday", } #Vòng lặp dem =1 while dem<=100 print(dem,"Công Sơn") dem+=1
e38b7dc98a9ff5e334cdb7562987d61df60cf7c5
ashishkchaturvedi/Python-Practice-Solutions
/Chapter05_if_statements/magic_number.py
144
3.71875
4
''' Created on Sep 5, 2019 @author: achaturvedi ''' answer = 17 if answer != 42: print("That is not the correct answer. Please try again")
8ef9a5bbc6941f035d260e611d970e3e9b9814cf
Xiaotih/gomoku_agent
/play.py
1,357
3.546875
4
import game iteration = 10 numberWin = [0, 0] numSteps = [[0 for i in range(iteration)] for i in range(0, 2)] boardSize = 15 for i in range(0, iteration): newGame = game.Gomoku(boardSize) # print "start a new Gomoku game with board size %dx%d"%(boardSize, boardSize) baselinePolicy = game.BaselinePolicy() randomPolicy = game.RandomPolicy() while (newGame.isEnd() < 0): nextPlayer = newGame.nextPlayer if (nextPlayer == 1): action = baselinePolicy.getNextAction(newGame) else: action = randomPolicy.getNextAction(newGame) # print "player %d places on (%d, %d)"%(nextPlayer, action[0], action[1]) newGame.updateBoard(action) losePlayer, totalStep0, totalStep1 = newGame.currentGame() winPlayer = 2 if losePlayer == 1 else 1 totalStep = (totalStep0, totalStep1) if newGame.isEnd() != 0: numberWin[winPlayer-1] += 1 numSteps[winPlayer-1][i] = totalStep[winPlayer-1] print "player 1 wins %d times, the average number of steps to win is %f"%(numberWin[0], 1.0*sum(numSteps[0])/numberWin[0]) print "player 2 wins %d times, the average number of steps to win is %f"%(numberWin[1], 1.0*sum(numSteps[1])/numberWin[1]) # if newGame.isEnd() == 0: # print "break even!" # else: # print "Game ends! player %d wins in %d steps"%(winPlayer, totalStep[winPlayer - 1]) # for i in range(0, boardSize): # print newGame.chessBoard[i]
4fce08358bbb16ca216e8c3ead247adad3ca6af7
JosiahRegencia/cs271a-admu
/project_1/tree_test.py
4,501
3.671875
4
class Node: def __init__(self,key,level): self.level = level self.key = key self.leftChild = None self.middleChild = None self.rightChild = None # return the key stored in node def getKey(self): return self.key class Tree: def __init__(self): # track number of keys self.keyTracker = 0 # track depth of tree self.depth = 0 # initialize fringe for BFS self.queue = [] #initialize fringe for DFS self.stack = [] # root of tree self.root = None def expand_bfs(self): # if root if (len(self.queue) == 0): # increment tracking of keys so that root node starts at 1 self.keyTracker = self.keyTracker + 1 # assign root node to tree object self.root = Node(self.keyTracker, self.depth) # enqueue the root node to queue self.queue.append(self.root) else: # get the 1st in queue, then create new node. points via leftChild self.queue[0].leftChild = Node(self.keyTracker+1,self.queue[0].level+1) # enqueue to fringe self.queue.append(self.queue[0].leftChild) # update max depth if a new level has been reached if (self.queue[0].level > self.depth): self.depth = self.queue[0].level # get the 1st in queue, then create new node. points via middleChild self.queue[0].middleChild = Node(self.keyTracker+2,self.queue[0].level+1) # enqueue to fringe self.queue.append(self.queue[0].middleChild) # update max depth if a new level has been reached if (self.queue[0].level > self.depth): self.depth = self.queue[0].level # get the 1st in queue, then create new node. points via rightChild self.queue[0].rightChild = Node(self.keyTracker+3,self.queue[0].level+1) # enqueue to fringe self.queue.append(self.queue[0].rightChild) # update max depth if a new level has been reached if (self.queue[0].level > self.depth): self.depth = self.queue[0].level # update the tracker (3 because 3 nodes were created) self.keyTracker = self.keyTracker + 3 # dequeue the 'incorrect' node self.queue.pop(0) # DOESN'T WORK YET def preorder(self,root): if (self.root != None): print(self.root.key) self.preorder(self.root.leftChild) self.preorder(self.root.rightChild) # HAVENT TESTED PERO PARANG GOODS def expand_dfs(self): # if root if (len(self.stack) == 0): self.keyTracker = self.keyTracker + 1 self.root = Node(self.keyTracker, self.depth) self.stack.append(self.root) else: temp = len(self.stack)-1 self.stack[temp].leftChild = Node(self.keyTracker+1,self.stack[temp].level+1) self.stack.append(self.stack[temp].leftChild) if (self.stack[temp].level > self.depth): self.depth = self.stack[temp].level self.stack[temp].middleChild = Node(self.keyTracker+2,self.stack[temp].level+1) self.stack.append(self.stack[temp].middleChild) if (self.stack[temp].level > self.depth): self.depth = self.stack[temp].level self.stack[temp].rightChild = Node(self.keyTracker+3,self.stack[temp].level+1) self.stack.append(self.stack[temp].rightChild) if (self.stack[temp].level > self.depth): self.depth = self.stack[temp].level self.keyTracker = self.keyTracker + 3 self.stack.pop(0) # Shows the contents of the queue to track contents and depth level def getQueue(self): for i in self.queue: print("key = {}, depth = {}".format(i.key, i.level)) def getStack(self): for i in self.stack: print("key = {}, depth = {}".format(i.key, i.level)) # driver method FOR MANUAL TESTING # test = Tree() # test.expand_bfs() # test.getQueue() # test.preorder(test.root) # driver method UPDATE THE DESIRED LEVEL INPUT level_input = 5 test = Tree() while (test.depth != level_input): test.expand_bfs() test.getQueue() level_input = 2 test = Tree() while (test.depth != level_input): test.expand_dfs() test.getStack()
5df0b58e3e32eee527dc9e524bd4e202ddacf612
MissHead/StringReplacer
/StringReplacer/replacewithlove.py
336
3.890625
4
def replacewithlove(texto): texto_final = '' lista = texto.split(',') for palavra in lista: if 'odiar' in palavra: texto_final += palavra + ' ❤ ' if 'amor' in palavra: texto_final += palavra + ' ¯|_(ツ)_|¯ ' return texto_final texto = input() print(replacewithlove(texto))
61f547fa01bd06ea215194e5ad67a4a7afd93fef
Egahi/algo-practice
/IncreasingTriplet.py
547
4
4
''' https://leetcode.com/problems/increasing-triplet-subsequence ''' from typing import List class Solution: def increasingTriplet(self, nums: List[int]) -> bool: first_num = second_num = float('inf') for num in nums: if num < first_num: first_num = num elif num < second_num: second_num = num else: return True return False obj = Solution() nums = [1,2,3,4,5] nums = [5,4,3,2,1] nums = [1,2,0,3] print(obj.increasingTriplet(nums))
d54028f5b2671efc1559afa35afc1830d39c4595
jackjyq/COMP9021_Python
/Roll_dice/input_players.py
693
3.625
4
def input_players(): """ input_players input a list of valid players Arguements: None Returns: a list of all_players """ while True: try: all_players = input('请输入玩家姓名,以空格键区分: ').split() if not all_players: print('你至少需要一位玩家!') raise ValueError if len(all_players) != len(set(all_players)): print('玩家姓名不能重复!') raise ValueError break except ValueError: print('请重新输入...') return all_players # Test Codes if __name__ == "__main__": print(input_players())
0b781e523cc7a09a4bdf7a3b592e701f2e2e7dc1
ankitaku2019/Term-Project-Open-CV
/UserAuthentication.py
2,877
3.9375
4
#Creates a user authentication class to create and save users import string class UserAuthentication(object): def __init__(self): self.userDict={} #creates a new User def createNewUser(self, username, password): self.userDict[username]=password countSpecialChar, countUpper, countLower, countDig=0, 0, 0, 0 for letter in password: if letter in string.ascii_letters: if letter in string.ascii_lowercase: countLower+=1 elif letter in string.ascii_uppercase: countUpper+=1 elif letter in string.digits: countDig+=1 elif letter in string.punctuation: countSpecialChar+=1 #passes the strong password test #ignore the special Char, because it's having problems # if countSpecialChar!=0 and if countUpper!=0 and countLower!=0 and countDig!=0: self.writeFile(r"C:\Users\ankit\Box\Carnegie Mellon University\First Semester Freshman Year\15-112 Fundamentals of Programming\Term Project\files\userDictionary.txt") #forces the person to try again with their password else: return False #makes sure the passwords match def checkPassword(self, username, password): #read text file that contains the user dictionaries userDict=UserAuthentication.readFile(r"C:\Users\ankit\Box\Carnegie Mellon University\First Semester Freshman Year\15-112 Fundamentals of Programming\Term Project\files\userDictionary.txt") index, pastIndex=0, -1 tmpKey="" tmpPassword="" while index<len(userDict): if userDict[index]==":": tmpKey=userDict[pastIndex+1:index] pastIndex=index elif userDict[index]=="\n": tmpPassword=userDict[pastIndex+1:index] self.userDict[tmpKey]=tmpPassword pastIndex=index index+=1 #goes through the user dictionary and checks the password for key in self.userDict: if username==key: if self.userDict[username]==password: return True return False return False #The two functions below are taken from the CMU course website: #Link: https://www.cs.cmu.edu/~112/notes/notes-strings.html#basicFileIO def writeFile(self, path): userString="" with open(path, "wt") as f: for key in self.userDict: userString+=key+":" userString+=self.userDict[key]+"\n" f.write(userString) @staticmethod def readFile(path): with open(path, "rt") as f: return f.read()
dc03a76b1c16e604a3ab46440e275414690a5785
jasch-shah/python_codes
/linear_regression2.py
1,370
3.984375
4
from __future__ import division import pandas as pd import numpy as np import matplotlib.pyplot as plt import math #read data into array data = np.genfromtxt('ex1data1.txt',delimiter=',') x=data[:,0] y=data[:,1] m=y.size() a=ones(m,2) def cost(x, y, theta=np.zeros((2,1))): """Computes the cost of linear regression theta = parameter for linear regression x and y are the data points This is done to monitor the cost of gradient descent""" m = len(x) J = 1/(2*m) * sum((x.dot(theta).flatten()- y)**2) return J def gradientDesc(x, y, theta=np.zeros((2,1)), alpha=.01,iterations=1500): """"Gradient Descent implementation of linear regression with one variable""" m = y.size J = [] for numbers in range(iterations): a = theta[0][0] - alpha*(1/m)*sum((x.dot(theta).flatten() - y)*x[:,0]) b = theta[1][0] - alpha*(1/m)*sum((x.dot(theta).flatten() - y)*x[:,1]) theta[0][0],theta[1][0]=a,b print theta[0][0] print theta[1][0] J.append(cost(x,y,theta)) print 'Cost: ' + str(J[-1]) return theta #scatterplot of data with option to save figure. def scatterPlot(x,y,yp=None,savePng=False): plt.xlabel('Population of City in 10,000s') plt.ylabel('Profit in $10,000s') plt.scatter(x, y, marker='x') if yp != None: plt.plot(x,yp) if savePng==false: plt.show() else: name = raw_input('Name Figure File: ') plt.savefig(name+'.png')
f3decde5b7542710474c94c9e037ab84b9e69d36
alopezja/Phyton
/UPB/Ejercicios/funciones.py
744
3.75
4
from os import system system("clear") def muliplicar(a,b): print(a*b) muliplicar(4,6) muliplicar(5,5) muliplicar(10,5) print("\n") def imprimir(x,y): print(x) print(y) """ x = input("Digite primer parámetro:") y = input("Digite segundo parámetro:") imprimir(x,y) """ imprimir("Hola","Como estás?") def nombre_completo(nombre,apellido): print("Bienvenido:",nombre,apellido) nombre = input("Digite primer parámetro: ") apellido = input("Digite segundo parámetro: ") nombre_completo(nombre,apellido) print("\nParámetros arbitrarios") def recorrer(param_fijo,*arbitrarios): print(param_fijo) for argumento in arbitrarios: print(argumento) recorrer("Alex","Hola","Como estás?","Espero que muy bien")
dd053c646d0aaadb865dd61fa22eaadb352b19f9
aplombhuang/python
/working through lists and tuples.py
258
3.953125
4
print("list") l=['d','c','b','a'] for char in l: print(char) print("tuple") t=('d','c','b','a') for char in t: print(char) print("range") for idx in range(len(t)): print(t[idx]) print("slice") for char in l[1:4:2]: print(char)
642788f3186a4b0854913247321f8ce30350392a
evmartie/sp1
/special project 1 .py
1,829
3.65625
4
#!/usr/bin/env python # coding: utf-8 # In[19]: import matplotlib.pyplot as plt import numpy as np x = np.arange(-.5, 5.01, 0.1) y = np.sin(x) plt.plot(x, y) plt.show() # In[ ]: #here we can see there are two root for the graph sin(x) in the domain [-.5,5] # In[ ]: import math from math import sin def f(x): return sin(x) def sgn(x): if x<-.5: return -5 elif x==-.5: return -.5 else: return 5 def bisection (a,b): if sgn((f(a)*f(b))>=0): print('f(a) and f(b) have the same sign therefore the bisection method cannot be used') c=a while ((b-a)>=.0001): c=(a+b)/2 if (f(c)*f(a)<0): b=c else: a=c print('value:') a=-.5 b=5 bisection(a,b) # In[ ]: #bisection theorem does not work here due to the fact that f(a) and f(b) are the same sign this was double checked using desmos #both f(a) and f(b) are negative therefore the algorthm does not take into account the rest of the code # In[6]: def newton(f,df,x0,epsilon,max_iter): xn = x0 for n in range(0,max_iter): fxn = f(xn) if abs(fxn) < epsilon: print('Found solution after',n,'iterations.') return xn dfxn = df(xn) if dfxn == 0: print('Zero derivative. No solution found.') return None xn = xn - fxn/dfxn print('Exceeded maximum iterations. No solution found.') return None # In[11]: import math from math import sin from math import cos p = lambda x: sin(x) dp = lambda x: cos(x) approx = newton(p,dp,-.5,1.e-14,1000) print(approx) # In[18]: import math from math import sin from math import cos p = lambda x: sin(x) dp = lambda x: cos(x) approx = newton(p,dp,2,1.e-14,1000) print(approx) # In[ ]: # In[ ]:
b4a0efbeca7086f288e4a8887704399111dcdb3b
joshavenue/python_notebook
/factorial.py
362
4.15625
4
def factorial(n): product = 1 while n: # Do not use while True to prevent poor optimization product *= n n -= 1 return product def main(): print(" 0! = {}".format(factorial(0))) print(" 1! = {}".format(factorial(1))) print(" 2! = {}".format(factorial(2))) print(" 3! = {}".format(factorial(3))) main()
8efde4beb616e355b7f191139120cdd8e9458b68
pewosas/DuongHieu-C4T6
/list-intro.py
230
4
4
color_list = ["red", "purple", "blue", "orange", "teal"] while True: new_color = input("New_color?") color_list.append(new_color) print("* " * 10) for color in color_list: print(color) print("* " * 10)
93703277c07445bd4cda68c582f2ef0103b4f2c1
domiee13/dungcaythuattoan
/Codeforces/wordCapitalization.py
284
4.21875
4
# Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. # Note, that during capitalization all the letters except the first one remains unchanged. s = input() a = [i for i in s] a[0] = a[0].upper() print("".join(a))
ecc591fe978e34a62cf348a8bd619553c464516e
Cryptious/learn-python
/Operator/operator-pembanding.py
485
3.75
4
# Biasanya digunakan untuk sebuah kondisi(if statemen) atau perulangan # Membandingkan 2 variabel dan menghasilkan TRUE atau FALSE x = 12.0 y = 5.0 print (" x == y ", x == y) # sama dengan, tanda "=" hanya digunakan untuk mendeklarasikan variabel print (" x != y ", x != y) # tidak sama dengan print (" x > y ", x > y) # Lebih besar dari print (" x >= y ", x >= y) # Lebih besar sama dengan print (" x < y ", x < y) # Lebih Kecil print (" x <= y ", x <= y) # Lebih Kecil sama dengan
f55ad797f73c5179b8f2061b92e6dd55e800a17e
StuBeattie/CP1404_practicals
/CP1404_practicals/prac_06/guitars.py
1,090
3.953125
4
"""List and store all the users guitars.""" from prac_06.guitar_type import GuitarInformation def main(): """Get, store, and display guitar information.""" guitars = [] # Get users to input guitar information and print to screen print("My guitars!") name = input("Name: ") while name != "": year = int(input("Year: ")) cost = float(input("cost: ")) add_input_to_guitars = GuitarInformation(name, year, cost) guitars.append(add_input_to_guitars) print("{} ({}) : ${} added.".format(name, year, cost)) print() name = input("Name: ") # Add extra guitars to guitars list for testing. guitars.append(GuitarInformation("Gibson L-5 CES", 1922, 16035.40)) guitars.append(GuitarInformation("Line 6 JTV-59", 2010, 1512.90)) # Display all users guitars neatly. print() print("These are my guitars:") for i, guitar in enumerate(guitars, 1): vintage_string = "(vintage)" if guitar.is_vintage() else "" print("Guitar {}: {} {}".format(i, guitar, vintage_string)) main()
7fd2e44f57e7b0465f0651e691e9eec9918f849f
naolchala/CSE1101
/worksheet/17.py
217
3.53125
4
def check_speed(speed): if speed < 70: print "Ok" else: points = (speed - 70)/5 if points > 12: print "License suspended" else: print "Points:", points
c37662c6ab77f851e8f6c20fea8ed4f4d6d0e6cc
MrRuiChen/CHEN-RUI
/18 阿姆斯特朗数.py
282
3.609375
4
# -*- coding: UTF-8 -*- a=int(input('请输入一个数字:')) sum=0 n=len(str(a)) temp=a while temp>0: digit = temp % 10 sum += digit ** n temp //=10 #整数除法 if a==sum: print(a,'是阿姆斯特朗数') else: print(a,'不是阿姆斯特朗数')
e73d6094da6d41eec40755d8a5e793ce261abbca
kriti-ixix/ml830
/python/dictionaries.py
612
4.1875
4
myDict = {'a':10, 'b':20, 5:'xyz', 10:False, 'z':[1, 2, 3, 4]} #print(myDict['z']) #print(myDict[10]) myDict['k'] = 20 #print(myDict) myDict[10] = "Hello" #print(myDict) newDict = {} for x in range(5): key = input("Enter a key: ") value = input("Enter a value: ") newDict[key] = value #print(newDict) for x in myDict: #Returns only the keys print(x) for x in myDict.values(): #Returns only the values print(x) for x in myDict.items(): #Returns both the keys and the values in a tuple print(x) for (x, y) in myDict.items(): #Dictionary unpacking print("Key:", x, "Value:", y)
278f207609952a22a9af106c21c464817dbf3170
ViniciusQueiros16/Python
/PythonExercicios/ex050.py
205
3.65625
4
print("{:=^40}".format('Soma dos Pares')) s = 0 for c in range(1, 7): num = int(input(f'Digite o {c} valor: ')) if num % 2 == 0: s += num print(f'A soma dos números pares é igual a {s}')
734a3d843e45f09c34452c452d8e49a0874c4591
petr-tik/lpthw
/ex35.py
2,290
3.921875
4
# -*- coding=utf-8 -*- from sys import exit import random # first room def let_the_games_begin(): print "You are in a dark room with 2 doors" print "Which one will you open:\n\tleft \t\t\t\t\t\tright" choice = raw_input("> ") if "left" in choice: bear_room() elif "right" in choice: ctulhu_room() else: dead("You stumble around the room until starvation") def dead(why): print why, "Good job, you are now dead!" exit(0) def bear_room(): print "There is a bear here and he has a lot of honey" print "The fat bear is blocking a door\nHow are you going to move him?" bear_moved = False in_bear_room = True while in_bear_room == True: # changed to false when you open door choice = raw_input("Are you going to:\n\t\ttaunt bear\n\t\ttake honey\n\t\tmove bear\n> ") if "take honey" in choice: # lose dead("The bear looks at you and slaps your face off.") elif "taunt bear" in choice: # first step to unblock door bear_moved = random.choice([True, False]) if bear_moved == True: print "The bear has moved from the door - you can squeeze past!" elif bear_moved == False: dead("The bear get pissed off.") elif "move bear" in choice: bear_moved = random.choice([True, False]) if bear_moved == True: print "Success! You managed to move the bear!" elif bear_moved == False: dead("Shouldn't have touched him.") elif "open" in choice and bear_moved or "door" in choice and bear_moved: print "You clever thing!" in_bear_room = False gold_room() else: print "I have no idea what you said" def gold_room(): choice = int(raw_input("This room is full of gold. How much do you want? ")) print "You have decided to take %d units of gold" % choice if choice > 0 and 50 > choice: print "You have limits" elif choice > 50: dead("You greedy bastard") else: dead("Man, learn to type a number") def ctulhu_room(): print "Here you see the great evil Ctulhu" print "If he stares at you for too long, you will go mad" print "Do you want to?\n\t\tflee for your life\n\t\teat your head" choice = raw_input("> ") if "flee" in choice: let_the_games_begin() elif "head" in choice or "eat" in choice: dead("That was nutritious.") else: ctulhu_room() let_the_games_begin()
7f900988bccb0a1ba4cd1129082317d0f19563bf
Aiooon/MyLeetcode
/python/304. 二维区域和检索 - 矩阵不可变.py
1,827
3.609375
4
""" 304. 二维区域和检索 - 矩阵不可变 给定一个二维矩阵,计算其子矩形范围内元素的总和, 该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2) 。 3, 0, 1, 4 , 2 5, 6, 3, 2 , 1 1,[2, 0, 1], 5 4,[1, 0, 1], 7 1,[0, 3, 0], 5 上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3), 该子矩形内元素的总和为 8。 示例: 给定 matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] sumRegion(2, 1, 4, 3) -> 8 sumRegion(1, 1, 2, 2) -> 11 sumRegion(1, 2, 2, 4) -> 12 提示: 你可以假设矩阵不可变。 会多次调用 sumRegion 方法。 你可以假设 row1 ≤ row2 且 col1 ≤ col2 。 date: 2021年3月2日 """ from typing import List class NumMatrix: def __init__(self, matrix: List[List[int]]): # todo 二维前缀和 row, col = len(matrix), len(matrix[0]) if matrix else 0 # preSum 矩阵比原矩阵多一行一列 保证公式通用 self.preSum = [[0]*(col + 1) for _ in range(row + 1)] _sum = self.preSum for i in range(row): for j in range(col): _sum[i+1][j+1] = _sum[i][j+1] + \ _sum[i+1][j] - _sum[i][j] + matrix[i][j] def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: _sum = self.preSum return _sum[row2+1][col2+1] - _sum[row1][col2+1] - _sum[row2+1][col1] + _sum[row1][col1] # Your NumMatrix object will be instantiated and called as such: # obj = NumMatrix(matrix) # param_1 = obj.sumRegion(row1,col1,row2,col2) matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] NumMatrix = NumMatrix(matrix) sum1 = NumMatrix.sumRegion(0, 0, 2, 2) print(sum1)
91f196b72073df2ca8791f96c424d52210ca5029
moevm/bsc_esikov
/tests/algorithms/test_heskel.py
1,867
3.625
4
import unittest from src.algorithms.heskel import Heskel class TestHeskel(unittest.TestCase): def test_split_into_n_gramms(self): self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", -1), set()) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 0), set()) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 1), {"A", "B", "C", "D", "E", "F"}) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 2), {"AB", "BC", "CD", "DE", "EF"}) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 3), {"ABC", "BCD", "CDE", "DEF"}) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 4), {"ABCD", "BCDE", "CDEF"}) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 5), {"ABCDE", "BCDEF"}) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 6), {"ABCDEF"}) self.assertSetEqual(Heskel.split_into_n_gramms("ABCDEF", 7), set()) def test_search(self): heskel = Heskel("ABCDEFGHIJ", length_n_gramm=2) self.assertEqual(heskel.search("ABCDEFGHIJ"), 100) self.assertEqual(heskel.search("KLMNOPQRST"), 0) self.assertEqual(heskel.search("ABCDEFGHIZ"), round((8 / 10) * 100)) self.assertEqual(heskel.search("ABCDEFGHZZ"), round((7 / 11) * 100)) self.assertEqual(heskel.search("ABCDEZZZZZ"), round((4 / 11) * 100)) self.assertEqual(heskel.search("ABCDEVWXYZ"), round((4 / 14) * 100)) heskel = Heskel("S{AM}R", length_n_gramm=2) self.assertEqual(heskel.search("S{AM}A"), round((4 / 6) * 100)) heskel = Heskel("S{AM}R", length_n_gramm=4) self.assertEqual(heskel.search("S{AM}A"), round((2 / 4) * 100)) heskel = Heskel("S{I{AM}}A", length_n_gramm=2) self.assertEqual(heskel.search("S{I{AR}}R"), round((5 / 11) * 100)) if __name__ == '__main__': unittest.main()
992befa58a0a8ffe9a2cdf35d90a38afd247d70f
tnakatani/Udacity_DAND
/1_Python_Numpy_Pandas/A1_Bikeshare/load_data.py
8,433
3.828125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } months = ['january', 'february', 'march', 'april', 'may', 'june'] def convert_to_d_h_m_s(seconds): """Return the tuple of days, hours, minutes and seconds.""" minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) return {'days':days, 'hours':hours, 'minutes':minutes, 'seconds':seconds} def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int month = months.index(month)+1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] return df def time_stats(df, city, month, day): """Displays statistics on the most frequent times of travel.""" print('Calculating The Most Frequent Times of Travel in ' + city.title() + '...\n') start_time = time.time() # display the most common month if month is 'all': print('Calculating the most popular month...') common_month = df['month'].mode()[0] print('The most popular month is: ' + months[common_month - 1].title() + '\n') # display the most common day of week if day is 'all': print('Calculating the most popular weekday...') common_day = df['day_of_week'].mode()[0] print('The most popular weekday is: ' + common_day + '\n') # display the most common start hour print('Calculating the most popular start hour...') common_hour= df['Start Time'].dt.strftime("%I:00%p").mode()[0] #.dt.strftime("%I:00%p") print('The most popular start hour is: ' + str(common_hour) + '\n') print("This took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df, city, month): """Displays statistics on the most popular stations and trip.""" start_time = time.time() # display the most common month if month == 'all': print('\nCalculating The Most Popular Stations and Trip in ' + city.title() + '...\n') else: print('\nCalculating The Most Popular Stations and Trip in ' + city.title() + ' During ' + month.title() + '...\n') # display most commonly used start station common_start_station = df['Start Station'].value_counts().index[0] print('The most popular start station is: ' + common_start_station + '\n') # display most commonly used end station common_end_station = df['End Station'].value_counts().index[0] print('The most popular end station is: ' + common_end_station + '\n') # display most frequent combination of start station and end station trip trips = df.groupby(['Start Station','End Station']).count().sort_values('Unnamed: 0',ascending=False).index[0] common_trip_start, common_trip_end = trips print('The most frequent combination of start / end station is:') print('Start Station: ' + common_trip_start + '\nEnd Station: ' + common_trip_end) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df, city, month): """Displays statistics on the total and average trip duration.""" if month == 'all': print('\nCalculating Trip Duration in ' + city.title() + '...\n') else: print('\nCalculating Trip Duration in ' + city.title() + ' During ' + month.title() + '...\n') start_time = time.time() # display total travel time total_travel_time = convert_to_d_h_m_s(df['Trip Duration'].sum()) tt_days = int(total_travel_time['days']) tt_hours = int(total_travel_time['hours']) tt_minutes = int(total_travel_time['minutes']) tt_seconds = int(total_travel_time['seconds']) print('Total travel duration of all riders was: ' + str(tt_days) + ' days, ' + str(tt_hours) + ' hours, ' + str(tt_minutes) + ' minutes, and ' + str(tt_seconds) + ' seconds.' ) # display mean travel time mean_travel_time = convert_to_d_h_m_s(df['Trip Duration'].mean()) m_hours = int(mean_travel_time['hours']) m_minutes = int(mean_travel_time['minutes']) m_seconds = int(mean_travel_time['seconds']) print('\nAverage travel duration of all riders was: ' + str(m_minutes) + ' minutes and ' + str(m_seconds) + ' seconds.' ) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df, city, month): """Displays statistics on bikeshare users.""" if month == 'all': print('\nCalculating Statistics on Bikeshare Users in ' + city.title() + '...\n') else: print('\nCalculating Statistics on Bikeshare Users in ' + city.title() + ' During ' + month.title() + '...\n') start_time = time.time() # Display counts of user types if 'User Type' in df.columns: user_types = df.groupby(['User Type']).size().reset_index(name='count') print('The breakdown of user types are listed below:') for index, row in user_types.iterrows(): print(row["User Type"] + ': ' + str(row["count"])) # Display counts of gender if 'Gender' in df.columns: gender_types = df.groupby(['Gender']).size().reset_index(name='count') print('\nThe breakdown of gender is listed below:') for index, row in gender_types.iterrows(): print(row["Gender"] + ': ' + str(row["count"])) # Display earliest, most recent, and most common year of birth if 'Birth Year' in df.columns: year_of_birth = df.sort_values(by=['Birth Year']) yob_earliest = int(year_of_birth['Birth Year'].min()) yob_recent = int(year_of_birth['Birth Year'].max()) yob_common = int(year_of_birth['Birth Year'].mean()) print('\nThe breakdown of birth years are listed below:') print('Earliest birth year was: ' + str(yob_earliest)) print('Most recent birth year was: ' + str(yob_recent)) print('Average birth year was: ' + str(yob_common)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) # Test script city = 'chicago' month = 'all' day = 'all' df = load_data(city, month, day) #time_stats(df, city, month, day) station_stats(df, city, month) #trip_duration_stats(df, city, month) #user_stats(df, city, month) #print(df.head()) #print(df['Start Station'].value_counts().head()) #print('\n') #print(df['End Station'].value_counts().head()) #print('\n') #print(df.groupby(['Start Station','End Station']).size().reset_index(name='count'))#.sort_values('count',ascending=False).head()) #.sort_values('count',ascending=False).head()) #print(df.groupby(['Start Station','End Station']).size().reset_index(name='count').sort_values('count',ascending=False).index[0][1]) #print(df.groupby(['Start Station','End Station']).size().index[0]) #print(df['Start Station'].value_counts().head()) #print(df['Start Station'].value_counts().index[0]) #print(df['End Station'].value_counts().head()) #print(df['End Station'].value_counts().index[0]) # Original version for combination trips #trips = df.groupby(['Start Station','End Station']).size().reset_index(name='count').sort_values('count',ascending=False).head() #common_trip_start = trips['Start Station'].iloc[0] #common_trip_end = trips['End Station'].iloc[0]
94aec39bde50306edff23f383f6fdd6264e49821
datAnir/GeekForGeeks-Problems
/Linked List/merge_sort_doubly_ll.py
1,451
4.09375
4
''' https://practice.geeksforgeeks.org/problems/merge-sort-on-doubly-linked-list/1 Given Pointer/Reference to the head of a doubly linked list of N nodes, the task is to Sort the given doubly linked list using Merge Sort in both non-decreasing and non-increasing order. Input: 2 8 7 3 5 2 6 4 1 8 5 9 15 0 -1 0 Output: 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 -1 0 0 9 15 15 9 0 0 -1 ''' def merge(a, b): if a == None: return b if b == None: return a if a.data <= b.data: head = a a = a.next else: head = b b = b.next temp = head while a!= None and b!= None: if a.data <= b.data: temp.next = a a = a.next else: temp.next = b b = b.next temp.next.prev = temp temp = temp.next if a: temp.next = a a.prev = temp if b: temp.next = b b.prev = temp return head def findmid(head): if head == None or head.next == None: return head slow = head fast = head.next while fast and fast.next: slow = slow.next fast = fast.next.next return slow def sortDoubly(head): if head == None or head.next == None: return head mid = findmid(head) a = head b = mid.next b.prev = None mid.next = None a = sortDoubly(a) b = sortDoubly(b) c = merge(a, b) return c
b8bd373b78c3c41ab19d5f91a7c83f2427b0fbea
milena-rubik/AssessmentBlocoEntrada
/Questao5B.py
1,688
3.53125
4
"""B) Desenvolva um programa contendo uma função que liste, por país, a estimativa de variação do PIB, em percentual, entre 2013 e 2020. Exemplo de saída do programa: EUA Variação de 34.13% entre 2013 e 2020. China Variação de 70.72% entre 2013 e 2020. Japão Variação de 0.2% entre 2013 e 2020. Alemanha Variação de 9.92% entre 2013 e 2020. Reino Unido Variação de 39.18% entre 2013 e 2020. [...] """ def variacaopib(nomearquivo): paises = list() pibspicados = list() arquivo = open(nomearquivo,'r') pibs = arquivo.read() pibs = pibs.split('\n') #gera lista, separa cada item por quebra de linha rotulos = pibs.pop(0) #cria a lista de rótulos (paises e os anos) como um item só rotulos = rotulos.split(',') #cada coisa separada por ',' vira um item em rótulos for x in pibs: listapibs = x.split(',') #gera lista, separa cada item pela vírgula paises.append(listapibs[0])#cria lista com os países listapibs.pop(0) #retira o primeiro item que se refere a países e deixa só os valores dos Pibs pibspicados.append(listapibs) paises.pop(15) #remover o item vazio da lista pasíses for x in paises: indicepais = paises.index(x)#captura o índice de cada país variacao = (float(pibspicados[indicepais][7])-float(pibspicados[indicepais][0]))/(float(pibspicados[indicepais][0])) variacaoporcentagem = round(variacao*100,2) print(f'{x}: Variação de {variacaoporcentagem} % entre 2013 e 2020') variacaopib('Assessment_PIBs.csv')
ad273fc05105f73d38242f667db28334802a4209
martinfairbanks/cs
/bubble_sort.py
418
4.0625
4
def bubbleSort(num): for i in range(len(num)-1, 0, -1): for j in range(i): #change place if the current value is greater than the next one if num[j] > num[j + 1]: #swap temp = num[j] num[j] = num[j + 1] num[j + 1] = temp numbers = [23, 100, 87, 999, 446, 76, 2, 65, 765, 1, 5, 501] bubbleSort(numbers) print(numbers)
ef086afa35ec9caf787349a19a5a22234e139e27
Masud-Parves/URI-Onilne-Judge-Python-
/URI 1074 Even or Odd.py
369
3.875
4
t=int(input()) list=[] for i in range(0,t): list.append(int(input())) for x in list: if x==0: print("NULL") elif x>0: if x%2==0: print("EVEN POSITIVE") else: print("ODD POSITIVE") else: if x%2==0: print("EVEN NEGATIVE") else: print("ODD NEGATIVE")
69e05c86edb03a9f763709483db750533e24845b
Priyam-29/NLP
/nlp1_Tokenizing.py
375
3.6875
4
from nltk.tokenize import word_tokenize, sent_tokenize example = "Hey! How are you? Dr. Sam - M.B.B.S., and M.D., is waiting for you. Mr. and Mrs. Shah are welcomed. Today's a pleasant day; Oh for a refreshing tea! Call us @123 for help." words = word_tokenize(example) for w in words: print(w) sentences = sent_tokenize(example) for s in sentences: print(s)
d19fa2db381434764b1a28b52f2e1338a5ec9e33
jiawulu/learn-python
/test/cart/test_cart.py
727
3.734375
4
shopping = [["iphone",5000],["s8",4000],["nokia",100]] print(shopping) print(shopping[0]) salary = int(input("input your salary : ")) print(salary) # print(type(salary)) cart = [] money = 0 while True : for i in range(len(shopping)) : print("{} {} {}".format(i,shopping[i][0], shopping[i][1])) index = input(">>>>> please input your index , q to exit : ") if "q" == index : break intdex = int(index) if money + shopping[intdex][1] > salary : print(" >>>>> over your salary,please select cheaper") continue else: print(" >>>>>> select " + shopping[intdex][0]) money += shopping[intdex][1] cart.append(shopping[intdex]) print(money) print(cart)
6448cbe4420acdd2678e763a6bc46658478b4901
PFCrtx/old_junk
/python/4thWeek/life.py
7,340
3.53125
4
class Cell(): status = ["dead", "alive"] population = [] def __init__(self, number = 0): self.number = number self.status = "dead" def change_status(self): """ Меняет состояние клетки на противоположное""" if self.status == "alive": self.status = "dead" elif self.status == "dead": self.status = "alive" def show_status(self): """ Возвращает текущее остояние клетки """ return self.status def show_number(self): """ Возвращает порядковый номер клетки""" return self.number def check_neighbors(self): """ Проверет 8 соседних клеток; определяет на основании проверки статус клетки в следующем поколении.""" dead_neighbor = 0 alive_neighbor = 0 my_number = self.number if 11 <= my_number <= 88 and len(str(my_number)) > 1 and my_number%10 != 0 and str(my_number)[1] != "9": n = str(self.number + 1) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number - 1) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number - 10) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number + 10) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number - 11) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number + 11) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number - 9) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 n = str(self.number + 9) if len(n) == 1: n = "0" + n test = Cell.population[int(n[0])][int(n[1])].show_status() if test == "alive": alive_neighbor +=1 if test == "dead": dead_neighbor +=1 else: if self.status == "alive": return "die" elif self.status == "dead": return "stay" if self.status == "dead" and alive_neighbor == 3: return "reborn" elif self.status == "alive" and alive_neighbor > 3: return "die" elif self.status == "alive" and 2 <= alive_neighbor <= 3: return "stay" elif self.status == "alive" and alive_neighbor < 2: return "die" elif self.status == "dead" and alive_neighbor < 3: return "stay" elif self.status == "dead" and alive_neighbor > 3: return "stay" def generation(): """ Проверяет статус будущего поколения для всех клеток в текущем массиве.""" q = 0 n = [] while q <= 9: subn = list(map(lambda x: x.check_neighbors(), Cell.population[q])) n.append(subn) q+=1 i = 0 k = 0 while k <= 9: while i <= 9: if n[k][i] == "die": Cell.population[k][i].change_status() if n[k][i] == "reborn": Cell.population[k][i].change_status() i+=1 i=0 k+=1 generation = staticmethod(generation) def create_field(): """ Создаёт массив из 100 "мёртвых" клеток""" i = 0 arr = [] while i < 100: while len(arr) < 10: c = Cell(i) arr.append(c) i+=1 Cell.population.append(arr) arr = [] create_field = staticmethod(create_field) def set_start_position(my_list): """Позволяет пользователю задать стартовое состояние поля, меняя состояние отдльных клеток.""" x = Cell.population i = 0 while i <= len(my_list)-1: if len(my_list[i]) < 2: my_list[i] = "0" + my_list[i] coord = my_list[i] a = int(coord[0]) b = int(coord[1]) x[a][b].change_status() i+=1 set_start_position = staticmethod(set_start_position) # def life(step): """step раз сменяет поколения клеток; иллюстрирует этот процесс в псевдографике""" j = 0 i = 0 s = "" kk = 0 while kk <= step: while j <=9: while i <= 9: if Cell.population[j][i].show_status() == "dead": y = " O " elif Cell.population[j][i].show_status() == "alive": y = " Z " i+=1 s += y print(s.center(80)) j+=1 i = 0 s = "" print(" ") kk+=1 j=0 Cell.generation() ####################################################################### st = "" for i in range(101): if i%10 == 0 and i != 0: st+="\n" print(st) st = " " if int(i) <= 9: st+=str(i) + " " elif int(i) > 9: st+=str(i) + " " Cell.create_field() my_list = [] while True: my_cell = input("Вводите номера полей с живыми клетками (от 1 до 99) по одному: ") if my_cell == "": break my_list.append(my_cell) print("Нажмиет Enter, если все необходимые координаты введены.") Cell.set_start_position(my_list) x = int(input("Введите кол-во поколений: ")) print(" ") life(x)
e541cee35258694759735a3e3793233df827b1fb
josdyr/dyrseth_jostein_set09117
/board.py
5,387
3.671875
4
import string from main import BOARD_SIZE from piece import Piece from player import Player from square import Square class Board(object): board = [[Square(x, y) for y in range(BOARD_SIZE)] for x in range(BOARD_SIZE)] def __init__(self, player1, player2): self.player1 = player1 self.player2 = player2 self.populate_board() def move_piece(self, turn): piece = turn.current_piece destination = turn.destination_square if abs(piece.current_square.y - destination[1]) == 2: import pdb pdb.set_trace() if piece.mandatory_moves: turn.extra_turn = True self.remove_piece_if_jump(piece, destination) piece.current_square.clear() self.board[destination[0]][destination[1]].set_piece(piece) def remove_piece_if_jump(self, piece, destination): x = piece.current_square.x y = piece.current_square.y if piece.player_owner.color == Player.PlayerColor.WHITE: direction_x = (1) else: direction_x = (-1) jump_right = ( destination[0] == self.board[x + (direction_x * 2)][y + 2].x and destination[1] == self.board[x + (direction_x * 2)][y + 2].y ) jump_left = ( destination[0] == self.board[x + (direction_x * 2)][y - 2].x and destination[1] == self.board[x + (direction_x * 2)][y - 2].y ) if jump_right: self.board[x + direction_x][y + 1].piece.current_square.clear() if jump_left: self.board[x + direction_x][y - 1].piece.current_square.clear() def populate_board(self): """place all pieces to the board""" self.create_player_pieces(self.player1) self.create_player_pieces(self.player2) def clear(self): for row in range(0, BOARD_SIZE): for col in range(0, BOARD_SIZE): self.board[row][col].clear() def create_player_pieces(self, player): for row, row_of_squares in enumerate(self.board): for col, square in enumerate(row_of_squares): for (x, y) in player.initial_points: if row == x and col == y: piece = Piece(player) square.set_piece(piece) def draw_board(self): for row, row_of_squares in enumerate(self.board): print() print("{} ".format(row), end='') print("{} ".format(row + 1), end='') for col, square in enumerate(row_of_squares): self.board[row][col].draw_item() print() print(" ", end='') letters = string.ascii_uppercase[:8] for l in letters: print(" {}".format(l), end="") print() print(" ", end='') for row in range(0, BOARD_SIZE): print(" {}".format(row), end="") print() def is_move_valid(self, piece, destination): x = piece.current_square.x y = piece.current_square.y if piece.player_owner.color == Player.PlayerColor.WHITE: direction_x = (1) else: direction_x = (-1) is_mandatory_move_right = ( x + direction_x * 2 >= 0 and x + direction_x * 2 <= 7 and y + 2 <= 7 and self.board[x + direction_x][y + 1].piece is not None and self.board[x + direction_x][y + 1].piece.player_owner is not piece.player_owner and self.board[x + (direction_x * 2)][y + 2].piece is None ) is_mandatory_move_left = ( x + direction_x * 2 >= 0 and x + direction_x * 2 <= 7 and y - 2 >= 0 and self.board[x + direction_x][y - 1].piece is not None and self.board[x + direction_x][y - 1].piece.player_owner is not piece.player_owner and self.board[x + (direction_x * 2)][y - 2].piece is None ) jump_right = ( destination[0] == x + (direction_x * 2) and destination[1] == y + 2 ) jump_left = ( destination[0] == x + (direction_x * 2) and destination[1] == y - 2 ) if is_mandatory_move_left or is_mandatory_move_right: if is_mandatory_move_left and jump_left: return True if is_mandatory_move_right and jump_right: return True return False possibility_right = ( x + direction_x >= 0 and x + direction_x <= 7 and y + 1 <= 7 and self.board[x + (direction_x * 1)][y + 1].piece is None ) possibility_left = ( x + direction_x >= 0 and x + direction_x <= 7 and y - 1 >= 0 and self.board[x + (direction_x * 1)][y - 1].piece is None ) move_right = ( destination[0] == self.board[x + (direction_x * 1)][y + 1].x and destination[1] == self.board[x + (direction_x * 1)][y + 1].y ) move_left = ( destination[0] == self.board[x + (direction_x * 1)][y - 1].x and destination[1] == self.board[x + (direction_x * 1)][y - 1].y ) if possibility_right and move_right: return True if possibility_left and move_left: return True return False
beab0cea9a0ce6eb1465c93a5675188ac8b869cb
jonny-han/barn
/hello.py
195
3.765625
4
def hello(): print('hello world') print('hello linux') print('hello github') for i in range(5): hello() for i in range(10): print(i) jack={'name':jack,'age':18,'sex':male}
e80da8a6c092cff088cfb15437945e8fc90619c2
RenanAbbade/Python-Concepts-and-Exc
/ExPythonBásico/Ex11Aula02.py
311
3.734375
4
import math ''' Renan Abbade 17/08/2017 Exercicio 11 ''' #ENTRADA area = float(input("Qual o tamanho em metros da area a ser pintada? ")) #PROCESSAMENTO lata = area/54 custo = lata*80 #SAIDA print("A quantidade de latas, e o preço total será respectivamente ", "Número de lata", math.ceil(lata),"custo",custo)
e608017b172643038da04f3aa462ed40dd3614c0
sabrina-boby/practice_some-python
/sum_of_n_numbers.py
100
3.625
4
j=int(input("j = ")) i=int(input("i = ")) sum=0 while i<=j: sum=sum+i i=i+1 print(sum)
6b4bab5d1af568235f346bac02a0c3ff62978475
pavanmaradia/202102-Python-Django-Training
/sessions/session_13.py
2,435
3.515625
4
""" Create class Property Override default class methods Iterators """ # class Employee(object): # # def __init__(self, **kwargs): # self.first_name = kwargs.get('first_name', "") # self.last_name = kwargs.get('last_name', "") # self.skill_sets = kwargs.get('skills') # # @property # def email(self): # return F"{self.first_name.lower()}.{self.last_name.lower()}@google.com" # # @property # def full_name(self): # return F"{self.first_name.lower()}.{self.last_name.lower()}" # # def __add__(self, other): # skills = [] # if self.skill_sets: # skills.extend(self.skill_sets) # if other.skill_sets: # skills.extend(other.skill_sets) # # return list(set(skills)) # # # payload_1 = { # 'first_name': 'Dhruv', # 'last_name': 'Sharma', # 'skills': ['Manage People', 'Manage Project', 'Manage Budget', 'Manage Scope'] # } # e1 = Employee(**payload_1) # print(e1.email) # # payload_2 = { # 'first_name': 'Mahesh', # 'last_name': 'Trlu', # 'skills': ['Client Communication', 'Demo', 'Coding', 'Manage Customer'] # } # e2 = Employee(**payload_2) # print(e2.email) # print(e1 + e2) # for i in range(1, 10): # print(i) # x = [1, 2, 3, 4, 5] # y = iter(x) # # print(y.__next__()) # print(y.__next__()) # print(y.__next__()) # class MyRange: # # def __init__(self, *args): # if len(args) == 3: # self.start = args[0] # self.end = args[1] # self.step = args[2] # elif len(args) == 2: # self.start = args[0] # self.end = args[1] # self.step = 1 # elif len(args) == 1: # self.start = 0 # self.end = args[0] # self.step = 1 # else: # raise KeyError # # def __iter__(self): # if self.step > 0: # self.start -= 1 # elif self.step < 0: # self.start += 1 # return self # # def __next__(self): # if self.start < self.end and self.step > 0: # self.start += self.step # return self.start # elif self.start > self.end and self.step < 0: # self.start += self.step # return self.start # else: # raise StopIteration # # # for i in MyRange(1): # print(i) # # print('---------') # for i in range(1): # print(i)
0d524d5b83c0ac1a9a580799b21c022460acef6e
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/hmldhr001/question1.py
1,469
4.0625
4
#Dhriven Hamlall def display(): print("Welcome to UCT BBS") print("MENU") print("(E)nter a message") print("(V)iew message") print("(L)ist files") print("(D)isplay file") print("e(X)it") x=input("Enter your selection:\n") # User makes a choice x=x.upper() # input will be in capitals return x # returning capital input def main(): choice="" # empty string message="no message yet" fileNotFoundMessage="File not found" #initialising while choice!="X": # while user did not try to exit using x choice=display() #will continue to show menu option if(choice=="E"): message=input("Enter the message:\n") elif(choice=="V"): print("The message is:",message) elif(choice=="L"): print("List of files: 42.txt, 1015.txt") elif(choice=="D"): fileName=input("Enter the filename:\n") if(fileName=="42.txt"): print("The meaning of life is blah blah blah ...") elif(fileName=="1015.txt"): print("Computer Science class notes ... simplified") print("Do all work") print("Pass course") print("Be happy") else: print(fileNotFoundMessage) #basically if 42.txt or 1015.txt is not entered else: print("Goodbye!") main()
401dd0be9c72c3896df8a77466031a339b4b054c
subodhgupta/tableau-api-lib
/src/tableau_api_lib/utils/pagination.py
2,624
3.625
4
def get_page_attributes(query): """ Get the page attributes (pageNumber, pageSize, totalAvailable) from a query and return their values. :param query: The results of the GET request query, containing paginated data. :type query: JSON or dict :return: page_number, page_size, total_available """ try: pagination = query['pagination'] page_number = int(pagination['pageNumber']) page_size = int(pagination['pageSize']) total_available = int(pagination['totalAvailable']) return page_number, page_size, total_available except KeyError: print("The query provided does not contain paged results.") def extract_pages(query_func, starting_page=1, page_size=100, limit=None, parameter_dict={}): """ :param query_func: A callable function that will issue a GET request to Tableau Server. :type query_func: function :param starting_page: The page number to start on. Defaults to the first page (page_number = 1). :type starting_page: int :param page_size: The number of objects per page. If querying users, this is the number of users per page. :type page_size: int :param limit: The maximum number of objects to return. Default is no limit. :type limit: int :param parameter_dict: A dict whose values are appended to the REST API URL endpoint as URL parameters. :type parameter_dict: dict :return: extracted_pages JSON or dict """ extracted_pages = [] page_number = starting_page extracting = True while extracting: params = parameter_dict.copy() paginating_params = { 'pageNumber': 'pageNumber={}'.format(page_number), 'pageSize': 'pageSize={}'.format(page_size) } params.update(paginating_params) query = query_func(parameter_dict=params).json() page_number, page_size, total_available = get_page_attributes(query) outer_key = [key for key in query.keys() if key != 'pagination'].pop() inner_key = list(query[outer_key].keys()).pop() extracted_pages += query[outer_key][inner_key] if limit: if limit <= len(extracted_pages): extracted_pages = extracted_pages[:limit] extracting = False elif total_available <= (page_number * page_size): extracting = False else: page_number += 1 return extracted_pages
26a431a7caa6b98a3f938497b540cfd161382a54
SamEhret/codeChallenge
/python_code_challenge/src/inputFunctions.py
1,009
3.859375
4
import sys import re # Take input or give default input def getInput(): inputString = input('Please enter the string to process') if not inputString: inputString='(id,created,employee(id,firstname,employeeType(id),lastname),location)' return inputString # Check that nesting in "()"" is valid # String will need to start with "(" and end with ")" # String will need same number of "(" and ")" def isValid(inputString): if inputString.count('(') != inputString.count(')'): return False elif inputString[0] != '(' or inputString[-1] != ')': return False else: return True # Process inputString to list # First removes start and end parenthesis # Split string on "(" ")" and "," # Filter out "[,]" and "[]" def processInput(inputString): inputString = re.search(r'\((.+)\)', inputString)[1] inputString = re.split('([(),])', inputString) processedString = filter(lambda s: not (s[:]==',' or s[:]==''), inputString) return processedString
80db0c746ba700b0c1918ee06d5b10f538fb222d
roncrisostomo/CrackingTheCodingInterview
/strings/stringCompression.py
872
4
4
def stringCompression(s): """ s: a string Returns a compressed version of string using counts of repeated characters """ if len(s) == 0: return '' result = '' # Initialize first run using first character curRunChar = s[0] curRun = 1 # Iterate starting from second character for character in s[1:]: # If different from current run, update result and start new run if curRunChar != character: result += curRunChar + str(curRun) curRunChar = character curRun = 1 # If same, update run length else: curRun += 1 # Add the last run to result result += curRunChar + str(curRun) return result s = 'a' # Ans: a1 s = 'aabcccccaaa' # Ans: a2b1c5a3 print(stringCompression(s))
95446cd643a2418ad1dec0ce49ddb47f9b51ee24
dcthomson/Advent-of-Code
/2019/18 - Many-Worlds Interpretation/perms.py
1,975
4.21875
4
# A Python program to print all # permutations using library function from itertools import permutations import string # Get all permutations of [1, 2, 3] # perm = permutations(list(string.ascii_lowercase), len(string.ascii_lowercase)) # # Print the obtained permutations # print(len(list(perm))) A_LOWERCASE = ord('a') ALPHABET_SIZE = 26 def _decompose(number): """Generate digits from `number` in base alphabet, least significants bits first. Since A is 1 rather than 0 in base alphabet, we are dealing with `number - 1` at each iteration to be able to extract the proper digits. """ while number: number, remainder = divmod(number - 1, ALPHABET_SIZE) yield remainder def base_10_to_alphabet(number): """Convert a decimal number to its base alphabet representation""" return ''.join( chr(A_LOWERCASE + part) for part in _decompose(number) )[::-1] def base_alphabet_to_10(letters): """Convert an alphabet number to its decimal representation""" return sum( (ord(letter) - A_LOWERCASE + 1) * ALPHABET_SIZE**i for i, letter in enumerate(reversed(letters.upper())) ) alphabet = "" low = 246244783208286292431866971536008152 # "aaaaaaaaaaaaaaaaaaaaaaaaaa" # print(high - low) # for i in range(low, int(high)): # # convert i to alpha 0-a, 1-b...P-z # print(i) i = low - 1 percent = 0 while True: # newpercent = i / low * 100 # roundedpercent = round(newpercent) # if roundedpercent > percent: # percent = roundedpercent # print(percent) alphabet = base_10_to_alphabet(i) i += 1 if len(alphabet) != 26: continue print(alphabet) if alphabet == "abcdefghijklmnopqrstuvwxyz" print("alpha:", i) break if alphabet == "aaaaaaaaaaaaaaaaaaaaaaaaaa": print("a:", i) if alphabet == "zzzzzzzzzzzzzzzzzzzzzzzzzz": print("z:", i) break
cc40bb3280daca967a5e02a4ce1bd518bc9fd193
abhi01274/FSDP2019
/day 3/solutions/untitled6.py
974
3.90625
4
""" Code Challenge Name: Teen Calculator Filename: teen_cal.py Problem Statement: Take dictionary as input from user with keys, a b c, with some integer values and print their sum. However, if any of the values is a teen -- in the range 13 to 19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times Input: {"a" : 2, "b" : 15, "c" : 13} Output: Sum = 17 """ dict1= {"a": 0, "b":0, "c": 0} print("enter the values for>>") a= int(input("a")) b= int(input("b")) c= int(input("c")) dict1['a']= a dict1['b']= b dict1['c']= c sum1=0 for val in dict1.values(): if val == (15 or 16): sum1=sum1+val elif val in range(13,20): continue else: sum1=sum1+val print("your sum is ",sum1)
d2de1248daa9522382bfa206d89cf4caf1de88e5
naman-32/Python_Snippets
/BASIC/v3.py
1,088
3.8125
4
courses = ['History' , 'Math', 'Physics', 'CompSci'] print(len(courses)) print(courses[1:3]) print(courses[0]) print(courses[1]) print(courses[:3]) print(courses[1:3]) courses_a = ['art','maths'] #courses.extend(courses_a) #courses.append(courses_a) courses.insert(1,courses_a) print(courses) courses.remove(courses_a) print(courses) courses.remove('History') print(courses) courses.sort() print(courses) num= [122123,51321,1312231,45454] num.sort() print(max(num)) print(min(num)) print(sum(num)) for item in courses: print(item) for index,courses2 in enumerate(courses ,start=20): print(index,courses2) for i,num2 in enumerate(num,start = 200): print(i,num2) courses.reverse() courses.sort(reverse = True)#T dc = courses.pop() print(dc) print(courses) num3= [122123,80000000,1312231,45454] n = sorted(num3) print(n) print (courses.index('Math')) print('Math' in courses)#truefalse course_join = ' - '.join(courses) print(course_join) course_split = course_join.split('-') print(course_split)
4163b192447416b6144fac3345d482f464e896ad
wenting-zhao/sudoku-zero
/baselines/sat/sudoku2cnf.py
2,286
3.84375
4
import sys import math class Sudoku: def __init__(self, n): self.n = n self.varmap = dict() # build a vertex map and an edge map (for mapping vertices and edges to their variables) i = 1 for x in range(1, self.n+1): for y in range(1, self.n+1): for z in range(1, n+1): self.varmap[(x,y,z)] = i i += 1 self.nvars = i - 1 def _getvar(self, x,y,z): return self.varmap[(x,y,z)] def i_per_row(self): for z in range(1, self.n+1): for x in range(1, self.n+1): i_in_row = [self._getvar(x,y,z) for y in range(1, self.n+1)] yield (i_in_row, "<= 1") yield (i_in_row, "0") def i_per_column(self): for z in range(1, self.n+1): for y in range(1, self.n+1): i_in_column = [self._getvar(x,y,z) for x in range(1, self.n+1)] yield (i_in_column, "<= 1") yield (i_in_column, "0") def i_per_square(self): sqrt_n = math.sqrt(self.n) assert sqrt_n == int(sqrt_n) sqrt_n = int(sqrt_n) for z in range(1, self.n+1): for x in range(1, self.n+1, sqrt_n): for y in range(1, self.n+1, sqrt_n): i_in_square = [self._getvar(p,q,z) for p in range(x, x+sqrt_n) for q in range(y, y+sqrt_n)] yield (i_in_square, "<= 1") yield (i_in_square, "0") def i_per_cell(self): for x in range(1, self.n+1): for y in range(1, self.n+1): i_in_cell = [self._getvar(x,y,z) for z in range(1, self.n+1)] yield (i_in_cell, "<= 1") yield (i_in_cell, "0") def make_cnf(self): for c in self.i_per_row(): yield c for c in self.i_per_column(): yield c for c in self.i_per_cell(): yield c for c in self.i_per_square(): yield c def print_cnf(self): print("p cnf+ %d %d" % (self.nvars, 1)) for clause in self.make_cnf(): print(" ".join([str(x) for x in clause[0]]) + " " + clause[1]) def main(): n = int(sys.argv[1]) d = Sudoku(n) d.print_cnf() if __name__ == '__main__': main()
3601cab2d21dea0b5a3e33fb601f1968be38dda0
longborough/projects.ayush
/game.py
2,504
4.0625
4
#!python from sys import exit from random import randint def main(): # Set up environment size = 5 name = getName(size) # Play the game gPlay(size, name) # gPlay is the game loop # When a game ends, it asks the player whether they want to pla again, # returning True if yes and False if no. def gPlay(size, name): playing = True while playing: board = [ [f"{x+y+1:3d} " for x in range(0,size)] for y in range(0,size*size,size) ] pMat(board) board = [ [" " for x in range(0,size)] for y in range(0,size*size,size) ] runGame(name, board) while True: yesno = input("Would you like to play again (y/n)?" ).upper() if yesno in ("Y","YES"): break if yesno in ("N","NO"): playing = False break def runGame(name, board): currPos = -1 size = len(board) target = size * size + 1 mark = f" {name[0]} " while True: lastPos = currPos throw = randint(1,size+1) currPos += throw print(f"You threw a {throw}.") # If still in first row, just place at random if currPos < size + 1: currPos = randint(0,size) + 1 print(f"Sorry, still stuck in the start row at position {currPos}.") # Check if we hit the target and won elif currPos == target: print(f"Congratulations, {name}, you won!") return # Bad luck, we overstepped the end - go backwards instead elif currPos > target: currPos -= 2*throw print(f"Sorry, overshot -- go back to {currPos}.") else: print(f"Looks good -- you're now at position {currPos}.") board = moveMe(board,size,lastPos," ") board = moveMe(board,size,currPos,mark) pMat(board) x = input("Enter for next move, anything else (like q) to quit?: ") if x != "": return def moveMe(board,size,pos,text): pos -= 1 row = pos // size col = pos % size board[row][col] = text return board def getName(size): name = input("Hi! What's your name (enter to stop)?: ") if name == "": print(f"Thanks, see you later!") exit() name = name[0].upper() + name[1:].lower() print(f"Hi, {name}! Today we are playing {size} x {size}") print(f"Your marker is '{name[0]}'") return name def pMat(matrix): for row in matrix: print(row) main()
c98b5f6e20a8b722287333b3643c684ad240f36f
RaniaRez/HomeWork1CLA
/HOMEWORK4/homework4.py
120
3.65625
4
a = 12 s = "hello" print("inside try") print(a + s) # will raise TypeError print("Printed using original data types")
f7f685af97a2bd0e3c2aa88341ff4fd756249f13
liushuai10000/3D-DenseNet-ChemShift
/model/regular_cnns.py
1,777
3.5625
4
""" Regular 3D-CNN and 3D-ResNet models """ from keras.models import Model from keras.layers.core import Flatten, Dense from keras.layers import Lambda, Input, Add, Concatenate from keras.layers.convolutional import AveragePooling3D from model.utils import conv_bn_relu, dense_bn_relu def cnn_3d(num_channel): """ The cnn with same number of 3x3x3 convolutional layers as 3D densenet Each block has 4 small conv_bn_relu blocks num_channel: number of channels """ # input layer inp = Input((16, 16, 16, num_channel)) # first block x = conv_bn_relu(inp, 64, 3, "same") for _ in range(4): x = conv_bn_relu(x, 64, 3, "same") x = AveragePooling3D(2)(x) # second block for _ in range(4): x = conv_bn_relu(x, 64, 3, "same") x = AveragePooling3D(2)(x) # final block x = Flatten()(x) x = dense_bn_relu(x, 256, 0.1) x = dense_bn_relu(x, 128, 0.1) y = Dense(1)(x) return Model(inp, y) def res_net_3d(num_channel): """ The resnet with same number of 3x3x3 convolutional layers as 3D densenet Each block has 4 small conv_bn_relu blocks num_channel: number of channels """ # input layer inp = Input((16, 16, 16, num_channel)) # first block x = conv_bn_relu(inp, 64, 3, "same") x1 = x for _ in range(4): x = conv_bn_relu(x, 64, 3, "same") x = Add()([x, x1]) x = AveragePooling3D(2)(x) # second block x1 = x for _ in range(4): x = conv_bn_relu(x, 64, 3, "same") x = Add()([x, x1]) x = AveragePooling3D(2)(x) # final block x = Flatten()(x) x = dense_bn_relu(x, 256, 0.1) x = dense_bn_relu(x, 128, 0.1) y = Dense(1)(x) return Model(inp, y)
5024c4d041f73cceedf8b68a6f45db3782a6c146
rwatsh/python
/codeacademy_proj/codeacademy/battleship.py
1,739
4.21875
4
__author__ = 'rushil' """ Battleship game. Build a simplified, one-player version of the classic board game Battleship! In this version of the game, there will be a single ship hidden in a random location on a 5x5 grid. The player will have 10 guesses to try to sink the ship. """ from random import randint # Create a 5x5 matrix viz. list of 5 lists of 5 'O's board = [] for i in range(0, 5): lst = [] for j in range(0, 5): lst.append('O') board.append(lst) def print_board(board): for row in board: """ Calling join() on string to connect all elements in the row list with " " """ print " ".join(row) print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board) - 1) ship_row = random_row(board) ship_col = random_col(board) print ship_row print ship_col # Player has 4 turns to guess right or else the game is over. for turn in range(4): guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Col: ")) if guess_row not in range(5) or guess_col not in range(5): print "Oops, that's not even in the ocean." elif board[guess_row][guess_col] == "X": print "You guessed that one already." else: if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sank my battleship!" break else: print "You missed my battleship!" board[guess_row][guess_col] = 'X' print "Turn", turn + 1 print_board(board) if turn == 3: print "Game Over"