text
stringlengths
37
1.41M
""" operation_data.py 读写文件 csv/Excel表格 使用pandas """ import os import xlrd import pandas import random from xlutils.copy import copy class OperationFile: def __init__(self,filename:str): base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"\\data" # 相当于"../data" self.filepath ...
import numpy as np # to deal with array and matrix calculation easily from sklearn.datasets.samples_generator import make_blobs # generate data import matplotlib.pyplot as plt # to plot import matplotlib.animation as animation # to animate the plot import matplotlib.patches as mpatches # to add legends eas...
class Stack(object): def __init__(self): self.items = [] def is_empty(self): return self.items == [] def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) def push(self, item): self.items.append(item) def pop(self): ...
''' per ricaricare lo script usa import importlib importlib.reload(module) or from importlib import reload reload(module) https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module ''' import numpy as np from random import randint def fun(): print("hello world from the fu...
COVERAGE = 400 length = float(input("Enter the length of the room in feet: ")) width = float(input("Enter the width of the room in feet: ")) height = float(input("Enter the height of the room in feet: ")) coats = float(input("Enter the number of coats in the room: ")) surface_area = (length * width) + (2 * length * h...
import doctest """ We cannot implement code to determine vector length because of the fact that zeroes are not shown in the sparse vectors. We could determine all the zeroes in between and before known values (e.g. {2:5, 6:3} would have a total of 5 zeroes). However, we could have many trailing zeroes, so first we mus...
import random import time #👌 -> rock, ✌ -> scissors, 🙌 -> Scissors moves = ['✌','🙌','👌'] user = input('hi user.Whats your name?\n') def play(): time.sleep(2) print('ready.....') time.sleep(2) print(random.choice(moves)) points = 1 while points <= 3: play() print('S...
# Scraping Numbers from HTML using BeautifulSoup In this assignment you will write # a Python program similar to http://www.py4e.com/code3/urllink2.py. The program will # use urllib to read the HTML from the data files below, and parse the data, extracting numbers # and compute the sum of the numbers in the file....
import math n = int(input("Digite um número inteiro: ")) fator = math.factorial(n) print(fator)
def conta_letras(frase, contar="vogais"): if contar == "vogais": return conta_vogais(frase) else: return conta_consoantes(frase) def conta_vogais(frase): vogal = 0 frase = frase.lower() for i in frase: if ord(i) == 97 or ord(i) == 101 or ord(i) == 105 or ord(i) == 111 or ord...
import math x1 = float(input("Digite a 1ª coordenada x: ")) y1 = float(input("Digite a 1ª coordenada y: ")) x2 = float(input("Digite a 2ª coordenada x: ")) y2 = float(input("Digite a 2ª coordenada y: ")) x = (x1 - x2) ** 2 y = (y1 - y2) ** 2 d = math.sqrt(x + y) if d >= 10: print("longe") else: print("perto...
valor = int(input("Digite um número inteiro: ")) resto1 = valor % 3 resto2 = valor % 5 if resto1 == 0 and resto2 == 0: print("FizzBuzz") else: print(valor)
class Robot: """repersents a robot, with a name.""" population = 0 def __init__(self,name): """initializes the data""" self.name = name print(f'initializing {self.name}') Robot.population += 1 def die(self): """i amd dying""" print(f'{self.name} is being...
# # 계산기 # import os # # while True: # os.system('cls') # s = input('계산식 입력>') # print(f'결과 : {eval(s)}') # os.system('pause') # 앞에 나오는 연산자부터 계산하기 import os operator = ["+","-","*","/","="] def string_calculator(user_input): lop = 0 string_list = [] if user_input[-1] not in operator: ...
# Exe065 - Digite varios números, pergunte [S/N] para continuar e tenha: # Media, maior e menor. num = soma = cont = media = 0 parada = '' maior = 0 menor = 0 while parada != 'N': num = int(input('Digite um número: ')) soma += num cont += 1 media = soma / cont if cont == 1: maior = menor = ...
# Exe011 - Digite dois valores em metros e descubra quantos litros de tinta é nescessario. # (1m^2 = 2L) l = float(input('Digite a largura em (m): ')) h = float(input('Digite a altura em (m): ')) a = l * h L = a / 2 print('Numa parede de {}m por {}m tem uma área de {}m'.format(l, h, a)) print('Numa área de {}m utili...
# Exe053 - Digite uma frase e descubra se é um palindromo. frase = str(input('Digite uma frase: ').replace(' ', '').lower()) # .strip # palavras = frase.split # junto = ''.join(palavras) inverso = '' # inverso = frase[::-1] print(inverso) for c in range(len(frase) - 1, -1, -1): inverso += frase[c] print(frase, inv...
# Exe093 - Coloque num dicionário e mostre: nome, partidas e quantidade de gols. Ficha = {} gols_partida = [] tot_gols = 0 Ficha['Nome'] = str(input('Nome do jogador: ')) Ficha['Jogos'] = int(input('Quantas partidas jogadas?: ')) for g in range(Ficha['Jogos']): gols_partida.append(int(input(f' Quantos gols no {g...
# Exe089 - Crie uma lista com os nome e notas e media dos alunos, # depois mostre suas notas boletins = [] aluno = [] while True: aluno.append(str(input('Nome do aluno: '))) aluno.append(float(input('Nota da P1: '))) aluno.append(float(input('Nota da P2: '))) boletins.append(aluno[:]) aluno.clear()...
# Exe007 - Digite duas notas e tenha a media. nota1 = float(input('Qual é a primeira nota? ')) nota2 = float(input('Qual é a segunda nota? ')) media = (nota1 + nota2) / 2 print('A media é: ', media)
# Exe074 - Gere 5 números numa tupla e tenha o maior e menor. from random import randint números = (randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9)) print('Os números sorteados foram: ') for n in números: print(n, end=' ') print(f'\nO maior número foi {max(números)}') print(f'...
# Exe081 - Digite varios números colocando numa lista, mostre: # Quantos números foram digitados; Em ordem decrescente e se tem 5. números = list() c = 0 while True: n = int(input('Digite um número: ')) # números.append(input...) números.append(n) parada = input('Continuar? [S/N]: ') c += 1 prin...
# Exe017 - Digite o valor dos catetos e calcule a hipotenusa. Co = float(input('Digite o valor do Cateto oposto: ')) Ca = float(input('Digite o valor do Cateto adjacente: ')) Hi = (Ca**2 + Co**2) ** (1/2) print() print('O valor de hipotenusa é {:.2f}'.format(Hi)) # import math # Hip = math.hypot(Co, Ca)
# Exe061 - Refaça o exe 51 para calcular PA com while. print('Calculadora de PA') primeiro = int(input('Digite o primeiro termo: ')) razão = int(input('Digite a razão da PA: ')) termo = primeiro contador = 1 print('{}'.format(primeiro), end=' > ') while contador <= 10: termo += razão contador += 1 print('{...
# Exe072 - Digite um número de 0 a 20 e tenha o número por extenso. números = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezeseis', 'Dezesete', 'Dezoito', 'Dezenove', 'Vinte') while True: digitado = ...
# 1)Create a file with the User classs... + Add a make_withdrawal method class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount def make_withdrawal(sel...
Notes: 10/27/2020 # Attributes!! class User: # Attributes def __init__(self): self.username = "awesome_pants" self.email = "fake@email.com" self.password = "123qweasd" # Methods john = User() print(john.username) print(john.email) print...
import pygame from pygame.sprite import Sprite class Alien(Sprite): """A class to represent a single alien in the fleet""" def __init__(self,first_play): """Initialize alien and set its starting position""" super().__init__() self.screen = first_play.screen self.settings = fir...
# input with open('input.txt') as f: data = [int(l.strip()) for l in f] def calc_fuel(mass): if mass <= 0: return 0 return mass + calc_fuel(mass // 3 - 2) # Part one print(sum([mass // 3 - 2 for mass in data])) # Part two print(sum([calc_fuel(mass) - mass for mass in data]))
############ UTILS ###############"" import math ##Factorial## def factorial(x): if x<0 : print("x is less than 0") ### raise ERROR if x == 0 : return 1 return x*factorial(x-1) #################### ######## DISCRETE FUNCTION ############ class Bernoulli: def __init__(self, prob = 0.5)...
# Add two number def two_num(lis1, lis2): # reverse the order of both lists # print() lis1 =lis1[::-1] lis2 = lis1[::-1] #convert into single digit string=(str(int) for int in lis1) string2=(str(int) for int in lis2) int1=int("".join(string)) int2 = int("".join(string2)) output=i...
from dataclasses import dataclass from psycopg2.extensions import register_adapter, adapt, AsIs @dataclass(repr=True) class Location: """ A simple structure for geo location information """ longitude: float latitude: float altitude: float def adapt_location(location): """ Adapts a :c...
class ListNode(object): def __init__(self, x): self.val = x self.next = None def remove_duplicates(head): slow = pre = ListNode(0) pre.next = slow.next = None if not slow: return head fast = head if not fast: return head v = None while fast.next: ...
def letterCombinations(digits): letters = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] def recursive_combinations(s, n, res=[]): if n == len(digits): if s: res.append(s) else: for l in letters[int(digits[n])]: recursi...
class Solution(object): def is_palindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False for i in range(int(len(str(x)) / 2)): if int(x / pow(10, len(str(x)) - i - 1)) % 10 != int(x / pow(10, i) % 10): return...
# File: Kumar_Shani_DSC540_Assignment_4_2_PDF.py # Name: Shani Kumar # Date: 12/22/2019 # Course: DSC-540 - Data Preparation # Desc: Setup a local database with Python and load in a dataset (can be any dataset). You can choose what back-end # to use, if you have never done this before, the book recommen...
# File: Assignment_8_2_Beautiful_Soup.py # Name: Shani Kumar # Date: 02/03/2020 # Course: DSC-540 - Data Preparation # Desc: Beautiful Soup – # Reading a Web Page with Beautiful Soup – following the example starting on page 300-304 of # Data Wrangling with Python, use the Beautiful Soup Python l...
# File: Assignment_9_2_Multiple_Queries.py # Name: Shani Kumar # Date: 02/09/2020 # Course: DSC-540 - Data Preparation # Desc: Practice pulling data from Twitter publicly available API # -> Create a Twitter API Key and Access Token # -> Do a single data pull from Twitter REST API # -> Ex...
""" l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) def fact(x): if x == 0: return 1 return x * fact(x - 1) x = int(raw_input()) print fact(x) import math dict_number = {} input_number = int(raw_input("Input your #:")) for i in range(1, in...
def minHeightBst(array): return constructMinHeightBst(array, 0, len(array) - 1) def constructMinHeightBst(array, startId, endId): if endId < startId: return None midId = (startId + endId) // 2 bst = BST(array[midId]) bst.left = constructMinHeightBst(array, startId, midId) bst.right = co...
def isMonotonic(array): if len(array) <= 2: return True isNonDecreasing = True isNonIncreasing = True for i in range(len(array)-1): if array[i] > array[i + 1]: isNonDecreasing = False if array[i] < array[i + 1]: isNonIncreasing = False return isNonDecr...
import pygame from pygame.locals import * import sys import wave_class import os.path """ Main file for wave generation code """ OUTPUT_FILENAME = "new-sound" LENGTH_OF_FILE_IN_SECONDS = 5 CHANNEL_COUNT = 1 SAMPLE_WIDTH = 2 SAMPLE_RATE = 44100 # How many time we sample per second SAMPLE_LENGTH = SAMPLE_RATE * LENGTH_...
class DoublyLinkedList(object): def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRU_Cache(object): def __init__(self, capacity): """ :type capacity: int """ self.head = DoublyLinkedList(-1, -1...
#!/usr/bin/python3 # Resources used: https://pythonprogramming.net/python-port-scanner-sockets/ # https://www.pythonforbeginners.com/code-snippets-source-code/port-scanner-in-python import socket import sys ip = sys.argv[1] fp = int(sys.argv[2]) lp = int(sys.argv[3]) def scan(port): sock = socket.socket(so...
class Mine: def __init__(self, element, index, x, y, quantity): self.x = x self.y = y self.index = index self.element = element self.quantity = quantity self.nearest_factories = [] def mine(self): if self.quantity < 1: print("You'r taking away...
# -*- coding: utf-8 -*- """ Created on Fri Jan 3 12:41:21 2020 @author: JC """ import networkx as nx #该库用于网络图的创建与绘制 import matplotlib.pyplot as plt G = nx.DiGraph()#创建有向图 G.add_node(1) G.add_node(2) G.add_nodes_from([3, 4, 5, 6]) G.add_cycle([1, 2, 3, 4]) G.add_edge(1, 3) G.add_edges_from([(3, 5), (...
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 00:02:03 2020 @author: JC """ import calendar # 输入指定年月 yy = int(input("输入年份: ")) mm = int(input("输入月份: ")) # 显示日历 print(calendar.month(yy,mm))
""" train_agent.py: This is the source code to train the agent. @author: Rohith Banka. Initial code has been provided by the team by Udacity Deep Reinforcement Learning Team, 2021. Unity ML agents have Academy and brains. Academy: This element in Unity ML, orchestrates agents and their decision-making process. Brain:...
from collections import defaultdict class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dict1=defaultdict(list) def helper(str1): hasharr=[0]*26 for i in str1: index=ord(i)-97 hasharr[index]+=1 ...
#Le juste prix # import random # n = random.randint(0,100) # commentaire = "?" # while True: # var = input("Entrez un nombre") # var = int(var) # if var < n : # commentaire = "trop bas" # print(var, commentaire) # else : # commentaire = "trop haut" # print(var, commen...
my_int = int(input('Give me an int >= 0: ')) # Fill in the missing code bstr= "" if my_int < 0: print("Number should be 0 or higher. Try again") my_int = int(input('Give me an int >= 0: ')) else: numb = my_int while numb > 0: #bstr = '{0:b}'.format(my_int) n = numb % 2 bstr += str(n...
n = int(input("Input an int: ")) # Do not change this line # Fill in the missing code below factor_int = 1 while factor_int <= n: if n % factor_int == 0: print(factor_int) factor_int += 1
num = int(input("Input an int: ")) # Do not change this line oddatala = 1 for i in (range(num*2)): if i % 2 == 1: print(i) # Fill in the missing code below
#number = 0x9b #isOdd = number & 0x01 #if isOdd: # print(str(number) + " is odd number") #else: # print(str(number) + " is even number") number = 0x7d9a print(number) # 0x7d9a == 0111 1101 1001 1010 # qqq q # aa #qqqq = 1100 #aa = 11 # 0111 1101 1001 1010 # 0000-0001-100...
n = int(input("Enter the length of the sequence: ")) # Do not change this line teljari = 0 num1 = 1 num2 = 2 num3 = 3 num2temp = 0 num3temp = 0 while n > teljari: print(num1) num3temp = num3 num2temp = num2 num3 = num1 + num2 + num3 num2 = num3temp num1 = num2temp teljari += 1
import pandas as pd df_upper = pd.read_excel('data/alphabet.xlsx', sheet_name='large', header=None) df_lower = pd.read_excel('data/alphabet.xlsx', sheet_name='small', header=None) def convert_alphabet(txt): num = 15 convert = [''] * num for i in txt: if i.isalpha(): if i.isupper(): ...
'''题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。 问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。 问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?''' def age(n): if n==1: c = 10 else: c = age(n-1)+2 return c print(age(5))
import numpy as np class KNN: def train_knn(self, k, data, data_class, inputs): """ K Nearest Neighbor from the book :param k: how many neighbors to check :param data: the data to process :param data_class: the standardized instance of the class :param inputs: what...
print("Challenge 3.1: Debug code snippets") print() print("Code Snippet 1:") u = 5 v = 2 # '=' is the assignment operator; '==' is the comparison operator if u * v == 10: print(f"The product of u ({u}) and v ({v}) is 10") else: print(f"The product of u ({u}) and v ({v}) is not 10") print() print("Code Sni...
''' Planning & pseudocode challenge! For each piece here, write out the pseudocode as comments FIRST, then write your code! At many points, you'll have to choose between using a list vs. dictionary. Justify your choices! ''' ''' 1. Shipping You are building a system to handle shipping orders. Each order should have 3...
print("hello world") #convert 100 degrees farenheit to celsius celsius_100= (100-32)*(5/9) print (celsius_100) #convert 0 degrees farenheit to celsius celsius_0= (0-32)*(5/9) print(celsius_0) #convert 34.2 farenheit to celsius print((34.2-32)*(5/9)) #convert 5 degrees celsius to farenheit print((5*9/5)+32) print(30...
#first I am going to create two variables #then set them equal to the information from the user print("~~~~~~~~~~Tip Calculator~~~~~~~~~~") price = int(input('Please, enter total price:\n')) percent = input('Please, enter tip percent amount :\n') numOfPpl=int(input('Please, enther the total number of people in y...
# MSPA 400 Session 7 Python Module #2. # Reading assignment: # "Think Python" 2nd Edition Chapter 8 (8.3-8.11) # "Think Python" 3td Editon (pages 85-93) # Module #2 objective: demonstrate some of the unique capabilities of numpy # and scipy. (Using the poly1d software from numpy, it is possible to # differentiate...
# MSPA 400 Session #2 Python Module #3 # Reading assignment "Think Python" either 2nd or 3rd edition: # 2nd Edition Chapter 3 (3.4-3.9) and Chapter 10 (10.1-10.12) # 3rd Edition Chapter 3 (pages 24-29) and Chapter 10 (pages 105-115) # Module #3 objective: demonstrate numpy matrix calculations. For # matrix c...
""" Main module of the game """ __author__ = 'Bojan Keca' import sys import timeit from random import randint from snake import Snake from constants import * sys.path.append(r'c:\pydev') import pygame as pg def secure_screen_size(): """ Ensures that screen size to snake width ratio is correct, incremen...
############DEBUGGING##################### # Describe Problem # Play Computer year = int(input("What's your year of birth?: ")) if year > 1980 and year < 1994: print("You are a millenial.") elif year >= 1994: print("You are a Gen Z.") #Solution: The indentation was wrong! In Python there should be indentatio...
# -*- coding: utf-8 -*- # @createTime : 2019/6/1 20:30 # @author : Huanglg # @fileName: 3_有效的字母异位词.py # @email: luguang.huang@mabotech.com """Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat",...
# -*- coding: utf-8 -*- # @createTime : 2019/6/14 14:31 # @author : Huanglg # @fileName: 6_判断是否有环.py # @email: luguang.huang@mabotech.com class ListNode(object): def __init__(self, x): self.val = x self.next = None # class Solution(object): # def hasCycle(self, head): # """ # ...
import re from bs4 import BeautifulSoup from nltk.corpus import stopwords def tweet_to_words(raw_tweets): # Function to convert a raw tweet to a string of words # The input is a single string (a raw tweet), and # the output is a single string (a preprocessed tweet) # # 1. Remove HTML tweet_text...
''' Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". ''' class Solution(object): def addBinary(self, a, b): if max(a.len(), b.len()) == a.len(): b.zfill(a.len()) else: a.zfill(b.len()) length = a.len() # l...
""" matematika.py práce s knihovnou math zaokrouhlování a mocniny round, ceil, floor, pow, sqrt """ import math #import random #modul pro generování náhodných čísel #cislo=math.pi cislo=float(input("Zadej číslo:")) #cislo2=float(random.random()) mocnina=float(input("Zadej mocninu:")) print(cislo) print("funkce ro...
""" nakup.py program načte názvy zboží, jejich cenu a nakoupené množství a vypíše do tabulky """ zbozi = "mléko", "brambory", "pivo" cena = "15", "30", "12" mnozstvi = "2", "1.5", "3" pocet = len(zbozi) for i in range(0,pocet): print(f"{zbozi[i]:>10}\t {mnozstvi[i]:>3} * {float(cena[i]):>5.2f} = {(float(mnozst...
""" palindrom.py program vyhodnotí, zda je dané slovo palindrom (slovo, které je zapředu a zezadu stejné) """ slovo = str(input("Zadej slovo: ")) slovo = slovo.lower() delka = len(slovo) zacatek = -1 konec = delka - 1 krok = -1 slovo_pozpatku = "" for i in range(konec, zacatek, krok): slovo_pozpatku = slovo_pozp...
""" vazenyPrumer.py Vytvoř program, který na vstupu získá dvě stejně velká pole -- hodnoty a k nim odpovídající váhy. Na výstupu vypíše hodnotu váženého průměru. """ import random def vytvorPole(pocet): pole = [] for i in range(0, pocet): cislo = random.randint(1, 255) pole.append(cislo) ...
""" trojuhelnik.py Vytvoř program, který na vstupu získá přirozené číslo, a na výstupu vykreslí tvar rovnostranného trojúhelníku. Př.: vstup = 4 výstup: o o o o o o o o o o """ def trojuhelnik(cislo): for i in range(1, cislo+1): print(" "*(cislo - i) + "o " * i) pass vstup = int(...
def print_menu(menu): print ("") for key in menu: print(f"\t\t {key}.-" + menu[key]["title"]) print("\t\t Pick a number from the list and an [option] if neccesary\n") print ("\t\t Menu|Quit")
rupee=int(input()) euro=rupee/80 print(euro)
def compare_lists(list0, list1): if len(list0) != len(list1): print "The lists are not the same." else: for i in range(0, len(list0)): if list0[i] != list1[i]: print "the lists are not the same." return print "The lists are the same." l1_a = [1,2,5,6,2] l1_b = [1,2,5,6,2] l2_a = [1,2,5,6,5] l2_b =...
import random import cmath import decimal from decimal import Decimal , ROUND_HALF_UP, localcontext class Qualean: ''' This is a Qualean Class. ''' def __init__(self, user_input): self.user_input = user_input if (user_input in [-1, 0, 1]): with localcontext() as ctx: ...
# -*- coding: utf-8 -*- """ Simulate voting behavior. Convert voter preferences into preferences & rankings for candidates. Typical function inputs ------------------------ voters : array shape (a, n) Voter preferences; a-dimensional voter preferences for n issues. - Each row of the array represents a ...
#Problem 18: Maximum path sum I #Michael Ge, June 13, 2015 ''' By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right ...
"""Una lista que guarda las ganancias maximas para cada presupuesto hasta el presupuiesto dado""" miniMochilas = [] """una lista donde se guardan diccionarios para poder tener las cantidades usadas para cada producto""" cantDiferentesPesos = [] """limite de stock del producto""" cantidadMaxima = [] """El producto asoci...
import pprint # x = -1 # print("Hello") # # if x < 0: # print("Меньше нуля") # print("Good bay") # a, b = 10, 5 # if a > b: # print("a > b") # # if a > b and a >0: # print("Good") # # if (a >b) and (a > 0 or b < 1000): # print("good") # # if 5 < b and b < 10: # print("Good") # if '34' > '123': # ...
from random import randint def input_matrix(no_Of_Elements, max_grad_polinom):#crearea matricei patratate de polinoame de la tastatura Matrix = [] for it1 in range(no_Of_Elements): row = [] for it2 in range(no_Of_Elements): polinom = [] print(f'Polinomul situ...
import random class Maze: def __init__(self, width, height): self.width = width // 2 * 2 + 1 self.height = height // 2 * 2 + 1 self.start = [-1, -1] self.goal = [-1, -1] self.quad = random.choice(range(4)) if self.quad == 0: self.start = [width-1, 0] ...
import numpy as np import matplotlib.pyplot as plt from enum import Enum # Methods & Derivative function def derivative(x, y): return (x + 20 * y) * np.sin(x * y) def rk_2nd_order(x, a2, h, initial=0, group='h'): a1 = 1 - a2 p1 = 0.5 / a2 q11 = 0.5 / a2 y = np.zeros(len(x)) y[0] = initia...
import time ######## THIS WAS SUPPOSED TO CONTAINS ALL THE MENUS OF THE GAME ####### #Menu only usefull for the combat, TODO all the others (Magic, consumables, lvl up , etc..) class Menu() : def intro(self): print(""" Preparez vous à rentrer dans la tour! Vous ouvrez la porte: ...
from tkinter import * def change_tex(): my_label.config(text='孙博是小肥猪') window =Tk() window.title('fat-pig') my_label=Label(window,width=50,height=5,text='') my_label.grid(row=0,column=0) my_button=Button(window,text='谁是小肥猪',width=10,command=change_tex) my_button.grid(row=1,column=0) window.mainloop()
"github.com/lewisgaul/python-tutorial" # WEEK 6 CHALLENGE - classes and GUIs # Work out how the code below works, add in some comments to make it clearer # where you can. # First change the code below so that clicking the button stops the timer. If # there's any style configuration you'd like to do try searching onli...
class BasicShoppingList: def __init__(self, L=[]): self.items = [[item,1] for item in L] def __str__(self): result = '' for i, n in self.items: result += '{:10s} x {}\n'.format(i, n) #e.g. 'Apples x 3\n' return result def add(self, product, quantity=1): ...
#!/usr/bin/env python # Useage: argparse --which arguments -do="we" match import sys for x in sys.argv: if x == '--which': print('--which') elif x == 'arguments': print('arguments') elif x == '-do="we"': print('-do="we"') elif x == 'match': print('match') else: print('no matching args fo...
age = int(input("age")) if age > 25: print("hello")
command = "" started = False stopped = False while command != "quit": command = input("> ").lower() if command == "start": # check if the car already started if started: print("Car has been started") else: started = True print("car started ...") el...
# 8/9/2021 ball class #practice OOP within python class Ball: def __init__(self,color,diameter): self.color = color self.diameter = diameter def roll(self,distance): self.distance = distance print("Ball rolled: "+ str(distance) + "! ") def bounce(self,jumps): self.ju...
## BMI Calculator 2.0 # Instructions # Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height. # It should tell them the interpretation of their BMI based on the BMI value. # - Under 18.5 they are underweight #- Over 18.5 but below 25 they have a normal weight # - Over 25 but ...
## Odd or Even # Instructions # Write a program that works out whether if a given number is an odd or even number. num = int(input("Enter a number")) if(num%2 == 0): print("The given num is Even") else: print("The given number is Odd")
print("Prime Number Checker") import time def prime_number_checker(number): b =[] for i in range(1, number): a = number % i if a == 0: b.append(i) if len(b) > 2: print(f"The {number} is not prime") else: print(f"The {number} is prime") a =int(input("Enter a ...
STARTING_POSITION = (0, -280) MOVE_DISTANCE = 10 FINISH_LINE_Y = 280 from turtle import Turtle class Player(Turtle): def __init__(self): super().__init__() self.shape("turtle") self.pu() self.color("black") self.setheading(90) self.goto(STARTING_POSITION) def t...
from turtle import Turtle,Screen import random screen = Screen() screen.screensize(2000,1500) my_turtle = Turtle() my_turtle.shape("arrow") my_turtle.speed("fastest") my_turtle.hideturtle() colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGre...
import random def partition(li, left, right): temp = li[left] while left < right: while left < right and li[right] >= temp: right -= 1 li[left] = li[right] while left < right and li[left] <= temp: left += 1 li[right] = li[left] li[left] = temp re...