text
stringlengths
37
1.41M
from random import randint from time import sleep from operator import itemgetter jogo = {"jogador1": randint(1, 6), "jogador2": randint(1, 6), "jogador3": randint(1, 6), "jogador4": randint(1, 6)} ranking = list() print("Valores sorteados: ") for k, v in jogo.items(): print(f"{k} tirou {v} ...
matrix1 = list() matrix2 = list() matrix3 = list() for p in range(0, 3): matrix1.append(input(f"Digite um valor para a posição [0, {p}]")) for b in range(0, 3): matrix2.append(input(f"Digite um valor para a posição [1, {b}]")) for c in range(0, 3): matrix3.append(input(f"Digite um valor para a posição [2, {...
r = "S" par = impar = 0 while r == "S": n = int(input("Digite um valor:")) r = str(input("Quer continuar? [S/N]")).upper() if n % 2 == 0: par += 1 else: impar += 1 print("Voce digitou {} numeros PARES e {} IMPARES".format(par, impar))
frase = input("Digite uma frase:") c1 = frase.strip().upper() a1 = c1.count("A") a2 = c1.find("A") a3 = c1.rfind("A") print("A letra 'A' aparece {}\nA primeira letra A aoarece na posição {}\nA ultima letra Aparece na posição {}".format(a1, a2, a3))
import random n1 = input('Digite o nome do primeiro aluno:') n2 = input('Digite o nome do segundo aluno:') n3 = input('Digite o nome do terceiro aluno:') n4 = input('Digite o nome do quarto aluno:') lista = (n1, n2 , n3 ,n4) n5 = random.choice(lista) print('O aluno sorteado foi {}'.format(n5))
boletim = list() while True: nome = str(input("Nome do aluno: ")) nota1 = float(input("Primeira nota:")) nota2 = float(input("segunda nota:")) media = (nota1 + nota2) / 2 boletim.append([nome, [nota1, nota2], media]) continuar = " " while continuar not in "SN": continuar = str(input("Dejesa ...
from random import randint computador = randint(0, 10) print("Seu computador pensou em um numero de 0 a 10 tente adivinhar") acertou = False palpites = 0 while not acertou: jogador = int(input("Tente advinhar:")) palpites += 1 if jogador == computador: acertou = True print("Acertou\nVoce consegui em...
from random import sample texto = print("Ordem de alunos que vão apresentar o trabalho") a1 = input('Primeiro aluno:') a2 = input('Segundo aluno:') a3 = input('Terceiro aluno:') a4 = input('Quarto aluno:') lista = [a1, a2, a3, a4] ordem = sample(lista, k=4) print('A ordem de apresentação será {}'.format(ordem))
# Problem link : https://leetcode.com/problems/first-unique-character-in-a-string/ class FirstUnique: frequency = dict() def __init__(self, nums: List[int]): self.frequency.clear() for item in nums: # Adding all numbers in dictionary if item not in...
from sys import argv script, filename = argv print ("We're going to arase %r." % filename) print ("If you don't want that, hit CTRL-C (^C).") print ("If you do want that, hit return.") input("? ") print ("Opening the file...") target = open(filename, 'w') #进入‘W’模式(打开一个文档若不存在则新建),因为原来的open默认是只读模式(‘r') print ("Trunc...
player1 = "" player2 = "" def welcome(): print("Welcome to Tic Tac Toe!") print("Choose your symbol ('X' or 'O') -- ") print("***********************************") while True: global player1 global player2 player1 = input("Player 1 : ").upper() if player1 == "X": ...
# -*- coding: utf-8 -*- """ Created on Wed Mar 25 19:34:47 2020 @author: khare """ f_t= "paris" str1=" " l=list(f_t) if l[0]=="A" or l[0]=="E" or l[0]=="I" or l[0]=="O" or l[0]=="U": l.append("way") else: l.remove(f_t[0]) l.append(f_t[0]) l.append("ay") print(str1.join(l))...
import nltk from nltk.tokenize import sent_tokenize def ret_res(text): sent_tokenize_list = sent_tokenize(text) return (sent_tokenize_list) def ret_len_res(text): sent_tokenize_list=sent_tokenize(text) y=len(sent_tokenize_list) return (y) #x=ret_res("whats up. My name is chin. i am expecting this to be 3rd ...
a = "Evan" arr = list(a) a_list = ['nEva', 'anEv', 'vanE', 'Evan'] count = [] for i in range(len(arr)): arr.insert(0, arr.pop()) joined = ''.join(arr) if joined in a_list: count.append(joined) list(arr) all(x in count for x in a_list) def contain_all(a, b): if a == '': return Tru...
""" Dynamic Array * Boyutunu önceden belirlemek zorunda olmadığımız daha sonra eleman ekleyip çıkartabildiğimiz yapılar * Growable and Resizable olarak tanımlanır """ import ctypes # yeni array oluşturmak için kullanacağız class DynamicArray(object): def __init__(self): # initialize (constructor) self...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(6) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(5) root.right.right = TreeNode(7) # if w...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import cv2 import math fingertips_touched_flag = np.zeros((10,1)) def touching_detection(tips, hand_mask, depth_image, draw_image=None): ''' by Yuan-Syun ye on 2019/06/17. To detect if the fingertips are touching or not, our algorit...
import pandas as pd import os #set the folder containingall my files as the active directory #os.chdir(r"C:\Users\huwro\Udacity_Projects\Udacity Pgm for DS Proj 2\bikeshare-2") # fishy """----------------------------------------------------------------------------------------------------------------- Section 1 - tw...
temperatures_C = [33, 66, 65, 0, 59, 60, 62, 64, 70, 76, 80, 81, 80, 83, 90, 79, 61, 53, 50, 49, 53, 48, 45, 39] min_temp = min(temperatures_C) max_temp = max(temperatures_C) hot_temps = [] for temp in temperatures_C: if temp >= 70: hot_temps.append(temp) avg_temp = sum(temperatures_C) / len(te...
def partition(elements, start, end): pivot = elements[start] left = start + 1 right = end while True: while left <= right and elements[left] <= pivot: left += 1 while left <= right and elements[right] >= pivot: right -= 1 if left <= right: ...
def add_it_up(n): if isinstance(n, int): result = n*(n+1)/2 return int(result) else: return 0 def better_approach(num): try: return sum(range(num+1)) except Exception: return 0 def main(): result = add_it_up(20) print(f"Sum of first 20 numbers is : {r...
# remove duplicate from a list of strings def remove_duplicate(li): return list(set(li)) def main(): li = ['Sourav', 'Ganguly', 'Gourab', 'Ganguly', 'Ratul', 'Rakshit', 'Ratul', 'Mukherjee'] new_list = remove_duplicate(li) print(f"New list : {new_list}") if __name__ == '__main__': main()
def insertion_sort(elements): for i in range(1, len(elements)): j = i - 1 key = elements[i] while j >= 0 and elements[j] > key: elements[j+1] = elements[j] j = j-1 elements[j+1] = key def display_elements(elements): for i in elements: print(i, e...
[car for car in['a','e','i','o','u'] if car not in('a','i','o')] edad,_peso = 20, 70.5 nombres = 'Jesus Quirumaby' dirDomiciliaria= "Paraiso de la flor " Tipo_sexo = 'M' civil = True usuario = ('jquirumbayr','1234','jquirumbayr@gmail.com') materias = ['Programa Web','PHP','POO'] docente = {'nombre':'Jesus','eda...
def wages(a): b = 0 c = 0 d = 0 if a <= 1000: b = a * 0.14 c = a * 0.02 d = a - b - c print(d) # ve ya print(int(d)) elif a >= 2500: b = a * 0.20 c = a * 0.05 d = a - b - c print(d) # və ya print(int(d)) ...
#Jared Hinkle #jah87410 #4.8 #This program sorts three integers first,second,third = eval(input("Enter x,y,z:")) small = min(first,second,third) large = max(first,second,third) middle = (first + second + third) - (small + large) print("The numbers in accending order are: ", small, middle, large)
#Jared Hinkle #jah87410 #5.1 #This program will use a while loop and a for loop to find the sum of number between 1 and 15 x = 1 total = 0 while x <= 15: total = total + x x = x + 1 print("Sum using while loop: ", total) total2 = 0 for i in range(1, 16): total2 = total2 + i print("Sum using for loop: ", t...
#Jared Hinkle #jah87410 #2.17 #This program will calculate the users BMI weightLBs = eval(input("Enter weight in pounds: ")) heightINCH = eval(input("Enter height in inches: ")) weightKG = weightLBs * 0.45359237 heightMeters = heightINCH * 0.0254 BMI = weightKG / (heightMeters * heightMeters) print("BMI is: ", roun...
#Jared Hinkle #jah87410 #final exam #program calculates BAC def estimatedBAC(alcohol, bodyWeight, r): if (r == 0): return(((alcohol)/(bodyWeight*(.68)))*100) if (r == 1): return(((alcohol)/(bodyWeight*(.55)))*100) alchol = eval(input("Enter amount of alcohol in grams: ")) bodyWeight = eval(inpu...
import random # Set your random roll range random_number = random.randint(1, 50) print("Your random number is " + str(random_number)) # Create dictionary for items and values gear = {'Arcanum of Wizardry': 10, 'Rib Cage of King Ragmussen': 20, 'Helm of Helia': 30, 'Flametooth Dagger': 40, 'Wand of Zeek': 50} ...
from typing import Optional from enum import Enum from abc import ABC class Display: # This class is given with implementation. And the ONLY one @staticmethod def read_input(display_text: str) -> str: pass @staticmethod def show_error(err_msg: str) -> None: pass @staticmethod...
import random from collections import OrderedDict, defaultdict from typing import List class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random self.prev = self.next = self.child = None class ListNode: def __init__(self, val): ...
import heapq from typing import List, Tuple class Solution: ''' * Order Book Take in a stream of orders (as lists of limit price, quantity, and side, like ["155", "3", "buy"]) and return the total number of executed shares. Rules - An incoming buy is compatible with a standing sell if the buy'...
import random from typing import List ''' Reservoir sampling: When to use: 1. list length is unknown 2. Save space How to use: Loop through entire data stream Use a counter cnt increment when meet target if random.randrange(cnt) == 0: swap into reservoir return the one in reservoir ''' class Sol...
"""This shows an example of how to use the Generator object to provide more control within loops. This could be used for things such as progress bars or emergency stops.""" from mandelpy import Settings, Generator s = Settings() with Generator(s) as g: blocks = g.blocks for i, block in enumerate(blocks): ...
def product2(num1,num2): p=num1*num2 return p def product3(num1,num2,num3): p=num1*num2*num3 return p print product2(2,3) print product3(2,3,4)
import random def merge_sort(arr): if len(arr) > 1: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) i = 0 j = 0 k = 0 while i < len(left) and j < len(right): if left[i] < r...
import cs50 import sys if len(sys.argv) == 2: k = int(sys.argv[1]) s = input() ss = "" for symbol in s: if symbol.islower(): ascii = ord(symbol) + k%26 if ascii > 122: ascii = ascii - 122 + 96 ...
import random class Unit: HP = 100 STR = 10 LUCK = 5 DEF = 5 name = "" def __init__(self, name): self.name = name def status(self): print("HP: %d, STR = %d, LUCK = %d, DEF = %d" % (self.HP, self.STR, self.LUCK, self.DEF)) class Battle: def attack(un...
# File with strings to print HELLO_PRINT = 'Hello! This is Vending Machine!' ENTER_CODE = "Enter code: " INSERT_BN = 'Insert your banknotes value one by one.' STOP_INSERT = 'To stop process - insert 0.' CUST_INSERT = 'Insert: ' CREDIT = 'Your credit is ' CHOOSE_IT = 'Write a number of choice: ' IT_NUM = 'Item number: ...
#part 3 file = input("Enter the name of file: ") e=open(file,'w') store_file = input("Enter the contents to be stored in a file: ") e.write(store_file) e.close()
#!/usr/bin/python3 ''' Python tool to hide information inside of text through a key. File: main.py @authors: - David Regueira - Santiago Rocha - Eduardo Blazquez - Jorge Sanchez ''' """ App entry point """ import text_stego, crawler from art import * import colorama as cla import sys, random, sign...
""" Entrada de Dados Sempre retorna uma String, independente do valor que seja digitado! """ #nome = input("Qual o seu nome?\n") ##idade = input("Qual sua idade?\n") ###ano_nascimento = 2021 - int(idade) #print(f"Usuário digitou {nome} e o tipo da variável {type(nome)}") #print(f"Tem {idade} anos") ##print(f"Nasceu...
""" Condições if elif e else """ if False: print('Verdadeira!') elif False: print("Agora é verdadeiro") elif False: print("Sempre verdadeiro") else: print('Não é verdadeira!')
import datetime from .. import db class Blog(db.Model): """Represents a blog model in the database.""" id = db.Column(db.Integer, primary_key=True, nullable=False) path = db.Column(db.String(64), unique=True, nullable=False) name = db.Column(db.String(256), nullable=False) created = db.Column(db.Da...
# -*- coding: utf-8 -*- """ Created on Tue Aug 3 19:33:57 2021 @author: Estefania """ def crealista(n): lista=[] for i in range(n): lista.append(i) return lista print(crealista(5)) def crealista(n): lista=[] for i in range(n+1): lista.append(i) return lista print(crealista(5...
# !/usr/bin/python3 import openpyxl import sys import csv def convert_excel(csvFile): # convert from csv to xlsx wb = openpyxl.Workbook() ws = wb.active with open(csvFile) as f: reader = csv.reader(f, delimiter=',') for row in reader: ws.append(row) fi...
def print_elem(letter, count): for i in range(count): print(letter, end = "") def print_group(corner_char, fill_char, fill_count): print_elem(corner_char, 1) print_elem(fill_char, fill_count) def print_line(corner_char, fill_char, fill_count, rep): for i in range(rep): print_...
import turtle screen = turtle.Screen() screen.title('Tic-Tac-Toe') screen.setworldcoordinates(-5, -5, 35, 35) pen = turtle.Turtle() for i in range(0, 4): pen.penup() pen.speed(0) pen.goto(0, i*10) pen.pendown() pen.speed(0) pen.forward(30) pen.left(90) for i in range(0, 4)...
def draw_board(board): print(" " + board[0] + " | " + board[1] + " | " + board[2] + " ") print("---+---+---") print(" " + board[3] + " | " + board[4] + " | " + board[5] + " ") print("---+---+---") print(" " + board[6] + " | " + board[7] + " | " + board[8] + " ") def get_player_move(board): # g...
numbers = [5, 3, 4, 43, 4, 3, 4, 3, 5, 56] numbers.sort() print(numbers) goodNumbers = [] for num in numbers: if num not in goodNumbers: goodNumbers.append(num) print(goodNumbers)
import math print('Hello again, You must study 2 hours a day! ') firstName = 'Mihail' secondName = 'Hadzhiev' print(f'my first name is {firstName}, and my second name is {secondName}') sum = 200 print(firstName + ' ' + str(sum)) course = "Mihail is cool and he is working Mihail hard cool cooll02 to learn Python" p...
is_hot = False is_cold = False if is_hot: print("It's a hot day, drink plenty of water Mihail ") elif is_cold: print("It's very cold, be careful ! ") else: print("It's cold stay home") priceHouse = 100000 has_good_credit = True if has_good_credit: down_payment = 0.1 * priceHouse else: down_paym...
''' Michael Borczuk SoftDev K05 - Program to print a random SoftDev student's name 2021-09-27 # SUMMARY OF TRIO DISCUSSION # We decided to send each other the code we had with our original trios. We then chose to pick the parts of the code that would make the program do as little work as possible to give us a random n...
# Team Sneakers: Yoonah Chang (Yelena), Kevin Cao (Pipi), Michael Borczuk (Liberty and Baby Yoda) # SoftDev # K10 -- Putting Little Pieces Together # 2021-10-04 from flask import Flask import csv import random app = Flask(__name__) # create instance of class Flask dict = {} with open('occupations.csv', mode='r') a...
import timeit """ The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 302...
def opposite(list): if len(list) == 1: return list else: return opposite(list[1:]) + [list[0]] """ This function revers the list Args: list: list of numbers Returns: opposite: list of int numbers Raises: ValueError Exam...
''' Script for server @author: hao ''' import config import protocol import os from socket import * class server: # Constructor: load the server information from config file def __init__(self): self.port, self.path=config.config().readServerConfig() # Get the file names from shared directory ...
def rev(x): y = 0 while x > 0: y *= 10 y += x % 10 x = x // 10 return y class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ return (rev(x) == x and x >= 0)
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return...
#!/bin/python3 import sys def print_staircase(n): for i in range(n): print( ( " " * ( (n - 1) - i) ) + ( "#" * (i + 1) ) ) n = int(input().strip()) print_staircase(n)
#!/bin/python3 import sys def sockMerchant(n, ar): # Complete this function my_map = {} for sock in ar: try: my_map[sock] += 1 except: my_map[sock] = 1 count = 0 for sock in my_map: count += my_map[sock]//2 return count...
class ProductItem: ''' ProductItem constructor, creates an instance of a product that has a name, a price, and sometimes a sale price. ''' def __init__(self, name, reg_price, sale_price=None): self.name = name self.reg_price = reg_price self.sale_price = sale_price ''' The override of the str() method. ...
import random as rand print("""Правила игры Камень = 0 Ножницы = 1 Бумага = 2 0>1>2>0""") while True: p1 = int(input("камень ножницы бумага")) p2 = rand.randint(0,2) if p1 == p2: print("Ничья") elif (p1 == 0 and p2 == 1) or(p1 == 1 and p2 == 2) or (p1 == 2 and p2 == 0): print...
strings a= 'apple is a fruit' a.lower() a.upper() a.title() a.islower() a.isupper() a.istitle() a.startswith('a') a.endswith('e') a.swapcase() a.replace('a','b') a.split() ' '.join(c) range b = list(range(1,11)) for i in b[::-1]: print(i, end =',')
#! python3 # run_tracker.py tracking my monthy stats import shelve def data_entry(): run_data = [] while True: runs = [] month = input('Enter Month:') runs = runs + [month] year = input('Enter year:') runs = runs + [year] dist = input('Enter dist...
#! python3 def median(seq): seq = sorted(seq) if len(seq) % 2 == 0: num_a = seq[int((len(seq)/2)-1)] print(num_a) num_b = seq[int(len(seq)/2)] print(num_b) return (num_a + num_b) / 2.0 else: i = int(len(seq)/2) return seq[i] seq = [4,5,5,4] print(m...
#! python3 def factorial(x): hold = [] result = 1 for i in range(1,x+1): hold.append(i) for j in hold: result = result * j return result num = input("Enter a number: ") print(factorial(int(num)))
""" Random algorithm Places all houses at a random spot. Constrains for this spot are: - a house doesn't overlap with another house - a house doesn't overlap with water - a house fits on the grid """ import random from classes.structure import House def random_placement(area): """ Places a new set of house-objec...
""" The main program to retrieve the solutions of the case. The user will be requested to give input for: the neighbourhood, amount of houses, algorithm and (optionally) the hill_climber. The result of the area will be shown and the data saved in the csv-ouput file. """ import sys import random from time import tim...
""" Program: -------- Program 5 - Query 2 Description: ------------ This program starts by importing help from other files and libraries. A class is created, which allows the MongoDB Server to be accessed by Pymongo, which has various methods for gathering data from MongoDB. There is also some de...
def pop_details(list_details): list_details.pop() #print(list_details) return list_details def remove_details(list_details,val): list_details.remove(val) return list_details def discard_details(list_details,val): list_details.discard(val) return list_details def main(): n = int(inp...
def main(): n = int(input()) s = [] for i in range(0,n): le = input() s.append(le) final_set = set(s) final_set_length = len(final_set) print(final_set_length) main()
text_array = ["x","o","*"] #text that will be used to compose the 3 blooms class Bloom(object): def __init__(self,temp_x,temp_y): max_blossom_spread_x = 80 #maximum width of blossom in pixels max_blossom_spread_y = 80 #maximum height of blossom in pixels...
from queue import * class BinaryTree: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def insert_left(self, value): if self.left_child == None: self.left_child = BinaryTree(value) else: new_node = Binar...
class Node: def __init__(self, data): self.item = data self.ref = None class LinkedList: def __init__(self): self.start_node = None def traverse_list(self): if self.start_node is None: print("list has no element") return else: n = self.start_node while n is not None: print(n.item, " ") ...
# imports the random library to python import random # greets the user with a message about the game print("Hi, welcome to the 'Guess the Number' game!") print("The CPU will guess a number between 1 - 100 and it's your job to guess it in 5 tries or less.") def numGame(): continue_game = 'y' guess = 0 # continues t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ASCII 一个字节 Unicode 2个字节 UTF-8 一个或者3个字节 print('包含中文的str') # ord()函数获取字符的整数表示 chr()将对应的整数转换成字符 print(ord('A')) # 65 print(ord('中')) # 20013 # 字符和字节的相互转换 'abc'.encode('ascii') 'abc'.encode('utf-8') b'abc'.decode('utf-8') # 字符串格式化 print('Hello ,%s' % 'World')
import turtle as t t.pensize(1) t.penup() t.goto(0,0) t.pendown() for i in range(3,9): for l in range(i): t.forward(20) t.left(360/i)
#Ashley Nkomo #09-10-14 #Question 2 Spot Check FirstName = input("Please enter your first name: ") LastName = input("Please enter your last name: ") Gender = input("Please enter your gender: ") if Gender == "male": print("Mr {0} {1}".format(FirstName, LastName)) elif Gender == "female": print("Ms {...
#Ashley Nkomo #30-09-14 #Revision Exercise 4 number1 = float(input("Please enter a number: ")) number2 = float(input("Please enter a second number: ")) number3 = float(input("Please enter a third number: ")) if number3 > number1 and number2: print("The third number entered is larger") elif number2 > nu...
def append(self, s): new = LinkedList() curr = self.head while curr != None: new.add(curr.item) curr = curr.next self.remove() self.add(s) curr = new.head while curr != None: self.add(curr.item) curr = curr.next def rotate(self): new = LinkedList() first = LinkedList() first.add(self.head.item) sel...
# Author: Joe Delia # In 2012-2013, I worked on a research project involving space-filling fractals. # I wrote a program in Python 2.7 that would draw out square- and hexagonal-shaped # fractals. # # This project is porting that original project to Python 3.x, and adding additional # functionality and speed to it as we...
# O uso do Async, Await e AsyncIO no python # O AsyncIO é um módulo que chegou no python 3.4 no qual permite que escrevemos códigos assíncronos # em uma unica thread utilizando Coroutines. # Coroutines # São rotinas cooperativas, ou seja, são rotinas (funções, métodos, procedimentos) que concordam em # parar sua ...
# -*- coding: utf-8 -*- import json class CommonHelper(object): @staticmethod def load_city_list_json(json_file): print "loading cities" cities = dict() with open(json_file) as data_file: city_list = json.load(data_file) for city_info in city_list: ...
''' velocidade_luzsolar = 300 print(velocidade_luzsolar) ''' salario_mensal = input(' Qual é o seu salário mensal? ') horas_trabalhadas_mensais = input(' Quantas horas você trabalha por mês? ') valor_hora = int(salario_mensal) / int(horas_trabalhadas_mensais) print(valor_hora)
######################### # !!! SOLUTION CODE !!! # ######################### class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root...
# example_001 # variable n = 1 x, y = 2, 3 x2 = y2 = 4 s = "hello world" s2 = 'hi' b = True b2 = False print("n:", n) print("x:", x , ", x:", y) print("x2:", x2 , ", y2:", y2) print("s:", s) print("s2:", s2) print("b:", b) print("b2:", b2) print("done") """ [output] ('n:', 1) ('x:', 2, ', x:', 3) ('x2:', 4, ', ...
# input a number print ("enter a number") for x in range(int(input())): print (f"the answer is : {x**2}") #the other coding assignment is in # https://github.com/rajsekharau9/codingchallenge/blob/master/cod-week-02%20day-4.py #assiignment is in # https://github.com/rajsekharau9/assignments ...
import pygame BLACK = (0, 0, 0) def draw_rounded_rectangle(screen, color, x0, y0, width, height, radius): rect1 = [x0, y0+radius, width, height - 2*radius] rect2 = [x0+radius, y0, width - 2*radius, height] pygame.draw.rect(screen, color, rect1) pygame.draw.rect(screen, color, rect2) pygame.draw.ci...
import board b = [[(i, j) for j in range(8)] for i in range(8)] for row in b: print(row) def direction(sqr1, sqr2): if sqr1[0] == sqr2[0] or sqr1[1] == sqr2[1]: return 's' if ((sqr1[0]-sqr2[0]) / (sqr1[1]-sqr2[1]))**2 == 1: return 'd' def between(sqr1, sqr2, sqr3...
''' equation balencer, that balences your chemical or math equations Created on Jun 23, 2016 @author: Lance Pereira ''' import re import numpy from itertools import chain from fractions import gcd from functools import reduce from builtins import max class Equation(): ''' Takes an equation, sp...
students = [] for _ in range(int(raw_input())): name = raw_input() score = float(raw_input()) students.append([name, score]) second_lowest=sorted(list(set([x[1] for x in students])))[1] second_students=sorted([s for s,g in students if g==second_lowest]) for s in second_students: print(s)
import json import pandas as pd import requests from sklearn.base import BaseEstimator, TransformerMixin class CategoriesExtractor(BaseEstimator, TransformerMixin): """ Extract categories from json string. By default it will only keep the hardcoded categories defined below to avoid having too many dummies...
class Sources: ''' Source class to define News Source Objects ''' def __init__(self,id,name,description,url,category,language,country): self.id = id self.name = name self.description = description self.url = url self.category = category self.language = lan...
#! /usr/bin/env python from collections import Counter from sys import maxsize t = int(input()) for it in range(1, t+1): n, l = [int(x) for x in input().rstrip('\n').split()] outlets = [int(x, 2) for x in input().rstrip('\n').split()] devices = [int(x, 2) for x in input().rstrip('\n').split()] devices...
# Base Converter Program - Converts from any desired base to any base ranging # from 2-64. """ Below are the three main variables for the code, the number to change, the original base the number you are converting is in, and the base you would like to convert to. """ n_to_change = raw_input("Number to cha...
import speech_recognition as sr class VOCAB(): def __init__(self): self.death_vocab = ["dead", "die", "death", "decease", "passed on", "passed away", "perish"] self.recovered_vocab = ["recover", "cure", "heal", "rehabilitate"] self.confirmed_vocab = ["confirm", "have coronavirus", "coronav...
from numpy import ndarray import cv2 class Normalizer: @classmethod def crop_make_binary_image(cls, image: ndarray): """ crops the image so that the borders of the picture touch the signature. AND converts image to binary :type image: ndarray :return: numpy.ndarray ...
""" import fibo fibo.fib(1000) fibsi=fibo.fib fibsi(500) """ """ from fibo import fib, fib2 fib(500) """ """ from fibo import * fib(500) """ # In most cases Python programmers do not use this facility # since it introduces an unknown set of names into the interpreter, # possibly hiding some things you have already ...