text
stringlengths
37
1.41M
import random # Random module used for random number generation """StarDraft""" """This program is for creating fantasy NBA lineups by drafting 5 NBA. players for each lineup and competing against a friend based on their players in-game performance.""" __author__ = "Oscar Fox" def roll_dice(): """Func...
# БСБО-05-19 Савранский С. def roots_of_quadratic_equation(a, b, c): if a == 0 and b == 0: return ['all'] if c == 0 else None elif a == 0: return [- c / b] d = b ** 2 - 4 * a * c if d < 0: return None elif d == 0: return [(-b - d**.5) / (2 * a)] x1 = (-b - d**....
# БСБО-05-19 Савранский С. def fractal_print(arr): res = '' for i in arr: ctr = 1 if i is arr: print() else: print(i, end=', ')
import pygame from pygame.sprite import Sprite def load_image(name): image = pygame.image.load(name) return image class Alien(Sprite): # This class represents a single alien def __init__(self, ai_settings, screen, img, img2): # Initialize Alien and set starting values. super(Alien, ...
while True: distance = float(input('Distance : ')) distance_choice = int(input('Which Unit did you use ? ' '\n1)Metre(m)\n2)Kilometre(Km) ' '\nType number of your choice :')) while distance_choice == 1 or distance_choice == 2: if ...
for i in xrange(int(raw_input())): x = raw_input() cnt = x.count('m') x = x.replace('sm','') x = x.replace('ms','') if x.count('s') == cnt: print "tie" elif x.count('s') > cnt: print "snakes" else: print "mongooses"
#Binary Search using randint from random import randint def bin_search(lst,item): mid = len(lst)//2 #Integer division low = 0 high = len(lst) - 1 while lst[mid] != item and low<=high: if item > lst[mid]: low = mid + 1 else: high = mid - 1 ...
# dict excercises from collections import defaultdict, Counter ### ex 1 - sort dict by value ''' composers = {'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35} # A composers = {i:v for i,v in sorted(composers.items(), key=lambda p: p[1])} print(composers) # B composers = dict(sorted(composers.items(), key=...
"""Functions to help parse strings into datetime objects""" import dateparser def parse_human_readable_time(time_string): """Parse human readable strings (e.g. "now", "2017-01-01" and "one hour ago") into datetime""" return dateparser.parse(time_string, settings={'RETURN_AS_TIMEZONE_AWARE': True})
def numeros(x): if x in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'): return print('True') else: print('False') def main(): valor = input('Digite um valor numérico:').lower() n = numeros(valor) if __name__=='__main__': main()
# 获取对象信息 # 使用type 判断对象类型 type(123) == int type('abc') == str #对象是函数 import types def fn(): pass type(fn) == types.FunctionType type(abs) == types.BuiltinFunctionType type(lambda x :x) == types.LambdaType type((x for x in range(10))) == types.GeneratorType #使用isinstance()判断已知类型 # 判断一个变量是否是某个类型中的一种 isinsta...
import random states = ['O', 'X'] for i in range(3): # choices creates a list, key or length = 3 # joining the list to create a string x = ''.join(random.choices(states, k=3)) print(x)
## You are given the year, and you have to write a function to check if the ## year is leap or not. ## https://www.hackerrank.com/challenges/write-a-function/problem def is_leap(year): leap = False # Write your logic here if (year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)): leap = Tr...
from board import clean_board, print_board, x, o, set_move, is_valid_move, is_occupied_space from display import win_screen, lose_screen def welcome(): msg = """ Welcome to AI Tic Tac Toe """ print(msg) # example of another change def get_user_name(): print("Tell me your name") name = input(...
def no_space(x): without_space = '' for letter in x: if letter != ' ': without_space += letter return without_space def no_space_replace(x): return x.replace(' ', '')
import functions print("Hello! welcome to a game of Mastermind code breakers.") secret_code = functions.secret_code_generator() while True: x = input("Please select a game mode: (1, 2 or help) ") # 1 = Speler raad, 2 = Systeem raad, help = information # about the game if x == "1": print("You wil...
# coding=utf-8 """ Daniel Calderon, CC3501, 2019-2 vertices and indices for simple shapes """ # A simple class container to store vertices and indices that define a shape class Shape: def __init__(self, vertices, indices, textureFileName=None): self.vertices = vertices self.indices = indices ...
import math import numpy as np #inputting positions of the the rocket xpos = 0 ypos = 0 zpos = 1000 #inputting the rotation of the rocket yaw = 180 pitch = -10 roll = 180 #inputting the pixel position of the fire xpic = 100 ypic = 30 #converting angles of -180 - 180 to angles of 0 - 360 def threesixty(angle): ...
# 定义函数 准备使用多层装饰器 def test_arg(s="hello"): # 闭包函数function_out为外层函数 def function_out(func): # function_in为内层函数 def function_in(a): print("正在进行验证---, a = ", a, s) # func ---> login return func(a) return function_in return function_out # 装饰过程: # 调用te...
""" 视图函数的作用很明确,即生成请求的响应。对最简单的请求来说,这就足够了。 但是一般而言,请求会改变程序的状态,而这种变化也会在视图函数中产生。 例如,用户在网站注册一个新的账户。用户在表单中输入电子邮件地址和密码,然后点击提交按钮。服务器接收到包含用户输入数据的请求, 然后Flask把请求分发到处理注册请求的视图函数。这个视图函数需要访问数据库,添加新用户,然后生成响应回送浏览器。 这两个过程分别称为 业务逻辑 和 表现逻辑。把两种逻辑混在一起回导致代码的难易理解和维护。把表现逻辑移到模板中能够提升程序的可维护性。 模板是一个包含响应文本的文件,其中包含用占位变量表示的动态部分,其具体值只在请求的上下文中才能知道。使用真实...
x=7 list=[] while x==7: score = input("Enter a score") print "welcome to the WAEC grading system." print "what was your results" marks=input("insert scores") if marks>=80 and marks<=100: print "GRADE A" elif marks>=70 and marks <=79: print "GRADE B" elif marks>=60 an...
x=1 while x==1: print "Welcome to the WAEC grading system." print "what was your results?" marks=input("insert scores") if marks>=80 and marks <=100: print"GRADE A" elif marks>=70 and marks<=79: print"GRADE B" elif marks>=60 and marks<=69: print"GRADE C" elif ma...
x=3 y=x*x print x, x+x, y def add(a,b): c = a + b print c print add(4, 5) def add(a, b): c = a + b return c var = add(4, 5) print var def addTwoNumbers(firstNumber,secondNumber): print "The sum of your number is:" print firstNumber + secondNumber addTwoNumbers("Vanessa", "Marilyn") def addTh...
foster=["akwaaba", "Saturday", "Yawenam"] foster.append("good") #print foster yam=["long", "short", "tall"] foster.extend(yam) #print foster foster.insert(3, "Ademang") #print foster foster.remove("Saturday") #print foster #print foster.count("Yawenam") foster.reverse() print foster
list =["Yawenam","Foster","Nicola"]; ##if len(list)>3: # print "Overload" #elif len(list)==3: # print"It is enough" #else: # print"Add more" # # # # # #age =input("Your age ") #print "Your age is " +str(age)# name=raw_input("Enter instructor name") if name in list print "Yes" else: print "Not an instr...
print "Your raw score" score=input() print "your score is " + str(score) if: score <100 and score >80 print "A" elif: score <79 and score >70 print "B" elif: score <69 and score >60 print "C" elif: score <59 and score >50 print "D" elif: score <49 and score >45 print "E" elif: ...
x = 7 while x == 7: y = input("Enter a number") if y<=100 and y>=80: print"A" elif y<=79 and y>=70: print"B" elif y<=69 and y>=60: print"C" elif y<=59 and y>=50: print"D" elif y<=49 and y>=45: print"E" else: print"F" x = input("E...
''' animals=['frog','dog','cat'] animals.insert(2,'mouse') letters=['a','b','c'] animals.extend(letters) print animals for i in animals: if i[0]=='c': print i x=0 while x<10: x=x+1 print x for i in range(10): print i*i ''' #this adds the elements in a list scores=[97,34,56,2...
def myFunction(argument1): print "This is my function" print "My favorite food is " + argument1 myFunction("jollof") def myFunction(argument1,argument2): print "This is my function" print argument1 + argument2 myFunction(6,5) def myFunction(argument1,argument2,argument3): print "The sum ...
#number={20,21,22,23,24,25} #guess=input("enter an integer:") #if guess in number: #print"yeeey,you gussed it" #elif guess in number: #print"not accepted.it is higher than that" #else: #print"it is lower" #print"done" #count=0 #while(count<9): # print count # count=count + 1 # print"good bye...
name = raw_input("name: ") #simplecalculator firstNumber = raw_input("pick a number ") secondNumber = raw_input("pick another number ") operator = raw_input("pick an operator (+, -,%,/,*) ") if operator == "+" : print firstNumber+secondNumber else operator == "-": print firstNumber-secondNumber else operator ==...
# TODO: # Implement changing screen size? Or full screen? from src.Simulations import * from src.RelativeDrawing import * # Defines colours needed in the simulation. black = color(0, 0, 0) white = color(255, 255, 255) red = color(255, 0, 0) green = color(68, 247, 10) blue = color(10, 187, 247) orange = color(247, ...
import requests from urllib.request import urlretrieve as downloadFromUrl class PodcastEpisode: """ PodcastEpisode is a class that holds all relevant metadata for a podcast episode. A webscraper or an API call will return this object. """ def __init__(self, id, podcastName, date, episodeTitle, aud...
# Fernando Villarreal # 11-23-15 # Period 4 # 9.2.1 # this will get a name and grade level, and print out a greeting name = input("What is your name? ") grade = int(input("What grade are you in? ")) if grade == 9: print (" hello %s, welcome to high school" %s(name)) elif grade == 10: print ("I hope to see...
import random myword = random.choice(open("hangmanwords.txt").read().split()) word_len = len(myword) myword_list = list(myword) alphabet = [chr(i) for i in range(ord('a'),ord('z')+1)] def diagram(i): file_name = "".join(["hangman", str(i), ".txt"]) with open(file_name, "r") as file: for line i...
''' Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. Example: Given an input string of: apples, pears # and bananas grapes bananas !apples The output expected would be: apples, pears grapes banan...
''' Given an array of positive or negative integers I= [i1,..,in] you have to produce a sorted array P of the form [ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...] P will be sorted by increasing order of the prime numbers. The final result has to be given as a string in Java, C#, C, C++ a...
''' This is my republished first kata(with issues fixed!), hope you guys will enjoy it! For input, you will be given a string in the form "(mx+n)(px+q)" where the character x can be any single lowercase alphabet from a-z, while m, n, p and q are integers(can be negative). Task Return a string in the format ax^2+bx+c ...
# Classe permettant d'instancier la boutique class Boutique: def __init__(self): # {objet : [prix, quantité]} self.contenu = { "potion de soin mineur" : [10, 99], "potion de soin" : [100, 99], "potion de soin majeur" : [1000, 99], "potion de mana min...
i = 28 print(f"i is {i}") f = 2.8 print(f"f is {f}") b = True print(f"b is {b}") n = None print(f"n is {n}") x = 28 if x > 0: print("x is positive") elif x < 0: print("x is negative") else: print("x is zero") print("Sequences") name = "alice" print (name[0], name[1]) print("tuple type") coord = (10.0, ...
""" File: anagram.py Name: Jael Lin ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 23 If you correctly implement this program, you should see the number of anagrams for each w...
""" ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string ...
""" *** Climbing Stairs *** You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2...
""" *** Add Binary *** Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: Each string consists only of '0...
""" Simple graph implementation compatible with BokehGraph class. """ import random class Queue: def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if (self.size()) > 0: return self.queue.pop(0) else: ...
#function checks if current move (player_row, player_column) couses win for current player def check_win(game_board, player,player_row, player_column, in_a_row): #function checks if line has in_a_row elemnts of the same type (1 or 2 [players]) def check_line(line, win_type): #check if win is even ...
import random a = 1 b = 20 Length=random.randint(a,b) Width=random.randint(a,b) print("Length = ") print(Length) print("Width = ") print(Width) print("Area = Length x Width") Area = Length*Width print("Area = ") print(Area) if Area >= 100: print("The room is huge!") if Area < 100: print("The room is sma...
num = input().split('+') num.sort() mylist = '' for i in num: mylist += i + '+' print(mylist[:-1])
def multiples(n): for i in range(1,21,2): k = n*i p = "{}*{} ={}".format(n,i,k) print(p) n=int(input("Enter a number: ")) multiples(n)
def substring(s1,s2): # if s2.find(s1)!=-1: # print('yes') # else: # print('no') if s2.count(s1)>1: print('yes') else: print('no') s1="geek" s2="geeks for geeks" substring(s1,s2)
# -*- coding: utf-8 -*- """ Created on Tue Nov 27 00:33:08 2018 @author: hagar """ #x = -14 #binint = int("{0:b}".format(x)) #convert to binary #print (type(binint)) #print(binint) ##flipped = ~binint #flip the bits ##print(flipped) ##flipped += 1 #add one (two's complement method) ###intflipped=int(str(flipped),2) #f...
from random import randint min_val = 1 max_val = 6 # Dice needs to return a random value between 1 and 6 def roll_dice(low, high): print(randint(low, high)) def start(): """ ASK USER IF THEY WANT TO ROLL A DICE """ roll_again = True while roll_again: roll_dice(min_val, max_val) prin...
#!/usr/bin/env python def anti_vowel(text): vowels = ['a','e','i','o','u', 'A', 'E', 'I' ,'O', 'U'] word = "" checker = False for x in range(0,len(text)): for y in range(0, len(vowels)): if text[x] == vowels[y]: print(text[x]) checker = ...
#!/usr/bin/env python3 # return the sum of the two polynomials p1 and p2. def poly_add(p1, p2): p1Length = len(p1) p2Length = len(p2) if p1Length < 1 and p2Length < 1: return [] elif p1Length < 1: return p2 elif p2Length < 1: return p1 if p1Length < p2Length: ...
#coding: utf-8 #Faça um algoritmo que leia um número e mostre se o mesmo é positivo, negativo ou zero. num = int(input("Digite um número: ")) print() if num < 0: print("%i é um número negativo." %num) elif num > 0: print("%i é um número positivo." % num) else: print("Foi digitado o número 0.")
#coding: utf-8 #Faça um algoritmo que calcule o cubo e o quadrado de um determinado número: num = float(input("Digite um número: ")) print() print("%.2f elevado ao quandro é %.2f e elevado ao cubo é %.2f " %(num, num**2, num**3))
# Turns an image into ASCII art. # requires python3 and PIL, and UbuntuMono-R.ttf # (you will have to change the font for different operating systems.) # usage: python3 imageToAscii.py [-h] [-i] [--fontsize FONTSIZE] filename # # Convert an image to ASCII # # positional arguments: # filename i...
x = 7 temp = 0 while x > 0: t = int(input("Podaj temperaturę: ")) x = x - 1 # x -= 1 temp = temp + t print(f"Średnia: {temp/7:.2f}") i = 10 while True: if i == 6: i -= 1 continue print(i) i -= 1 if i == 0: break
class Monitor: def __init__(self, brand, model): self.brand = brand self.model = model def __str__(self): return f"<Monitor {self.brand} | {self.model}>" def wlacz(self): print(self, "włącza się") def wylacz(self): print(self, "wyłączony ...") lista = list()...
""" first_set = {27, 43, 34} second_set = {34, 93, 22, 27, 43, 53, 48} first_set.issubset(second_set) """ lista = [9, 1, 6, 8, 4, 3, 2, 0] for indeks_podstawienia in range(len(lista)): indeks_min_wartosci = indeks_podstawienia for indeks_ogona in range(indeks_podstawienia + 1, len(lista)): if list...
# pol_ang = dict() pol_ang = { "kot": "cat", "ptak": "bird" } pol_ang["pies"] = "dog" pol_ang["kot"] = "kitty" dict_2 = dict(a=10, b=22, c=33) dict_3 = dict([ ["x", "ala"], ["y", "kot"] ]) print(dir(dict_3)) print(dict_3.keys()) print(dict_3.values()) print(dict_3.items()) print(dict_3.get("x")) p...
def find_even_index(arr): for i in range(len(arr)): sommeDroite = 0 sommeGauche = 0 for j in range(0, i): sommeGauche += arr[j] for j in range(i+1, len(arr)): sommeDroite += arr[j] if sommeDroite == sommeGauche: return i return -1 de...
from matplotlib import pyplot as plt class Biquad: def __init__(self, a1, a2, b0, b1, b2): self.a1, self.a2 = a1, a2 self.b0, self.b1, self.b2 = b0, b1, b2 self.w1, self.w2 = 0, 0 def process(self, x): w0 = x + -self.a1*self.w1 + -self.a2*self.w2 y = self.b0*w0 + self....
# Given a string, return the count of the number of times that a substring # length 2 appears in the string and also as the last 2 chars of the string, # so "hixxxhi" yields 1 (we won't count the end substring). # last2('hixxhi') → 1 # last2('xaxxaxaxx') → 1 # last2('axxxaaxx') → 2 def last2(str): # leng...
''' Created on Jan 29, 2011 @author: Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com) ''' import numpy P1 = 1 P2 = -1 EMPTY = 0 NOT_STARTED = -2 IN_PROGRESS = 2 P1_WON = 1 P2_WON = -1 DRAW = 0 class Engine(object): ''' Provides helper methods for Tic-Tac-Toe game and interface for AI-like algorithm...
foods = ["apples", "bananas", "cherries", "donuts"] amounts = [11, 22, 33, 44] for i, x in enumerate(foods): print("{} - {}".format(amounts[i], x)) ######### # With zip() do_I_like_it = [True, False, False, True] for y, x, z in zip(amounts, foods, do_I_like_it): print("{} - {} - {}".format(y,x,z))
# -*- coding:utf-8 -*- """Implementation of vertex for graph.""" from graph_algorithms.exception.graph_exception import NotContainsElementException from graph_algorithms.exception.messages import not_contains_vertex_message class Vertex(object): """Class implements vertex for graph.""" def __init__(self, ...
"""Implementation of edge for graph.""" class Edge(object): """Class implements edge for graph.""" def __init__(self, first_vertex, second_vertex, weight=0): """Construct a new edge for graph. Args: first_vertex: first vertex id of edge second_vertex: second vertex i...
# -*- coding:utf-8 -*- """Implementation iterative depth-first search.""" def dfs_iterative(graph): """Visit all the vertex of graph. Args: graph: graph for search Returns: visited (dict): key (vertex id), value (true if vetrex is visited) """ visited = {vertex: False for vertex...
# -*- coding: utf-8 -*- # 面向对象 # 有意义的面向对象的代码 # 类 = 面向对象 # 类、对象 # 类的名字首字母需要大写,不要像变量一样用下划线 # 实例化 # 类最基本的作用:封装 # 类和对象 class Student(): sum = 0 name = 'mf' # 类变量 age = 0 # '类变量' '实例变量' def __init__(self,name,age): # 实例方法 对象 # 构造函数 # 初始化对象的属性 self.name = name # 实例变量 self.a...
# -*- coding: utf-8 -*- import time def decorator(func): # key word def wrapper(*args,**kw): # args通用叫法 print(time.time()) func(*args,**kw) return wrapper @decorator # 装饰器的一个语法糖 @符号 def f1(func_name): print('This is a function named ' + func_name) @decorator def f2(func_name1,func_...
import pandas as pd import numpy as np from datetime import timedelta, date, datetime import collections def trailing_days_df(df, date, trailing_days=3): """ Return a sliced dataframe starting and t=0 and going backwards n days. Date should be a string with yyyy-mm-dd format """ current_index = df.loc[df['date']...
from random import shuffle SUITS = "Diamond Clubs Heart Spade".split() RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split() FACE_CARDS = "10 J Q K".split() class Deck: # create deck def __init__(self): self.new_deck = [(suit, rank) for suit in SUITS for rank in RANKS] # shuffle new_deck def shuffle(...
from Tree import * #Example 1: Fibonacci def fib_tree(n): if n == 1: return Tree(0) elif n == 2: return Tree(1) else: left = fib_tree(n-2) right = fib_tree(n-1) return Tree(left.label + right.label, (left, right))
# TO-DO: complete the helpe function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO arrAIndex = 0 arrBIndex = 0 mergedArrIndex = 0 while arrAIndex < len(arrA) and arrBIndex < len(arrB): if arrA(arrAInd...
"""Fibonacci Sequence The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. The 2 is found by adding the two numbers before it (1+1) Similarly, the 3 is found by adding the two numbers before it (1+2), And the 5 is (2+3...
class HumanPlayer: _color = None _type = None def __init__(self, color): self._type = "Human" self._color = color def get_move(self, board): column = None while column == None: try: column = int(raw_input("Select your move : ")) - 1 ...
class MovementEvaluator: #the movements follow always the same order: 1)up, 2)right, 3)down, 4)left def get_possible_movements(self, matrix): free_position_row = self.search_free_position_row(matrix) free_position_column = self.search_free_position_column(matrix) movements_list = None ...
class Player: game = None hand = [] def get_card(self, card): self.hand.append(card) def clean_hand(self): self.hand = [] def calculate_value(self): value = 0 for card in self.hand: value += card.get_value() return value class HumanPlayer(Pl...
SQL Staff Table with their supervisor details. Find all the staff who are earning more than their supervisor. Table: Staff +----+-------+--------+-----------+ | Id | Name | Salary | SupervisorId | +----+-------+--------+---------------+ | 1 | Jack | 70000 | 3 | | 2 | William | 80000 | 4 ...
# -*- coding: utf-8 -*- from deap import tools, base, creator, algorithms import random import matplotlib.pyplot as plt rewards = [500, 1000, 2000, 3000, 4000, 5000, 7500, 10000] # evaluate score maximizing financial gains and minimizing missed oppotunities def evaluate(member): rewards = 0 rewards = member[1...
""" leetcode 387. First Unique Character in a String Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. """ class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ dic = {} ...
""" 547. Number of Provinces There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other ...
#!/usr/bin/python # -*- coding:utf-8 -*- # Author : Lv Yang # Created : 01 March 2017 # Modified : 17 March 2017 # Version : 1.0 import re """ used to judge whether data is valid """ class AppValid(object): @staticmethod def validPhone(phone): pattern = re.compile('^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7...
#! /usr/bin/python # comparelists.py # Takes any number of files with lists of gene names and reports which # genes are in each list and every combination of lists. Suitable for # generating data to display on a venn diagram. import sys master_list = {} # A dictionary with key=gene name and value= a list showing whe...
from tkinter import * from tkinter import Menu,ttk tk =Tk() canvas = Canvas(tk,width = 600,height = 500) tk.title("Drawing circle") canvas.grid() coord_label = Label(tk, text="Координаты центра окружности: ",font=("Times New Roman", 16)) coord_label.place(x=0,y = 0) radius_label = Label(tk,text="Радиус: ",font=...
# Databricks notebook source # DBTITLE 1,QUEUE class Queue: def __init__(self): self.items = [] def enqueue(self,key): self.items.append(key) def dequeue(self): if not self.is_empty(): return self.items.pop(0) def peek(self): if not self.is_empty(): return self.items[0] ...
# Databricks notebook source # MAGIC %md ### Bubble Sort # COMMAND ---------- def bubble_sort(alist): l = len(alist) no_swap = True for x in range(l-1,0,-1): for y in range(0,x): if alist[y+1] < alist[y]: alist[y+1],alist[y] = alist[y],alist[y+1] no_swap=False if no_swap: ...
from tkinter import * import os class GUI: def __init__(self): self.Window = Tk() self.Window.withdraw() self.login = Toplevel() self.login.title("Login usando RPC") self.login.resizable(width=False, height=False) self.login.configure(width=400, height=300) ...
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- name = 'Zed A. Shaw' age = 35 # not a lie height = 2.54 * 74 # centimeters weight = 0.45 * 180 # kg eyes = 'Blue' teeth = 'White' hair = 'Brown' print "Let's talk about %s." % name print "He's %f centimeters tall." % height print "He's %f kilograms heavy." % weight ...
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- # prints the string print "Mary had a little lamb." # prints the string and evaluates %s as the first string option snow print "Its fleece was white as %s." % 'snow' # prints the string print "And everywhere that Mary went." # prints a decimal or dot 10 times. print ...
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" MakeUpperCaseServerUsingUDP Module Description : This module will use the UDP connection to perform the data transfer. A UDP connection will be est...
import unittest from employee import Employee, Person from parameterized import parameterized class TestPerson(unittest.TestCase): def test_get_person(self): person = Person("Claudio", 32) listPerson = person.get_person() self.assertEqual(listPerson, ["Claudio", 32]) class TestEmployee(...
from repository import Repository from person import Person class PersonService: def get_personList(self): print("\n----> \tLista de personas:\n") return Repository.person # Agrega una persona en el dicionario person, definido en Repository def add_person(self, person): print("\n-...
from person import Person from personService import PersonService class App(): def menu_person(self): print("\n\n1. Listar persona") print("2. Agregar persona") print("3. Modificar persona") print("4. Eliminar persona") return int(input("Elija una opción: ")) if __name__ ==...
import unittest from person import Person, Employee class TestPerson(unittest.TestCase): def test_get_person(self): self.name = 'Federico' self.age = 20 p1 = Person.get_person(self) self.assertEqual(p1,['Federico',20]) class TestEmployee(unittest.TestCase): def test_get_emplo...
from repository import Repository from person import Person class PersonService: def get_personList(self,): return Repository.person # Agrega una persona en el dicionario person, definido en Repository F def add_person(self, per=None): print("\n Agregando persona: ") if per is ...
from repository import Repository from person import Person class PersonService(): def get_personList(self): print(Repository.dictPerson) def crearPersona(self): print("\n----Agregar persona----") name = input('Ingrese un nombre: ') surname = input('Ingrese un apellido: ') ...
from employee import Employee, Person class Administrtion: listEmployee={} def add_employee(self, employee): legajo = len(self.listEmployee) self.listEmployee[legajo] = employee return if __name__ == '__main__': adm = Administrtion() adm.add_employee({'name':'Santiago', 'lastn...
import unittest from emp import Person from emp import Employee from parameterized import parameterized class Test_person(unittest.TestCase): @parameterized.expand([ ("Paula", 20, "Cibeira", 424242, {"name":"Paula", "age":20, "surname":"Cibeira", "phone":424242}) ]) def test_get_person(self, name,...