text
stringlengths
5
121k
def move(): global curr, direction, range_ for scanner in curr: if curr[scanner] == range_[scanner]: curr[scanner] -= 1 direction[scanner] = "up" elif curr[scanner] == 1: curr[scanner] = 2 direction[scanner] = ...
import Motor from MotorState import MotorState class MotorManager(): def __init__(self, motorLeft, motorRight): self.mLeft = motorLeft self.mRight = motorRight self.state = MotorState.CENTER def setDirection(self, horizontal, depth): if horizontal == "left": if depth == "forward": print("forward left...
d={'a':5, 'b':10,'c':15} for x, y in d.items(): print(x, y)
import sqlite3 from IPython.display import clear_output """connection=sqlite3.connect("Info.db") sql=\"""CREATE TABLE if not EXISTS questions( Question VARCHAR(50), Topic VARCHAR(20), difficulty_level VARCHAR(20), Option_A VARCHAR(20), Option_B VARCHAR(20), Option_...
import random def RockPaperScissor(): number = random.randint(1,3) if (number == 1): return 'rock' elif (number == 2): return 'paper' elif (number == 3): return 'scissors' else: return 'Facing errors'
from random import randint def createGrid(rows, columns): grid = [[0 for i in range(rows)] for j in range(columns)] for i in range(0, rows): for j in range(0, columns): grid[i][j] = randint(0, 1) return grid def newGeneration(grid): newGrid = [[0 for i in range(...
""" recursividad ejemplo fibonacci """ def fibonacci(n): """ Este metodo es demasiado ineficiente """ if n == 0 or n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) n = int(input('Ingrese un numero mayor a 0:')) if n>0: print(f'En el mes {n} habra un total de {fibonacc...
import random import collections PALOS = ["corazon","trebol","diamante","pica"] VALORES = ['as','1','2','3','4','5','6','7','8','9','10','J','Q','K'] def formar_baraja(): cartas = [] for palo in PALOS: for valores in VALORES: cartas.append((palo,valores)) return cartas def ob...
""" aproximacion de soluciones """ objetivo = int(input('Ingrese un numero : ')) epsilon = 0.01 paso = epsilon**2 respuesta = 0.0 while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo: print(abs(respuesta**2-objetivo)) respuesta += paso if abs(respuesta**2 - objetivo) >= epsilon: ...
import math import os import random import re import sys def countApplesAndOranges(s, t, a, b, apples, oranges): apple_count= 0 orange_count= 0 for apple in apples: if s<=(apple+a)<=t: apple_count+=1 else: continue for orange i...
''' STACK OPERATIONS s :- stack n :- node that is being pushed push(s,n) :- pushed at the top of the stack pop(s) :- removes the top element and returns it Note :- A stack is both Abstract Data Type(ADT) and Data Structure. ADT :- Abstract Data type (ADT) is a type (or class) for objects whose behaviou...
def binary_search(arr, item): low = 0 high = len(arr) - 1 while low <= high: mid = int((low + high) / 2) if arr[mid] == item: return mid elif arr[mid] < item: low = mid + 1 else: high = mid - 1 return -1 if __name__ == '__main__': ...
def calculateRentCost(new,normal): total = (45*new)+(27*normal) return total def main(): new = int(input("Ingrese cantidad de peliculas estreno rentadas")) normal = int(input("Ingrese cantidad de peliculas normales rentadas")) total = calculateRentCost(new,normal) print("Peliculas de e...
""" Change a Range of Item Values To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: """ thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermel...
from tkinter import * def Click(event): new_height = float(textboxHeight.get()) new_weight = float(textboxWeight.get()) BMI = new_weight/((new_height/100)**2) if BMI > 30.0: result.configure(text="BMI = %f = %s"%(BMI,"อ้วนมาก")) elif 25.0<=BMI<=29.9: result.configure(text="BMI = %f...
days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMarch\nApril\nMay" print ("I am \"Super\" tall") print("The days are:" , days) print ("here are the months:", months) print(""" Hey babe! I know what it says!! You said so e'h dont you dare hahaha Bye """)
import json, requests, sys def current(location): url = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&APPID=2c72b19f0de8d493671eb73e9c4cf39c" % (location) response = requests.get(url) weatherData = json.loads(response.text) w = weatherData['weather'] print('C...
""" Given two strings s1 and s2, determine if s2 is a rotated version of s1. For example, is_rotated("hello", "llohe") returns True is_rotated("hello", "helol") returns False accepts two strings returns bool """ def is_rotated(s1, s2): if len(s1) == len(s2): return s2 in s1 + s1 else: return F...
""" Defines media types with their attributes """ class Movie(): """Class stores the information related to a movie. Attributes: movie_title: The movie's title. poster_image: URL to the movie's poster or box art. trailer_youtube: URL to the movie's trailer on YouTube """ ...
def clean(fname): c="" with open(fname,'r', encoding='utf8', errors ='ignore') as fin: fstring = fin.read().lower() for i in range(len(fstring)-1): if fstring[i].isalpha() or fstring[i].isdigit() or fstring[i]=='.' or fstring[i]==',' or fstring[i]=="'"or fstring[i]=='-': ...
"""strategies_traditional Example to show one way of implementing different design pattern strategies in Python. The example shown here resembles a 'traditional' implementation in Python (traditional = the one you may implement in languages like C++). For a more Pythonic approach, see the file strategies_pythonic.py...
"""wargame.gameutils This module contains some utility function for the game Attack of the Orcs This modue is compatible with Python 3.5.x and later. It contains supporting code for the book, Learning Python Application Development Packt Publishing. This is my version of the code, it is pretty much similar to the or...
"""python_adapter_foreignunitadaptermulti This method represents an adapter class that will make other game units compatible between themselves. """ class ForeignUnitAdapterMulti: """Generalized adapter class for 'fixing' incompatible interfaces. :arg adaptee: An instance of the 'adaptee' class. For example,...
"""pool_example Shows a trivial example on how to use various methods of the class Pool. """ import multiprocessing def get_result(num): """Trivial function used in multiprocessing example""" process_name = multiprocessing.current_process().name print("Current process: {0} - Input number: {1}".format(proc...
"""simple_application_2 A 'Hello World' GUI application OOP using Tkinter module. """ import sys if sys.version_info < (3, 0): from Tkinter import Tk, Label, Button, LEFT, RIGHT else: from tkinter import Tk, Label, Button, LEFT, RIGHT class MyGame: def __init__(self, mainwin): """Simple Tkinter G...
import math import sys class Node: def __init__(self, value, char, left=None, right=None, parent=None, code=None): self.value = value self.char = char self.right = left self.left = right self.code = code self.parent = parent def setChildren(self, left = None, right = None): self.right = ...
from __future__ import print_function import sys class MyTrieNode: def __init__(self, isRootNode): self.isRoot = isRootNode self.isWordEnd = False self.isRoot = False self.count = 0 self.next = {} def addHelper(self...
''' Using the country_list library create a list of all countries in many different languages (~620). Store them in a disk. (ONE TIME EXECUTION) ''' import sys, os from country_list import available_languages from country_list import countries_for_language out_dir = sys.argv[1] countries = {} for lang in available...
def no_dups(s): clean = [] if s == "": return "" else: for word in s.split(): if word in clean: continue else: clean.append(word) answer = "" for word in clean: answer += word answer += " " return answer.str...
import sys def MinGroupsNaive(C): R = set() i = 1 n = len(C) - 1 while i <= n: (l, r) = (C[i], C[i]+1) R.add((l,r)) i += 1 while i <= n and C[i] <= r: i += 1 return len(R) if __name__ == '__main__': input = sys.stdin.read() C = [float(i) ...
import numpy as np def sq_err(w, u, rotation, cor): """ cor: the correlation matrix (of the axis aligned) Gaussian distribution. So cor is diagonal. We assume that each entry of cor is between 0.1 and 1 rotation: the rotation matrix applied to vectors drawn from N(0, cor) w, u : vectors in the transformed (rota...
import rasterio import rasterio.plot import pyproj import numpy as np import matplotlib import matplotlib.pyplot as plt from rasterio.windows import Window class Raster: """Raster is used to manage importing, manipulating and visualizing raster files.""" def __init__(self, filepath, coords): """ ...
def append_list(item, lst=[]): lst.append(item) return lst print(append_list("item 1")) print(append_list("item 2")) def append_list(item, lst= None): if lst is None: lst = [] lst.append(item) return lst msg= "" for i in range(1000): msg+= "hello" def double_list(lists...
''''' измени алгоритм так, чтобы внути цикла рисовалось все правильно ''' import os import sys import random as r def forest(amount): foresthigh = [r.randrange(2,15) for i in range(amount)] myforest = ["" for i in range(amount)] for i in range(0,max(foresthigh)): branch = 1 for j in rang...
import matplotlib.pyplot as plt import numpy as np xpoints = np.array(range(1,101)) ypoints = xpoints * xpoints plt.plot (xpoints, ypoints) plt.show()
numbers = [] number = int(input("enter number (0 to quit): ")) while number != 0: numbers.append(number) number = int(input("enter another (0 to quit): ")) for value in numbers: print (value) average = float(sum(numbers)) / len(numbers) print ("The average is", average)
percentage = float(input("Enter the percentage: ")) if percentage < 39.4: print ("Fail") elif percentage <= 49.4: print ("Pass") elif percentage <= 59.4: print ("Merit 2") elif percentage <= 69.4: print ("Merit 1") else: print ("Distinction")
filename = "count.txt" def writeNumber(number): with open (filename, "wt") as f: f.write(str(number)) writeNumber (3)
def displayMenu (): print ("What would you like to do?") print ("\t (a) Add new student") print ("\t (v) View students") print ("\t (q) Quit") choice = input ("Type one letter (a/v/q):").strip () return choice def doAdd (): print ("in adding") def doView (): print ("in viewing") ...
import numpy as np minSalary = 20000 maxSalary = 80000 numberOfEntries = 10 np.random.seed(1) salaries = np.random.randint(minSalary, maxSalary, numberOfEntries) print (salaries) salariesMult = salaries * 1.05 print (salariesMult) newSalaries = salariesMult.astype(int) print (newSalaries)
message = 'John said\t"hi"\nI said\t\t"bye"' print (message)
sentence = input("Please enter a sentence: ") print (sentence [::-1][::2])
with open ("count.txt", "x") as f: data = f.write("0") print (data)
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns data = pd.read_csv('C:\\Users\\amand\\Desktop\\GMIT\\Programming\\pands-project2021\\iris.csv') sns.set_style("whitegrid") sns.FacetGrid(data, hue = 'class', height = 5).map(sns.histplot, 'petal_length', bins = 5).add_legend(title = 'Sp...
import random def create_stories(): weird_news = 'A sub was arrested this morning after he sub in front of sub. sub, had a history of sub, but' \ ' no one - not even his sub ever imagined he\'d sub with a sub stuck in his sub.' \ " I always thought he was sub, but I never thought ...
def ducci_sequence(test_list,n): for i in range(n+1): a=test_list[0] test_list[0]=abs(test_list[1]-test_list[0]) test_list[1]=abs(test_list[2]-test_list[1]) test_list[2]=abs(test_list[3]-test_list[2]) test_list[3]=abs(test_list[3]-a) return test_list ducci...
marks_table={'John':86.5,'Jack':91.2,'Jill':84.5,'Harry':72.1,'Joe':80.5} top=3 print("Top {} scorer of subject--".format(top),end=" ") for i,j in sorted(marks_table.items(),key=lambda x:x[1]): if top>0: print(i,end=" ") top-=1 print("\nAverage score of all students: ",end=" ") average=0...
""" Created on Wed Jul 22 07:53:58 2020 @author: Nitish """ i=0 def num_convert(a): global i i+=1 if i%2==0: return a else: return int(a) speciality={'P':'Pediatrics','O':'Orthopedics','E':'ENT'} s=list(map(num_convert,input("Enter id and medical speciality visi...
""" Created on Mon Jul 27 02:02:08 2020 @author: Nitish """ def fact(num): if num==0: return 1 else: return fact(num-1)*num num_list=list(map(int,input("Enter list: ").split())) strong_num=list() for i in num_list: b=0 j=i while i>0: a=i%10 i=i//1...
variable = int(input("""Choose a variable: [1] Pressure [2] Volume [3] Number of moles [4] Temperature """)) R = 0.082 if variable == 1: V = float(input('Volume (L): ')) T = float(input('Temperature (K): ')) n = float(input('Number of moles: ')) P = (n * R * T) / V print(f'The p...
''' 给定一个可包含重复数字的序列,返回所有不重复的全排列。 示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] ''' def permuteUnique(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] visited = set() def backtrack(nums, tmp): if len(nums) == len(tmp): res.append(tmp) return ...
''' 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 例如,给定三角形: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 ''' def minimumTotal(self, triangle: List[List[int]]) -> int: self.res = float("inf") row = len(triangle) def helper(level,i,j,tmp): if level == row: ...
from random import random class RandomGen(object): _random_nums = [-1,0,1,2,3] _probabilities = [0.01,0.3,0.58,0.1,0.01] def next_num(self): ran = random() print(ran) lower = 0 higher = 0 for prob in self._probabilities: higher += prob ...
""" 词典工具类 """ def double_set(d, k, v_k, v_v): """ 往词典对应key添加k-v :param d: 词典 :param k: 键 :param v_k: 值的key :param v_v: 值的value :return: """ if isinstance(d, dict): if k not in d: d[k] = dict() d[k][v_k] = v_v def append(d, k, v): """ ...
def is_palindrome(n:str): for i in range(len(n)//2): if n[i] != n[-(i+1)]: return False return True with open("/root/Downloads/2T_part1.txt", "r") as primes: with open("palprimes.txt", "w") as palprimes: for line in primes.readlines(): numbers = line.split() ...
import user_interface class CommandLine(user_interface.UI): symbol = [" ", "X", "O"] def render(self, board=None): row_strings = [] for row in range(3): values = [self.symbol[board.cell((row, col))] for col in range(3)] row_strings.append(" " + " | ".join(values) + " ...
import os def main(): print_sum() def print_sum(): try: a = float(input("Gunawardana Shiron. IS-92. Please enter a, b, c.\na = ")) b = float(input("b = ")) c = float(input("c = ")) T = ex_sum(a, b, c) print(T) except KeyboardInterrupt: print("\nProgram execu...
class OrbitMap: def __init__(self, name): self.name = name self.children = [] self.parent = None def __repr__(self): return f"{self.name}" def find(self, name): if self.name == name: return self else: for child in self.children: ...
import ex25 sentence = "All good things come to those who wait." words = ex25.break_words(sentence) sorted_words = ex25.sort_words(words) ex25.print_first_word(words) ex25.print_last_word(words) ex25.print_first_word(sorted_words) ex25.print_last_word(sorted_words) sorted_words = ex25.sort_sentence(sentence) e...
player = str(input("Enter a Player Name: ")) print('you just wrote: ', player) player = int(input("Enter a Player Jersey Number: ")) print('you just wrote: ', player) batsmen01 = str(input("Enter Player01 name: ")) batsmen02 = str(input("Enter Player02 name: ")) play01 = int(input("Enter a player jersey number: ...
mytuple = (100,200,300,400,500,600,700,800,900) print(mytuple[2]) print(mytuple[4]) print(mytuple[5]) print(mytuple[-3]) print(mytuple[-5]) print(mytuple[-4]) print(mytuple[:]) print(mytuple[1:3]) print(mytuple[::-3]) print(mytuple[-1::-5])
from tkinter import * gameMode = "" difficulty = "" username = None def start_main_page(): def back(): main_window.destroy() start_main_page() def showBackButton(): backButton = Button( main_window, image=img1, ...
def connectstr(): st=input("Enter the connect string: ") d1={"server":'',"dbname":'',"user":'',"passwd":''} i1=int(0) i2=int(0) ctr=int(0); for j in range(0,len(st)): if st[j]=='=': ctr+=1 i1=j for k in range(j,len(st)): if ...
class T: def __init__(self, data): self.data = data def __eq__(self, a): print("This is in __eq__") if self.data == a.data: return True; else: return False if __name__ == "__main__": a = T(1) b = T(1) print(a == b)
class ClassTest: def __init__(self): print("This is in ClassTest") def echo(self): ...
if 3 > 10: print('yes') print('ok') else: print('no') if -0.0: print('yes') if 0.1: print('0.1 yes') if ' ': print('space ok') a = 10 b = 20 if a < b: smaller = a else: smaller = b print(smaller) s = a if a < b else b print(s)
user = input("username:") passwd = input("password:") if user == "yy" and passwd == "123456": print("Login successful") else: print("Login inorrect")
import re from collections import Counter class CountPatt: def __init__(self, patt): self.cpatt = re.compile(patt) def count_patt(self, fname): result = Counter() with open(fname) as fobj: for line in fobj: m = self.cpatt.search(line) if m: ...
l=['moyu','niupi','xuecaibichi','shengfaji','42'] for i in range(len(l)): print(l[i])
import tkinter win = tkinter.Tk() win.title("YY") win.geometry('400x400+200+200') def showinfo(): print(entry.get()) entry = tkinter.Entry(win) entry.pack() button =tkinter.Button(win, text='提交', command=showinfo) button.pack() win.mainloop() if __name__ == '__main__': pass
while True: yn = input('Continue(y/n): ') if yn in ['n', 'N']: break print('running...') sum100 = 0 counter = 0 while counter < 100: counter += 1 if counter % 2 == 1: continue sum100 += counter print(sum100)
alist = [1, 2, 3, 'bob', 'alice'] alist[0] = 10 alist[1:3] = [20, 30] alist[2:2] = [22, 24, 26, 28] alist.append(100) alist.remove(24) alist.index('bob') blist = alist.copy() alist.insert(1, 15) alist.pop() alist.pop(2) alist.pop(alist.index('bob')) alist.sort() alist.reverse() alist.count(20) alist.clear(...
""" 重写:可将函数重写定义一遍 __str__() __repr__() """ class Person(object): """ :param :parameter """ def __init__(self, name, age): self.name = name self.age = age def myself(self): print("I'm %s , %s years old " % (self.name, self.age)) def __str__(self): ...
from person import Person class Worker(Person): def __init__(self, name, age, money): super(Worker, self).__init__(name, age, money) def work(self): print(A._Person__money) A = Worker('bob', 30, 10000) A.work() A.get_mon()
import time print('#' * 20, end='') counter = 0 while True: print('\r%s@%s' % ('#' * counter, '#' * (19 - counter)), end='') counter +=1 if counter == 20: counter = 0 time.sleep(0.3)
import tkinter from functools import partial def hello(word): def welcome(): lb.config(text="Hello %s!" % word) return welcome root = tkinter.Tk() lb = tkinter.Label(text="Hello world!", font="Times 26") MyBtn = partial(tkinter.Button, root, fg='white', bg='blue') b1 = MyBtn(text='Button 1', command...
def Fib(n): return 1 if n<=2 else Fib(n-1)+Fib(n-2) print(Fib(int(input()))) target=int(input()) res=0 a,b=1,1 for i in range(target-1): a,b=b,a+b print(a)
class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def say_hi(self): print('hello world!') @classmethod def create_date(cls, str_date): y, m, d = map(int, str_date.split('-')) return cls(y, m, d) ...
py_str = 'hello world!' py_str.capitalize() py_str.title() py_str.center(50) py_str.center(50, '#') py_str.ljust(50, '*') py_str.rjust(50, '*') py_str.count('l') py_str.count('lo') py_str.endswith('!') py_str.endswith('d!') py_str.startswith('a') py_str.islower() py_str.isupper() 'Hao123'.isdigit() 'Hao123'...
bdict = {}.fromkeys(['bob', 'alice', 'tom'], 7) print(bdict) for key in bdict: print('%s: %s' % (key, bdict[key])) print('%(bob)s' % bdict) bdict['tom'] = 8 bdict['john'] = 6 print(bdict) bdict.pop('alice') 7 in bdict 'tom' in bdict cdict = bdict.copy() bdict.get('bob') bdict.get('jane', 'not foun...
Max=lambda x,y:x*(x>=y)+y*(y>x) Min=lambda x,y:x*(x<=y)+y*(y<x) a=int(input('1:')) b=int(input('2:')) print(Max(a,b)) print(Min(a,b))
from random import choice num = int(input("请输入密码的位数:")) string = "123456absimport!#@%" password = "" for i in range(num): password = password + choice(string) else: print(password)
class Book: def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages def __str__(self): return '《%s》' % self.title def __call__(self): print('《%s》is written by %s' % (self.title, self.author)) if __name__ == '__main__': ...
import threading import time def oo(): event = threading.Event() def run(): for i in range(5): event.wait() event.clear() print('sunck is a good man') threading.Thread(target=run).start() return event event =oo() for i in range(5...
import random all_choice = ['剪刀', '石头', '布'] win = [['剪刀', '布'], ['石头', '剪刀'], ['布', '石头']] num_player = 2 num_computer = 2 while num_player > 0 and num_computer > 0: computer = random.choice(all_choice) prompt = ''' (0)剪刀 (1)石头 (2)布 请出拳(0/1/2):''' player = int(input(prompt)) player = ...
from functools import partial def add(a, b, c, d): return a + b + c + d if __name__ == '__main__': print(add(10, 20, 30, 5)) print(add(10, 20, 30, 15)) print(add(10, 20, 30, 25)) print(add(10, 20, 30, 35)) myadd = partial(add, 10, 20, 30) print(myadd(5)) print(myadd(15)) print(myad...
kg = int(input()) if kg in [1,2,4,7]: print(-1) elif kg%5==1 or kg%5==3: print(kg//5+1) elif kg%5==2 or kg%5==4: print(kg//5+2) else: print(kg//5)
""" Created on Mon Mar 25 01:06:23 2019 @author: Rekt77 """ import sys from itertools import islice def Fibonacci_numbers(): prev, curr = 0,1 while True: yield curr prev, curr = curr, prev+curr if __name__ == "__main__": f = Fibonacci_numbers() n = int(sys.stdin.readline().st...
string = "abaaba" stack = [] if len(string)%2 != 0: print(0) for each in string: stack.append(each) if len(stack) != 1 and (stack[-1]==stack[-2]): stack.pop() stack.pop() print(stack) if stack: print(0) else: print(1)
''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). ''' cl...
''' The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 incl...
''' You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. For example, given: s: "barfoothefoobarman" words: ["foo", "bar"] You sho...
''' Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. ''' class Solution(object): def maxProduct(self, nums): """ :type nums: Lis...
''' The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicat...
''' Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. ''' class Solution(object): def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int]...
def print_max_value(nums): print("The max value is: ") print(max(nums)) def max_value(nums): return max(nums) def my_max_value(nums): tmp = nums[0] for i in range(1, len(nums)): if nums[i] > tmp: tmp = nums[i] return tmp l1 = [1, 3, 0, 5, -2] ans1 = max_value(l1) print(ans1) ans2 = my_max_v...
import tkinter as tk racine = tk.Tk() racine.title("Calculatrice") def carre0(): x = 1 y = 0 print("0") bouton_carre0 = tk.Button(racine, text="0", command=carre0) bouton_carre1 = tk.Button(racine, text="1") bouton_carre2 = tk.Button(racine, text="2") bouton_carre3 = tk.Button(racine, text="3") bouto...
from abc import ABC, abstractmethod class Person(ABC): @abstractmethod def get_gender(self): return 0 class Male(Person): def get_gender(self): print("I am from Male Class") class Female(Person): def get_gender(self): print("I am from Female Class") unknown = Per...
''' Xinyi Huang (Nicole) xhuang78@binghamton.edu B58 Jia Yang Assignment #5(2) ''' ''' RESTATEMENT: this program is based on lucky sevens ask a user to input a money value OURPUT to monitor: rolls number money value INPUT to keyboard: money ''' import random SEVEN = 7 FOUR = 4 ONE = 1 def invalidMoney(money_s...
from tkinter import * ''' Demonstrates Button widget and info dialog box ''' class MyGUI: def __init__(self): self.__main_window = Tk() self.__my_button = Button(self.__main_window, \ text='Click Me!', \ comma...