text
stringlengths
37
1.41M
print('-------爱你鱼C---------') temp = input('你输入的数字是啥呢:') guess = int(temp) while guess != 8: temp = input('猜错了,不妨在输入一次:') guess = int(temp) if guess == 8: print("一下子就猜中了") print("不玩了") else: if guess > 8: print("大了大了") else: print("小了小了") print("游戏结束不玩了")
from tkinter import * root = Tk() def callback(): print("你好") menubar = Menu(root) filemenu=Menu(menubar,tearoff=True) filemenu.add_command(label="打开",command=callback) filemenu.add_command(label="保存",command=callback) filemenu.add_separator() filemenu.add_command(label="退出",command = root.quit) menubar.add_cascade(label="文件",menu=filemenu) editmenu=Menu(menubar,tearoff=False) editmenu.add_command(label="剪切",command=callback) editmenu.add_command(label="拷贝",command=callback) editmenu.add_command(label="粘贴",command = root.quit) menubar.add_cascade(label="编辑",menu=editmenu) root.config(menu=menubar) mainloop()
""" Виселица. Програма выбирает слово из списка. Дается количество жизней по длине слова. Игрок должен называть букву. Если буква в списке есть, программа должна поставить ее на место и вывести в консоль. если нет -1 жизнь И так пока игрок не угадает слово или его не повесят. """ import random print("*" * 3, " Игра 'Виселица' ", "*" * 3) name = input('Пожалуйста введите ваше имя: ') words = ['Животное', 'крокодил', 'птица', 'Пирамида', 'треугольник', 'мячик', 'Обруч', 'Скакалка', 'Мама', 'окно', 'Магазин', 'стол', 'машина', 'шкаф', 'ручка', 'Молоко', 'телевизор', 'телефон', 'Париж'] word = random.choice(words).lower() print(word) task_word = [] for b in word: task_word += ['_'] print(*task_word) n = len(word) if (10 < n < 20) or (n % 10 in [0, 5, 6, 7, 8, 9]): print(f'У вас есть {n} попыток.') elif n % 10 == 1: print(f'У вас есть {n} попытка.') else: print(f'У вас есть {n} попытки.') count = 0 while True: if count == len(word): print('Вы спасли себе жизнь!') break elif n == 0: print('Вас повесят!') break elif ''.join(task_word).isalpha(): print('Вы спасли себе жизнь!') break user_letter = input(f'{name} введите букву: ') n -= 1 if user_letter in word: print(user_letter) for i in range(len(task_word)): s = len(task_word) a = -1 while s != 0: a = word.find(user_letter, a+1) if a == -1: break elif i == a: task_word[i] = user_letter count += 1 elif i != a: continue s -= 1 print(''.join(task_word)) print(f'У вас осталось {n} попыток')
""" task_2.1 - сортировка списка из 6 чисел Создать лист из 6 любых чисел. Отсортировать его по возрастанию """ print(*sorted([10, 2, 35, 43, 5, 68, 19])) # 2 5 10 19 35 43 68 numbers = [10, 2, 35, 43, 5, 68, 19] numbers.sort() print(*numbers) # 2 5 10 19 35 43 68
""" Библиотека Pygame / Часть 2. Работа со спрайтами https://pythonru.com/uroki/biblioteka-pygame-chast-2-rabota-so-sprajtami """ """ Вторая часть серии руководств «Разработка игр с помощью Pygame». Она предназначена для программистов начального и среднего уровней, которые заинтересованы в создании игр и улучшении собственных навыков кодирования на Python. Начать стоит с урока: «Библиотека Pygame / Часть 1. Введение». """ """ Что такое спрайт? Спрайт — это элемент компьютерной графики, представляющий объект на экране, который может двигаться. В двухмерной игре все, что вы видите на экране, является спрайтами. Спрайты можно анимировать, заставлять их взаимодействовать между собой или передавать управление ими игроку. Для загрузки и отрисовки спрайтов в случай этой игры их нужно добавить в разделы “Обновление” и “Визуализация” игрового цикла. Несложно представить, что если в игре много спрайтов, то цикл довольно быстро станет большим и запутанным. В Pygame для этого есть решение: группировка спрайтов. Набор спрайтов — это коллекция спрайтов, которые могут отображаться одновременно. Вот как нужно создавать группу спрайтов в игре: """ # Pygame шаблон - скелет для нового проекта Pygame # clock = pygame.time.Clock() # all_sprites = pygame.sprite.Group() """ Теперь этой возможностью можно воспользоваться, добавив группу целиком в цикл: """ # # Обновление # all_sprites.update() # # # Отрисовка # screen.fill(BLACK) # all_sprites.draw(screen) """ Теперь при создании каждого спрайта, главное убедиться, что он добавлен в группу all_sprites. Такой спрайт будет автоматически отрисован на экране и обновляться в цикле. """ """ Игровой цикл — это цикл while, контролируемый переменной running. Если нужно завершить игру, необходимо всего лишь поменять значение running на False. В результате цикл завершится. Теперь можно заполнить каждый раздел базовым кодом. """ """ Создание спрайта Можно переходить к созданию первого спрайта. В Pygame все спрайты выступают объектами. Если вы не работали с этим типом данных в Python, то для начала достаточно знать, что это удобный способ группировки данных и кода в единую сущность. Поначалу это может путать, но спрайты Pygame — отличная возможность попрактиковаться в работе с объектами и понять, как они работают. Начнем с определения нового спрайта: """ # class Player(pygame.sprite.Sprite): """ class сообщает Python, что определяется новый объект, который будет спрайтом игрока. Его тип pygame.sprite.Sprite. Это значит, что он будет основан на заранее определенном в Pygame классе Sprite. Первое, что нужно в определении class — специальная функция __init__(), включающая код, который будет запущен при создании нового объекта этого типа. Также у каждого спрайта в Pygame должно быть два свойства: image и rect. """ # class Player(pygame.sprite.Sprite): # def __init__(self): # pygame.sprite.Sprite.__init__(self) # self.image = pygame.Surface((50, 50)) # self.image.fill(GREEN) # self.rect = self.image.get_rect() """ Первая строка, Pygame.sprite.Sprite.__init__(self) требуется в Pygame — она запускает инициализатор встроенных классов Sprite. Далее необходимо определить свойство image. Сейчас просто создадим квадрат размером 50х50 и заполним его зеленым (GREEN) цветом. Чуть позже вы узнаете, как сделать image спрайта красивее, используя, например, персонажа или космический корабль, но сейчас достаточно сплошного квадрата. Дальше необходимо определить rect спрайта. Это сокращенное от rectangle (прямоугольник). Прямоугольники повсеместно используются в Pygame для отслеживания координат объектов. Команда get_rect() оценивает изображение image и высчитывает прямоугольник, способный окружить его. rect можно использовать для размещения спрайта в любом месте. Начнем с создания спрайта по центру: """ # class Player(pygame.sprite.Sprite): # def __init__(self): # pygame.sprite.Sprite.__init__(self) # self.image = pygame.Surface((50, 50)) # self.image.fill(GREEN) # self.rect = self.image.get_rect() # self.rect.center = (WIDTH / 2, HEIGHT / 2) """ Теперь, после определения спрайта игрока Player, нужно отрисовать (создать) его, инициализировав экземпляр (instance) класса Player. Также нужно обязательно добавить спрайт в группу all_sprites. """ # all_sprites = pygame.sprite.Group() # player = Player() # all_sprites.add(player) """ Сейчас, если запустить программу, по центру окна будет находиться зеленый квадрат. Увеличьте значения WIDTH и HEIGHT в настройках программы, чтобы создать достаточно пространства для движения спрайта в следующем шаге. """ # for event in pygame.event.get(): # # проверить закрытие окна # if event.type == pygame.QUIT: # running = False """ Движение спрайта В игровом цикле есть функция all_sprites.update(). Это значит, что для каждого спрайта в группе Pygame ищет функцию update() и запускает ее. Чтобы спрайт двигался, нужно определить его правила обновления: """ # class Player(pygame.sprite.Sprite): # def __init__(self): # pygame.sprite.Sprite.__init__(self) # self.image = pygame.Surface((50, 50)) # self.image.fill(GREEN) # self.rect = self.image.get_rect() # self.rect.center = (WIDTH / 2, HEIGHT / 2) # # def update(self): # self.rect.x += 5 """ Это значит, что при каждом игровом цикле x-координата спрайта будет увеличиваться на 5 пикселей. Запустите программу, чтобы посмотреть, как он скрывается за пределами экрана, достигая правой стороны. Исправить это можно, заставив спрайт двигаться по кругу — когда он добирается до правой стороны экрана, просто переносить его влево. Это легко сделать, используя элемент управления rect спрайта: Так, если левая сторона rect пропадает с экрана, просто задаем значение правого края равное 0: """ # class Player(pygame.sprite.Sprite): # def __init__(self): # pygame.sprite.Sprite.__init__(self) # self.image = pygame.Surface((50, 50)) # self.image.fill(GREEN) # self.rect = self.image.get_rect() # self.rect.center = (WIDTH / 2, HEIGHT / 2) # # def update(self): # self.rect.x += 5 # if self.rect.left > WIDTH: # self.rect.right = 0 """ На этом все. Отправляйтесь изучать и экспериментировать, но не забывайте, что все, что вы помещаете в метод update(), будет происходить в каждом кадре. Попробуйте научить спрайт двигаться сверху вниз (изменив координату y) или заставить его отталкиваться от стен (изменяя направлении по достижении края). """ """ Код урока: """ # Pygame шаблон - скелет для нового проекта Pygame import pygame import random WIDTH = 800 HEIGHT = 650 FPS = 30 # Задаем цвета WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 50)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) def update(self): self.rect.x += 5 if self.rect.left > WIDTH: self.rect.right = 0 # Создаем игру и окно pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("My Game") clock = pygame.time.Clock() all_sprites = pygame.sprite.Group() player = Player() all_sprites.add(player) # Цикл игры running = True while running: # Держим цикл на правильной скорости clock.tick(FPS) # Ввод процесса (события) for event in pygame.event.get(): # check for closing window if event.type == pygame.QUIT: running = False # Обновление all_sprites.update() # Рендеринг screen.fill(BLACK) all_sprites.draw(screen) # После отрисовки всего, переворачиваем экран pygame.display.flip() pygame.quit() """ В следующем уроке речь пойдет о том, как использовать арт в спрайтах — перейти от обычного квадрата к анимированному персонажу. Часть 3. Больше о спрайтах """
""" task_2.7 - Создать матрицу Создать матрицу любых чисел 3 на 4, сначала вывести все строки, потом все столбцы https://silvertests.ru/GuideView.aspx?id=34372 """ m = [ [5, 6, 7, 8], [15, 13, 9, 4], [6, 18, 15, 28] ] x = [x[:] for x in m] print(x) # вывод в строку print() x = [x[0] for x in m], [x[1] for x in m], [x[2] for x in m], [x[3] for x in m] print(x) # вывод всех столбцов в строку
""" Виселица. Програма выбирает слово из списка. Дается количество жизней по длине слова. Игрок должен называть букву. Если буква в списке есть, программа должна поставить ее на место и вывести в консоль. если нет -1 жизнь И так пока игрок не угадает слово или его не повесят. """ import random count = 0 def attempt(x): """ Функция вывода окончания слова """ if (10 < n < 20) or (n % 10 in [0, 5, 6, 7, 8, 9]): return f'У вас есть {n} попыток.' elif n % 10 == 1: return f'У вас есть {n} попытка.' else: return f'У вас есть {n} попытки.' def is_alpha(letter): """ Функция проверки ввода буквы """ if letter.isalpha() and len(letter) == 1: return str(letter) else: print('Введите одну букву: ') return is_alpha(input()) def play_again(answer): """ Функция повтора игры """ if answer.lower() == 'д': return play_start(), True else: print('До встречи.') def play_start(): """ Функция начала игры """ global n, word, task_word words = ['Животное', 'крокодил', 'птица', 'Пирамида', 'треугольник', 'мячик', 'Обруч', 'Скакалка', 'Мама', 'окно', 'Магазин', 'стол', 'машина', 'шкаф', 'ручка', 'Молоко', 'телевизор', 'телефон', 'Париж'] word = random.choice(words).lower() # выбор случайного слова из списка # print(word) task_word = [] for b in word: task_word += ['_'] # замена букв в слове на нижний пробел print(*task_word) n = len(word) print(attempt(n)) # определяем количество попыток print('Введите букву: ') play_gallows() # вызываем игру def play_gallows(): """ Функция игры """ global count, n, task_word while True: if count == len(word): print('Вы спасли себе жизнь!') break elif n == 0: print('Увы, Вас повесят!') break elif ''.join(task_word).isalpha(): print('Правильно. Вы спасли себе жизнь!') break user_letter = is_alpha(input()) # вводим букву и определяем правильность ввода if user_letter in task_word: print('Вы такую букву уже вводили') n -= 1 if user_letter in word: for i in range(len(task_word)): s = len(task_word) a = -1 while s != 0: # если введенная буква есть в загаданном слове, вставляем a = word.find(user_letter, a + 1) if a == -1: break elif i == a: task_word[i] = user_letter count += 1 elif i != a: continue s -= 1 print(''.join(task_word)) print(attempt(n)) print("*" * 3, " Игра 'Виселица' ", "*" * 3) name = input('Пожалуйста введите ваше имя: ') play_start() a = True while a: print('Хотите сыграть ещё раз? (д/н)') a = play_again(input())
""" inheritance - наследование """ # class Parent(object): запись ниже идеинтична class Calc: def __init__(self, number): self.number = number def calc_and_print(self): value = self.calc_value() self.print_number(value) def calc_value(self): return self.number * 10 + 2 def print_number(self, value_to_print): print('-----') print('Number is', value_to_print) print('-----') c = Calc(5) c.calc_and_print() # Number is 52 """ Чуть чуть модернизируем, добавим дочерний класс """ class Calc: def __init__(self, number): self.number = number def calc_and_print(self): value = self.calc_value() self.print_number(value) def calc_value(self): return self.number * 10 + 2 def print_number(self, value_to_print): print('-----') print('Number is', value_to_print) print('-----') class CalcExtraValue(Calc): def calc_value(self): return self.number - 100 c = Calc(5) c.calc_and_print() # Number is 52 # создадим экземпляр класса CalcExtraValue c = CalcExtraValue(5) c.calc_and_print() # Number is -95
import re import urllib.request str = ''' "we need to inform him with the latest information" ''' s1 = re.findall("inform", str) print(s1) str = "sat, mat, hat, pat" s1 = re.findall("[shmp]at",str) print(s1) s1 = re.findall("[h-m]at",str) print(s1) # Validate a phone number of pattern XXX-XXX-XXXX phnum = "333-111-1234" if re.search("\d{3}-\d{3}-\d{4}", phnum): print("This is a valid phone number") else: print("It isnt a phone number") # web scrape the phone numbers from a website url = "http://www.summet.com/dmsi/html/codesamples/addresses.html" response = urllib.request.urlopen(url) html = response.read() htmlStr = html.decode() pdData = re.findall("\(\d{3}\) \d{3}-\d{4}", htmlStr) for item in pdData: print(item)
def print_out_phrase(uni, phrase): i = 0 one_atatime = [] for e, letter in enumerate(uni): if i <= len(phrase) - 1: if phrase[i] == letter: i += 1 one_atatime.append(uni[:e] + letter.upper() + uni[e + 1:]) for one in one_atatime: for n, letter in enumerate(one): if letter != uni[n]: uni = uni[:n] + letter.upper() + uni[n + 1:] return uni def find_phrase(uni, phrase): i = 0 duplicate = '' for letter in uni: if i <= len(phrase) - 1: if phrase[i] not in uni: return False elif phrase[i] == letter: duplicate += letter i += 1 if duplicate == phrase: return True else: return False def main(): print(find_phrase(input(), input())) if __name__ == '__main__': main()
""" 斐波那契数列(Fibonacci sequence),又称黄金分割数列,是意大利数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)在《计算之书》中 提出一个在理想假设条件下兔子成长率的问题而引入的数列,所以这个数列也被戏称为"兔子数列"。 斐波那契数列的特点是数列的前两个数都是1,从第三个数开始,每个数都是它前面两个数的和, 形如:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...。 斐波那契数列在现代物理、准晶体结构、化学等领域都有直接的应用。 """ num = 2 a = 1 b = 1 c = 0 print(a, ',', b, end='') while num < 20: c = a + b print(',', c, end='') a = b b = c num += 1
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author: 了无此生 # DateTime: 2020/5/24 16:16 # File: 一元二次方程求根 import math def quadratic(a, b, c): d = b ** 2 - 4 * a * c if d < 0: return '方程无解' x1 = (- b + math.sqrt(d)) / (2 * a) x2 = (- b - math.sqrt(d)) / (2 * a) return x1, x2 if __name__ == '__main__': a, b, c = map(float, input('请按顺序输入方程的a,b,c值,记得以空格隔开:').split()) print("方程的解为:", quadratic(a, b, c))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: 了无此生 # DateTime: 2020/5/27 18:39 # File: 使用函数求特殊a串数列和 def fn(a, b): sum = res = 0 for i in range(b): sum += a #sum是a第i+1位数的值 a = a * 10 res += sum return res a, b = input().split() s = fn(int(a),int(b)) print(s)
# -*- coding:utf-8 -*- # Author: 了无此生 # DateTime: 2020/5/24 0:13 # File: 用函数实现52周存钱法 """ 52周存钱法,即52周阶梯式存钱法,是国际上非常流行的存钱方法。 按照52周存钱法,存钱的人必须在一年52周内,每周递存10元 例子: 第1周:10元,第2周:20元,第3周:30元·······一直到第52周:520元。 总计:10+20+30+······+520 = 13780元 """ def save_money(num): sum = 0 for n in range(1, 53): sum += num print('现在是第%d周,你要存入的金额是%d元,累计存入金额为:%d元' % (n, num, sum)) num += 10 return sum if __name__ == '__main__': first_money = int(input('请输入你第一周要存的初始金额:')) print("一年后你将存下的钱为:%d元" % save_money(first_money))
message1 = '{0} is easier than {1}'.format('Python', 'Java') message2 = '{1} is easier than {0}'.format('Python', 'Java') message3 = '{:10.2f} and {:d}'.format(1.234234234, 12) message4 = '{}'.format(1.234234234) print (message1) print (message2) print (message3) print (message4) car = '{0} and {1} is a car'.format('Mini', 'BMW') print (car) nofloaty = 'here is a float 1.234234234 here is the float as a precison of 3 number {:0.2f} {:s} {:d} {:d}'.format(1.234234234, 'h', 12, 14) print (nofloaty)
message1 = "Global Variable (shares same name as a local variable)" def myFunction(): message1 = "Local Variable (shares same name as a global variable)" print("\nINSIDE THE FUNCTION") print (message1) #Calling the function myFunction() #Printing message1 OUTSIDE the function print ("\nOUTSIDE THE FUNCTION") print(message1) message1 = "Global Variable" def myFunction(): print("\nINSIDE THE FUNCTION") #Global variables are accessible inside a function print (message1) #Declaring a local variable message2 = "Local Variable" print (message2) ''' Calling the function Note that myFunction() has no parametrers. Hence, when we call this function, we use a pair of empty parentheses. ''' myFunction() print("\nOUTSIDE THE FUNCTION") #Global variables are accessible outside function print(message1) #Local variables are NOT accessible outside function. print(message2) message1 = "Global Variable (shares same name as a local variable)" def myFunction(): message1 = "Local Variable (shares same name as a global variable)" print("\nINSIDE THE FUNCTION") print (message1) #Calling the function myFunction() #Printing message1 OUTSIDE the function print ("\nOUTSIDE THE FUNCTION") print(message1)
# raw_input() was renamed to input(). That is, the new input() function # reads a line from sys.stdin and returns it with the trailing newline stripped age = input("How old are you? ") height = input("How tall are you? ") print("So you're {0} old and {1} tall.".format(age, height)) print("Dat: {0!r}".format(input("Wat? ")))
def count(str): dict = {} for v in list(str): if v not in dict.keys(): dict[v] = str.count(v) # print(dict) return dict t = "x.nowcoder.com" s = "oooy" t_dict = count(t) s_dict = count(s) set_s = set(s_dict.keys()) set_t = set(t_dict.keys()) flag = True # print(set_s.intersection(set_t)) if set_s.intersection(set_t) == set_s: for i in set_s: if s_dict[i] != t_dict[i]: flag = False else: flag = False if flag: print("Yes") else: print("No")
# a = "1 2 3 4" # b = a.split() # print(" ".join(b[::-1])) # a = "absba" # print(a[::-1]) # print(type(a[::-1])) # if a == a[::-1]: # print("true") # else: # print("false")
from animal_class import Animal class Dog(Animal): def __init__(self, name, fur, eye_colour, pet_id): self.name = name super().__init__(fur, eye_colour) self.__pet_id = pet_id def growl(self, animal): return f"BARK! I see {animal}" def get_pet_id(self): return self.__pet_id def set_pet_id(self, new_id): self.__pet_id = new_id return f"congrats, your new pet id is {new_id}" german_shepherd = Dog("german shepherd", "scruffy", "brown", 1) print(german_shepherd.growl("samir")) german_shepherd.set_pet_id(300) print(german_shepherd.get_pet_id())
def printl(list): print "[" for elet in list: print "\t" + str(elet) print "]" row = [-2] * 10 board = [row] * 20 printl(board) pieces = [0,0,0] pieces[0] = [[0,0,0,0]] pieces[1] = [[1,1,1], [-2,-2,1]] pieces[2] = [[2,2], [2,2]] printl(pieces)
varone = int(input()) vartwo = int(input()) varthree = int(input()) if(varone>vartwo and varone>varthree): print('hey this is varone') elif(vartwo>varone and vartwo>varthree): print('vartwo is here') else print('i am varthree')
import multiprocessing class Node: parent = None horses = None priority = 1 def __init__(self, parent, horses, dept=0): self.parent = parent self.horses = horses self.dept = dept def __repr__(self): return str(self.horses) def __eq__(self, other): """the lists must be sorted""" z = zip(self.horses, other.horses) for i, j in z: if i != j: return False return True def __hash__(self): return hash(self.horses) def __lt__(self, other): return self.priority < other.priority
def read_text_file(file_path): with open(file_path, 'r', encoding='utf-8') as text_file: # can throw FileNotFoundError result = tuple(l.rstrip() for l in text_file.readlines()) return result example_string = 'ZUi there' #u'\u063a\u064a\u0646\u064a' # for c in example_string: # print (repr(c), c) for c in example_string: print(ord(c), hex(ord(c)), c.encode('utf-8')) print ()
croissantjes = input("hoeveel croissants :") prijsC = 0.39 stokbrood = input("hoveel stokbroden :") prijsS = 2.78 kortingsbonnen = input("hoveel kortngsbonnen :") korting = 0.50 #Prijs print(int(croissantjes) * prijsC + int(stokbrood) * prijsS - int(kortingsbonnen) * korting) prijs = (int(croissantjes) * prijsC + int(stokbrood) * prijsS - int(kortingsbonnen) * korting) #Factuur print("De feestlunch kost " + str(prijs) + " euro voor de " + str(croissantjes) + " croissantjes en de " + str(stokbrood) + " stokbroden als de " + str(kortingsbonnen) + " kortingsbonnen nog geldig zijn! ")
def printGame(data): print(' A | B | C ') print(' ---|---|---') print("1|", data['a1'], "|", data['b1'], "|", data['c1'], "|") print(' ---|---|---') print("2|", data['a2'], "|", data['b2'], "|", data['c2'], "|") print(' ---|---|---') print("3|", data['a3'], "|", data['b3'], "|", data['c3'], "|") print(' ---|---|---') def go(player): global data print('Ход игрока ', player) wait=True while wait: nextStep=input('Введите ячейку в формате букваЦифра (например a1): ') if nextStep in data.keys(): if data[nextStep]==' ': data[nextStep]=player wait=False else: print('Ячейка уже занята. Выберите другую.') else: print('Такой ячейки нет на поле. Выберите с a1 по c3') def winner(player): if (data['a1']==data['b1']==data['c1']==player) or (data['a2']==data['b2']==data['c2']==player) or (data['a3']==data['b3']==data['c3']==player) or (data['a1']==data['a2']==data['a3']==player) or (data['b1']==data['b2']==data['b3']==player) or (data['c1']==data['c2']==data['c3']==player) or (data['a1']==data['b2']==data['c3']==player) or (data['a3']==data['b2']==data['c1']==player): print('Player ', player, 'WIN!') return True def isItAll(data): for item in data: if data[item]==' ': return False print('НИЧЬЯ!') return True def replay(): return input('Сыграем еще раз? Enter Yes or No: ').lower().startswith('y') while True: data = {'a1': ' ', 'b1': ' ', 'c1': ' ', 'a2': ' ', 'b2': ' ', 'c2': ' ', 'a3': ' ', 'b3': ' ', 'c3': ' '} printGame(data) while True: player='X' go(player) printGame(data) if winner(player): break if isItAll(data): break player='O' go(player) printGame(data) if winner(player): break if isItAll(data): break if not replay(): break
from .direction import Direction class Bot(object): def __init__(self, board, loc, speed, id, team_id=None): """Initializes a basic bot.""" if board: (board.get(loc)).add_bot(self) else: self.loc = loc self.board = board self.progress = 0 self.speed = speed self.type = None self.id = id self.team = team_id self.direction = Direction.NONE self.new_direction = Direction.NONE def __str__(self): return "{}: {}".format(self.id, self.loc) def __repr__(self): return "{}: {}".format(self.id, self.loc) def copy(self): """Generate a copy of the bot for player copy.""" new_bot = Bot(None, self.loc, self.speed, self.id) new_bot.progress = self.progress new_bot.type = self.type new_bot.direction = self.direction new_bot.new_direction = self.new_direction return new_bot def set_id(self, new_id): self.id = new_id def get_id(self): return self.id def get_team_id(self): return self.team def set_loc(self, loc): """DANGEROUS: do not use except in tile.py""" self.loc = loc def get_loc(self): """Returns the location of the bot.""" return self.loc def set_new_direction(self, dir): """Set the direction of this bot if it is valid. Only should be used when setting direction specified from the player.""" if type(dir) != Direction: self.new_direction = Direction.NONE else: self.new_direction = dir def compute_step(self): """Computes the next step and places it into self.new_direction.""" raise "You must implement compute_step" def update_progress(self): """Updates the movement progress of the bot.""" if self.direction == Direction.NONE: self.progress = 0 return elif self.direction == Direction.ENTER: print("Entering line.") self.progress = 0 self.board.get(self.loc).add_to_line(self) self.direction = Direction.NONE return self.progress += self.speed new_loc = (self.direction).get_loc(self.loc) dest_tile = (self.board).get(new_loc) if self.progress >= dest_tile.get_threshold(): curr_tile = (self.board).get(self.loc) curr_tile.remove_bot(self) dest_tile.add_bot(self) self.direction = Direction.NONE self.progress = 0 def execute_step(self): """Executes the computed step, if valid.""" if self.new_direction != self.direction: if not self._is_valid(): self.new_direction = Direction.NONE self.direction = self.new_direction self.progress = 0 self.update_progress() def _is_valid(self): """Checks if self.new_direction is a valid direction.""" new_loc = (self.new_direction).get_loc(self.loc) if (0 <= new_loc[0] < (self.board).x_dim() and 0 <= new_loc[1] < (self.board).y_dim()): dest_tile = (self.board).get(new_loc) if not dest_tile.get_booth(): return True return False
import urllib.request import re def GetImage(url, img_path, img_name): ''' This function take url and image url as input. If the url is valid then it save the in local disk and generate true response if the url is invalid then it generate false response. Then return the response to ReadFile() function for further action. ''' try: urllib.request.urlretrieve(url, img_path+img_name) return True except: return False def ReadFile(file_path, img_path): ''' This function take file path as input and extract urls from file. Then in a for loop it request GetImage() function to download the image that contains in url. Then it grab returned response and print feedback against that response. ''' with open(file_path, "r") as urls: url_dict = {'valid': 0, 'invalid': 0} for url in urls: # Split the url temp_img_name = re.sub(r'\s', '', url).split('/') # Pick last part of the url as image name img_name = temp_img_name[3] + '.jpeg' flag = GetImage(url, img_path, img_name) if flag: print(img_name, 'This image downloaded successfully in {} folder.'.format(img_path)) url_dict['valid'] = url_dict['valid'] + 1 else: print('Error!!! Image download failed. {} This url is invalid.'.format(url.rstrip())) url_dict['invalid'] = url_dict['invalid'] + 1 return url_dict
# reference # https://scipython.com/blog/quadtrees-2-implementation-in-python/ import numpy as np import matplotlib.pyplot as plt # from matplotlib import gridspec class Point: """A point located at (x, y) in 2D space. Each Point object may be associated with a payload object. """ def __init__(self, x, y, payload=None): self.x, self.y = x, y self.payload = payload # def __repr__(self): # return "{}: {}".format(str((self.x, self.y)), repr(self.payload)) # def __str__(self): # return "P({:.2f}, {:.2f})".format(self.x, self.y) def distance_to(self, other): try: other_x, other_y = other.x, other.y except AttributeError: other_x, other_y = other return np.hypot(self.x - other.x, self.y - other.y) class Rect: """A rectangle centered at (cx, cy) with width w and height h. Livesu calls this a "Cell" and I think that may be a good name, or alternatively "Subdomain". """ def __init__(self, cx, cy, w, h): self.cx, self.cy = cx, cy self.w, self.h = w, h self.west_edge, self.east_edge = cx - w / 2, cx + w / 2 self.north_edge, self.south_edge = cy - h / 2, cy + h / 2 # def __repr__(self): # return str((self.west_edge, self.east_edge, self.north_edge, self.south_edge)) # def __str__(self): # return "({:.2f}, {:.2f}, {:.2f}, {:.2f})".format( # self.west_edge, self.north_edge, self.east_edge, self.south_edge # ) def contains(self, point): """Is point (a Point object or (x,y) tuple) inside this Rect?""" try: point_x, point_y = point.x, point.y except AttributeError: point_x, point_y = point return ( point_x >= self.west_edge and point_x < self.east_edge and point_y >= self.north_edge and point_y < self.south_edge ) # note that Hill inverts the y-axis, so this test is ok def intersects(self, other): """Does Rect object other interesect this Rect? CBH: maybe call this method "touch" or "neighbor" ? """ return not ( other.west_edge > self.east_edge or other.east_edge < self.west_edge or other.north_edge > self.south_edge or other.south_edge < self.north_edge ) def draw(self, ax, c="k", lw=1, **kwargs): x1, y1 = self.west_edge, self.north_edge x2, y2 = self.east_edge, self.south_edge ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], c=c, lw=lw, **kwargs) class QuadTree: """A class implementing a quadtree.""" def __init__(self, boundary, max_points=4, depth=0): """Initialize this node of the quadtree. boundary is a Rect object defining the region from which points are placed into this node; max_points is the maximum number of points the node can hold before it must divide (branch into four more nodes); depth keeps track of how deep into the quadtree this node lies. """ self.boundary = boundary self.max_points = max_points self.points = [] self.depth = depth # A flag to indicate whether this node has divided (branched) or not. self.divided = False # CBH: better have some definition of all data in __init__ # overwrite on "divide" method # self.nw = None # self.ne = None # self.se = None # self.sw = None # def __str__(self): # """Return a string representation of this node, suitably formatted.""" # sp = " " * self.depth * 2 # s = str(self.boundary) + "\n" # s += sp + ", ".join(str(point) for point in self.points) # if not self.divided: # return s # return ( # s # + "\n" # + "\n".join( # [ # sp + "nw: " + str(self.nw), # sp + "ne: " + str(self.ne), # sp + "se: " + str(self.se), # sp + "sw: " + str(self.sw), # ] # ) # ) def divide(self): """Divide (branch) this node by spawning four children nodes.""" cx, cy = self.boundary.cx, self.boundary.cy w, h = self.boundary.w / 2, self.boundary.h / 2 # The boundaries of the four children nodes are "northwest", # "northeast", "southeast" and "southwest" quadrants within the # boundary of the current node. self.nw = QuadTree( Rect(cx - w / 2, cy - h / 2, w, h), self.max_points, self.depth + 1 ) self.ne = QuadTree( Rect(cx + w / 2, cy - h / 2, w, h), self.max_points, self.depth + 1 ) self.se = QuadTree( Rect(cx + w / 2, cy + h / 2, w, h), self.max_points, self.depth + 1 ) self.sw = QuadTree( Rect(cx - w / 2, cy + h / 2, w, h), self.max_points, self.depth + 1 ) self.divided = True def insert(self, point): """Try to insert Point point into this QuadTree.""" if not self.boundary.contains(point): # The point does not lie inside boundary: bail. return False if len(self.points) < self.max_points: # There's room for our point without dividing the QuadTree. self.points.append(point) return True # No room: divide if necessary, then try the sub-quads. if not self.divided: self.divide() return ( self.ne.insert(point) or self.nw.insert(point) or self.se.insert(point) or self.sw.insert(point) ) def query(self, boundary, found_points): """Find the points in the quadtree that lie within boundary.""" if not self.boundary.intersects(boundary): # If the domain of this node does not intersect the search # region, we don't need to look in it for points. return False # Search this node's points to see if they lie within boundary ... for point in self.points: if boundary.contains(point): found_points.append(point) # ... and if this node has children, search them too. if self.divided: self.nw.query(boundary, found_points) self.ne.query(boundary, found_points) self.se.query(boundary, found_points) self.sw.query(boundary, found_points) return found_points # def query_circle(self, boundary, centre, radius, found_points): # """Find the points in the quadtree that lie within radius of centre. # boundary is a Rect object (a square) that bounds the search circle. # There is no need to call this method directly: use query_radius. # """ # if not self.boundary.intersects(boundary): # # If the domain of this node does not intersect the search # # region, we don't need to look in it for points. # return False # # Search this node's points to see if they lie within boundary # # and also lie within a circle of given radius around the centre point. # for point in self.points: # if boundary.contains(point) and point.distance_to(centre) <= radius: # found_points.append(point) # # Recurse the search into this node's children. # if self.divided: # self.nw.query_circle(boundary, centre, radius, found_points) # self.ne.query_circle(boundary, centre, radius, found_points) # self.se.query_circle(boundary, centre, radius, found_points) # self.sw.query_circle(boundary, centre, radius, found_points) # return found_points # def query_radius(self, centre, radius, found_points): # """Find the points in the quadtree that lie within radius of centre.""" # # First find the square that bounds the search circle as a Rect object. # boundary = Rect(*centre, 2 * radius, 2 * radius) # return self.query_circle(boundary, centre, radius, found_points) def __len__(self): """Return the number of points in the quadtree.""" npoints = len(self.points) if self.divided: npoints += len(self.nw) + len(self.ne) + len(self.se) + len(self.sw) return npoints def draw(self, ax): """Draw a representation of the quadtree on Matplotlib Axes ax.""" self.boundary.draw(ax) if self.divided: self.nw.draw(ax) self.ne.draw(ax) self.se.draw(ax) self.sw.draw(ax) def main(): DPI = 72 np.random.seed(60) # width, height = 600, 400 n_pixels = 400 width, height = n_pixels, n_pixels n_points = 60 # 500 # N = n_points # coords = np.random.randn(N, 2) * height / 3 + (width / 2, height / 2) # points = [Point(*coord) for coord in coords] px = np.linspace(start=150, stop=250, num=n_points, endpoint=True, dtype=float) py = np.linspace(start=0, stop=400, num=n_points, endpoint=True, dtype=float) coords = np.transpose([px, py]) points = [Point(*coord) for coord in coords] domain = Rect(width / 2, height / 2, width, height) qtree = QuadTree(boundary=domain, max_points=3) for point in points: qtree.insert(point) print("Number of points in the domain =", len(qtree)) fig = plt.figure(figsize=(700 / DPI, 500 / DPI), dpi=DPI) ax = plt.subplot() ax.set_xlim(0, width) ax.set_ylim(0, height) qtree.draw(ax) ax.scatter([p.x for p in points], [p.y for p in points], s=4) # ax.set_xticks([]) # ax.set_yticks([]) # region = Rect(140, 190, 150, 150) # found_points = [] # qtree.query(region, found_points) # print("Number of found points =", len(found_points)) # ax.scatter( # [p.x for p in found_points], # [p.y for p in found_points], # facecolors="none", # edgecolors="r", # s=32, # ) # region.draw(ax, c="r") # ax.invert_yaxis() # inversion for photograph analogy, not used for meshing ax.set_aspect("equal") ax.set_xlabel(r"$x$") ax.set_ylabel(r"$y$") plt.tight_layout() # plt.savefig("search-quadtree.png", DPI=72) # plt.savefig("search-quadtree.png") filename = "search-quadtree.pdf" fig.savefig(filename, bbox_inches="tight", pad_inches=0) print(f"Serialized to {filename}") plt.show() if __name__ == "__main__": main() """ Copyright 2023 Sandia National Laboratories Notice: This computer software was prepared by National Technology and Engineering Solutions of Sandia, LLC, hereinafter the Contractor, under Contract DE-NA0003525 with the Department of Energy (DOE). All rights in the computer software are reserved by DOE on behalf of the United States Government and the Contractor as provided in the Contract. You are authorized to use this computer software for Governmental purposes but it is not to be released or distributed to the public. NEITHER THE U.S. GOVERNMENT NOR THE CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this sentence must appear on any copies of this computer software. Export of this data may require a license from the United States Government. """
def bubble_sort(list1): #""" sort list two-by-two until completely sorted """ #sorting pair n=len(list1)-1 p=0 r=0 while n>0: for i in range(1, len(list1)): if list1[p]>list1[i]: list1[p], list1[i]= list1[i], list1[p] p=p+1 n=n-1 r=r+1 else: p=p+1 n=n-1 #repeating until no move made if r>0: bubble_sort(list1) return list1 #bubble_sort([1,8,6,4]) print (bubble_sort([9,8,6,4,2, 7, 17, 19, 16, 10])) #bubble_sort([5,19,4,1,36,99,2]) # unit tests assert bubble_sort([9,8,6,4,2, 7, 17, 19, 16, 10]) == sorted([9,8,6,4,2, 7, 17, 19, 16, 10]) assert bubble_sort([5,19,4,1,36,99,2]) == sorted([5,19,4,1,36,99,2]) assert bubble_sort([9,8,6,4,2, 7, 17, 19, 16, 10]) == sorted([9,8,6,4,2, 7, 17, 19, 16, 10]) assert bubble_sort([5,19,4,1,36,99,2]) == sorted([5,19,4,1,36,99,2]) assert bubble_sort(["Greg", "Armen", "Ken"]) == sorted(["Greg", "Armen", "Ken"])
class ShoppingSurveyDiv2: def minValue(self, N, s): # infer total number of items in the store as sum(s) # return sum(s) s = ShoppingSurveyDiv2() # print s.minValue(5, (3, 3)) # 6 purchases, 2 items, 5 customers, 1 has bought both # print s.minValue(100,(97)) #97 # print s.minValue(10, (9,9,9,9,9)) #5 # print s.minValue(7,(1,2,3)) #0, 6 total purchases, 7 customers, noboy could have been a big shopper # # print s.minValue(5,(3,3,3)) #0 9 total purchases, 5 customers, nobody could have bought all 3 once?
# SRM 636 DIV 2 250, 12.5 minutes coding, 185.15 pts class GameOfStones: def count(self, stones): if (len(stones) == 1): return 0 total = 0 for i in stones: total = total + i rem = total % len(stones) if (rem > 0): return -1 avg = total / len(stones) diffs = [] for i in stones: diffs.append(i-avg) posSum = 0 for i in diffs: if (i % 2 > 0): return -1 if (i > 0): posSum = posSum + i return posSum / 2 # testing g = GameOfStones() t1 = (7,15,9,5) print g.count(t1)
# Exercício 2. Faça um programa que leia 4 valores, calcule a média e imprima positivo ou negativo (para ser positivo a média deve ser acima de 1). #Inicialização da variável soma soma = 0 for i in range(0,4): # loop para digitar 4 números numero = int(input("\nDigite um numero: ")) soma += numero # a cada loop a variável soma recebe a soma dos valores digitados media = soma / (i + 1) # cálculo da média: soma dividido pelo numero de valores digitados print(f'\nA média dos numeros digitados é: {media}\n') if media > 1: print("Positivo\n") else: print("Negativo\n")
#!/usr/bin/env python pi = [int(ch) for ch in '31415926535897932384626433833'] for _ in range(int(raw_input())): candidate = [len(word) for word in raw_input().split()] if candidate == pi[0:len(candidate)]: print "It's a pi song." else: print "It's not a pi song."
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 18:39:27 2018 @author: hp """ import unittest #import unittest and below import all functions from our file, newCalculator. from newCalculator import * class CalculatorTest(unittest.TestCase): def testAdd(self):#Make sure all functions run normally through ASsertEqual testing self.assertEqual(6, add([2,2,2])) def testSubtract(self): self.assertEqual(2, subtract(4,2)) def testMultiply(self): self.assertEqual(6, multiply(2,3)) def testDivision(self): self.assertEqual('Division By Zero Not Allowed', division(1,0)) self.assertEqual(0.5, division(1,2)) def testSquared(self): self.assertEqual(9, squared(3)) def testCubed(self): self.assertEqual(27, cubed(3)) def testPower(self): self.assertEqual(27, power(3,3)) def testSqrt(self): self.assertEqual(5, sqrt(25)) def testSin(self): self.assertEqual(1, sin(90)) def testCos(self): self.assertEqual(0.5000000000000001, cos(60)) def testTan(self): self.assertEqual(1.7320508075688767, tan(60)) if __name__ == '__main__': unittest.main() #look through all the code for the word 'test.'
a=10 b=20 print("Before swapping a is :",a," b is ",b) c=a a=b b=c print("After swapping a is :",a," b is ",b) print("****************************************") print("Before swapping a is :",a," b is ",b) a,b=b,a print("After swapping a is :",a," b is ",b) print("****************************************") print("Before swapping a is :",a," b is ",b) a=a+b b=a-b a=a-b print("After swapping a is :",a," b is ",b)
class Node: def __init__(self): self.data = data self.pointer = pointer def __str__(self): return str(self.data) class LinkedList(): def __init__(self, head=None): self.head = None def insert(self, data): new_node = Node(data) new_node.pointer = self.head self.head = new_node def size(self): current = self.head count = 1 while current != None: count = count + 1 current = current.pointer return count def search(self, target): current = self.head while current: if current.data == target: return current else: current = current.pointer if current is None: return None if __name__ == "__main__": ll = LinkedList(20) ll.insert(30) ll.insert(40) print(ll.head.data, ll.head.pointer) print(ll.size) print(ll.search(30)) print(ll.search(50))
# -*-coding:Latin-1 -* def add(x,y): z=x+y print(z) def soust(x,y): z=x-y print(z) def mult(x,y): z=x*y print (z) def div(x,y): z=x/y print(z) import socket hote = '' port = 12800 connexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connexion_principale.bind((hote, port)) connexion_principale.listen(5) print("Le serveur écoute à présent sur le port {}".format(port)) connexion_avec_client, infos_connexion = connexion_principale.accept() msg_recu = b"" while msg_recu != b"fin": msg_recu = connexion_avec_client.recv(1024) # L'instruction ci-dessous peut lever une exception si le message # Réceptionné comporte des accents val1=msg_recu print("ici :"msg_recu.decode()) print("ici :" val1) connexion_avec_client.send(b"5 / 5") print("Fermeture de la connexion") connexion_avec_client.close() connexion_principale.close()
#!/usr/bin/env python # coding: utf-8 # In[1]: a=10 #a is a varibale name which isalso called identifier # '=' is the assignment operator print(a) # In[2]: a=10.6#over riding of variables print(a) # In[8]: #to check the type of variable a=10.6 type(a) # In[9]: a='HUZAIFA' type(a) # In[10]: a=10 type(a) # In[14]: name='Huzaifa' city='Karachi' print(name,"lives in",city) # In[15]: #concatination a='Pakistan' b='zindabad' print(a+b) # In[16]: num1=3 num2=5 sum=num1+num2 print(sum) # In[ ]:
""" cakefinity.py ===== Do you want cake (again) __Repeatedy ask if user wants cake until user says yes or yeah: Do you want cake? > no Do you want cake? > No Do you want cake? > yeah Have some cake! """ usr = raw_input("Do you want cake?\n> ") while usr not in ["yes", "yeah"]: usr = raw_input("Do you want cake?\n> ") print("Have some cake!")
""" FOLLOWED TUTORIAL:https://www.pyimagesearch.com/2020/03/02/anomaly-detection-with-keras-tensorflow-and-deep-learning/ Author: S.Hoogeveen Machine learning project for Special Topics in Computational Science & Engineering: Scientific Machine Learning, MSc Applied Mathematics, TU Delft """ # import the necessary packages import tensorflow as tf from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import Conv2DTranspose from tensorflow.keras.layers import ReLU from tensorflow.keras.layers import Activation from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Reshape from tensorflow.keras.layers import Input from tensorflow.keras.layers import MaxPool2D from tensorflow.keras.layers import UpSampling2D from tensorflow.keras.models import Model from tensorflow.keras import backend as K import numpy as np import os import matplotlib.pyplot as plt import pydot #from tensorflow_core.python.keras.layers import GaussianNoise, Dropout ROOT_PATH = "/Users/eriksieburgh/PycharmProjects/ScientificML/Data_Sylle" train_dir = os.path.join(ROOT_PATH, "TrainingData") val_dir = os.path.join(ROOT_PATH, "ValidationData") IMAGES = ROOT_PATH SHAPE = (52, 52) #height, width INIT_LR = 1e-3 EPOCHS = 1 #loss stabiel na 185 EPOCHS BS = 1 class ConvAutoencoder: @staticmethod def build(height, width, depth, latentDim=1024): # initialize the input shape to be "channels last" along with # the channels dimension itself inputShape = (height, width, depth) chanDim = -1 # define the input to the encoder inputs = Input(shape=inputShape) x = inputs # Adding noise: keras.layers.Dropout(0.5)(x) or keras.layers.GaussianNoise(stddev = 0.2)(x) # x = Dropout(0.5)(x) #Noise added to images #x = GaussianNoise(stddev = 0.2)(x) # apply a CONV => RELU => BN operation x = Conv2D(filters=50, kernel_size=3, strides=1, padding="same")(x) x = ReLU(max_value=None, negative_slope=0, threshold=0)(x) x = MaxPool2D(2)(x) x = BatchNormalization(axis=chanDim)(x) x = Conv2D(filters=100, kernel_size=3, strides=1, padding="same")(x) x = ReLU(max_value=None, negative_slope=0, threshold=0)(x) x = MaxPool2D(2)(x) x = BatchNormalization(axis=chanDim)(x) # flatten the network and then construct our latent vector volumeSize = K.int_shape(x) x = Flatten()(x) latent = Dense(latentDim)(x) # build the encoder model encoder = Model(inputs, latent, name="encoder") # start building the decoder model which will accept the # output of the encoder as its inputs latentInputs = Input(shape=(latentDim)) x = Dense(np.prod(volumeSize[1:]))(latentInputs) x = Reshape((volumeSize[1], volumeSize[2], volumeSize[3]))(x) # apply a CONV_TRANSPOSE => RELU => BN operation x = Conv2DTranspose(filters=100, kernel_size=3, strides=1,padding="same")(x) x = ReLU(max_value=None, negative_slope=0, threshold=0)(x) x = UpSampling2D(2)(x) x = BatchNormalization(axis=chanDim)(x) x = Conv2DTranspose(filters=50, kernel_size=3, strides=1, padding="same")(x) x = ReLU(max_value=None, negative_slope=0, threshold=0)(x) x = UpSampling2D(2)(x) x = BatchNormalization(axis=chanDim)(x) # apply a single CONV_TRANSPOSE layer used to recover the # original depth of the image x = Conv2D(depth, (3, 3), padding="same")(x) outputs = Activation("sigmoid")(x) # build the decoder model decoder = Model(latentInputs, outputs, name="decoder") # our autoencoder is the encoder + decoder autoencoder = Model(inputs, decoder(encoder(inputs)),name="autoencoder") # return a 3-tuple of the encoder, decoder, and autoencoder return (encoder, decoder, autoencoder) (encoder, decoder, autoencoder) = ConvAutoencoder.build(SHAPE[0], SHAPE[1], 3) opt = tf.optimizers.Adam(learning_rate=INIT_LR, decay=INIT_LR / EPOCHS) autoencoder.compile(loss="mse", optimizer=opt) encoder.summary() decoder.summary() image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0/255) train_gen = image_generator.flow_from_directory( os.path.join(IMAGES, "TrainingData"), class_mode="input", target_size=SHAPE, batch_size=BS,shuffle=True ) val_gen = image_generator.flow_from_directory( os.path.join(IMAGES, "ValidationData"), class_mode="input", target_size=SHAPE,batch_size=BS,shuffle=True ) hist = autoencoder.fit(train_gen, validation_data=val_gen, epochs=EPOCHS) print("[INFO] making predictions...") batchX, batchy = train_gen.next() print('Batch shape=%s, min=%.3f, max=%.3f' % (batchX.shape, batchX.min(), batchX.max())) print(train_gen.next()) print(type(train_gen.next())) decoded = autoencoder.predict(val_gen) print(type(decoded)) for i in range (0,2): recon = (decoded[i]* 255).astype("uint8") plt.imshow(recon) plt.show() # construct a plot that plots and saves the training history N = np.arange(0, EPOCHS) plt.style.use("ggplot") plt.figure() plt.plot(N, hist.history["loss"], label="train_loss") plt.plot(N, hist.history["val_loss"], label="val_loss") plt.title("Training Loss") plt.xlabel("Epoch #") plt.ylabel("Loss") plt.legend(loc="lower left") plt.show() # This makes two images of the model. Examples can be found in this directory. # tf.keras.utils.plot_model( # encoder, # to_file="encoder.png", # show_shapes=True, # show_dtype=True, # show_layer_names=False, # rankdir="TB", # expand_nested=False, # dpi=96, # ) # # tf.keras.utils.plot_model( # decoder, # to_file="decoder.png", # show_shapes=True, # show_dtype=True, # show_layer_names=False, # rankdir="TB", # expand_nested=False, # dpi=96, # )
import sys import json import os.path from collections import OrderedDict #TODO Text in alphabetical order // listOfStrings.sort() ? txtfile = sys.argv[1] def readTextFile(): try: f = open(txtfile) f.close() except FileNotFoundError: print('File does not exist') else: #print('file is here!') with open(txtfile) as json_file: data = json.load(json_file) alldata = data['library'] #sorted_string = json.dumps(x, indent=4, sort_keys=True) ? # alldata = OrderedDict(sorted(alldata.data['library']['writer'])) # alldata = sorted(alldata, key=data['library'][0]) #print(alldata) return alldata usr_input = 0 while usr_input != 3: #TODO create user_input try except validation print(f""" Reading the file {sys.argv[1]} Do you want to: 1) Add new book 2) Print current database content in ascending order by writer’s name 3) Exit the program? """) usr_input = int(input("Select option? ")) #print(usr_input) if(usr_input == 1): #txtfile = sys.argv[1] book_name = input("\nAdd name of the book: ") writer_name = input("Add name of the writer: ") isbn_name = input("Add ISBN of the book: ") print(f'{book_name} {writer_name} {isbn_name}') ask_send_db = input('Do you want to send the data to database. yes/no ') if ask_send_db == 'yes': print('Send to database!') send_db_data = {"book": book_name, "writer": writer_name, "isbn": isbn_name } print(send_db_data) #refactor this into a function ---> #Fix appending outside objects array with open(txtfile, 'a') as f: #json.dump(data['library'], f) f.write(json.dumps(send_db_data)) f.close() #<----------- continue if ask_send_db == 'no': print('Return to main menu') continue else: print('Computer says no') if(usr_input == 2): print(readTextFile()) continue if(usr_input == 3): print('Quit the program') break else: print('You did nothing John Snow')
#%% [markdown] # # Week 3: Exercise 3.2 # File: DSC540_Paulovici_Exercise_3_2.py (.ipynb)<br> # Name: Kevin Paulovici<br> # Date: 12/15/2019<br> # Course: DSC 540 Data Preparation (2203-1)<br> # Assignment: Exercise 3.2, csv, json, xml, excel #%% [markdown] # ## Data Files # Data files used for this exercise can be found here: https://github.com/jackiekazil/data-wrangling #%% import csv import json from xml.etree import ElementTree as ET import xlrd import pprint #%% [markdown] # ## CSV #%% [markdown] # Using Python, import the CSV file provided under Chapter 3 in the GitHub repository using the csv library. Put the data in lists and print each record on its own dictionary row (Hint: Page 51-52 of Data Wrangling with Python). #%% # open the csv file with open("data-text.csv", "r", newline='') as file_in: # read the csv file as a dict csv_in = csv.DictReader(file_in) # print each row of the csv file for row in csv_in: pprint.pprint(row) #%% [markdown] # ## JSON #%% [markdown] # Using Python, import the JSON file provided in the GitHub repository under Chapter 3. Print each record on its own dictionary row (Hint: page 53-54 of Data Wrangling with Python). #%% # open the json file with open("data-text.json", "r") as file_in: # read/load the json file json_in = json.load(file_in) # print each dict for d in json_in: pprint.pprint(d) #%% [markdown] # ## XML #%% [markdown] # Using Python, import the XML file provided in the GitHub repository under Chapter 3. Print each record in its own dictionary row (Hint: page 64 of Data Wrangling with Python). #%% # read the xml data tree = ET.parse("data-text.xml") root = tree.getroot() data = root.find("Data") # create list to hold the xml structure all_data = [] for observation in data: record = {} for item in observation: lookup_key = list(item.attrib)[0] # Numeric is unique compared to other Categories so it needs special consideration if lookup_key == "Numeric": rec_key = "NUMERIC" rec_value = item.attrib["Numeric"] else: rec_key = item.attrib[lookup_key] rec_value = item.attrib["Code"] # add records to the dict record[rec_key] = rec_value # add dict to list all_data.append(record) # print list pprint.pprint(all_data) #%% [markdown] # ## Excel #%% [markdown] # Using Python, import the Excel file provided in the GitHub repository under Chapter 4. Print each record in its own dictionary row. (Hint: page 85-88 of Data Wrangling with Python). #%% # open the excel file excel_file = xlrd.open_workbook("SOWC 2014 Stat Tables_Table 9.xlsx") # define the sheet to read table_9 = excel_file.sheet_by_name("Table 9 ") # define dict for rows table_9_data = {} # loop through the rows, starting with row 14 (data starts) for i in range(14, table_9.nrows): row = table_9.row_values(i) country = row[1] # column B table_9_data[country] = { 'child_labor': { 'total': [row[4], row[5]], 'male': [row[6], row[7]], 'female': [row[8], row[9]] }, 'child_marriage': { 'married_by_15': [row[10], row[11]], 'married_by_18': [row[12], row[13]], } } # Zimbabwe is the last country so break out of loop if country == 'Zimbabwe': break pprint.pprint(table_9_data)
import datetime ''' Inspired by https://www.reddit.com/r/IsTodayFridayThe13th/ ''' print('Is Today Friday the 13th?') today = datetime.date.today() if today.weekday() == 5 and today.strftime('%d') == 13: print('Yes.') else: print('No.')
import random import time computer_antworten = ['Schere', 'Stein', 'Papier',] end_abfrage = "y" print("Willkommen zu Schere, Stein, Papier") time.sleep(1) eingabe_spieler = input("Wähle [1] Schere [2] Stein [3] Papier") if eingabe_spieler == "1": print("Du hast Schere ausgewählt!") time.sleep(1) print("Nun wählt der Computer!") time.sleep(1) antwort_auf_schere = random.choice(computer_antworten) print("Er wählt:") time.sleep(1.5) print(antwort_auf_schere) if antwort_auf_schere == 'Schere': time.sleep(0.5) print("**Unentschieden!**") elif antwort_auf_schere == 'Stein': time.sleep(0.5) print("**Du hast Verloren!**") else: time.sleep(0.5) print("**Du hast Gewonnen!**") if eingabe_spieler == "2": print("Du hast Stein ausgewählt!") time.sleep(1) print("Nun wählt der Computer!") time.sleep(1) antwort_auf_stein = random.choice(computer_antworten) print("Er wählt:") time.sleep(1.5) print(antwort_auf_stein) if antwort_auf_stein == 'Schere': time.sleep(0.5) print("**Du hast Gewonnen!**") elif antwort_auf_stein == 'Stein': time.sleep(0.5) print("**Unentschieden!**") else: time.sleep(0.5) print("**Du hast verloren!**") if eingabe_spieler == "3": print("Du hast Papier ausgewählt!") time.sleep(1) print("Nun wählt der Computer!") time.sleep(1) antwort_auf_papier = random.choice(computer_antworten) print("Er wählt:") time.sleep(1.5) print(antwort_auf_papier) if antwort_auf_papier == 'Schere': time.sleep(0.5) print("**Du hast Verloren!**") elif antwort_auf_papier == 'Stein': time.sleep(0.5) print("**Du hast Gewonnen!**") else: time.sleep(0.5) print("**Unentschieden!**")
alph="" Q="q" while(alph!=Q): alph=input("enter the alphabet") print(alph) if(alph==Q): print("exit")
x=int(input()) #ввод даных y=int(input()) i=0 while (x+x//10)<y: x+=x//10 i+=1 print(i)
h = int(input('часы - ')) #часы m = int(input('минуты - ')) #минуты s = int(input('секунды - ')) #секунды a = (h*30+m*0.5+s/120) #условие (подсказка 30-градусов 1 час,0,5 - градусов прибавляют минуты, и 1/120 секунды) print(a)
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] s = 0 for row in a: for elem in row: s += elem print(s)
def distance(x1,y1,x2,y2): return(((x1-x2)**2 + (y1-y2)**2)**0.5) x1 =float(input('Введите координаты центра окружности')) y2 =float(input('Введите координаты вне окружности')) x2 =float(input()) y1 =float(input()) r =float(input('Радиус окружности')) def IsPointInCircle(x,y,xc,yc,r): return distance(x,y,xc,yc) <= r if IsPointInCircle(x1,y1,x2,y2,r) == True: print('Yes') else: print('No')
i=0 n=1 print('Введите последовательность чисел, для окончания введите 0(ноль)') while n!=0: n=int(input('Введите число:')) if i<n: i=n print('Наибольшим числом последовательности является:',i)
a= int(input("Enter first number: ")) b= int(input("Enter second number:")) c= int(input("Enter third number:")) smallest=a if(b < smallest ): smallest = b if (c < smallest): smallest = c print(smallest, " is smallest") ## ##a= int(input("Enter first number: ")) ##b= int(input("Enter second number:")) ##c= int(input("Enter third number:")) ## #### ####if(a > b): #### print(a, " is bigger") #### ####if(a < b): #### print(b, " is bigger") #### ####if(a == b): #### print(" they are equal") ## ##if (a > b): ## print(a, " is bigger") ##else: ## print(b, " is bigger") ## ##a= int(input("Enter first number: ")) ##b= int(input("Enter second number:")) ##c= int(input("Enter third number:")) ## ##if ((a < b) and (a < c)): ## print(a, " is smallest") ## ##if ((b < a) and (b < c)): ## print(c, " is smallest") ## ##if ((c < a) and (c < b)): ## print(c, " is smallest") ## ##a= int(input("Enter first number: ")) ##b= int(input("Enter second number:")) ##c= int(input("Enter third number:")) ## ##if(a < b): ## if (a < c): ## ## print(a, " is smallest") ## else : ## print(c, " is smallest") ##else: ## if(b < c): ## print(b, " is smallest") ## else: ## print(c, " is smallest") ## ##a= int(input("Enter first number: ")) ##b= int(input("Enter second number:")) ##c= int(input("Enter third number:")) ## ##if( (a < b)and (a < c )): ## print(a, " is smallest") ## ##else: ## if(b < c): ## print(b, " is smallest") ## else: ## print(c, " is smallest")
prices = [] tax = .065 while (True): p = float(input("Enter a price: ")) prices.append(p) for i in range(len(prices)): print(prices[i]) if(prices[i] == -1): break; print("Subtotal is ", sum(prices)) tax = sum(prices)*.065 print(" Your tax amount is ", tax) total = tax + sum(prices) print("Your total is: ", total)
from tkinter import * master = Tk() canvas_width = 800 canvas_height = 800 w = Canvas(master, width=canvas_width,height=canvas_height, bg="blue") w.pack() operand1 = int(input("Enter first operand: ")) operator = str(input("Enter operator: ")) operand2 = int(input("Enter second operand: ")) result = int sign = str if(operator == "+"): sign = "Sum" result = operand1 + operand2 print("Result", result) if(operator == "-"): sign = "Diffrence " result = operand1 - operand2 print("Result", result) if(operator == "*"): sign = "Product" result = operand1 * operand2 print("Result", result) if(operator == "/"): sign = "Quotient" result = operand1 / operand2 print("Result" , result) show = operand1 , operator, operand2, "=", result w.create_text (canvas_width / 2, canvas_height / 2, font=("Ariel",30), text=show, fill= "red") w.create_text(300, 300, text=sign, fill = "red", font=("Ariel", 30))
##a = [0]*5 ## ##print(a) ## ##print(a[2]) ## ##a[0]= 5 ##print(a) ##a[2]=10 ##print(a) ## ##a[4]="hello" ##print(a) ## ##print(a[-5]) a1 = [2, 5, 6, 9, 6, 4, 3, 3, 5] print(a1) for i in range(4): a1[i]+=3 print(a1[3:7]) a2 = [3, 3, 3] a3 = a1 + a2 print(a3) if (3 in a1): print("3 is in the list") print(len(a3)) ##a3[12] = 20 a3.append(20) print(a3) del a3[3] print(a3) a3.extend(a2) print(a3) #insert increase list size a3.insert(4, 100) print(a3) print(len(a3)) # assignment replace the value a3[4]=200 print(a3) print(len(a3)) b = "hello" print(b[0]) print(max(a3)) print(min(a3)) a3.pop(4) a3.reverse() print(a3) a3.sort() print(a3) a3.sort(reverse=True) print(a3) a4 = ['b', 'c', 'f', 'a', 'x'] a4.sort(reverse=True) print(a4) print(sum(a1))
# cara input dan output file contoh .txt """ mode dalam membuat file w = write mode -> mode menulis dan menghapus file lama, jika file tidak ada, maka akan di buat file baru r = read mode only -> hanya bisa baca a = appending mode -> menambahkan data di akhir baris r+ = write dan read mode """ # MEMBUAT file file = open("data.txt", 'w') file.write("ini adalah data text yang dibuat dengan menggunakan python") file.write("\nini baris kedua") file.write("\nini baris ketiga") file.write("\nini baris keempat") file.close() # setelah open jangan lupa close, supaya tersimpan # MEMBACA file text file2 = open("data.txt",'r') # print(file2.read()) # print(file2.read(10)) # 10 adalah jumlah karakter print(file2.readline()) # baca sebaris file2.close() # APPENDING mode file3 = open("data.txt",'a') file3.write("\nbaris ini dibuat dengan menggunakan mode APPEND") file3.close()
def jumlah(a,b): c = a + b return c hasil = jumlah(4,5) print(hasil) # lambda function untuk mempermudah seperti fungsi di atas # misal, membuat anonymous function dengan lambda kali = lambda argumen: print(argumen) kali('test') kali = lambda x,y: x*y print(kali(3,4))
# list sebagai iterables gorengan = ["bakwan", "cireng", "bala-bala", "gehu", "combro", "pisang goreng", "pukis", "risoles", "tahu isi", "tempe goreng"] for g in gorengan: print(g) print(len(g)) # string sebagai iterable bakwan = 'bakwan' for i in bakwan: print(i) # for di dalam for buah = ['semangka', 'jeruk', 'apel', 'anggur'] sayur = ['kangkung', 'wortel', 'tomat'] Daftar_belanja = [gorengan, buah, sayur] print(Daftar_belanja) print("\n") for subDaftarBelanja in Daftar_belanja: print(subDaftarBelanja) for komponen in subDaftarBelanja: print(komponen)
import pprint # Setup, create menues main_menu = ''' Home Menu------ 1. Print Room Status 2. Check-In a customer 3. Check-Out a customer 4. Admin Features 5. Exit ''' check_in_menu = ''' Check In------ 1. Print Room Status 2. Add Customer Info 3. Request Room Specifics 4. Exit ''' check_out_menu = ''' Check Out------ 1. Print Room Status 2. Check Out of Room# 3. Exit ''' admin_menu = ''' Admin------ 1. Print Guest List 2. Save Hotel Info 3. Load Hotel Info 4. Check if room vacant 5. Exit ''' #Setup define functions #checks to is if room is vacant def is_vacant(location, room_number): if hotels[location][room_number] == '': print('This Room is vacant') else: print(f'{room_number} is occupied by {hotels[location][room_number]}') #function that checks in guest, assigning them to room number def check_in(number, guest, which_location): hotels[which_location][number] = guest #function that checks out guest, removes them from the corresponding key room number #include the print() in the function or else there will be nothing to bring after function runs! def check_out(number,): print(f'{hotels[0][number]} has been checked out of room {number}') hotels[0][number] = '' #Setup create hotel location dictionaries hotel_atlanta = { 'name' : 'atlanta', '101' : '', '102' : '', '103' : '', '104' : '', '105' : '', } hotel_boston = { 'name' : 'boston', '101' : '', '102' : '', '103' : 'test', '104' : '', '105' : '', } hotel_barcelona = { 'name' : 'barcelona', '101' : 'test', '102' : '', '103' : '', '104' : '', '105' : '', } hotels = [hotel_atlanta, hotel_boston, hotel_barcelona] guests = [] #Begin while True: menu_choice = int(input(main_menu)) # 1. Room Status if menu_choice == 1: count = 0 for location in hotels: for room_number in hotels[0].keys(): if hotels[count][room_number] == '': print(f'{room_number} is vacant') else: print(f'{room_number} is occupied by {hotels[count][room_number]}') count += 1 # Check In Menu elif menu_choice == 2: while True: menu_choice = int(input(check_in_menu)) # Print Room Status if menu_choice == 1: count = 0 for location in hotels: for room_number in hotels[0].keys(): if hotels[count][room_number] == '': print(f'{room_number} is vacant') else: print(f'{room_number} is occupied by {hotels[count][room_number]}') count += 1 # Add Customer Info elif menu_choice == 2: #create a dictionary with the guests last name #formatted like this # guests_last_name = { # 'name' : 'firstname lastname', # 'phone_number' : '109520358', # 'has_prepaid' : 'yes', # } guest_last_name = input('What is the guests last name? ') guests_first_name = input('What is the guets first name? ') guest_name = f'{guests_first_name} {guest_last_name}' #creates dictionary which_location = int(input('Which location are they checking into? ')) guest_last_name = {} guest_last_name['name'] = f'{guest_name}' guest_phone = input('What is the guests phone number? ') guest_last_name['phone_number'] = guest_phone has_prepaid = input('Has the guest prepaid? ') guest_last_name['has_prepaid'] = has_prepaid #what room number to assing this dictionary to? room_num = input(f'What room shall we assign {guest_last_name["name"]} to? ') #call the function check_in check_in(room_num, guest_name, which_location) #append the guests list with the dictionary for future reference guests.append(guest_last_name) # print(hotels[0][room_num][name]) # room_number = input('Which Room Number? ') # guest_name = input('Guests Name? ') # check_in(room_number, guest_name) # print(f'{hotels[0][room_number]} has been checked in to room {room_number}') # Request Room Specifics elif menu_choice == 3: pass #Exit elif menu_choice == 4: break # 3. Check Out Menu elif menu_choice == 3: while True: menu_choice = int(input(check_out_menu)) # Print Room Status if menu_choice == 1: count = 0 for location in hotels: for room_number in hotels[0].keys(): if hotels[count][room_number] == '': print(f'{room_number} is vacant') else: print(f'{room_number} is occupied by {hotels[count][room_number]}') count += 1 #Check Out elif menu_choice == 2: room_number = input('Which Room Number? ') which_location = int(input('Which Location? ')) check_out(room_number, which_location) #exit elif menu_choice == 3: break # 4. Admin Features Menu elif menu_choice == 4: while True: menu_choice = int(input(admin_menu)) # Print Guest List if menu_choice == 1: print(guests) # Save Hotel Info # Would like to save both the hotels var and the guests var to the same JSON file ??????????? elif menu_choice == 2: import json file_name = 'hotel_list.json' with open(file_name, 'w') as file_to_save: json.dump(hotels, file_to_save) print('The file has been saved') # Load Hotel Info elif menu_choice == 3: print(hotels) temp = input('What file would you like to import? ') import json file_name = temp with open(file_name, 'r') as file_to_load: hotels = json.load(file_to_load) print('The file has been loaded') print(hotels) # Is room vacant elif menu_choice == 4: location = int(input('Which Location? ')) room_number = input('Which Room Number? ') is_vacant(location, room_number) elif menu_choice == 5: break # 5. Exit elif menu_choice == 5: print('Thank You') break ####### Why does one work and not the other # count = 0 # while count < len(hotels): # name = hotels[0]["name"] # print(name) # count += 1 # count = 0 # while count < len(hotels): # name = hotels[count]["name"] # print(name) # count += 1
def min (a,b,c,d): if a<=b and a<=c and a<=d: return a elif b<=c and a<=d: return b elif c<=d: return c else: return d l=str.split(input()) a,b,c,d=int(l[0]),int(l[1]),int(l[2]),int(l[3]) print(min(a,b,c,d))
#!/usr/bin/python3 def complex_delete(my_dictionary, value): keys_to_del = [] for key in my_dictionary: if my_dictionary[key] == value: keys_to_del.append(key) for key in keys_to_del: del my_dictionary[key] return my_dictionary
class Queue: ''' Implementation of a queue using a fixed sized array (ring buffer). ''' def __init__(self, size): self.a = [None] * size self.read = 0 self.write = 0 def is_empty(self): return self.read == self.write def enqueue(self, val): ''' Adds the value to the back of the queue. The list provides a single space buffer when adding in order to tell the difference between empty and full queue ''' if (self.write + 1) % len(self.a) == self.read: raise IndexError('The queue is full') self.a[self.write] = val self.write = (self.write + 1) % len(self.a) def dequeue(self): ''' Removes and returns the least recently added value from the queue. ''' if self.is_empty(): raise IndexError('The queue is empty') val = self.a[self.read] self.read = (self.read + 1) % len(self.a) return val
import heapq class Node: def __init__(self, val, weight): self.val = val self.weight = weight self.next = None class Alist: def __init__(self): self.list=[] def addNode(self, n): self.list.append(n) def addEdge(self, n1, n2): new2 = Node(n2.val) end = n1.next n1.next = new2 new2.next = end def getNeighbors(self, n): new = [] while n.next: new.append(n.next) n = n.next return new def getEdge(self, node, n): while node.next: if node == n: return node.weight node = node.next def networkDelayTime(times, N, K): distance_heap = [] for i in times: distance_heap.append(times[i][2], times[i][1])) #use heapq to make this a min heap above adjlist = Alist() times_dict = dict() for i in range(N): adjlist.addNode(i+1,0) for f, t , w in times: adjlist.addEdge(Node(f,0),Node(t,w)) for i in range(len(times)): n1 = Node(times[i][0]) n2 = Node(times[i][1]) adjlist.addEdge(n1, n2) #we only want to go one direction mate for i in range(len(times)): times_dict.update({times[i][2] : (times[i][2], INT_MAX)}) #initialize dictionary to infinity for each weight and make its prev node itself times_dict.update({ K : (K, 0)}) while distance_heap: (distance,node) = distance_heap.dequeue() neighbors = adjlist.getNeighbors(node) for n in neighbors: w = adjlist.getEdge(node,n) #get edge from adjacency list if distance+w < times_dict[n][1]: # if the distance of that node to its neighbor node is less than the distance in the dictionary for that neighbor node, update it time_dict[n] = (node, distance+w)
# Game # Snake water gun import random choices=["Snake","Water","Gun"] player=input("Enter player name : ") play_again="Y" while(play_again.upper()=="Y"): games = 10 computer_points = 0 player_points = 0 draw = 0 while (games>0): print(f"------------- Game number : {11-games} -------------") print(f"Score : COMPUTER : {computer_points} | {player.upper()} : {player_points} | DRAW : {draw}") computer_choice = random.choice(choices) user_choice=input("Please enter your choice [Snake/Watr/Gun] 'S' for Snake 'W' for Water 'G' for Gun : ") if(user_choice.upper()=="S" and computer_choice=="Water") \ or (user_choice.upper()=="W" and computer_choice=="Gun")\ or (user_choice.upper()=="G" and computer_choice=="Snake"): player_points=player_points+1 print("You win the match...!!!") elif(user_choice.upper()=="S" and computer_choice=="Snake") \ or (user_choice.upper()=="W" and computer_choice=="Water")\ or (user_choice.upper()=="G" and computer_choice=="Gun"): draw=draw+1 print("Draw the match...!!!") else: computer_points=computer_points+1 print("You lost the match...!!!") games=games-1 print("--"*50) print(f"| {' '* 48}|") print(f"| Scorecard : COMPUTER : {computer_points} | {player.upper()} : {player_points} | DRAW : {draw}") if player_points>computer_points: print(f"| {player.upper()} win the series.....!!! Congratulations....!!!") elif player_points<computer_points: print(f"| COMPUTER win the series.....!!!") else: print(f"| Series Drawn ") print(f"| {' ' * 48}|") print("--" * 50) play_again=input("Do u want to play again? Y/N : ") print("Thanks for playing the game... !!!")
#dinamicamente tipado """ numero = 3 numero = "hola" print(numero) """ texto = "hola como estas" texto = texto.upper() print(texto) print(texto.isnumeric()) texto.isnumeric print(texto[0:3])
# https://leetcode.com/problems/invert-binary-tree/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ head = root if root != None: tree_queue = [root] else: return None while(len(tree_queue) > 0): curr = tree_queue.pop(0) if curr.left: tree_queue.append(curr.left) if curr.right: tree_queue.append(curr.right) # Swap if we have left and right old_right = curr.right curr.right = curr.left curr.left = old_right return head
import numpy as np x = np.array([1,2,3]) y = np.array([1,0,2]) print("x ndim: ", x.ndim) print("x shape: ", x.shape) print("x size: ", x.size) print("x data type: ", x.dtype) print("-" * 20) print(x) print("-" * 20) print("y ndim: ", y.ndim) print("y shape: ", y.shape) print("y size: ", y.size) print("y data type: ", y.dtype) print("-" * 20) print(y) print("-" * 20)
vocal= input("Ingrese una vocal: ") while vocal not in ("a", "e", "i", "o", "u"): if vocal == "-": break vocal = input("Vocal:") print ("Su vocal o punto es:{}".format(vocal))
"""Funciones matematicas""" import math num1, num2, num, men = 12.572, 15.4, 4, '1234' print(math.ceil(num1), '\t',math.floor(num1)) print(round(num1,1),'\t',type(num),'\t',type(men)) # funciones de cadenas mensaje = "Hola" + "mundo " + "Python" men1=mensaje.split() men2=' '.join(men1) print(mensaje[0],mensaje[0:4],men1,men2) print(mensaje.find("mundo"), mensaje.lower()) # funciones de fecha from datetime import datetime,timedelta,date hoy, fdia = datetime.now(), date.today() futuro = hoy + timedelta(days=30) dif, aa, mm, dd = futuro - hoy, hoy.year, hoy.month, hoy.day fecha = date(aa, mm, dd+2) print(hoy, fdia, futuro, dif, fecha)
x=int(input("Ingrese un numero entero: ")) if x<0: x = 0 ptint("Negativo cambiando a cero") elif x== 0: print ("Cero") elif x== 1: print ("Uno") else: print ("Ninguna opcion") print("Ok") if type(x) == int else print ("-")
# coding: utf-8 # ----- IMPORT ----- import csv, time import matplotlib.pyplot as plt # ----- /IMPORT ----- # ----- OPEN .CSV FILE ----- print("Reading the document...") with open("chicago.csv", "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) # ----- /OPEN .CSV FILE ----- # ----- FUNCTION DEFINITIONS ----- def column_to_list(data, index): """ Create a new list from a given column of a matrix. Args: data: Dataset. index: Column index. Returns: List containing the column elements. """ column_list = [] for item in range(0,len(data)): list_item = data[item][index] column_list.append(list_item) return column_list def count_gender(data_list): """ Count genders within a given list. Args: data_list: Dataset. Returns: male: integer of "Male"'s sum famele: integer of "Female"'s sum """ male = 0 female = 0 for item in range(0,len(data_list)): if data_list[item][-2] == "Male": male = male + 1 if data_list[item][-2] == "Female": female = female + 1 return [male, female] def most_popular_gender(data_list): """ Check the most popular gender of a list. Args: data_list: List dataset. Returns: answer: string containing the most popular gender """ if count_gender(data_list)[0] > count_gender(data_list)[1]: answer = "Male" elif count_gender(data_list)[0] < count_gender(data_list)[1]: answer = "Female" else: answer = "Equal" return answer def count_user_types(data_list): """ Count user types within a given list. Args: data_lisr: Dataset. Returns: intergers: number of customer, number of subscriber, number of dependents """ customer = 0 subscriber = 0 dependent = 0 for item in range(0,len(data_list)): if data_list[item][-3] == "Customer": customer = customer + 1 if data_list[item][-3] == "Subscriber": subscriber = subscriber + 1 if data_list[item][-3] == "Dependent": dependent = dependent + 1 return [customer, subscriber, dependent] def median_list(data_list): """ Calculate the median of a sorted list. Args: data_list: List dataset. Returns: median_trip: float value of list's median """ if len(trip_duration_list) % 2 == 0: index = int(len(trip_duration_list)) median = (trip_duration_list[index] + trip_duration_list[index+1]) / 2 else: index = int(((len(trip_duration_list))/2)+0.5) median = trip_duration_list[index] return median def count_items(column_list): """" Count types and quantity of elements in a list Args: column_list: list dataset Returns: item_types_list: list of different elements in the list count_items: how many times each element repeat in the list """ item_types = [] count_items = [] item_types_list = [] item_types = set(column_list) index_max = len(item_types) for index in range(0,index_max): item = item_types.pop() item_types_list.append(item) print(item) index += 1 items = len(column_list) for index_types in range(0,len(item_types_list)): counter = 0 for index_list in range(0,len(column_list)): if column_list[index_list] == item_types_list[index_types]: counter += 1 count_items.append(counter) return item_types_list, count_items # ----- /FUNCTION DEFINITIONS ----- # ----- DESIGN ----- print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("Ok!") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print(" _ _ _ _ _ \n| | | | __| | __ _ ___(_) |_ _ _ \n| | | |/ _` |/ _` |/ __| | __| | | |\n| |_| | (_| | (_| | (__| | |_| |_| |\n \___/ \__,_|\__,_|\___|_|\__|\__, |\n |___/") print("----------------------------------------------------") print("Machine Learning & AI Foundations Nanodegree Program") print("Project: Explore Chicago Bikeshare Data") print("version 2") print("----------------------------------------------------") print("by Daniel Cruz") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("----------------------------------------------------") # ----- /DESIGN ----- print("Number of rows:") print(len(data_list)) print("Row 0: ") print(data_list[0]) print("Row 1: ") print(data_list[1]) # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n _ \n/ |\n| |\n| |\n|_|") # ----- /DESIGN ----- # TASK 1 # TODO: Print the first 20 rows using a loop to identify the data. print("\n\nTASK 1: Printing the first 20 samples") print("----------------------------------------------------") data_list = data_list[1:] for item in range(0,20): print(data_list[item]) # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n ____ \n|___ \ \n __) |\n / __/ \n|_____|") # ------ /DESIGN ------ # TASK 2 # TODO: Print the `gender` of the first 20 rows print("\nTASK 2: Printing the genders of the first 20 samples") print("----------------------------------------------------") for item in range(0,20): print(data_list[item][6]) # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n _____ \n|___ / \n |_ \ \n ___) |\n|____/ ") # ----- /DESIGN ----- print("\nTASK 3: Printing the list of genders of the first 20 samples") print("----------------------------------------------------") print(column_to_list(data_list, -2)[:20]) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(column_to_list(data_list, -2)) is list, "TASK 3: Wrong type returned. It should return a list." assert len(column_to_list(data_list, -2)) == 1551505, "TASK 3: Wrong lenght returned." assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[1] == "Male", "TASK 3: The list doesn't match." # ----------------------------------------------------- # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n _ _ \n| || | \n| || |_ \n|__ _|\n |_|") # ----- /DESIGN ----- male = 0 female = 0 for item in range(0,len(data_list)): if data_list[item][-2] == "Male": male = male + 1 if data_list[item][-2] == "Female": female = female + 1 print("\nTASK 4: Printing how many males and females we found") print("----------------------------------------------------") print("Male: ", male, "\nFemale: ", female) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert male == 935854 and female == 298784, "TASK 4: Count doesn't match." # ----------------------------------------------------- # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n ____ \n| ___| \n|___ \ \n ___) |\n|____/ ") # ----- /DESIGN ----- print("\nTASK 5: Printing result of count_gender") print("----------------------------------------------------") print(count_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(count_gender(data_list)) is list, "TASK 5: Wrong type returned. It should return a list." assert len(count_gender(data_list)) == 2, "TASK 5: Wrong lenght returned." assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, "TASK 5: Returning wrong result!" # ----------------------------------------------------- # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n __ \n / /_ \n| '_ \ \n| (_) |\n \___/ ") # ----- /DESIGN ----- print("\nTASK 6: Which one is the most popular gender?") print("----------------------------------------------------") print("Most popular gender is: ", most_popular_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(most_popular_gender(data_list)) is str, "TASK 6: Wrong type returned. It should return a string." assert most_popular_gender(data_list) == "Male", "TASK 6: Returning wrong result!" # ----------------------------------------------------- # Graph - gender gender_list = column_to_list(data_list, -2) types = ["Male", "Female"] quantity = count_gender(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('Gender') plt.xticks(y_pos, types) plt.title('Quantity by Gender') plt.show(block=True) # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n _____ \n|___ |\n / / \n / / \n /_/") # ----- /DESIGN ----- print("\nTASK 7: Check the chart (User types)! ") print("----------------------------------------------------") # graph - user types user_types_list = column_to_list(data_list, -3) types = ["Customer", "Subscriber","Dependent"] quantity = count_user_types(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('User Types') plt.xticks(y_pos, types) plt.title('Quantity by User Types') plt.show(block=True) # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n ___ \n ( _ ) \n / _ \ \n| (_) |\n \___/ ") # ----- /DESIGN ----- male, female = count_gender(data_list) print("\nTASK 8: Why the following condition is False?") print("----------------------------------------------------") print("male + female == len(data_list):", male + female == len(data_list)) answer = "Because there are customers that didn't inform their genders" print("Answer:", answer) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert answer != "Type your answer here.", "TASK 8: Write your own answer!" # ----------------------------------------------------- # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n ___ \n / _ \ \n| (_) |\n \__, |\n /_/ ") # ----- /DESIGN ----- trip_duration_list = column_to_list(data_list, 2) min_trip = 0. max_trip = 0. mean_trip = 0. median_trip = 0. trip_duration_list = [int(i) for i in trip_duration_list] trip_duration_list.sort() total_trip = 0. qtd_trip = int(len(trip_duration_list)) for item in range(0, qtd_trip -1): total_trip = total_trip + int(trip_duration_list[item]) mean_trip = total_trip / qtd_trip min_trip = trip_duration_list[0] max_trip = trip_duration_list[len(trip_duration_list)-1] median_trip = median_list(data_list) print("\nTASK 9: Printing the min, max, mean and median") print("----------------------------------------------------") print("Min: ", min_trip, "Max: ", max_trip, "Mean: ", mean_trip, "Median: ", median_trip) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert round(min_trip) == 60, "TASK 9: min_trip with wrong result!" assert round(max_trip) == 86338, "TASK 9: max_trip with wrong result!" assert round(mean_trip) == 940, "TASK 9: mean_trip with wrong result!" assert round(median_trip) == 670, "TASK 9: median_trip with wrong result!" # ----------------------------------------------------- # ----- DESIGN ----- print("____________________________________________________") input("Press Enter to continue...") print(".") time.sleep(1) print(".") time.sleep(1) print(".") time.sleep(1) print("\n _ ___ \n/ |/ _ \ \n| | | | |\n| | |_| |\n|_|\___/ ") # ----- /DESIGN ----- user_types= set(column_to_list(data_list, 3)) print("\nTASK 10: Printing start stations:") print("----------------------------------------------------") print(len(user_types), " stations: \n") print(user_types) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert len(user_types) == 582, "TASK 10: Wrong len of start stations." # ----------------------------------------------------- print("____________________________________________________") input("Press Enter to continue...") # TASK 11 # Go back and make sure you documented your functions. Explain the input, output and what it do. Example: # def new_function(param1: int, param2: str) -> list: # """ # Example function with annotations. # Args: # param1: The first parameter. # param2: The second parameter. # Returns: # List of X values # """ input("Press Enter to continue...") # TASK 12 - Challenge! (Optional) # TODO: Create a function to count user types without hardcoding the types # so we can use this function with a different kind of data. print("Will you face it?") answer = "yes" if answer == "yes": # ------------ DO NOT CHANGE ANY CODE HERE ------------ column_list = column_to_list(data_list, -2) types, counts = count_items(column_list) print("\nTASK 11: Printing results for count_items()") print("Types:", types, "Counts:", counts) assert len(types) == 3, "TASK 11: There are 3 types of gender!" assert sum(counts) == 1551505, "TASK 11: Returning wrong result!" # -----------------------------------------------------
# -*- coding: utf-8 -*- import re from functools import reduce import csv import json import _pickle as pickle def main(filename): # read file into lines f = open(filename) lines = f.readlines() # declare a word list all_words = [] pattern = re.compile(r'\w+\W*\w+|\w+') # extract all words from lines for line in lines: # split a line of text into a list words # "I have a dream." => ["I", "have", "a", "dream."] words = line.split(' ') # check the format of words and append it to "all_words" list for word in words: # then, remove (strip) unwanted punctuations from every word # "dream." => "dream" word = (pattern.search(word)).group() if pattern.search(word) else None # check if word is not empty if word: # append the word to "all_words" list all_words.append(word) # compute word count from all_words def st(dic, k): if not k in dic: dic[k] = 1 else: dic[k] +=1 return dic counter = sorted(reduce(st, all_words, {}).items(), key=lambda d: d[1], reverse=True) #print(counter) # dump to a csv file named "wordcount.csv": # word,count # a,12345 # I,23456 # ... with open('wordcount.csv', 'w', newline='') as cf: # create a csv writer from a file object (or descriptor) writer = csv.writer(cf) # write table head writer.writerow(['word', 'count']) # write all (word, count) pair into the csv writer #for key in counter: writer.writerows(counter) # dump to a json file named "wordcount.json" with open('wordcount.json','w') as json_file: json.dump(counter, json_file) # BONUS: dump to a pickle file named "wordcount.pkl" # hint: dump the Counter object directly #print(type(counter)) with open('wordcount.pkl','wb') as f: pickle.dump(counter, f) #print(type(counter)) #with open('wordcount.pkl','rb') as f: #tes = pickle.load(f) #print(tes == counter) if __name__ == '__main__': main("i_have_a_dream.txt")
number1 = int(input()) inheritance = {} # print(number) for x in range(number1): inputted = input().split(":") cn_left = inputted[0] if len(inputted) == 1: cn_right = [] inheritance[cn_left.strip()] = cn_right else: cn_right = inputted[1] inheritance[cn_left.strip()] = cn_right.split() # print(cn_left) # print(cn_right) number2 = int(input()) def check(a, b): if a in inheritance[b]: return "Yes" else: temp = "No" for element in inheritance[b]: if check(a, element) == "Yes": temp = "Yes" return temp for y in range(number2): cn_out_left, cn_out_right = input().split() if cn_out_right in inheritance: if cn_out_right == cn_out_left: print("Yes") else: print(check(cn_out_left, cn_out_right)) else: print("No") # print(inheritance) # 15 # G : F # A # B : A # C : A # D : B C # E : D # F : D # X # Y : X A # Z : X # V : Z Y # W : V # Q : P # Q : R # Q : S # 7 # A G # A Z # A W # X W # X QWE # A X # X X # 1 1 # Q # # # # Ответы: # # Yes # No # Yes # Yes # No # No # Yes # No # Yes
'''# формируем множество известных слов на основании построчного ввода dic = {input().lower() for _ in range(int(input()))} # заводим пустое множество для приема текста wrd = set() # т.к. текст построчно подается, а также в каждой строке несколько слов, # то каждую строку превращаем во множество и добавляем в единое множество wrd for _ in range(int(input())): wrd |= {i.lower() for i in input().split()} # на вывод отправляем результат вычитания словарного множества dic # из текстового множества wrd; впереди ставим *, чтобы раскрыть поэлементно print(*(wrd-dic), sep="\n") Основа работы кода - свойство множеств хранить только уникальные значения. wrd |= {...} отвечает за добавление множества {...} в единое wrd (аналог метода update) Обращаем внимание на звездочку *, которая вытаскивает элементы на вывод, вместо того, чтобы печатать в виде множества''' dictionary, text, res = [input().lower() for _ in range(int(input()))], [input() for _ in range(int(input()))], set() for line in text: for word in line.split(): if word.lower() not in dictionary: res.add(word) print("\n".join(res)) '''Простейшая система проверки орфографии основана на использовании списка известных слов. Каждое слово в проверяемом тексте ищется в этом списке и, если такое слово не найдено, оно помечается, как ошибочное. Напишем подобную систему. Через стандартный ввод подаётся следующая структура: первой строкой — количество d записей в списке известных слов, после передаётся d строк с одним словарным словом на строку, затем — количество l строк текста, после чего — l строк текста. Напишите программу, которая выводит слова из текста, которые не встречаются в словаре. Регистр слов не учитывается. Порядок вывода слов произвольный. Слова, не встречающиеся в словаре, не должны повторяться в выводе программы.  Sample Input: 3 a bb cCc 2 a bb aab aba ccc c bb aaa Sample Output: aab aba c aaa'''
def my_min(fname): smallest_so_far= None for num in fname: if smallest_so_far is None: smallest_so_far = num continue elif smallest_so_far > num: smallest_so_far = num return smallest_so_far def my_max(fname): largest_so_far=None for a in fname: if largest_so_far is None: largest_so_far= a continue elif largest_so_far < a: largest_so_far = a return largest_so_far def my_average(fname): sum=0 for b in fname: sum += b avg=sum/len(fname) return avg def my_median(fname): fname.sort() r=int(len(fname)/2) c=len(fname) if c%2==0: median=(fname[r-1]+fname[r])/2 elif c%2==1: median=fname[r] return median def my_range(fname): range=(my_max(fname))-(my_min(fname)) return range def getFilelines(fname): fhandle = open(fname) lines = [] for line in fhandle: line = line.rstrip() if line: line = float(line) lines.append(line) fhandle.close() return lines data = getFilelines('/Users/jacobzhu/Desktop/MH8811-04-Data.csv') print('Min:', my_min(data)) print('Max:', my_max(data)) print('Average:', my_average(data)) print('Median:', my_median(data)) print('Range:',my_range(data)) #------------------------------------------------------------------ y=sum(data) for x in data: x=int(x) mean=y/len(data) total_sum=0 for x in data: total_sum +=(x-mean)**2 sample_variance = (total_sum)/(len(data)-1) print('Sample variance:', sample_variance)
A = raw_input("subject1: ") a = input("score: ") B = raw_input("subject2: ") b = input("score: ") C = raw_input("subject3: ") c = input("score: ") sum = a + b + c aver = round(float(sum) / 3, 3) print A + " " + str(a) print B + " " + str(b) print C + " " + str(c) print "sum: " + str(sum) print "average: " + str(aver)
print('Hello World!') va1= 'Sveika ' print(va1) va2 ='Pasaule' print(va1,va2) print(len(va1)) print("val[2:4]:", va1[::-1]) print(va1*2) va2 = 'Sashka' print(va1+va2) #pirma metode print("Mes te - %s - kaut ko ieleksim" %'kaut kas', end='\n\n') #otra metode print("Teksta ievetosana ar .format metodi: {}". format ('Hey, tev sanaca')) print("{1} {0}".format('Juuhhhuu,','sacanaca!!!!!')) print("{0} {1}".format('Juuhhhuu,','sacanaca!!!!!')) #3 metode vards= "saule" print(f"Ara spid {vards}")
import unittest import re #Define exceptions class RomanError(Exception): pass class OutOfRangeError(RomanError): pass class NotIntegerError(RomanError): pass class InvalidRomanNumeralError(RomanError): pass romanNumeralMap = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)) def toRoman(n): """convert integer to Roman numeral""" if not (0 < n < 5000): #print OutOfRangeError("number out of range (must be 1..4999)") return "" if int(n) != n: raise NotIntegerError("decimals can not be converted") result = "" for numeral, integer in romanNumeralMap: while n >= integer: result += numeral n -= integer return result #Define pattern to detect valid Roman numerals romanNumeralPattern = re.compile(""" ^ # beginning of string M{0,4} # thousands - 0 to 4 M's (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), # or 500-800 (D, followed by 0 to 3 C's) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), # or 50-80 (L, followed by 0 to 3 X's) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), # or 5-8 (V, followed by 0 to 3 I's) $ # end of string """ ,re.VERBOSE) def fromRoman(s): """convert Roman numeral to integer""" if not s: #print InvalidRomanNumeralError('Input can not be blank') return "" if not romanNumeralPattern.search(s): raise InvalidRomanNumeralError('Invalid Roman numeral: %s' % s) result = 0 index = 0 for numeral, integer in romanNumeralMap: while s[index:index+len(numeral)] == numeral: result += integer index += len(numeral) return result class RomanNumeralsTest(unittest.TestCase): def test_0(self): self.assertEqual("", toRoman(0)) def test_1(self): self.assertEqual("I", toRoman(1)) def test_5(self): self.assertEqual("V", toRoman(5)) def test_2(self): self.assertEqual("II", toRoman(2)) def test_3(self): self.assertEqual("III", toRoman(3)) def test_10(self): self.assertEqual("X", toRoman(10)) def test_4(self): self.assertEqual("IV", toRoman(4)) def test_6(self): self.assertEqual("VI", toRoman(6)) def test_8(self): self.assertEqual("VIII", toRoman(8)) def test_24(self): self.assertEqual("XXIV", toRoman(24)) def test_1983(self): self.assertEqual("MCMLXXXIII", toRoman(1983)) def test_2412(self): self.assertEqual("MMCDXII", toRoman(2412)) def test_3309(self): self.assertEqual("MMMCCCIX", toRoman(3309)) def test_empty(self): self.assertEqual("", fromRoman(0)) def test_I(self): self.assertEqual(1, fromRoman("I")) def test_V(self): self.assertEqual(5, fromRoman("V")) def test_II(self): self.assertEqual(2, fromRoman("II")) def test_III(self): self.assertEqual(3, fromRoman("III")) def test_X(self): self.assertEqual(10, fromRoman("X")) def test_IV(self): self.assertEqual(4, fromRoman("IV")) def test_VI(self): self.assertEqual(6, fromRoman("VI")) def test_VIII(self): self.assertEqual(8, fromRoman("VIII")) def test_XXIV(self): self.assertEqual(24, fromRoman("XXIV")) def test_MCMLXXXIII(self): self.assertEqual(1983, fromRoman("MCMLXXXIII")) def test_MMCDXII(self): self.assertEqual(2412, fromRoman("MMCDXII")) def test_MMMCCCIX(self): self.assertEqual(3309, fromRoman("MMMCCCIX")) if __name__ == "__main__": unittest.main()
import unittest def searchinMatrixO_N(v, matrix): i = 0 j = len(matrix)-1 while i < v and j >= 0 : if matrix[i][j] == v: return (i,j) elif matrix[i][j] > v: j = j - 1 else: i = i + 1 return (-1, -1) def binSearchinList(v, l): low = 0 high = len(l) while low < high: mid = int((low + high)/2) if l[mid] < v: high = mid - 1 elif l[mid] > v: low = mid + 1 else: return mid return -1 class BinSearchTest(unittest.TestCase): def test_index_0(self): l = [1] expectedIndex = 0 self.assertEqual(0, binSearchinList(1, l)) def test_index_1(self): l = [1, 2, 3] expectedIndex = 1 self.assertEqual(1, binSearchinList(2, l)) def test_missing_number(self): l = range(100) expected = -1 self.assertEqual(-1, binSearchinList(200, l)) def test_sortedMatrix_test_33(self): n = 0 l = [[], [], [], [], [], [], [], [], [], []] for i in range(10): for j in range(10): l[i].append(n) n = n + 1 #override the 3rd row l[3] = [33, 33, 33, 33, 33, 33, 33, 33, 33 ,33] self.assertEquals((-1, -1), searchinMatrixO_N(32, l)) if __name__ == "__main__": unittest.main()
import calendar def search(year, month, day1): while year >= 2019 and 1 <= month <= 12 and day1 == 1: yield year, month, day1 month -= 1 if not month: year -= 1 latest_year, latest_month, day2 = 2019, 6, 1 your_day = input('Введите день: ') day = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6} for i in search(latest_year, latest_month, day2): if calendar.weekday(*i) == day[your_day]: print(*i) break
def count(start, step): while True: print (start) start += step count(int(input('Введите start: ')), int(input('Введите step: ')))
import random def even(): positive_answer = 'yes' negative_answer = 'no' number = random.randint(1, 99) is_number_even = number % 2 == 0 correct_answer = positive_answer if is_number_even else negative_answer answer_type = str return number, correct_answer, answer_type
import prompt from brain_games.cli import welcome_user MAX_CORRECT_ANSWERS = 3 ANSWER_TYPE_MAP = { int: prompt.integer, str: prompt.string } def game(greeting, get_task_items): player_name = welcome_user() correct_answers_num = 0 print(greeting) while correct_answers_num < MAX_CORRECT_ANSWERS: question, correct_answer, correct_answer_type = get_task_items() print(f'Question: {question}') answer_prompt = ANSWER_TYPE_MAP[correct_answer_type] answer = answer_prompt('Your answer: ') if answer == correct_answer: print('Correct!') correct_answers_num += 1 else: print( f"'{answer}' is wrong answer ;(. " f"Correct answer was '{correct_answer}'." ) print(f'Let\'s try again, {player_name}!') break if correct_answers_num == MAX_CORRECT_ANSWERS: print(f'Congratulations, {player_name}!')
m = list([]) n = int(input('Введите количество критериев: ')) for i in range(n): # Создаем двумерный массив m.append([]) for j in range(n): m[i].append(0) for i in range(len(m)): for j in range(len(m)): if i < j: m[i][j] = float( input(f'Введите важность критерия {i + 1} относительно {j + 1} ')) # Заполняем массив коэффициентами m[j][i] = 1 / float(m[i][j]) elif i == j: m[i][j] = 1 sum_line = [] for i in range(len(m)): k = 0 for j in range(len(m)): k += float((m[i][j])) sum_line.append(k) # Заполняем новый массив суммой строк массива с коэффициентами full_sum = 0 for i in sum_line: # Находим сумму элементов нового массива full_sum += i kriter = [] for i in sum_line: # Заполняем еще один новый массив весом критерия kriter.append(i / full_sum) for i in range(len(kriter)): # Выводим вес каждого критерия print(f'Вес критерия №{i + 1} - {"%.2f" % kriter[i]}')
''' Dynamic Programming Approach Accepted on leetcode(139) time - O(N^2) space - O(N) ''' class Solution: def wordBreak(self, s: str, wordDict) -> bool: # Edge case if len(s) == 0: return True HashSet = set(wordDict) # make a HashSet(O(1) search operation) # initialize Dp of size (length of given string + 1) dp = [False for i in range(len(s) + 1)] dp[0] = True # Iterate over all possible combinations by using recursion for i in range(1, len(dp)): for j in range(0, i): print(s[j:i]) if s[j:i] in HashSet and dp[j]: # above condition only passes when the word exists in the HashSet dp[i] = True return dp[len(dp) - 1]
'''сумма чисел от числа_1 до числа_2''' from_num = int(input()) to_num = int(input()) summ = 0 i = from_num while i <= to_num: summ += i i += 1 print(summ)
from typing import List import requests, zipfile from io import BytesIO, StringIO import pandas as pd def get_epc_data(zip_file_url: str, local: bool) -> pd.DataFrame: """ Takes the local of the epc data and outputs a string :param zip_file_url: location of file :param local: Whether or not file is local :return: string of certificates file """ if local: archive = zipfile.ZipFile(zip_file_url, 'r') else: file = requests.get(zip_file_url, stream=True).content archive = zipfile.ZipFile(StringIO(file)) data = archive.open('certificates.csv').read() return pd.read_csv(BytesIO(data), encoding='utf8', sep=",") def clean_data(csv: pd.DataFrame, data_columns: List[str]) -> pd.DataFrame: """ Takes a pandas data frame and picks data columns :param csv: raw pd :param data_columns: columns to filter :return: """ return csv[data_columns]
from json import load from random import shuffle from collections import Counter deck = [] hands = [] card = [] players = 0 ### Builds the deck using the data from the json ### def build(): ### Takes the data from the json and puts it into the data variable ### with open('Cards.json', 'r') as j: data = load(j) ### Gets the suits and pairs them with the numbers ### w = 0 while w != len(data["card"]): for y in data["card"][w]: for x in data["card"][w][y]: card = (x,y) deck.append(card) w += 1 return deck ### Shuffles the deck ### def shuffles(theDeck): shuffle(theDeck) ### Splits the deck evenly depending on how many players there are ### def split(players, theDeck): numEachHand = int(len(theDeck)/players) end = numEachHand start = 0 for x in range(players): hands.append(theDeck[start:end]) start = 1 + end end += numEachHand return hands
num = int(input("Enter a number: ")) f = 1 while num>0: f = f * num num = num -1 print(f)
a = [1,2,3] n = int(input("Enter N:")) mul=1 for i in range(0,len(a)): mul =mul * a[i] print(mul%n)
# -*- coding: utf-8 -*- """ Created on Jan 2017 @author: relbaff """ import pandas import numpy # bug fix for display formats to avoid run time errors - put after code for loading data above pandas.set_option('display.float_format', lambda x:'%f'%x) # Load data from csv file original_data = pandas.read_csv('addhealth_pds.csv', low_memory=False) original_data['H1GI15'] = pandas.to_numeric(original_data['H1GI15']) original_data['H1PF5'] = pandas.to_numeric(original_data['H1PF5']) # Keep only the observations with value 0 (no) for var H1GI16M # so that we have only not married people older than or equal to 15 subset_data_min15_not_married = original_data[(original_data['H1GI15'] == 0)] # copy data data = subset_data_min15_not_married.copy() # Print number of observations and vars print('Addhealth - Number of observations: ' + str(len(data))) # 4428 print('Addhealth - Number of variables: '+ str(len(data.columns))) #2829 # Function that convert the column to numeric, calculates frequencies and display results def calculate_frequency(column_name, message, is_numeric: bool): # Convert data to numeric in case it is numeric if is_numeric: data[column_name] = pandas.to_numeric(data[column_name]) # Calculate the frequency of the variable frequency_as_count = data[column_name].value_counts(sort=False) frequency_as_percentile = data[column_name].value_counts(sort=False, normalize=True) # Print results print('***********************************************') print(message) print('Frequency in numbers:') print('---------------------') print(frequency_as_count) print('Frequency in percentile:') print('------------------------') print(frequency_as_percentile) print('***********************************************') # This function: # - Prints the distribution of the data for a specific var # - Cleans the data by replacing list of values with nan # - Prints the distribution of the data for a specific var after cleaning def clean_data(column_name, message, is_numeric: bool, values_to_nan_list): # Print frequency before changes print('BEFORE CLEANING THE DATA') calculate_frequency(column_name, message, is_numeric) # Replace all the values to nan for x in values_to_nan_list: data[column_name] = data[column_name].replace(x, numpy.nan) # Print frequency after changes print('AFTER CLEANING THE DATA') calculate_frequency(column_name, message, is_numeric) print('__________________________________________________') # Q: How close do you feel to your {MOTHER/ADOPTIVE MOTHER/ STEPMOTHER/ FOSTERMOTHER/etc.}? # A: 1=Not at all, 2=Very little, 3=somewhat, # 4=quit a bit, 5=very much, 6=refused, 7=skip-no mom, 8=don't know description_H1WP9 = 'Q: How close do you feel to your {MOTHER/ADOPTIVE MOTHER/ STEPMOTHER/ FOSTERMOTHER/etc.}?' \ '\nA: 1=Not at all, 2=Very little, 3=somewhat, 4=quit a bit, 5=very much, 6=refused, ' \ '7=skip-no mom, 8=don\'t know' clean_data('H1WP9', description_H1WP9, True, [6, 7, 8]) # Q: How close do you feel to your {FATHER/ADOPTIVE FATHER/STEPFATHER/FOSTERFATHER/etc.}? # A: 1=Not at all, 2=Very little, 3=somewhat, # 4=quit a bit, 5=very much, 6=refused, 7=skip-no mom, 8=don't know description_H1WP13 = 'Q: How close do you feel to your {FATHER/ADOPTIVE FATHER/STEPFATHER/FOSTERFATHER/etc.}?' \ '\nA: 1=Not at all, 2=Very little, 3=somewhat, 4=quit a bit, 5=very much, 6=refused, ' \ '7=skip-no dad, 8=don\'t know' clean_data('H1WP13', description_H1WP13, True, [6, 7, 8]) # Q: Most of the time, your mother is warm and loving toward you. # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don't know description_H1PF1 = 'Q: Most of the time, your mother is warm and loving toward you.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no mom, 8=don\'t know \n' clean_data('H1PF1', description_H1PF1, True, [6, 7, 8]) # Q: Your mother encourages you to be independent. # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don't know description_H1PF2 = 'Q: Your mother encourages you to be independent.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no mom, 8=don\'t know \n' clean_data('H1PF2', description_H1PF2, True, [6, 7, 8]) # Q: When you do something wrong that is important, your mother talks # about it with you and helps you understand why it is wrong. # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don't know description_H1PF3 = 'Q: When you do something wrong that is important, your mother talks ' \ 'about it with you and helps you understand why it is wrong.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no mom, 8=don\'t know \n' clean_data('H1PF3', description_H1PF3, True, [6, 7, 8]) # Q: You are satisfied with the way your mother and you communicate # with each other. # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don't know description_H1PF4 = 'Q: You are satisfied with the way your mother and you communicate with each other.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no mom, 8=don\'t know \n' clean_data('H1PF4', description_H1PF4, True, [6, 7, 8]) # Q: Overall, you are satisfied with your relationship with your mother # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don't know description_H1PF5 = 'Q: Overall, you are satisfied with your relationship with your mother.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no mom, 8=don\'t know \n' clean_data('H1PF5', description_H1PF5, True, [6, 7, 8]) # Q: Most of the time, your father is warm and loving toward you. # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no father, 8=don't know description_H1PF23 = 'Q: Most of the time, your father is warm and loving toward you.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no dad, 8=don\'t know \n' clean_data('H1PF23', description_H1PF23, True, [6, 7, 8]) # Q: You are satisfied with the way your father and you communicate # with each other. # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no father, 8=don't know description_H1PF24 = 'Q: You are satisfied with the way your father and you communicate.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no dad, 8=don\'t know \n' clean_data('H1PF24', description_H1PF24, True, [6, 7, 8]) # Q: Overall, you are satisfied with your relationship with your father # A: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, # 4=disagree, 5=strongly disagree, 6=refused, 7=skip-no father, 8=don't know description_H1PF25 = 'Q: Overall, you are satisfied with your relationship with your father.' \ '\nA: 1=Strongly Agree, 2=agree, 3=neither agree nor disagree, 4=disagree,' \ ' 5=strongly disagree, 6=refused, 7=skip-no mom, 8=don\'t know' \ '7=skip-no dad, 8=don\'t know \n' clean_data('H1PF25', description_H1PF25, True, [6, 7, 8]) # IDEAL RELATIONSHIP EXPECTATIONS # A: 1=card kept (expect it in ideal relationship), 2=card rejected, 6=refused, 8=don't know, 9=not applicable print('SECTION: IDEAL RELATIONSHIP EXPECTATIONS') print('What do you think will happen in an ideal relationship?') description_H1ID1B = 'Q: I would meet my partner’s parents.' \ '\nA: 1=card kept, 2=card rejected, 6=refused, 8=don\'t know, 9=not applicable \n' clean_data('H1ID1B', description_H1ID1B, True, [6, 8, 9]) description_H1ID1I = 'Q: I would tell my partner that I loved him or her.' \ '\nA: 1=card kept, 2=card rejected, 6=refused, 8=don\'t know, 9=not applicable \n' clean_data('H1ID1I', description_H1ID1I, True, [6, 8, 9]) description_H1ID1J = 'Q: My partner would tell me that he or she loved me.' \ '\nA: 1=card kept, 2=card rejected, 6=refused, 8=don\'t know, 9=not applicable \n' clean_data('H1ID1J', description_H1ID1J, True, [6, 8, 9]) description_H1ID1Q = 'Q: We would get married.' \ '\nA: 1=card kept, 2=card rejected, 6=refused, 8=don\'t know, 9=not applicable \n' clean_data('H1ID1Q', description_H1ID1Q, True, [6, 8, 9]) # Re-mapping variables recode = {1: 5, 2: 4, 3: 3, 4: 2, 5: 1} data['STRONG_M'] = data['H1WP9'].map(recode) data['STRONG_F'] = data['H1WP13'].map(recode) # After cleaning the data we want to create a new variable data['PARENT_RELATION'] = round((data['STRONG_M'] + data['STRONG_F'] + data['H1PF1'] + data['H1PF2'] + data['H1PF3'] \ + data['H1PF4'] + data['H1PF5'] + data['H1PF23'] + data['H1PF24'] + data['H1PF25']) \ / 10) description_PARENT_RELATION = 'Average of all the values related to the questions of the subjects and his/her parent(s)' calculate_frequency('PARENT_RELATION', description_PARENT_RELATION, True)
#Anton Danylenko #SoftDev1 pd8 #16 No Trouble #2018-10-05 import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O DB_FILE="discobandit.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #facilitate db ops #========================================================== #INSERT YOUR POPULATE CODE IN THIS ZONE # courses.csv with open('raw/courses.csv') as csvfile: #open csv file and store as DictReader reader = csv.DictReader(csvfile) #{header: element, header2, element2,..} command = 'CREATE TABLE courses (code TEXT, id INTEGER, mark INTEGER)' c.execute(command) for lines in reader: #print(lines.keys()) #print(lines) #print(lines.values()) command = 'INSERT INTO courses VALUES(\"{}\",{},{})'.format(lines['code'], int(lines['id']), int(lines['mark'])) #print(command) c.execute(command) with open('raw/occupations.csv') as csvfile: #open csv file and store as DictReader reader = csv.DictReader(csvfile) #{header: element, header2, element2,..} command = 'CREATE TABLE occupations (Job Class TEXT, Percentage INTEGER)' c.execute(command) for lines in reader: cleaned_job = lines['Job Class'].strip('\"') command = 'INSERT INTO occupations VALUES(\"{}\",{})'.format(cleaned_job, float(lines['Percentage'])) c.execute(command) with open('raw/peeps.csv') as csvfile: #open csv file and store as DictReader reader = csv.DictReader(csvfile) #{header: element, header2, element2,..} command = 'CREATE TABLE peeps (name TEXT, age INTEGER, id INTEGER)' c.execute(command) for lines in reader: command = 'INSERT INTO peeps VALUES(\"{}\",{},{})'.format(lines['name'], int(lines['age']), int(lines['id'])) c.execute(command) #========================================================== db.commit() #save changes db.close() #close database
from random import randrange mystere3 = randrange(0, 1000) mystere2 = randrange(0, 100) mystere1 = randrange(0, 20) running = True print("niveau 1: 0 à 20") print("niveau 2: 0 à 100") print("niveau 3: 0 à 1000") saisie = int(input("Entrez le niveau de difficulté")) if saisie == 1: print("Le plus simple bien sûr !") input("Appuyer sur entrer pour continuer...") while running: saisie1 = int(input("Entrez un nombre entre 0 et 20")) if saisie1 < mystere1: print("C'est plus") elif saisie1 > mystere1: print("C'est moins") else: print("Bravo tu as gagné !") running = False if saisie == 2: print("ça commence à être pas mal !") input("Appuyer sur entrer pour continuer...") while running: saisie2 = int(input("Entrez un nombre entre 0 et 100")) if saisie2 < mystere2: print("C'est plus") elif saisie2 > mystere2: print("C'est moins") else: print("Bravo tu as gagné !") running = False if saisie == 3: print("Bonne chance pour celui là !") input("Appuyer sur entrer pour continuer...") while running: saisie3 = int(input("Entrez un nombre entre 0 et 1000")) if saisie3 < mystere3: print("C'est plus") elif saisie3 > mystere3: print("C'est moins") else: print("Bravo tu as gagné !") running = False input("Appuyer sur entrer pour fermer...")
#!/usr/bin/env python3 """ Elliptic curve class, associated functions, and instances of SEC2 curves """ from math import sqrt from typing import Tuple, NewType, Union, Optional from btclib.numbertheory import mod_inv, mod_sqrt Point = Tuple[int, int] # infinity point being represented by None, # Optional[Point] do include the infinity point # elliptic curve y^2 = x^3 + a * x + b class EllipticCurve: """Elliptic curve over Fp group""" def __init__(self, a: int, b: int, prime: int, G: Point, order: int) -> None: assert 4*a*a*a+27*b*b !=0, "zero discriminant" self.__a = a self.__b = b self.__prime = prime self.bytesize = (prime.bit_length() + 7) // 8 checkPoint(self, G) self.G = G # check order with Hasse Theorem t = int(2 * sqrt(prime)) assert order <= prime + 1 + t, "order too high" # the following assertion would fail for subgroups assert prime + 1 - t <= order, "order %s too low for prime %s" % (order, prime) self.order = order # check (order-1)*G + G = Inf T = self.pointMultiply(order-1, self.G) Inf = self.pointAdd(T, self.G) assert Inf is None, "wrong order" def checkPointCoordinate(self, c: int) -> None: assert type(c) == int, "non-int point coordinate" assert 0 <= c, "point coordinate %s < 0" % c assert c < self.__prime, "point coordinate %s >= prime" % c def __y2(self, x: int) -> int: self.checkPointCoordinate(x) # skipping a crucial check here: # if sqrt(y*y) does not exist, then x is not valid. # This is a good reason to have this method as private return ((x*x + self.__a)*x + self.__b) % self.__prime # use this method also to check x-coordinate validity def y(self, x: int, odd1even0: int) -> int: assert odd1even0 in (0, 1), "must be bool or 0/1" y2 = self.__y2(x) # if root does not exist, mod_sqrt will raise a ValueError root = mod_sqrt(y2, self.__prime) # switch even/odd root when needed return root if (root % 2 + odd1even0) != 1 else self.__prime - root def __str__(self) -> str: result = "EllipticCurve(a=%s, b=%s)" % (self.__a, self.__b) result += "\n prime = 0x%032x" % (self.__prime) result += "\n G =(0x%032x,\n 0x%032x)" % (self.G) result += "\n order = 0x%032x" % (self.order) return result def __repr__(self) -> str: result = "EllipticCurve(%s, %s" % (self.__a, self.__b) result += ", 0x%032x" % (self.__prime) result += ", (0x%032x,0x%032x)" % (self.G) result += ", 0x%032x)" % (self.order) return result def pointDouble(self, P: Optional[Point]) -> Optional[Point]: if P is None or P[1] == 0: return None f = ((3*P[0]*P[0]+self.__a)*mod_inv(2*P[1], self.__prime)) % self.__prime x = (f*f-2*P[0]) % self.__prime y = (f*(P[0]-x)-P[1]) % self.__prime return x, y def pointAdd(self, P: Optional[Point], Q: Optional[Point]) -> Optional[Point]: if Q is None: return P if P is None: return Q if Q[0] == P[0]: if Q[1] == P[1]: return self.pointDouble(P) else: return None lam = ((Q[1]-P[1]) * mod_inv(Q[0]-P[0], self.__prime)) % self.__prime x = (lam*lam-P[0]-Q[0]) % self.__prime y = (lam*(P[0]-x)-P[1]) % self.__prime return x, y # efficient double & add, using binary decomposition of n def pointMultiply(self, n: int, P: Optional[Point]) -> Optional[Point]: n = n % self.order # the group is cyclic result = None # initialized to infinity point addendum = P # initialized as 2^0 P while n > 0: # use binary representation of n if n & 1: # if least significant bit is 1 add current addendum result = self.pointAdd(result, addendum) n = n>>1 # right shift to remove the bit just accounted for # then update addendum for next step: addendum = self.pointDouble(addendum) return result ### Functions using EllipticCurve #### def checkPointCoordinates(ec: EllipticCurve, Px: int, Py: int) -> None: ec.checkPointCoordinate(Py) y = ec.y(Px, Py % 2) # also check Px validity assert Py == y, "point is not on the ec" def checkPoint(ec: EllipticCurve, P: Point) -> None: assert isinstance(P, tuple), "not a tuple point" assert len(P) == 2, "invalid tuple point length %s" % len(P) checkPointCoordinates(ec, P[0], P[1]) GenericPoint = Union[str, bytes, bytearray, Point] # infinity point being represented by None, # Optional[GenericPoint] do include the infinity point def tuple_from_Point(ec: EllipticCurve, P: Optional[GenericPoint]) -> Point: """Return a tuple (Px, Py) having ensured it belongs to the curve""" if P is None: raise ValueError("infinity point cannot be expressed as tuple") if isinstance(P, str): # BIP32 xpub is not considered here, # as it is a bitcoin convention only P = bytes.fromhex(P) if isinstance(P, bytes) or isinstance(P, bytearray): if len(P) == ec.bytesize+1: # compressed point assert P[0] == 0x02 or P[0] == 0x03, "not a compressed point" Px = int.from_bytes(P[1:ec.bytesize+1], 'big') Py = ec.y(Px, P[0] % 2) # also check Px validity else: # uncompressed point assert len(P) == 2*ec.bytesize+1, \ "wrong byte-size (%s) for a point: it should be %s or %s" % \ (len(P), ec.bytesize+1, 2*ec.bytesize+1) assert P[0] == 0x04, "not an uncompressed point" Px = int.from_bytes(P[1:ec.bytesize+1], 'big') Py = int.from_bytes(P[ec.bytesize+1:], 'big') checkPointCoordinates(ec, Px, Py) return Px, Py # must be a tuple checkPoint(ec, P) return P def bytes_from_Point(ec: EllipticCurve, P: Optional[GenericPoint], compressed: bool) -> bytes: """ Return a compressed (0x02, 0x03) or uncompressed (0x04) point ensuring it belongs to the curve """ # enforce self-consistency with whatever # policy is implemented by tuple_from_Point P = tuple_from_Point(ec, P) if compressed: prefix = b'\x03' if (P[1] % 2) else b'\x02' return prefix + P[0].to_bytes(ec.bytesize, byteorder='big') Pbytes = b'\x04' + P[0].to_bytes(ec.bytesize, byteorder='big') Pbytes += P[1].to_bytes(ec.bytesize, byteorder='big') return Pbytes def pointAdd(ec: EllipticCurve, P: Optional[GenericPoint], Q: Optional[GenericPoint]) -> Optional[Point]: if P is not None: P = tuple_from_Point(ec, P) if Q is not None: Q = tuple_from_Point(ec, Q) return ec.pointAdd(P, Q) def pointDouble(ec: EllipticCurve, P: Optional[GenericPoint]) -> Optional[Point]: if P is not None: P = tuple_from_Point(ec, P) return ec.pointDouble(P) Scalar = Union[str, bytes, bytearray, int] def int_from_Scalar(ec: EllipticCurve, n: Scalar) -> int: if isinstance(n, str): # hex string n = bytes.fromhex(n) if isinstance(n, bytes) or isinstance(n, bytearray): assert len(n) == ec.bytesize, "wrong lenght" n = int.from_bytes(n, 'big') if not isinstance(n, int): raise TypeError("a bytes-like object is required (also str or int)") return n % ec.order def bytes_from_Scalar(ec: EllipticCurve, n: Scalar) -> bytes: # enforce self-consistency with whatever # policy is implemented by int_from_Scalar n = int_from_Scalar(ec, n) return n.to_bytes(ec.bytesize, 'big') def pointMultiply(ec: EllipticCurve, n: Scalar, P: Optional[GenericPoint]) -> Optional[Point]: n = int_from_Scalar(ec, n) if P is not None: P = tuple_from_Point(ec, P) return ec.pointMultiply(n, P) # http://www.secg.org/sec2-v2.pdf __a = 0 __b = 3 __prime = 2**192 - 2**32 - 2**12 - 2**8 - 2**7 - 2**6 - 2**3 - 1 __Gx = 0xDB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D __Gy = 0x9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D __order = 0xFFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D secp192k1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) __a = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC __b = 0X64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1 __prime = 2**192 - 2**64 - 1 __Gx = 0x188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012 __Gy = 0x07192B95FFC8DA78631011ED6B24CDD573F977A11E794811 __order = 0xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 secp192r1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) __a = 0 __b = 5 __prime = 2**224 - 2**32 - 2**12 - 2**11 - 2**9 - 2**7 - 2**4 - 2 - 1 __Gx = 0xA1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C __Gy = 0x7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5 __order = 0x010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7 secp224k1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) __a = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE __b = 0XB4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4 __prime = 2**224 - 2**96 + 1 __Gx = 0xB70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21 __Gy = 0xBD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34 __order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D secp224r1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) # bitcoin curve # __a = 0 __b = 7 __prime = 2**256 - 2**32 - 977 __Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 __Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 __order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 secp256k1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) __a = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC __b = 0X5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B __prime = 2**256 - 2**224 + 2**192 + 2**96 - 1 __Gx = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 __Gy = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5 __order = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 secp256r1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) __a = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC __b = 0XB3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF __prime = 2**384 - 2**128 - 2**96 + 2**32 - 1 __Gx = 0xAA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7 __Gy = 0x3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F __order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973 secp384r1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order) __a = 0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC __b = 0x0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00 __prime = 2**521 - 1 __Gx = 0x00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66 __Gy = 0x011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650 __order = 0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409 secp521r1 = EllipticCurve(__a, __b, __prime, (__Gx, __Gy), __order)
import math import fractions class InvalidArgumentException(Exception): def __init__(self, exp_str): Exception.__init__(self) self.exp_str = exp_str class Fraction: def __init__(self, numerator=None, denominator=None): """ :type numerator: int float str """ self.numerator = numerator self.denominator = denominator if numerator is None: self.numerator = 0 else: self.fraction() def __str__(self): if self.denominator is not None: return str(self.numerator) + "/" + str(self.denominator) else: return str(self.numerator) def __eq__(self, other): if isinstance(other, self.__class__): return self.numerator == other.numerator and self.denominator == other.denominator elif isinstance(other, str): return True if str(self.numerator) + "/" + str(self.denominator) == other else False elif isinstance(other, float): return True if self.numerator / self.denominator == other else False def __lt__(self, other): if isinstance(other, self.__class__): if self.args_not_none() and other.args_not_none(): return self.numerator / self.denominator < other.numerator / other.denominator elif self.args_not_none(): return self.numerator / self.denominator < other.numerator elif other.args_not_none(): return self.numerator < other.numerator / other.denominator else: return self.numerator < other.numerator def __le__(self, other): if isinstance(other, self.__class__): if self.args_not_none() and other.args_not_none(): return self.numerator / self.denominator <= other.numerator / other.denominator elif self.args_not_none(): return self.numerator / self.denominator <= other.numerator elif other.args_not_none(): return self.numerator <= other.numerator / other.denominator else: return self.numerator <= other.numerator def __ge__(self, other): if isinstance(other, self.__class__): if self.args_not_none() and other.args_not_none(): return self.numerator / self.denominator >= other.numerator / other.denominator elif self.args_not_none(): return self.numerator / self.denominator >= other.numerator elif other.args_not_none(): return self.numerator >= other.numerator / other.denominator else: return self.numerator >= other.numerator def __repr__(self): if self.denominator is not None: return str(self.numerator) + "/" + str(self.denominator) else: return str(self.numerator) def __add__(self, other): if isinstance(other, self.__class__): return self.add_objects(other) else: return None def __sub__(self, other): if isinstance(other, self.__class__): return self.sub_objects(other) else: return None def __mul__(self, other): if isinstance(other, self.__class__): return self.mul_objects(other) else: return None def __truediv__(self, other): if isinstance(other, self.__class__): return self.div_objects(other) else: return None def __abs__(self): return Fraction(abs(self.numerator)) def __ceil__(self): if self.args_not_none(): return Fraction(math.ceil(self.numerator / self.denominator)) else: return Fraction(math.ceil(self.numerator)) def __floor__(self): if self.args_not_none(): return Fraction(math.floor(self.numerator / self.denominator)) else: return Fraction(math.floor(self.numerator)) def fraction(self): if self.denominator is not None: self.convert_to_fraction() else: if isinstance(self.numerator, float): self.set_denominator() elif isinstance(self.numerator, str): if "/" in self.numerator: arg_list = self.numerator.strip().split("/") try: self.numerator = int(arg_list[0]) self.denominator = int(arg_list[1]) except Exception: raise InvalidArgumentException("Invalid argument") self.convert_to_fraction() elif "." in self.numerator: self.numerator = float(self.numerator) self.set_denominator() else: try: self.numerator = int(self.numerator) except Exception: raise InvalidArgumentException("Invalid argument") def set_denominator(self): flt = str(self.numerator) mul = 10 ** (len(flt) - flt.find(".") - 1) self.numerator = int(self.numerator * mul) self.denominator = mul self.convert_to_fraction() def convert_to_fraction(self): gcd = math.gcd(self.numerator, self.denominator) self.numerator = math.floor(self.numerator / gcd) self.denominator = math.floor(self.denominator / gcd) if self.denominator == 1: self.denominator = None def args_not_none(self): return self.numerator is not None and self.denominator is not None def add_objects(self, other): if self.args_not_none() and other.args_not_none(): return Fraction((self.numerator * other.denominator + other.numerator * self.denominator), (self.denominator * other.denominator)) elif self.args_not_none(): return Fraction((self.numerator + self.denominator * other.numerator) / self.denominator) elif other.args_not_none(): return Fraction((other.denominator * self.numerator + other.numerator) / other.denominator) else: return Fraction(self.numerator + other.numerator) def sub_objects(self, other): if self.args_not_none() and other.args_not_none(): return Fraction((self.numerator * other.denominator - other.numerator * self.denominator), (self.denominator * other.denominator)) elif self.args_not_none(): return Fraction((self.numerator - self.denominator * other.numerator), self.denominator) elif other.args_not_none(): return Fraction((-other.denominator * self.numerator + other.numerator), other.denominator) else: return Fraction(self.numerator - other.numerator) def mul_objects(self, other): if self.args_not_none() and other.args_not_none(): return Fraction(self.numerator * other.numerator, other.denominator * self.denominator) elif self.args_not_none(): return Fraction((self.numerator * other.numerator), self.denominator) elif other.args_not_none(): return Fraction(other.numerator * self.numerator, other.denominator) else: return Fraction(self.numerator * other.numerator) def div_objects(self, other): if self.args_not_none() and other.args_not_none(): return Fraction(self.numerator * other.denominator, other.numerator * self.denominator) elif self.args_not_none(): return Fraction(self.numerator, (self.denominator * other.numerator)) elif other.args_not_none(): return Fraction(other.denominator * self.numerator, other.numerator) else: return Fraction(self.numerator / other.numerator) def test(): assert Fraction(3 / 4) == Fraction('0.75') == Fraction(0.75) == Fraction('3/4') assert Fraction(1) * Fraction(5) == Fraction(5) assert Fraction(1) < Fraction(2) assert Fraction(1 / 2) == 1 / 2 assert Fraction(1) <= Fraction(2.8) assert Fraction(1) <= Fraction(1) assert Fraction(4) >= Fraction(2) assert Fraction(4) >= Fraction(4) assert abs(Fraction(-1)) == Fraction(1) half = Fraction(0.5) one = Fraction(1) assert math.ceil(half) == one assert Fraction(3, 10) + Fraction(5, 10) == Fraction(4 / 5) assert Fraction(1, 2) + Fraction(5, 3) == Fraction(13, 6) assert Fraction(1, 2) - Fraction(5, 3) == Fraction(-7, 6) assert Fraction(3 / 10) - Fraction(-5 / 10) == Fraction(4 / 5) assert Fraction(1, 2) * Fraction(5, 3) == Fraction(5, 6) assert Fraction(1, 2) * Fraction(5) == Fraction(5, 2) assert Fraction(1, 2) / Fraction(5) == Fraction(1, 10) assert Fraction(1, 2) / Fraction(5, 3) == Fraction(3, 10) assert math.floor(half) == Fraction(0) if __name__ == "__main__": test()
# 递归函数 def factorial(n): if n == 1: return 1 return n * factorial(n-1) print(factorial(10)) ## 使用尾递归 ## @尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式 def tail_factorial(n, result): if n == 1: return result # 这里是关键的一步 return tail_factorial(n-1, n*result) print(tail_factorial(10, 1)) print(factorial(10))
import copy num = [1, 2, 3] print(tuple(num)) test = (1, 2, 3) print(list(test)) test1 = (1) test2 = (1,) print(type(test1)) print(type(test2)) source = [1, 2, 3, 4] target1 = copy.copy(source) print(target1) target1[0] = -1 print(target1) print(source) source[0] = [4, 5, 6] target2 = copy.copy(source) print(source) print(target2) target2[0][0] = -1 print(target2) print(source) target3 = copy.deepcopy(source) target3[0][0] = -100 print(target3) print(source)
class Animal(object): def __init__(self): pass def run(self): print('this animal is running!') class Dog(Animal): def run(self): print('this dog is running') class Cat(Animal): def run(self): print('this cat is running') animal1 = Animal() dog1 = Dog() cat1 = Cat() animal1.run() dog1.run() cat1.run() # 多态的好处 def run(animal): animal.run() run(animal1) run(dog1) run(cat1) # 使用方法isinstance判断一个对象是不是一个类的实例 print(isinstance(animal1, Animal)) print(isinstance(dog1, Dog)) print(isinstance(cat1, Cat))
i = 0 while i < 5: i += 1 # i = 4 终止循环 if i == 4: break # i= 2 跳过本次循环 if i == 2: continue print(i) for j in range(3): print(j) for k in range(10, 13): print(k) for l in range(0, 10, 3): print(l)
# 条件判断 a = 24 if a > 20: print('yeah, welcome!') elif a > 30: print('hello, welcome') else: print('nice, welcome') age = input('输入您的年龄:') age = int(age) # 将字符串转换整数 if age > 17: print('00前') elif age > 27: print('90前') else: print('00后') # 第二次学习条件判断 if None: print('None') else: print('Else if') # 使用elif: x = input('请输入一个数字:') num = int(x) if num >= 8: print('num >= 8') elif num >= 3: print('num >= 3') else: print('num?')