text
stringlengths
37
1.41M
import multiprocessing from multiprocessing.synchronize import Lock def f(lock: Lock, i: int): lock.acquire() try: print('hello world', i) print('hello world', i + 1) finally: lock.release() if __name__ == '__main__': lock: Lock = multiprocessing.Lock() for num in range(10...
from dataclasses import dataclass import os.path import sqlite3 db_name = 'dvd_lib.sqlite3' def connect(name: str) -> sqlite3.Connection: create = not os.path.exists(name) conn = sqlite3.connect(name) if create: cursor = conn.cursor() cursor.execute("CREATE TABLE dvds (" "id IN...
from queue import Queue from threading import Thread def producer(clerk: Queue): for product in range(10): clerk.put(product) print(f'店員進貨 ({product})') def consumer(clerk: Queue): for product in range(10): print(f'店員賣出 ({clerk.get()})') clerk: Queue = Queue(1); Thread(target = produc...
def account(name: str, number: str, balance: float) -> dict: return {'name': name, 'number': number, 'balance': balance} def deposit(acct, amount): if amount <= 0: print('存款金額不得為負') else: acct['balance'] += amount def withdraw(acct, amount): if amount > acct['balance']: print('...
import random wins = 0 loss = 0 ties = 0 valid_moves = ['r', 'p', 's'] while True: # Ask the player for a move human_move = '' # Set move to empty to enter the loop while human_move not in valid_moves: # Check if player entered a valid move human_move = input('Enter a valid move (r, p, s): ') # A...
""" The goal of this class is to take an unsorted array and return the sorted array. This class will take and store an array, held as a python list object (may change to np.array). The class will contain a variety of sorting methods that can be called. https://www.geeksforgeeks.org/ <- useful source with nice implemen...
def Fileanaly(filename): list = [] with open(filename, 'r') as f: line = f.readlines() for i in line: list.append(i.strip()) return list a = Fileanaly('E:\python学长\qa.txt') print(a)
import random print("H A N G M A N") while True: gameStart = input('Type "play" to play the game, "exit" to quit: ') if gameStart == "play": print("") wordList = ['python', 'java', 'kotlin', 'javascript','rainbow', 'computer', 'science', 'programming', 'python', 'mathematics', ...
# define function to print sort def sortString(str) : str = ''.join(sorted(str)) print(str) a = "131/265 is where I and Sam Live." sortString(a)
# -*- coding: utf-8 -*- # Programa Python otimiza o trabalho do Marceneiro, uma vez definido o tamanho da peça (pedaço) o # programa calculas quantas peças dentro uma metragem maior (taboas). Dessa forma o Marceiro # pode escolher qual a melhor metragem de taboa. # # Acesse e execute esse código Python em: http://pyth...
# -*- coding: utf-8 -*- # Programa Python implementa uma calculadora, com uma função para cada operação básica. # Objetivos: # - uso de funções, variáveis e escopo; # # Módulo: Lógica de programação # Author: Eder Magalhães # Soma todos os elementos contidos no array. def somar(numeros): # é possível utilizar u...
# -*- coding: utf-8 -*- # Programa Python demonstra como inverter um número inteiro. # # Acesse e execute esse código Python em: http://pythonfiddle.com/inverte-numero-ap/ # # Módulo: Lógica de programação # Author: Eder Magalhães numero = int(raw_input("Entre com o nũmero... ")); print "Número informado ",numero nu...
# -*- coding: utf-8 -*- # Programa Python define uma função para verificar se um determinado ano é ou não Bissexto. # Objetivos: # - uso de funções; # - uso de repetições com o comando for in. # # Acesse e execute esse código Python em: http://pythonfiddle.com/ano-bissexto-ap/ # # Módulo: Lógica de programação # A...
# -*- coding: utf-8 -*- # Programa Python utiliza a entrada via teclado para criar e preencher um array de inteiros. # Depois de preencher o array, o programa coloca os números contidos no array em ordem # numérica natural (ascendente). # # Na computação existem vários algoritmos para ordenação dos dados. As diferenç...
def sometuple(array): output = 0 for k in array: output += k return output tuple = [2,3] result = sometuple(tuple) print("some =" , result) tuple2 = [1,2,3] result2 = sometuple(tuple2) print("some = ", result2)
import sqlite3 conexao = sqlite3.connect("redesocial.db") gerenciador = conexao.cursor() #sql = 'create database if not exists redesocial.db;' #gerenciador.execute(sql) sql = ''' create table if not exists usuario( id_usuario integer not null Primary key AUTOINCREMENT, nome varchar(20)...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from inter.interfaces import Environment, Bot class Interaction(object): """ This is rather for test purposes once the robot has learned something from its experience. For the main interaction class please lo...
#!/usr/bin/python3 def no_c(my_string): str_new = "" for position in range(0, len(my_string)): if my_string[position] == 'c' or my_string[position] == 'C': continue str_new += my_string[position] return(str_new)
#!/usr/bin/python3 """ module prints a text with 2 new lines """ def text_indentation(text): """ prints text with 2 new lines argc: text: text """ if type(text) is not str: raise TypeError("text must be a string") for i in range(len(text)): identification = ['.', '?',...
#!/usr/bin/python3 """Documentation for a load_from_json function""" import json def load_from_json_file(filename): """ function that creates an Object from a “JSON file Args: filename: text file """ with open(filename) as file: j_son = json.load(file) return j_son
#!/usr/bin/python3 for alpha in range(97, 123): if alpha not in [101] and alpha not in [113]: print("{}".format(chr(alpha)), end="")
""" THIS PROGRAM AIMS TO IMPLEMENT SENTIMENT ANALYSIS USING PYTHON PROGRAMMING LANGUAGE It receives a line of text as input and the polarity of the text i.e. positive, negative or neutral is returned as output """ __authors__ = ["Anu Mary Abey" , "Athena E."] __version__ = [1] # function definition def...
import sys import re from os import stat def sort_list(lst): type_idx = {} for idx in range(len(lst)): if lst[idx].replace("-", "").isdigit(): type_idx[idx] = "integer" else: type_idx[idx] = "word" # Extract separate lists for word and integers from scrambled_list ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/5 上午11:31 # @Author : Aries # @Site : # @File : py015_common_divisor.py # @Software: PyCharm # 求两个整数的最大公约数,和最小公倍数 # 最大公约数 def getCommonDivisor(number1, number2): temp = abs(number1 - number2) if (number1 % temp) == (number2 % temp) == 0: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/12/8 上午10:58 # @Author : Aries # @Site : # @File : py012_fibonacci_seq.py # @Software: PyCharm ''' python实现斐波那契数列 ''' # 斐波那契数列 f(n) = f(n-1) + f(n-2) def fibonacci_seq(n): if n == 0: return 0 elif n == 1: return 1 else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/5 下午4:24 # @Author : Aries # @Site : # @File : py020_summation.py # @Software: PyCharm ''' 求和 循环崁套的 式计算连续整数之和,要求输出结果如下。如果输 数5,输出连续5个 数字之和: 1=1 1+2 =3 1+2+3 = 6 1+2+3+4 = 10 1+2+3+4+5 = 15 ''' # 求位数之和 # def getStrSum(strArr): # result = 0 #...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/12/21 上午11:58 # @Author : Aries # @Site : # @File : py107_numerical_custom.py # @Software: PyCharm ''' 数值定制 ''' class Time60(object): def __init__(self, hr, min): self.hr = hr self.min = min def __str__(self): retur...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/3 下午1:20 # @Author : Aries # @Site : # @File : py007_leap_year.py # @Software: PyCharm # 判断公元1年到公元3000年中那些是闰年 leap_year = [] for year in range(1, 3001): if year % 4 == 0 and (year % 100 != 0 or year % 100 == 0): leap_year.append(year)...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/17 下午8:48 # @Author : Aries # @Site : # @File : py036_access_dictionary.py # @Software: PyCharm ''' 访问字典 ''' # 1 .遍历字典,使用key() mydict = { 2: 'two', 4: 'four', 6: 'six', 8: 'eight' } for key in mydict.keys(): print key, ',', my...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/7 下午5:15 # @Author : Aries # @Site : # @File : py024_number_triangle_03.py # @Software: PyCharm ''' 样式三 ''' i = 0 j = 0 num = 6 while i < num: i += 1 j = i arr = [] count = 0 # 插入空格符 while count < num - j: arr.app...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/12/8 下午3:48 # @Author : Aries # @Site : # @File : py099_function_02.py # @Software: PyCharm ''' 11-3 函数。 在这个练习中,我们将实现max()和min()内建函数。 (a) 写分别带两个元素返回一个较大和较小元素,简单的max2()和min2()函数。他们应该可以用任意的python 对象运作。 举例来说,max2(4,8)和min2(4,8)会各自每次返回8 和4。 (b) 创建使用了...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/12/8 上午11:57 # @Author : Aries # @Site : # @File : py014_nested_list_sum.py # @Software: PyCharm ''' 递归:嵌套列表求和 ''' def nested_list_sum(numList): sum = 0 for eachItem in numList: if isinstance(eachItem, list): sum += nes...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/22 下午5:46 # @Author : Aries # @Site : # @File : py070_text_processing_01.py # @Software: PyCharm ''' 8-10.文本处理 统计一句话中的元音,辅音及单词(以空格分割)的个数.忽略元音和辅音的特 殊情况,如"h","y","qu"等. 附加题:编写处理这些特殊情况的代码. ''' vowels = ['a', 'e', 'i', 'o', 'u'] def wordCount(my...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/11/20 下午4:46 # @Author : Aries # @Site : # @File : py055_reverse_dictionary.py # @Software: PyCharm ''' 颠倒字典 颠倒字典中的键和值。用一个字典做输入,输出另一个字典,用前者的键做值,前者的值做键. ''' # 使用压缩器 dict1 = { 1: 'Java', 2: 'Python', 3: 'JavaScript' } dict1 = dict(zip(dic...
""" Scrapes movie data from IMdB using BeautifulSoup """ import urllib from bs4 import BeautifulSoup def load_page(url): """ return BS object from the given url """ page = urllib.request.urlopen(url) return BeautifulSoup(page, 'html.parser') def good_imdb_url(url): """ check if url is valid (i.e. from imdb) """ ...
__author__ = 'macuser' class Job(object): def __init__(self, position, salary): self.position = position self.salary = salary class Employee(object): def __init__(self, name, age, position, salary): self.name = name self.age = age self.job = Job(position, salary) joh...
def word_to_integer(): user_input = raw_input("how fast can you run?: ") if user_input.isdigit(): if int(user_input) >= 10: print "You can't run that fast!" word_to_integer() elif user_input.isdigit(): return float(user_input) elif user_input == "zer...
#-*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding("utf-8") import numpy as np class LR(object): def __init__(self): self.b0 = None self.b1 = None #采用最小二乘方法 def LinearRegression(self, X, y): n = float(len(X)) Sx = np.sum(X) Sy = np.sum(y...
import random def dice_roll(num_dice): """Rolls number between 1 and 6 using the random module""" outcomes = [] roll_num = 0 while num_dice != 0: num_dice -= 1 die = random.randint(1, 6) outcomes.append(die) for outcome in outcomes: roll_num += 1 print("Di...
def remove_substring_by_delimiters(super_string, first_delimiter, second_delimiter): while first_delimiter in super_string: substring_start = super_string.find(first_delimiter) substring_end = super_string.find(second_delimiter, substring_start) + len(second_delimiter) super_string = super_s...
def ConvertASCIInPrime(): x=input ("give your input:") while x=="": x=input ("Please give a valid input:") Inascii=''.join(str(ord(k)) for k in x) #print (Inascii) number =int (Inascii) if number > 1: for i in range(2, number): ...
import tkinter as tk from camera import * HEIGHT=550 WIDTH=1300 #MAIN WINDOW root=tk.Tk() root.title("WELCOME") canvas=tk.Canvas(root,height=HEIGHT,width=WIDTH,bg='PeachPuff') canvas.pack() #For background image background_image=tk.PhotoImage(file='l.png') background_label=tk.Label(root,image=backg...
# Найти среднее арифметическое трех последних элементов списка. import random list_length = int(input("Размер списка: ")) my_list = [] for i in range(list_length): numb = random.randint(0, 99) my_list.append(numb) print(my_list) my_list.reverse() print((my_list[0] + my_list[1] + my_list[2])/3)
grade=[100,100,90,40,80,100,85,70,90,65,90,85,50.5] print ("Grades:",grade) #print grades def print_grades(grades): for i in grades: print (i) print (print_grades(grade)) #Sum def grades_sum(grades): total=0 for i in grades: total += i return total print (grades_sum(grade)) #Average d...
# Sci-Kit-Learn is a central library for machine learning in python # Contains most standard regression, clustering and modeling algorithms # Features to modeling such as prepocessing, cross validation and data pipelines import sklearn # Load data because of great compatilibity with pandas import pandas as pd import ...
def my_basic_function(a,b): print a**b my_basic_function(3,4) a = 10 def print_increment(a): a += 1 print a print_increment(a) print a def summed_squares(a,b,c): return a**2 + b**2 + c**2 print summed_squares(1,2,3) c = summed_squares(1,2,3) print c def is_prime(numerator): denominator = ...
zoo_animals=["pangolin","cassowary","sloth","lion"]; if len(zoo_animals)>3: print ("The first animal at the zoo is the "+ zoo_animals[0]) print ("The second animal at the zoo is the "+ zoo_animals[1]) print ("The third animal at the zoo is the "+ zoo_animals[2]) number=[5,6,7,8] print ("Adding the numbe...
""" Authors: Perry Gowdy (pgowdy1@gmail.com) License: GPL 3.0 Description: This file contains a function that allows the user to change volume of a .wav file at specific segments Comments: None. """ from lib import pydub """ Input: filename , gaptime, gaplength, decibel filename (string): the path to the soundfile...
"""A general-purpose DB class for storing nested sequential data.""" import numpy as np SAMPLE = 0 SEQUENCE = 1 class BasicDB(object): """ Base class DB """ def __init__(self, keys=(), db=None): """ Constructor :param keys: db keys :param db: external data dictionary...
# Given [3,4,5,7,12,13,14,18] return a string noting the continuous ranges ei: "3-5, 7, 12-14, 18" # Page 61 of the algos book # First Iteration # def bookmarkIndexes(arrInput): # strOutput = str(arrInput[0]) # lastConsecutive = arrInput[0] # for i in range(1, len(arrInput)-1, 1): # if type(arrInp...
from Kurs import Kurs kurser = [] def add_course(): global kurser print("\nLägg till kurs:") name = input("Namn: ") points = int(input("Poäng: ")) grade = input("Betyg: ") kurs = Kurs(name, points, grade) kurser.append(kurs) def calc_merit(): global kurser total_points = 0 ...
abc="with three words" xyz=abc.split() print xyz print len(xyz) print xyz[0] for w in xyz: ///// print w line= "a lots of spaces" etc=line.split() print etc line= "first;second;third" thong=line.split() print thong //// print len(thong) thong=line.split(";") print thong print len(thong)
#Triangle Quest #You are given a positive integer N. Print a numerical triangle of height N-1 like the one below: #1 #22 #333 #4444 #55555 #...... #Can you do it using only arithmetic operations, a single for loop and print statement? #Use no more than two lines. The first line (the for statement) is already written f...
#power-ModPower #Task #You are given three integers:a,b,and m, respectively. Print two lines. #The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). #Input Format #The first line contains a,the second line contains b,and the third line contains. #Sample Input #3...
#1. Write a Python program to print the following string in a specific format (see the output). #Twinkle, twinkle, little star, #How I wonder what you are! # Up above the world so high, # Like a diamond in the sky. #Twinkle, twinkle, little star, # How I wonder what you are print ("Twinkle twinkle little ...
# 29. Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2. # color1 = ["saffron","orange","pink","blue","black","magenta"] # color2 = ["black","blue","magenta","white","pink","orange","green"] # common = set(color1).intersection(color2) # print (...
# # # 24. Write a Python program to test whether a passed letter is a vowel or not. # # def vowels(char): # # if char == ("a"): # # return ("vowel") # # else: # # return ("consonant") # # if char == ("e"): # # return('vowel') # # else: # # return('consonant') # # if char == ("i"): # # re...
#mutable #You are given an immutable string, and you want to make changes to it. s=raw_input("") #take a string like abrakadabra l=list(s) #convert the given string s into list l a,b=(raw_input("")).split() #take a variable a and b with space like 5 k a=int(a) # variable a represent integer value lets take 5 l[a]= b ...
#7. Write a Python program to accept a filename from the user print the extension of that. #Sample filename : abc.java #Output : java s='abc.java' print s[4:] abc=raw_input('file name') pqr=abc[4:] print(abc) print(pqr) abc=raw_input('') pqr=abc.split('.')[-1] # print only extension after "." print(abc) print(pq...
""" Пример программы для расчета почасовой зарплаты Данные - пользователь вводит стоимость часа (число) - пользователь вводит количество дней (число) Сделать - найти размер оплаты в руб (по кол-во дней) - найти размер налога 13% в руб (по кол-во дней) """ while True: try: hour_cost = int(input("Введите с...
import sys, time, argparse print = sys.stdout.write class Tower: def __init__(self, n=0): self.floors = [i for i in reversed(range(1, n+1))] def stack(self, floor): if len(self.floors) > 0: assert floor < self.floors[-1], "Tower must be shaped pyramid, {}".format(self.floors) ...
weight = eval(input('masukkan berat badan anda ')) height = eval(input('masukkan tinggi badan anda (dalam cm) ')) height = height/100 bmi = weight/(height*height) print(bmi) if bmi<15: print('Very severely underweight') elif 15<=bmi and bmi<16: print('Severely underweight') elif 16<=bmi and bmi<18.5: print...
from socket import * from config import * from pickle import * import argparse import os """ Parsing the Command Line Arguments by using ArgParse Module""" # Checking if host entered exists or not class check_host(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): try: ...
#variable controls loop and holds operation choice val_operation = -1 #function that calculates inputs base of operation choice def calc(num1, num2, op): if(op == 1): return num1+num2 elif(op == 2): return num1-num2 elif(op == 3): return num1*num2 elif(op == 4): return num1/num2 #while loop ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def computeCost(X,y,theta): m=y.size cost=0 cost=sum((np.dot(X,theta)-y)**2)/(2*m) return cost def gradientDescent(X,y,theta,alpha,iterations): m=y.size J_history=np.zeros((iterations,1)) for i in range(iterations): ...
# -*- coding: utf-8 -*- """ Created on Sun Sep 13 20:02:51 2020 @author: Andreas Fiehn """ import numpy as np def removeIncomplete(id): # removes decimal by converting to int idInt = id.astype(int) # Numbers are counted and ordered (number, count) = np.unique(idInt,return_counts = True) # A...
# -*- coding: utf-8 -*- """ Created on Tue Sep 29 21:18:59 2020 @author: Andreas Fiehn """ import numpy as np def thermoEquilibrium(N, r): t = 0 NL = N NR = 0 # Loop as long as NL and NR are not the same # I expect r to contain enough numbers to not end up in an infinite loop while...
import tkinter as tk from tkinter import messagebox as msg import auth #auth.read_auth_data(path) class LoginFrame(tk.Frame): def __init__(self, parent, controller): # ID and password text boxes plus labels, save inputs to variables for future use # Set up the frame and create all buttons ...
class User: ''' Class to create user accounts and save their information ''' # Class Variables # global users_list users_list = [] def __init__(self,first_name,last_name,password): ''' Method to define the properties for each user object will hold. ''' # instance variables self.first_name = first_name...
import os import re import sys def prep_fldr(): '''Asks user for abs path to directory, then checks if directory exists, if directory does not exist, creates directory''' print 'Provide empty directory to store output of script' fldr = raw_input('Empty Output directory: ') if os.path.exists(fldr): ...
factors = list() def find_factors(n): i=2 print "n=" + str(n) while(i<=n): if n%i==0: factors.append(i) n = n/i else: i+=1 return factors find_factors(100) print factors
# .format function # .format function in fizz/buzz example # .looping and modulo operator % # .https://pyformat.info/ if __name__ == "__main__": name = "Martin" second_name = "Gic" print("{} {}".format(name, second_name)) for x in range(100): fizzValue = "fizz" if x % 10 == 0 else "" buzzValue = ...
# list comprehensions in Python # list comprehension of a class variables of a list # list list_1 = range(10) print(list_1) # multiplying each element of the list with 2 list_2 = [elem * 2 for elem in list_1] print list_2 # dividing each element from the list list_3 = [float(elem) / 5 for elem in list_2] print list_...
# -*- coding: utf-8 -*- """ Cameron Reading Data 119 Python 1 4/24/19 In-Class Assignment """ import random ''' Function that will open files that contain a list of states and states capoitals, and return a completed dictionary that will be used for the quiz! ''' def states_and_capital_dictionary(): state_name_li...
# -*- coding: utf-8 -*- """ Cameron Reading Data 119 Python 3/20/2019 In-Class Work/Practice """ excellent_words = ["Dogs", 'Cats', 'Hamsters', 'Seals', 'Birbs'] for word in excellent_words: print(word, '', end = '') print('') user_num_choice = int(input("Pick a number from 1 through 5: ")) print("The anim...
# -*- coding: utf-8 -*- """ Cameron Reading 2/27/2019 In-Class Practice A simple program that tells you what day it is """ user_num = int(input("Please enter a number from 1 to 7, and I will tell you what day it is! ")) if user_num == 1: print("It's Monday!") elif user_num == 2: print("It's Tuesday!") elif u...
def partial_pivot(a,b): for i in range((len(a))-1): if(a[i][i]==0): for j in range(i+1,len(a)): if(abs(a[j][i]) > abs(a[i][i])): a[i],a[j]=a[j],a[i] b[i],b[j]=b[j],b[i] def gauss_jordan(a,b): partial_pivot(a,b) for i in range(len(a)): pivot=a[i][i] for j in range(i,len(a)): a[i][j]=a[i][j]...
# File Name: largestProductInAGrid.py # Author: Esther Heralta Espinosa # Date: 04/06/19 # Description of the program: We have a 20 x 20 grid of numbers # What is the greatest product of four adjacent numbers in the same direction # (up, down, left, right, or diagonally) in the 20 x 20 grid? MAX_ADJAC...
# File Name: non-abundantSums.py # Author: Esther Heralta Espinosa # Date: 04/21/19 # Description of the program: A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. # For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, # ...
# File Name: primeNumber.py # Author: Esther Heralta Espinosa # Date: 04/05/19 # Description of the program: By listing the first six prime numbers: # 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 1000 prime number? MAX = 1000 def isPrime(number): """ returns true if the...
#!/usr/bin/python3 import re path = 'puzzleinputs/day2.txt' lines = open(path, 'r').read().splitlines() def valid_password_1(line): splitted = re.split(' ', line.replace(':', '')) numbers = list(map(int, re.split('-', splitted[0]))) char = splitted[1] pw = splitted[2] count = sum(map(lambda x: 1...
import compare import random # All different sorting methods # Not all of them work def bubble(list, connn, inactive_clients): for i in range(len(list) - 1, 0, -1): for b in range(0, i): if compare.left_is_smaller(list[b], list[b + 1], connn, inactive_clients): pass else: list[b], list[b + 1] = list...
''' Description: Nathan loves cycling. Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling. You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value. For example: time = 3 ----> litres = 1 time ...
list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] print(f"Исходный список: {list}") new_list = [] new_list = [el for el in list if el < list(el+1)] # как обратиться к следующему значению списка? print(f"Новый список: {new_list}")
test = [2, 7, 11, 15] def two_sum_by_hash(nums, target): h = {} for i, num in enumerate(nums): if (target - num) in h: return h[target - num], i else: h[num] = i def two_sum(nums, target): i = 0 while nums: num = nums.pop(0) if (target - num) i...
""" Written by Mohammad Qureshi Goes through all titles in the database and POS tags them to find a common structure to be used as a template """ import nltk import json from collections import defaultdict with open("comments.json", encoding='utf-8') as data: # create a dictionary to hold POS structure and numb...
""" Sample programs for the simple microprocessor """ """ Adds the values in memory positions 0 and 1 and sets r0. It keeps INC [0] and DEC [1] until value in [1] is zero. """ add_values = """ MOV 0, 5 MOV 1, 3 INC 0 DEC 1 MOV r0, [1] JNZ 2 MOV r0, [0] """ """ Sets in r0 the maximum va...
import random import numpy as np class Piece(): """ A Tetris piece. The piece can have one of five shapes: Stick, L-shaped, inverse-L, inverse-S, or a Block. Parameters: * x: The position on the x-axis. * y: The position on the y-axis. * shape: An integer between 0 and 4 for one of the ...
my_list = ["cat", 2, "dog", 4] if 2 in my_list: print('yes') else: print('no')
# -*- coding: utf-8 -*- from Tkinter import * CANVAS_WIDTH = 600 CANVAS_HEIGHT = 600 CELL_X = CELL_Y = 35 def paint_grid(canvas): for x in range(CELL_X, CANVAS_WIDTH, CELL_Y): canvas.create_line(x, 0, x, CANVAS_HEIGHT, fill="black") for y in range(CELL_X, CANVAS_HEIGHT, CELL_Y): canvas.create_line(0, y, CANVAS_...
import math def primeFactorizationMaxi(num): while num%2 == 0: num/=2 #print 2 maxi = 2 if num == 1 : return 2 for i in range(3,int(math.sqrt(num))+1,2): while num%i == 0 : num/=i ...
from datetime import datetime class SensorReading(object): def __init__(self, data): self._data = data self._created = datetime.strptime(self._data['created_at'], '%Y-%m-%dT%H:%M:%S.%fZ') @property def value(self): return self._data['value'] @property def location(self): ...
from math import log "HELPER FUNCTIONS BELOW THIS LINE" "_____________________________________________________________________________________________" def reader(filename): f = open(filename, 'r') lines = [line.strip() for line in f.readlines() if '>' not in line] f.close() return lines def GC_cou...
# Finding the order/all points on elliptic curve # y^2 = x^3 + Ax + B(mod p) def squareAndMultiply(r, m): total = r mString = bin(m)[2:] for i in range(1, len(mString)): total *= total if(mString[i] == '1'): total *= r return(total) A = 7 B = 15 p = 3571 root1 = 0 root2 = 0 r = 0 m = (p+1)//4 count = 1 fo...
import os #The Main function of the moudlue. #Can Delete String in one file or run on all files in folders and delete a string inside. def Delete(File_Name, StringToBeDelted): print("Delete Script Activated:\n") #Test for which operation: change on file or running on all files. operation = File_Nam...
# Returns a dataframe with the average unemployment rates grouped by year # Could be more malleable if we leave the grouping to pandas # But this is a very specific question. def average_unemployment_rate(): query = """ SELECT date_trunc('year', observation_date), AVG(value) avg_yearly_unemployment_rate F...
cost=float(input()) tip=int(input()) tax=int(input()) final=cost+(cost*tip/100)+(cost*tax/100) print(round(final))
# There are four collections # list # tuples # set # dictionary # list - collection of ordered and changeable thislist = ["apples", "bananas", "cherry", 2, 1, 2, 4] print(len(thislist)) if 2 in thislist: print("Yes") thislist[4] = True thislist.insert(2, "melons") thislist.append("Mangoes") thislist.remove(4) ...
#9번, B835193 석채원 strin = input("문자열을 입력하시오:") letter = input("문자를 입력하시오:") #count indicates the number of letters within the string count = 0 for i in strin: if(i==letter): count+=1 if(i=='$'): break; print(count)
#2번문제 import random x = random.randint(0, 100) y = random.randint(0, 100) z = x + y print(x, '+', y, '의 값은?', end='') calculation = int(input()) while z != calculation: print('틀렸습니다.') print(x, '+', y, '의 값은?', end='') calculation = int(input()) else: print('맞았습니다.') ...