text
stringlengths
37
1.41M
#Realizar un programa que cumpla el siguiente algoritmo utilizando siempre que sea posible operadores #de asignación numero_magico = 12345679 #numeros enteros entre el 0 al 65.535 numero_usuario = int(input("Ingrese un numero entre el 1 al 9: ")) numero_usuario *= 9 numero_magico *= numero_usuario print(f"El número m...
#Realiza un programa que sume todos los números enteros pares desde el 0 hasta el 100. num_par=list(range(0,101,2)) print(num_par) print(f"La suma de los numeros pares de la lista {num_par} = ", sum(num_par) )
'''Realiza un programa que pida al usuario un número entero del 0 al 9, y que mientras el número no sea correcto se repita el proceso. Luego debe comprobar si el número se encuentra en la lista de números y notificarlo: Concepto útil La sintaxis [valor] in [lista] permite comprobar si un valor se encuentra en una ...
'''Dadas dos listas, debes generar una tercera con todos los elementos que se repitan en ellas, pero no debe repetirse ningún elemento en la nueva lista:''' l_1 = ['E', 'l', ' ', 'a', 'm', 'o', 'r', ' ', 'e', 't', 'i', 'e', 'm', 'p', 'o', 's', ' ', 'd', 'e', ' ', 'c', 'l', 'e', 'r', 'a'] l_2 = ['H', 'o', 'l', ...
# Simple Snake Game in Python 3 import turtle import time import random delay = 0.1 # Score Pontuacao = 0 Pontuacao_maxima = 0 # Set up da tela wn = turtle.Screen() wn.title("Snake Game by Luan Jesus") wn.bgcolor("purple") wn.setup(width=600, height=600) wn.tracer(0) # Snakehead head = turtle.Turtle() head.spee...
choice = input("""Type 1 for a Gift, Type 2 for a surprise, Type for free fortnite Vbucks link: """) if choice == '1': print("here take a gift") elif choice == '2': print("Surprise!") elif choice == '3': print("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab")
products = []#products是大火車,裝大清單,裝一組一組的小p;p小火車裝小清單,一個商品一個清單 while True:#while迴圈通常用在不確定幾次的迴圈 name = input('請輸入商品名稱: ') if name == 'q': break price = input('請輸入商品價格: ') products.append([name, price])#將每1小組的p清單裝入products大清單中 print(products )#會印出[['01','02'], ['11', '12']]有2個[] for p in products: print(p[0], '的價格是',...
from Registration import Registration def GetVehicleDetails(): from Vehicle import Vehicle print("1. Enter Car details: ") print("Make: ") make = input() print("Model: ") model = input() print("Price: ") price = input() print("Color: ") color = input() vehicle = Vehicle(mak...
from core.src import admin, student, teacher view_map = { "1": student, "2": teacher, "3": admin } def run(): while 1: choice = input(''' 1:学生视图 2:老师视图 3:管理视图 (输入q退出) >>> ''') if choice == "q": print("已退出,结束程序") break if choice in view_map: ...
import random import NEMO print random.randrange(1,5) def main(): ans = random.randrange(1,11) keepGoing = True while keepGoing: guess = NEMO.userInt("Enter a guess from 1 to 10:") if guess == ans: print "You win!" keepGoing = False main()
import NEMO import random #------------------------------------------------------------------------------- # selects a random word from a file and returns it #------------------------------------------------------------------------------- def pickWord(): words = [] # read the file and place each word in o...
from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score import re import pandas as pd import sklearn import matplotlib.pyplot as plt import time #Import and read the dataset df = pd.read_csv(r'data/Corona_NLP_train.csv') # M...
from Projectile import Projectile from time import sleep startingVelocity = float(input("What is the initial velocity of the projective? ")) angle = float(input("What angle was the projectile launched at? ")) starting_height = float(input("What was the starting height of the object? ")) myProjectile = Projecti...
rivers = { 'nile' : 'egypt', 'mississippi' : 'usa', 'red' : 'somewhere' } for river, location in rivers.items(): print("The {} river is located in {}".format(river, location)) print(river) print(location)
class User: def __init__(self, first, last, age): self.first_name = first self.last_name = last self.age = age def describe_user(self): print("{} {} is {} years of age.".format(self.first_name, self.last_name, self.age)) def greet_user(self): print("Hello {}, welcome....
pizza = ['supreme', 'meat', 'pineapple'] for choice in pizza: print(choice) print("Nothing else compares to {}".format(choice)) print("I really, really like pizza")
names = ['nicki minaj', 'sabrina claudio', '6lack'] print('{} you are invited.\n{} you are invited.\n{} you are invited.'.format(names[0], names[1], names[2])) print(len(names))
vacation = {} poll_active = True number = 1 user = None while poll_active: print("If you can visit one place in the world, where?") user = input("> ") vacation[str(number)] = user number += 1 print(vacation) if user == 'q': poll_active = False print("Exiting")
#!/usr/bin/python # -*- coding: UTF-8 -*- '''题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。 程序分析:关键是计算出每一项的值。 程序源代码:''' a=input('输入要相加的数是:') n=input('相加的数个数为:') s=a end=0 for i in range(n) : a=a*10+s print a end =end +a print end
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。 最后问第一个人,他说是10岁。请问第五个人多大? 程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推,推到第一人(10岁),再往回推。 程序源代码: ''' s=8 for i in range(1,6): s=s+2 print ('第%d个人的岁数是%d'%(i,s))
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:求1+2!+3!+...+20!的和。 程序分析:此程序只是把累加变成了累乘。 ''' def sum(n): w=0 all=0 for i in range (1,n+1): s=1 for j in range(1,i+1): s=s*j w =s print 'w',w all =all+w print 'all',all sum(20)
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数 程序分析:无。 程序源代码: ''' from collections import deque m = 3 a = [1,2,3,4,5,6,7] # 7 个数 f = deque(a) f.rotate(m) print list(f) ######方法2 m = 3 a = [1,2,3,4,5,6,7] def rot(a,n): l = len(a) n = l-n return a[n:l]+a[0:n] ...
#!/usr/bin/python # -*- coding: UTF-8 -*-\ ''' 题目:列表排序及连接。 程序分析:排序可使用 sort() 方法,连接可以使用 + 号或 extend() 方法。 程序源代码: ''' if __name__=="__main__": str1=[1,3,2,7,6,5] str2=[3,3,3] str1.sort() print str1 str3=str1+str2 str1.extend(str2) print str3 print str1
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。 程序分析:首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。 程序源代码: ''' import numpy as np a=([1,3,4,5,7]) y=input('输入一个数字:') a.append(y) a.sort() print a
#!/usr/bin/python # -*- coding: UTF-8 -*- '''题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。 程序分析:无。 程序源代码:''' sting= raw_input('please input 5 string:') x=len(sting) w=[] for i in range(x): w.append(sting[x-i-1]) print w
name = 'steven' result ='eve' in name print(result) #not in result = 'tv' not in name print(result) #r 保留原格式 有r就不转义,没有r则转义 name = 'jason' print(r'%s: \'hahaha!\''%name) filename = 'picture.png' print(filename[5]) #通共【】结合位置获取字母,只能一个 #包前不包后 print(filename[0:7])#0123456 print(filename[3:])#省略后面就一直到结尾 print(filename[...
#字符串的格式化输出 #format 也是一种格式化输出,用{}占位然后 .format调用,不管type age = 2 s = 'already' message = ' George said: I am {} years old,{} go to school'.format(age,s) print(message) name = 'George' age = 3 hobby = 'Game' money = 5.89 message = '{} is {} years old, love {}, and have {} dollars'.format(name, age, hobby, money) print(mes...
# Question 3 print("What is your number:") num_str = str(input()) num_list = [] sum = 0 # Loop through the numbers for i in num_str: if i == "2": continue elif i == "9": i = int(i) i *= 2 # create a list of numbers with each number as a string num_list.append(str(i)) # sum the elements ...
# Question 2 print("What is your number:") num_str = str(input()) num_list = [] sum = 0 # Loop through the numbers for i in num_str: # create a list of numbers with each number as a string num_list.append(i) # sum the elements sum += int(i) # join all items into one string seperated by " + " a = " + ".join(n...
class Binary: # Binary Class | used for converting binary to other 3 formats def toDecimal(self, binary): # Converts binary to decimal remainder = 0; maxlength = len(str(binary)); length = 0; decimal = 0 while length <= maxlength: remainder = binary % 10 decimal += (rema...
""" open file """ import csv def copy_book_list(): with open("BooksRead.csv") as infile: csv_reader = csv.reader(infile) with open("new_book_list.csv", "w") as new_file: new_csv = csv.writer(new_file, delimiter='\t') for line in csv_reader: new_...
"""Merge Sort Algorithm. The Merge Sort is a recursive sort of order n*log(n). It is notable for having a worst case and average complexity of O(n*log(n)), and a best case complexity of O(n) (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have...
# -*- coding: utf-8 -*- #Lesson: while structure x = 1 y = 5 def compare_values(x, y): if x > y: #print("x is higher than y") return "x is higher than y" else: if x == y: #print ("x is the same than y") return "x is the same than y" else: #p...
''' Some calcs for analog filters. ''' import all_pass def rc_f(r, c): ''' Calculate the cutoff frequency of a simple RC filter. r = resistance (ohms) c = capacitance (F) ''' from math import pi return 1.0/(2.0*pi*r*c) def rc_r(f, c): ''' Calulate the resistance required for a simple RC filter. f = c...
from collections import OrderedDict class LRUCache(OrderedDict): def __init__(self, limit=10): self.maxsize = limit """ Retrieves the value associated with the given key. Also needs to move the key-value pair to the top of the order such that the pair is considered most-recently used. Returns...
import sys import ast def perceptron(A, w, b, x): sum = 0 for f, o in zip(w, x): sum+=int(f)*int(o) return A(sum+float(b)) def step(num): if num>0: return 1 else: return 0 #XOR HAPPENS HERE def perceptron_network(input_val): o3 = perceptron(step, (2, 2), -1, input_val)...
def PairsofSum(arr, n, k): count = 0 list = [] # Pick all elements one by one for i in range(0, n): # See if there is a pair of this picked element for j in range(i+1, n) : if arr[i] + arr[j] == k or arr[j] + arr[i] == k: ...
import sys import re __book = {} def add(): """Function adds a name (str) and a number (int) in the dict. Name and number need to be entered. Function checks if the amount of digits in number are 6 or 11. :raises: ValueError """ key = input("Enter a name: ") if not key.isalpha(): ...
#!/usr/bin/env python def validate(low_bound=0, upper_bound=256): """Estimates function parameters (there should be three of them between low_bound and upper_bound). If they aren't, prints "Function call is not valid!". :param low_bound: int. 0 by default :param upper_bound: int. 256 by default :re...
class Price: """Checks parameters (0-100).""" def __init__(self, label): self.label = label def __get__(self, instance, owner): print("Descr.__get__") return self.__dict__[self.label] def __set__(self, instance, value): print("Descr.__set__") if value < 0 o...
#Richard Burke #9/17/18 #Programming in Python #HW 2-3 #initialize i = 0 NUM_DAYS = 7 highest = 0 #loop through for each day, comparing highest to each input while (i < NUM_DAYS): numBugs = int(input("Enter score: ")) if numBugs > highest: highest = numBugs i+=1 #print highest p...
def cubic_algorithm(array): global_max_sum = 0; index_i = 0; """for each element of the array""" for i in array: local_max_sum = 0; #print("\n ******************************************************* value i:", i) #print("\n i to end array", array[index_i:len(array)]) inde...
def primeChecker(num, printPrime = False): isPrime = True factors = [1] for x in range(2,(num-1)): if num % x == 0: factors.append(x) isPrime = False factors.append(num) if printPrime == True: if isPrime == True: print(str(num) + ' is Prime!!!') ...
# Autor: Roberto Emmanuel González Muñoz A01376803 # Programa que combina letras checa si tiene vocales, # forma un nombre de usuario y checa si un nombre esta escrito correctamente. def combinarLetras(cadena): counter = 0 cadenaB = [] for i in range(len(cadena)): counter += 1 if...
# Import the necessary package to process data in JSON format try: import json except ImportError: import simplejson as json # We use the file saved from last step as example tweets_filename = raw_input("file name: ") tweets_file = open(tweets_filename, "r") #output_file = open("test_converted.txt", "w") #tota...
def RepresentsInt(s): try: int(s) return True except ValueError: return False n=input() for i in range(n): s=raw_input() s=raw_input() s=s.split() # print s if RepresentsInt(s[0]) and RepresentsInt(s[2]): print s[0]+' + '+s[2]+' = '+str(int(s[0])+int(s[2])) elif RepresentsInt...
def cnt(n,i,l): if i==n: return 1 else: if l==1: return cnt(n,i+1,3) elif l==3: return cnt(n,i+1,1)+cnt(n,i+1,5) elif l==5: return cnt(n,i+1,7) elif l==7: return cnt(n,i+1,5)+cnt(n,i+1,3) t=input() while t: t-=1 a=input() print cnt(a,1,1)+cnt(a,1,3)+cnt(a,1,5)+cnt(a,1,7)
s = "Ola Mundo"; print(s) num1 = 10 num2 = 20 if num1 > num2: print("Número 1 é > que Número 2") else: print("N2 > que N1")
neerslag = input("Geef de hoeveelheid neerslag (overvloed, veel, matig, geen): ") dagen = 7 templist = [] neerslagen = [] laagste = 50 som = 0 veel = False while dagen != 0 and neerslag != "overvloed": dagen -= 1 temperatuur = int(input("Geef de temperatuur (gehele getallen): ")) templist.append(temperatuur...
fahrenheit = float(input("Geef het aantal graden fahrenheit: ")) celcius = (fahrenheit -32) / (9/5) print(int(celcius*10 + 0.5) / 10)
list = [] text = input("Geef een tekst: ") text = text.lower() for letter in text: if ord(letter) >= ord("a") and ord(letter) <= ord("z"): list.append(letter) list.sort() teller = 1 for letter in list: while list.count(letter) > 1: list.remove(letter) teller += 1 print(letter,"komt"...
afstand = 36 inschrijvingsnummer = int(input("geef het inschrijvingsnummer: ")) tijd = int(input("tijd in seconden: ")) langer_dan_uur = 0 snelste_tijd = tijd teller = 0 while inschrijvingsnummer >= 0: teller += 1 if tijd >=3600: langer_dan_uur += 1 if tijd < snelste_tijd: snelste = inschri...
def betpaal_vervoer(code): if code == 1: vervoer = "met de bus" elif code == 2: vervoer = "te voet" elif code == 3: vervoer = "met de trein" else: vervoer = "met de auto" return vervoer teller_auto = 0 minumum = 3600 #Hoog getal omdat het altijd lager gaat zijn, Grot...
brutoloon = int(input("Geef het brutoloon: ")) jaarlijks_vakantiegeld = 0.05*brutoloon if jaarlijks_vakantiegeld >= 350: jaarlijkse_bijdrage = 0.08*350 else: jaarlijkse_bijdrage = 0.08 * jaarlijks_vakantiegeld print("Brutoloon = ",brutoloon, "vakantiegeld = ",jaarlijks_vakantiegeld, "jaarlijkse bijdrage = ",ja...
tekst = input("Geef een tekst: ") positie = tekst.lower().find("t") if positie == -1: print("geen letter T in tekst") else: if len(tekst) % 2 != 0: tekst = tekst[:positie] + tekst[positie:].upper() else: tekst = tekst[:positie] + tekst[positie:].lower() print(tekst)
for i in range(-10, 11, 1): if i > 0: print("+" + (str(i))) else: print(i) #efficienter: for i in range(-10,1): print(i) for i in range(1,11): print("+"+str(i))
getallenlijst = [] getal = int(input("geef getal, 0 om te stoppen: ")) while getal != 0: if getal not in getallenlijst: getallenlijst.append(getal) else: print(getal, "komt voor op plaats", getallenlijst.index(getal)) getallenlijst.remove(getal) getal = int(input("Geef een getal, 0...
def ZetOmNaarRomeinsCijfer(getal, romeins, cijfer): uitkomst = 0 for i in range(len(waarde)): aantal = getal // waarde[i] getal = getal % cijfer[i] uitkomst += aantal * romeins[i] return uitkomst from random import randint roman = ["XL", "X", "IX", "V", "IV", "I"] waarde = [40, 10,...
# Exercises from book chapter 3 # 1. List of diary products dairy_section = ['Cheese', 'Milk', 'Butter', 'Cream'] # 2. Print first and last element first = dairy_section[0] last = dairy_section[len(dairy_section)-1] print("First is %s, Last is %s" % (first, last)) # 3. Tuple with expiration date parts milk_expiratio...
''' Three parts to list comprehension 1. the loop 2. the transformation 3. filtering ''' mylist = [1, 2, 3, 4, 5] modlist = [] for i in mylist: j = i * 2 modlist.append(j) print(modlist) mylist = [100, 200, 300, 400, 500] r, t = 10, 1 #modlist = [lambda p: p*t*r/100 for p in mylist] #print(modlist) ...
import re text_to_search = ''' Regular Expressions Basics 1. Always safer to use raw strings (r'' | r""). Tells Python not to handle special characters in any way And rather pass the string as it is to the objects r'' on patterns doesn't have any impact 2. re.match() matches starting a...
""" File: Sqr_mult_logic Name: Matt Robinson Description: This file is going to just be a test to see if I can successful write a program to do SQR and MULT for me Language: Python """ def square_and_multiply(base, exponent, modulo): """ Function: square_and_multiply Description: The main logic for the Sq...
import sys def read_file(file): item_list = [] with open(file) as f: for line in f: line_lst = [int(x) for x in line.split(' ')] item_list.append(line_lst) return item_list def return_max_value_knapsack(items, weight): n = len(items) w = weight + 1 a = [0 for i ...
str = input('Enter the string:- ') new_str = str[::-1] print(new_str)
from random import randrange n = int(input('Enter no of times the coin should be tossed: ')) h = 0 t = 0 for i in range (1, n+1): s = randrange(2) if s == 0: h += 1 else: t += 1 print('Head:- ',h) print('Tail:- ',t)
print("factorial(!)") print("enter a number") x=int(input()) product=1 if x==0: product=1 if x==1: product=1 while x>1: product=product*x x=x-1 print("factorial is ",product) m=input("\n press the enter key to exit")
import os import yaml import logging def yaml_file_to_dict(config_file, base_config=None): """ Adds extra configuration information to given base_config """ # validate input base_config = base_config or {} if not os.path.exists(config_file): raise SystemExit("Extra config file not found: {}".f...
# -*- coding: utf-8 -*- """ Created on Wed Oct 7 20:25:41 2020 @author: JOliv """ #PANDAS #Instalacion de Pandas #!pip install pandas #!pip install numpy import pandas as pd import numpy as np """ NOTA IMPORTANTE: si alguna linea no hace nada aparentemente, correr con f9 """ #%% """ SERIES ...
import numpy as np import cv2 ## Black Image and displaying it ## black = np.zeros([200,200,1], "uint8") cv2.imshow("Black Image", black) print("pixel value in black image is", black[0,0]) ## Black Image with three channels and displaying it ## ones = np.ones([200,200,3], "uint8") cv2.imshow("Ones", ones) ...
import cv2 import numpy as np image = np.ones((512,512,3), np.uint8) print(image) image[:] = 255,0,255 ################ RECTANGLE ##################### ## Deifne Rectangle with points ## cv2.rectangle(image,(0,0),(255,255),(255,255,0),3) ## Cv2.FILLED is used to fill the space of the shape ## cv2.recta...
import cv2 cap = cv2.VideoCapture(0) color = (255,0,234) line_width = 3 radius = 100 point = (0,0) ### Initialize the Event Click ### def click (event, x, y, flags, param): global point, pressed if event == cv2.EVENT_LBUTTONDOWN: print("pressed", x,y) point = (x,y) ### Name the W...
''' Esteban Camarillo ID#: 1636095 ''' team={} i=1 count=1 for i in range(1,6): jersey = int(input('Enter player {}\'s jersey number:\n' .format(i))) rating = int(input('Enter player {}\'s rating:\n\n' .format(i))) if jersey < 0 and jersey > 99 and rating < 0 and rating > 9: print('inva...
def nama_function(name, job): print("Hi {}, your job is {}".format(name, job)) def tambah(a, b): """tambah untuk menambahkan dua bilangan a dan b""" return a + b kali = lambda x, y: x * y nama_function("Budi", "Security Consultant") print("tambah(2,5) = {}".format(tambah(2, 5))) print(tambah.__doc__) ...
import copy n = int(input()) a = list(map(str,input().split())) a_b = copy.deepcopy(a) a_s = copy.deepcopy(a) # バブルソート def bubble(a_b, n): for i in range(n): for j in range(n-1,i,-1): if int(a_b[j][1]) < int(a_b[j-1][1]): tmp = a_b[j] a_b[j] = a_b[j-1] ...
n = int(input()) ans_list = list() for i in range(1,n+1): if i % 3 == 0: ans_list.append(str(i)) elif i % 10 == 3: ans_list.append(str(i)) elif '3' in str(i): ans_list.append(str(i)) print('', ' '.join(ans_list))
''' Created on Feb 24, 2017 @author: BhavinSoni ''' ''' def fastED(S1, S2): '''''' Returns the edit distance between the strings first and second.'''''' def fastEDhelper(S1, S2, memo): if (S1, S2) in memo: return memo [(S1, S2)] if S1 == '': result = len(S2) elif...
''' Created on Apr 13, 2015 Last modified on April 7, 2016 @author: Brian Borowski CS115 - Functions that merge lists ''' def num_matches(list1, list2): '''Returns the number of elements that the two lists have in common.''' list1.sort() list2.sort() matches = 0 i = 0 j = 0 ...
''' Created on Apr 11, 2017 @author: BhavinSoni ''' import sys '''a class is a blueprint for something you wish to represent. classes contain attributes and methods. attributes are variables that represent the state of the object''' '''methods are functions inside the class that allows you to change the state of a...
''' Program Title A Programmer 01/01/1970 A brief description of what the program does ''' student = [] student.append(input('Please enter name: ')) student.append(int(input('Please enter age: '))) while student[1] < 1 or student[1] > 150: student[1] = int(input('Between 1 and 150: ')) student.append(float(input...
#!/usr/bin/env python # encoding: utf-8 """ @description: 迭代器模式 @author: BaoQiang @time: 2017/6/19 14:03 """ import re import reprlib import itertools RE_WORD = re.compile('\w+') class Sentence: def __init__(self, text): self.text = text def __repr__(self): return 'Sentence(%s)' % reprli...
import pandas from matplotlib import pyplot from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split, cross_val_score, ShuffleSplit data_file = '../data/cali_housing.csv' data = pandas.read_csv(data_file) #------------------------------------------------------------------...
import sys import os import random from nltk import ngrams def weighted_choice(choices): total = sum(w for c, w in choices.items()) r = random.uniform(0, total) upto = 0 for c, w in choices.items(): if upto + w > r: return c upto += w def ngram_init(): # N Gram value ...
from game_master import GameMaster from read import * from util import * import pdb class TowerOfHanoiGame(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ See overridden parent class method for more information. Returns: ...
file = open('10_input.txt', 'r') lines = file.readlines() nums = [int(l.strip()) for l in lines] nums.sort() nums = [0] + nums count_3 = 1 # device is 3 over last one count_1 = 0 for n in range (1, len(nums)): if (nums[n] - nums[n-1]) == 1: count_1 = count_1 + 1 elif (nums[n] - nums[n-1]) == 3: ...
number = int(input("I am thinking of a number between 1 and 10. What's the number? ")) import random my_random_number = random.randint(1, 10) while number != my_random_number: if number < my_random_number: print("{} is too low. ".format(number)) number = int(input("What's the number? ")) if num...
# Напишите функцию которая принимает число 'N' и # возвращает квадраты всех натуральных чисел кроме числа 'N', в порядке возрастания # например если число 'N' = 4 ,то должен выйти список из чисел: 0,1,4,9 def Number_N(): a = int(input()) new_list = [] for num in range(a): new_list.append(num**2) ...
import math import random def mean(n): """ Computes the mean value of a list of parameter n """ total = 0 for i in n: total += i return total/len(n) def median(n): """ Computes the median value of a list of parameter n """ n.sort() length_of_n = len(n) if length_of_n%2==0: after = lengt...
# Count XML Tags in Text def tag_count(tokens): count = 0 for token in tokens: if token[0] == '<' and token[-1] == '>': count += 1 return count # Create an HTML List def html_list(list_items): HTML_string = "<ul>\\n" for item in list_items: HTML_string += "<li>{}</li>\\n...
# condiciones del scrip para juego de dados: # 1)Simular el lanzamiento de dos dados de seis caras. # 2)Para ganar la mano, la suma entre ambos dados debe ser igual a cuatro. # 3)Si la suma entre ambos dados es menor a cuatro, entonces se pierde esta mano. # 4)Si la suma entre ambos dados es mayor a cuatro, debe volver...
import time # welcome the user user_name = input("Hello Player enter your name") print("Hello "+user_name+" Let's play Hangman ") time.sleep(1) print("Start Guessing ......") time.sleep(0.5) # Guessing word word = "apple" guesses = '' turns = 10 # Create a while loop while turns > 0: failed= 0 for char in...
import sys import unicodedata #creating dictionairies globals enAlphabet = "abcdefghijklmnopqrstuvwxyz" letToNumber= dict(zip(enAlphabet, range(len(enAlphabet)))) numberToLetter = {v:k for k, v in letToNumber.items()} def chooseLanguage(): print("Portugues(1) English(2)") lang = input() return lang def ...
################## #Set game to be on or off from random import randint import time import sys game = True newnames = 1 def printcleanspace(howmanyyouwant = 1): print('\n'*howmanyyouwant) def cointoss(): cointossresult = "" cointoss = randint(0, 100) for i in range(0,2): if cointoss%2==0: return...
import random def Start(): board=["-" for i in range(0,9)] possible_places = [i for i in range(0,9)] def pr_board(): print(*board[0:3]) print(*board[3:6]) print(*board[6:9]) if "-" not in board: if check_winner("X"): print("X has Won") ...
import pandas as pd # Create a dictionary of sales data #course_sales = {'course':['Python','Ruby','Excel','C++'], #'day':['Mon','Tue','Wed','Tue'], #'price':[5,10,15,20], #'sale':[2,3,5,7] #} # Convert sales data into a DataFrame #df_sales = pd.DataFram...
""" bittrex.client returns balances as a list of dictionaries with: Currency, Balance, CryptoAddress, Pending, Requested, Uuid A portfolio is the type and amount of each cryptocurrency held along with some basic operations. . There is a desired 'state' and due to fluctuations some currencies will have more (or less) ...
class Bruch(object): """ Class Bruch is the equivalent to a mathematical fraction. You can create a fraction by passing another fraction to the :func:`__init__` constructor, or by providing a nominator and a denominator. You can also use a static method called :func:`_Bruch_makeBruch` to create ...
""" The main driver module for the code =================================== This module contains the main driver function for the code, which should be called by the executable of the program. """ import argparse from .renderdriver import render_driver def main(): """The main driver function""" parser ...
# 1. Определение количества различных подстрок с использованием хеш-функции. Пусть на вход функции дана строка. Требуется вернуть количество различных подстрок в этой строке. # # Примечания: # # * в сумму не включаем пустую строку и строку целиком; # # * без использования функций для вычисления хэша (hash(), sha1() или...
# print(10 + 20) # print(int(10).__add__(int(20))) # print.__call__(int.__add__(int(10), int(20))) # bob = { "name": "Bob", "last": "the Builder", "age": 42 } # bob = object.__new__(dict).__init__(...) # print("Hello world!") # print.__call__(str("Hello world")) # print(bob.name) # print.__call__(Person.__getattribu...
#Python3 program to implement Leetcode 74. Search a 2D Matrix #Problem statememt: ''' Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer...