text
stringlengths
37
1.41M
import random import pprint import sys import re spin = 0 next_move = '' landed_on_dict = { 'straight_up': list(range(37)), 'red': [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36], 'black': [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 21, 22, 24, 26, 28, 29, 31, 33, 35], 'even': list(range(...
vowels = {'a', 'e', 'i', 'o', 'u'} word = 'aeou' if set(word).issuperset(vowels) or set(word) == vowels: print(f'{word} is supervocalic.') else: print(f'{word} is not supervocalic.')
class Scoop(): def __init__(self, flavor): self.flavor = flavor def create_scoops(): scoops = [Scoop('chocolate'), Scoop('vanilla'), Scoop('persimmon')] for scoop in scoops: print(scoop.flavor) create_scoops() class Beverage(): def __init__(self, name, temperature = 0): ...
def join_numbers(integer): return ','.join(str(i) for i in range(integer)) print(join_numbers(15)) # With list comprehension print(sum(x*x for x in range(10) if x%2 == 0)) # Without list comprehension total = 0 for i in range(0,10): if i % 2 == 0: total += i*i print(total)
#!/usr/bin/python3 """ Module 7-rectangle Module that contains the class MyList """ class MyList(list): """ Rectangle class A empty MyList class. """ def print_sorted(self): """Returns nothing This function prints the list in order. """ print(sorted(self)) ...
#!/usr/bin/python3 """ Module 6-peak Function to find the peak number """ def find_peak(list_of_integers): """ Returns the peak number Function to find the peak number Args: list_of_integers (list): The numners list. """ li = list_of_integers if li == []: return (None) i...
#!/usr/bin/python3 """ Module 8-load_from_json_file Module that contains the function load_from_json_file that return a Python object from a JSON sting file. """ def load_from_json_file(filename): """Returns an object from a JSON string. A function that get the Python object from the JSON string in an t...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Module 7-base_geometry This module contains the BaseGeometry class """ class BaseGeometry: """BaseGeometry class A simple empty BaseGeometry class """ def area(self): """Returns an Exception""" raise Exception("area() is not implemented"...
#!/usr/bin/python3 """multiple_returns Function to return a tuple with the lengt and first character """ def multiple_returns(sentence): new_tuple = [] lengt = len(sentence) new_tuple.append(lengt) new_tuple.append(None if lengt is 0 else sentence[0]) return (tuple(new_tuple))
#!/usr/bin/python3 """print_list_integer Function to print all the integers of a list. """ def print_list_integer(my_list=[]): for i in my_list: print("{:d}".format(i))
#!/usr/bin/python3 """element_at Function to get an elemen of a list. """ def element_at(my_list, idx): if idx < 0 or idx > len(my_list) - 1: return (None) return (my_list[idx])
#!/usr/bin/python3 """safe_print_integer Python function to print an integer of a list. """ def safe_print_integer(value): try: print("{:d}".format(value)) return (True) except (TypeError, ValueError): pass return (False)
#!/usr/bin/python3 """ Read n lines of a text file """ def read_lines(filename="", nb_lines=0): """ Function that reads n lines of a text file """ with open(filename, encoding="UTF-8") as myFile: if nb_lines <= 0: print(myFile.read(), end="") else: counter = 0 ...
#!/usr/bin/python3 """ Write an object to a text file """ import json def save_to_json_file(my_obj, filename): """ Function that wrutes an obkedct to a text file """ with open(filename, mode="w") as myFile: json.dump(my_obj, myFile)
import numpy as np import time import matplotlib.pyplot as plt #--------------------------------------- heap part def max_heapify(a, i, n): left_i = (2*i)+1 right_i = (2*i)+2 max_i = i if right_i < n and a[right_i] > a[i]: max_i = right_i if left_i < n and a[left_i] > a[m...
class req: """class representing the requirements a player must meet in order to be considered for an invitation to a tournament""" def __init__(self, req_list): """req_list should be a list of strings in the form of a boolean test, all references to the player should use 'p' (for example: ...
import os def ClearScreen(): os.system("cls") def Pause(): os.system("pause") def DisplayStringTable(string_table, pre_clear = 1, pause = 0, horizontal_padding = 3): if pre_clear: ClearScreen() Display(str(string_table)) if pause: Pause() def DisplayTable(string_t...
import math class vector_t: def __init__(self, vec=(0, 0)): self.x = vec[0] self.y = vec[1] def length(self): return math.sqrt(self.x * self.x + self.y * self.y) def __float__(self): return self.length() def __add__(self, other): return vector_t((self.x + oth...
#Author: Charles D. Maddux #Date: 12/28/2020 #Description: Think Python Chapter 5 exercises import time import turtle def exercise_1(current_time): """ times the current time and converts to days, hours, minutes, seconds since the epoch """ #declare variables unit_min = 60 ...
number1, number2 = map(int, input().strip().split()) minimum_number = number1 if number1 < number2 else number2 print(minimum_number)
# Formatting : # Here are some basic argument specifiers you should know: # %s - String (or any object with a string representation, like numbers) # %d - Integers # %f - Floating point numbers # %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. # %x/%X - Integers in h...
# list data-types with their built-in functions : l = [1, 2, 3, 4, 5, "0.354"] bif_of_list = dir(l) print("\n\n", "Built-in function of list data".upper().center(160, '-')) print("Total functions are : ", len(dir(l))) for i in range(0, len(dir(l))): print(bif_of_list[i], end=" ") if (i % 10) == 0 and (i !=...
def string_test(s): a = len(s) if a > 2 and s[0] == s[-1]: return('True') else: return('False') def add_x(s):
# Automating google search using python - selenium # for this task we need browser driver running . I used chrome browser which can be downloaded form 'http://chromedriver.chromium.org/downloads' #pip install selenium #Tested on windows machine. we have to give local installation path while loading chrome webdriver ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from threading import Thread, Lock from time import time, sleep from random import uniform # mutex resource class Fork: def __init__(self): self.lock = Lock() def use(self): self.lock.acquire() # lock def put(self): self.lock.release() ...
menu=input() stri="" for i in menu: uppercase=i.upper() if(uppercase==i): stri=stri+i.lower() else: stri=stri+i.upper() print(stri)
n=int(input()) l=[] for i in range(n): l.append(int(input())) sum=l[0] print(round(sum/1,3)) j=1 for i in range(1,n): j=j+1 sum=sum+l[i] avg=sum/j print(round(avg,3))
n=int(input()) l=[] for i in range(n): l.append(int(input())) print(l[0]) sum=l[0] for i in range(1,n): sum=sum+l[i] print(sum)
password = input() contains_digit = False for character in password: is_digit = character.isdigit() if is_digit: contains_digit = True is_all_lower = (password.lower() == password) is_all_upper = (password.upper() == password) contains_lower_and_upper = (not is_all_lower) and (not is_all_upper) is_va...
""" MTRX5700 - Experimental Robotics Major Project - Blackjack Robot Year: 2021 Group 5 - Curry Shop File: Info: . """ # Imports from blackjack_classes.BlackjackCard import BlackjackCard # Class declaration class BlackjackDealer: # Class constructor def __init__(self): # Initialise empty han...
# -*- coding:utf-8 -*- import json import urllib2 date = "20181002" server_url = "http://www.easybots.cn/api/holiday.php?d=" vop_url_request = urllib2.Request(server_url + date) vop_response = urllib2.urlopen(vop_url_request) vop_data = json.loads(vop_response.read()) print vop_data if vop_data[date] == '0': prin...
inputData = "" with open("input.txt") as fp: inputData = fp.read().strip() def solve(testdata): stringSum = int(testdata[0]) if testdata[0] == testdata[-1] else 0 for i in range(1, len(testdata)): if testdata[i-1] == testdata[i]: stringSum += int(testdata[i]) return stringSum print...
"""============================================================================ Game object is the base of an in game object ============================================================================""" import pygame import globals class Gameobject: def __init__(self, boundry, position, size, speed, direction): ...
"""============================================================================ Animation Loads an animation series (or just a still) and creates a pygame surface for it. Animations are a collection of images, displayed with a given frame rate. The images can be separate files, named so that only index numbers diffe...
ativo = True while ativo: try: print("Informe agora os dados para obtenção do volume do cilindro: ") raioCilindro = float(input("raio(r) -> ")) alturaCilindro = float(input("altura(h) -> ")) volume = (3.14 * (raioCilindro ** 2)) * alturaCilindro print(f"Volume do Cilindro: ...
import random from storage import * def carve_passages_from(maze, row, col): directions = ["N", "S", "E", "W"] random.shuffle(directions) for d in directions: maze.print_maze() p = maze.cell_in_direction(row, col, d) # Check if the cell in the given direction is not outside th...
""" 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры. """ NUMB_ONE = int(input("Количество вводимых чисел? ")) NUMB_TWO = int(input("Цифра, которую необходимо посчитать: ")) COU...
""" #5. В массиве найти максимальный отрицательный элемент. # Вывести на экран его значение и позицию (индекс) в массиве. """ from random import randint IN_LIST = [randint(-30, 30) for i in range(30)] MIN_EL = -30 MIN_EL_KEY = 0 for key, value in enumerate(IN_LIST): # поиск минимального элемента и его индекса ...
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. """ NUMB = int(input('Введите число: ')) """ Решение MY_STR[::-1] будет более простым тут, но ... """ NUMB_R = 0 while NUMB > 0: NUMB_R = NUMB_R * 1...
""" 3. Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом. Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой – не больше медианы. Задачу можно решить без сортировки исходного массива. Н...
""" 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число. """ ...
#!/usr/bin/env python3 import sys import time from math import * def display_binomial(d): i = 0 p = d / (3600 * 8) n = 3500 overload = 0 begin = time.time() print("Binomial distribution:") while (i <= 50): if ((i % 6) != (0)): print("\t", end='') a = (binomial...
import requests from bs4 import BeautifulSoup from urllib.parse import urljoin base_site = "https://en.wikipedia.org/wiki/Music" response = requests.get(base_site) html = response.content soup = BeautifulSoup(html, "lxml") headings = soup.find_all('h2') print(headings) print("\n") heading_text = [a.text for a in he...
""" 1. Gather the parameters of interest 2. Construct the URL and send a GET request to it 3. For unsuccessful requests: print the error message 4. For successful requests: extract the relevant data and calculate the result 5. Display the results to the user """ import json import requests base_url = "https://api.exch...
import numpy as np arr1 = np.array([1,2,3,4,5,6,7,8,9,10]) print(arr1) print(arr1[0:5]) print(arr1.size) print(arr1[::-1]) #Copying a Array arr2 = arr1[5:].copy() print(arr2) #Reverse an Array arr3 = arr1[::-1].copy() print(arr3)
# _*_ encoding=utf-8 _*_ # author zdh # date 2021/4/21--19:24 #第一种方法: # def singleton(cls): # instances = {} # def weapper(*args,**kwargs): # if cls not in instances: # instances[cls] = cls(*args,**kwargs) # return instances[cls] # return weapper() # # @singleton # class Foo(obje...
# _*_ encoding=utf-8 _*_ # author zdh # date 2021/4/23--12:01 # map函数 遍历列表的每一个 from functools import reduce l1 = map(lambda x: x * x, [1, 2, 3, 4, 5]) print(list(l1)) l2 = map(lambda x, y: x * y, [1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) print(list(l2)) l3 = map(lambda x, y: (x * y, x + y), [1, 2, 3, 4, 5], [2, 4, 6, 8, ...
class Pokemon: def __init__(self, name, level, type, is_knocked_out): self.name = name self.level = level self.type = type self.is_knocked_out = is_knocked_out self.exp = 0 self.max_health = level self.health = self.max_health def __repr__(self): return "Pokemon info. {}, current...
import re #import pyperclip #text = pyperclip.paste() #Reads the data to be extracted from list.txt file with open("list.txt", 'r') as f: email = re.findall(r'[\w.-]+@[\w-]+[\.][\w]+', f.read()) with open("emailid.txt", 'w+') as f: for line in email: f.write(line+"\n") print(line) with open("list.t...
import random import logging class LetsMakeADealGame: def __init__(self, switch: bool = False): self.switch = switch self.doors = [False, False, False] # initialise all the doors to have no prize self.doors[random.randint(0, 2)] = True # put the prize behind a random door loggin...
# a123_apple_1.py import turtle as trtl import random as rand #-----setup----- apple_image = "apple.gif" # Store the file name of your shape xOffset = -20 yOffset = -47 wn = trtl.Screen() wn.setup(width=1.0, height=1.0) wn.addshape(apple_image) # Make the screen aware of the new file wn.bgpic("background.gif") apple ...
# Python program to display the Fibonacci sequence up to nth term using recursive function """Fibonacci is a sequence of number in which each number is the sum of two preceeding number. In this program, I am using swap technique of python""" print("Hi, This program will tell you the Fibonacci Series for a given nu...
# Python program to display the Fibonacci sequence up to nth term using recursive function """Fibonacci is a sequence of number in which each number is the sum of two preceeding number. In this program, I am using swap technique of python""" print("Hi, This program will tell you the Fibonacci Series for a given nu...
import RPi.GPIO as gpio val = None; pin = None; state = None; gpio.setmode(gpio.BCM) # gpio.setup(17, gpio.IN, pull_up_down=gpio.PUD_DOWN) # gpio.output(12, gpio.HIGH) # gpio.output(12, gpio.LOW) while(True): try: val = input("Enter GPIO number [0, 27] or set the current GPIO to [h | high] or [l | low]: ...
##Texto Criptografado = (Texto normal ^ E) mod N def encrypt(mensagem, eh, mod): codigo = "" for i in range(0,len(mensagem)): codigo += chr( ord(mensagem[i]) ** eh % mod ) return codigo ##Texto Normal = (Texto Criptografado ^ D) mod N def decrypt(mensagem, de, mod): msg = "" for i...
#Question #You Are given an array representing the heights of neighboring buildings on a city street from east to west (rises in the east sets in the west) #The city assessor would like you to write an algorithm that returns how many of these buildings have a view of the setting sun, in order to properly value the stre...
#Calculates the sum of an input list of integers grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def grades_sum(scores): total=0 for i in scores: total+=i return total print grades_sum(grades) #Calculates average based on sum calculations def grades_average(grades_input): to...
t = 12345, 54321, 'hello!' print(t[0]) # 12345 print(t) # (12345, 54321, 'hello!') # Tuples may be nested: u = t, (1, 2, 3, 4, 5) print(u) # ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# 嵌套列表解析 # Python的列表还可以嵌套。 # # 以下实例展示了3X4的矩阵列表: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] # 以下实例将3X4的矩阵列表转换为4X3列表: print([[row[i] for row in matrix] for i in range(4)]) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] print("------------------------") # 以下实例也可以使用以下方法来实现: transposed = ...
# 集合 # 集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。 # 可以用大括号({})创建集合。注意:如果要创建一个空集合,你必须用 set() 而不是 {} ;后者创建一个空的字典,下一节我们会介绍这个数据结构。 # 以下是一个简单的演示: basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) # 删除重复的 # {'orange', 'banana', 'pear', 'apple'} print('orange' in basket) # 检测成员 # True print('crabgras...
"""Write a python program to find the square root of the given number""" def main(): """Writing inside this function""" squ_apprx = int(input()) epsilon_1 = 0.01 guess_1 = 0.0 step = 0.1 num_guesses = 0 while abs(guess_1**2 - squ_apprx) >= epsilon_1 and guess_1 <= squ_apprx: guess_1 ...
'''Problem 1 - Build the Shift Dictionary and Apply Shift''' # The Message class contains methods that could be used to apply a # cipher to a string, either to encrypt or to decrypt a message # (since for Caesar codes this is the same action). # In the next two questions, you will fill in the methods of the # Message ...
"""Exercise: eval quadratic. This function takes in four numbers and returns a single number.""" def eval_quadratic(a_in, b_in, c_in, x_in): """square""" return a_in*(x_in**2) + b_in*x_in + c_in def main(): """Writing inside this function""" data = input() data = data.split(' ') data = list(map(...
# Exercise: PowerRecr # Write a Python function, recurPower(base, exp), that takes in two numbers and returns the base^(exp) of given base and exp. # This function takes in two numbers and returns one number. def recurPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^ex...
''' Write a function to clean up a given string by removing the special characters and retain alphabets in both upper and lower case and numbers. ''' import re def clean_string(string): '''Clean string function''' regex = re.compile('[^a-zA-z0-9]') cleared_string = regex.sub('', string).replace('^', '') ...
''' This is a continuation of the social network problem There are 3 functions below that have to be completed Note: PyLint score need not be 10/10 for this assignment. We expect 9.5/10 ''' def follow(network, arg1, arg2): ''' 3 arguments are passed to this function network is a diction...
"""Exercise: coordinate""" class Coordinate(object): '''This is a class and its name is Coordinate''' def __init__(self, x_input, y_input): self.x_input = x_input self.y_input = y_input def getx_input(self): '''Getter method for a Coordinate object's x coordinate.''' return s...
#!/bin/python3 import sys def insertionSort1(n, arr): last = arr[-1] last = arr[-1] x = 0 while arr[n-(n+2) - x] > last: arr[-1-x] = arr[n-(n+2) - x] print (' '.join(str(y) for y in arr)) if x+2 == len(arr): arr[n-(n+2) - x] = last break else: ...
import math import MathUtils import StringUtils def TrouverClePrivee(n, c): """ Trouve la clé privée associée à une clé publique param n: n de la clé publique param c: d de la clé publique return: l'entier d de la clé publique """ divider = [d for d in range(2, int(math.sqrt(n))) if n%d == 0] p = divider[0]...
produtos=[] custos=[] codigo = 1 while codigo != 0: codigo,quantidade,preco = input().split() codigo = int(codigo) quantidade = float(quantidade) preco = float(preco) custo = quantidade * preco produtos.append([codigo,quantidade,custo,preco]) custos.append(custo) maior_custo = m...
def potencias(n): for i in range(n): p=2**(i+1) print(p,end=' ')
def f(b): return a*b a = 0 print('f(3) = {}'.format(f(3))) print('a é {} '.format(a))
def main(): pri = Carro('brasilia', 1968, 'amarela', 80) seg = Carro('fuscao', 1981, 'preto', 95) Carro.acelere(pri, 40) pri.acelere(40) Carro.acelere(seg, 50) Carro.acelere(pri, 80) Carro.pare(pri) seg.pare() Carro.acelere(seg, 100) class Carro: def __init__(self,...
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # If end of array is greater than or equal to, need equal in case target is there if end >= start: # Get the value in the middle of the array middle = (start + end) // 2 # If targe...
print("program to print the modules odd number") odd number (1 to 100) result=num1++ print (result)
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/10/22 name_list = ['zhangsan', 'lisi', 'wangwu'] print (name_list[2]) print (name_list.index('wangwu')) # 2 修改 name_list[1] = '李四' # 3.增加 name_list.append('大哥') name_list.append('dage') name_list.insert(1,'xiaomeimei') # extend 可以把其他列表追加到当...
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/10/23 str1 = "hello world" str2 = '我的名字是"大西瓜"' # for char in str1: # # print char print len(str1) print str1.count("l") print str1.index('or')
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2018/1/8 # 之前都是拿 函数 来装饰 函数, 现在是拿 类 来装饰 函数 # class Test(object): # # def __call__(self, *args, **kwargs): # print('-------test-------') # # t = Test() # t() # 因为 __call__ 所以类实例化的对象才能直接()调用 # ############################################...
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/12/28 # xx:公有变量 # _x:单前置下划线,私有化属性或方法,from somemoudule import * 禁止导入,类对象和子类可以访问 # __xx:双前置下划线,避免与子类中的属性命名冲突,无法在外部直接访问(名字重复所以访问不到),想访问,_类名__xx(系统不推荐) # __xx__:双前后下划线,用户名字空间的系统方法或属性 # xx_:单后置下划线,用于避免与python关键词冲突 if_ = 100 class Test(object): ...
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/12/3 # 面向对象三大特性: # 1. 封装 ,根据职责将 属性和方法 封装 到一个抽象的 类 中 # 2. 继承 ,实现代码的重用,相同的代码不需要重复编写 # 3. 多态 ,不同的 子类对象 调用相同的父类方法,产生不同的执行结果 class Dog(object): def __init__(self,name): self.name = name def game(self): prin...
class Dishes: total_price = 0 def __init__(self, type="Cup", colour="Green", price=100, size=250, print1="With cat", material="ceramics"): self.type = type self.colour = colour self.price = price self.size = size self.print1 = print1 self.material = material ...
#Ryan #Practice Using expression and conditonal statements #An expression is a problem that must be solved #5 + 5 is "arithmetic" expression x = 5 + 5 #Fumctions/methods must be resolved as expressions as well answer = input("What is your name?") #Comparison expression resolve as Ture/False print(7>7) print(7>=7) pr...
# Devin Hurley # 03/14/2013 from numpy import matrix import pylab from numpy import polyfit # define def polyfit(x,y,m): # we want this function to output coefficients N=len(x) b = matrix([[0.0]] *(m+1)) # column vector M = matrix([[0.0]*(m+1)]*(m+1)) for k in range(m+1): for i in range(N)...
# Devin Hurley # CSIS310 # 02/17/2013 # part a - derivative of f is # # 12*x^2 - x*e^((x^2)/2) # # part b - at x = 2 # it reaches the root near 1 # # problem number 13 import math def fnc(x): y = 4*(x*x*x) -1 - math.exp((x*x)/2) return y def fncPrime(x): y = 12*x*x - x*math.exp((x*x)/2) return y de...
#!/bin/python import random class FairDice(object): """ These 'dice' implement the probability mechanics described by Sid Meier and Rob Pardo at GDC 2010. see: http://www.shacknews.com/featuredarticle.x?id=1302 They are meant to be more 'fair' than normal probability, following natural lan...
import re from .box import Box class Interface: def __init__(self, table): self.table = table self.goal_tree = self.table.goal_tree self.box_names = Box.boxes_names def parse_question(self, question: str): """This method parses the queston and creates a dictionary that describ...
#!/usr/bin/env Python # Aingty Eung # 9/07/2017 # EE 381 Project 2 # Bernoulli Trials, Bayes' Rule, and General Probability print('\nBernoulli Trial Simulation.') # Cast the number to float for success rate p = float(input('Enter the Probability of Success: ')) k = int(input('Enter the number of trails: ')) # U...
def reverse(n): rev = 0 while (n > 0): digit = n % 10 rev = rev * 10 + digit n = n // 10 print("Reverse of the number:", rev) n=int(input("Enter number: ")) reverse(n)
""" Python tkinter GUI Tutorial # 123 Custom Message Box Popup Simple example of custom message boxes """ from tkinter import * class Application(Frame): def __init__(self, master): super().__init__(master) self.master.title("ProMCS") self.master.geometry("400x100") self.popup = ...
#!/usr/bin/python3 """ Module used to add two arrays """ def validUTF8(data): """ Method that determines if a data set represents a valid UTF-8 encoding. 1. A character in UTF-8 can be 1 to 4 bytes long 2. The data set can contain multiple characters Args: data (lst): List ...
#!/usr/bin/python3 """ Module used to """ def rain(arr): """ Given a list of non-negative integers representing walls of width 1, calculate how much water will be retained after it rains. Assume that the ends of the list (before index 0 and after index walls[-1]) are not walls, meaning they will ...
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv from enum import unique with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The tel...
""" You are given the head of a linked list and two integers, i and j. You have to retain the first i nodes and then delete the next j nodes. Continue doing so until the end of the linked list. Example: linked-list = 1 2 3 4 5 6 7 8 9 10 11 12 i = 2 j = 3 Output = 1 2 6 7 11 12 """ class Node: def __init__(self,...
def tax_calculation(): income = int(input()) tax = 0 if 15527 < income < 42708: tax = 15 elif 42707 < income < 132407: tax = 25 elif income >= 132407: tax = 28 calculated_tax = int(round(income * (tax / 100))) print(f"The tax for {income} is {tax}%. That is {calculate...
import math import time #Problem 5: 2520 is the smallest number that can be divided by each # of the numbers from 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible # by all of the numbers from 1 to 20? checklist=[11,13,14,16,17,1...
import math import time #Problem 3: The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143? primeFactor = 1 #Determine largets Factor def primeFactors(val): #loop for 2 as a factor while val%2==0: primeFactor = 2 val = ...
class Glass: cnt = 1 def __init__(self, capacity: float = 200, occupied: float = 0): self.capacity_volume: float self.occupied_volume: float self.cnt = Glass.cnt if not isinstance(capacity, (int, float)): raise TypeError("Некоррктный тип capacity") if not is...
import random #First Prompt print "Well hello hail and harty traveler, welcome to my humble Inn. May I ask your name?" NAME= raw_input(" Full Name?:") print "Ahhh so your name is "+NAME+ " ....I see." #Second Prompt CLASS= raw_input(" What Vocation are you?:_") print "Ohh so you are a mighty, "+CLASS+", Very interes...
import re with open("files/regex-test.txt") as names: for line in names.readlines(): valid = re.match("([A-Z][a-z]+)( [A-Z][a-z]*){1,2}", line) if valid: print(valid.group()) else: print(valid) names.close()
# codinf:utf-8 # 插入即表示将一个新的数据插入到一个有序数组中,并继续保持有序。例如有一个长度为N的无序数组, # 进行N-1次的插入即能完成排序;第一次,数组第1个数认为是有序的数组,将数组第二个元素插入仅有1个有序的数组中; # 第二次,数组前两个元素组成有序的数组,将数组第三个元素插入由两个元素构成的有序数组中...... # 第N-1次,数组前N-1个元素组成有序的数组,将数组的第N个元素插入由N-1个元素构成的有序数组中,则完成了整个插入排序。 def insert_sort(nums): count = len(nums) for i in range(1, count): ...