text
stringlengths
37
1.41M
numero= int(input("Dame un numero: ")) for i in range (numero): print (numero - i)
numero= int (input("Dame un número: ")) while numero <= 0: print ("Pon uno positivo") numero= int (input("Dame un número: ")) for i in range(numero): if i%2 != 0: print(i, end=", ")
""" Takes in a vector and set of weights for that vector Returns their dot-product """ def dot_product(vector, weights): return sum(elem * weight for elem, weight in zip(vector, weights)) if __name__ == '__main__': print(dot_product((1, 1, 1), (.5, .25, .5))) print(dot_product((0, 1, 0), (.5, .25, .5)))
class KnwingTheError: value_current=1 value_last = 1 value_highest = 1 error_from_highest = 0 error_from_last = 0 def __init__(self): pass def adding_value(self,value_taked): self.value_current = int(value_taked) if self.value_current >= self.value_highes...
""" insertion.py Insertion Sort Implementation """ from .sorter import Sorter class InsertionSorter(Sorter): """ Insertion Sort -=-=-=-=-=-=-= A much much much faster algorithm that takes advantage of the relations of the input array. It also gets faster as more of the array is sorted — much...
import os import csv file_to_load = os.path.join('Resources', 'election_results.csv') file_to_save = os.path.join('Resources', 'election_analysis.txt') total_votes = 0 candidate_option = [] candidates_votes = {} winning_count = 0 winning_candidate = '' winning_percentage = 0 #Read the data from the csv file with...
#imports the ability to get a random number (we will learn more about this later!) from random import * #Generates a random integer. Num = randint(1, 20) # For Testing: print(aRandomNumber) guess = 0 guess = input("Guess a number between 1 and 20 (inclusive) ==> ") i = 0 while i < 5 or (guess != Num): ...
import math ''' a = float(input('첫번째 직각변의 길이(cm) : ')) b = float(input('두번째 직각변의 길이(cm) : ')) c = math.sqrt(a**2 + b**2) ± print('빗변의 길이는 {} cm 입니다'.format(c)) ''' ''' print('이차방정식 ax² + bx + c 해 계산기입니다.') a = int(input('a 값 : ')) b = int(input('b 값 : ')) c = int(input('c 값 : ')) d = [] back_len = len(str(e).split('.'...
theBoard = { '1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' ', } POS = '123456789' winner = 'Nobody' def printBoard(board): print(board['7'] + '|' + board['8'] + '|' +board['9']) print('-+-+-') print(board['4'] + '|' + board['5'] ...
def mul(times): def wrapper(x): print("{times} times {x} is".format(times=times, x=x), end=" ") return times * x return wrapper ten_times = mul(10) print(ten_times(2)) print(ten_times(3)) five_times = mul(5) print(five_times(2)) print(five_times(3))
# The Zipf distribution (also known as the zeta distribution) # is a continuous probability distribution that satisfies Zipf’s law # the frequency of an item is inversely proportional to its rank in a frequency table. # Reference link: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.zipf.html ...
''' Given a directed graph and two nodes (S and E), design an algorithm to find out whether there is a route from S to E. ''' class Node: def __init__(self, value): self.value = value self.adj = [] def DFS(s, e, visited_nodes = None, found = False): if visited_nodes == None: visited_nodes = set()...
''' Given an array of integers, write a method to find indices m and n such that if you sorted elements m through n, the entire array would be sorted. Minimize n-m ''' def find_min_max(arr, start, end): # (arr, 6, 7) mini = arr[start] # 7 maxi = arr[end] # 12 for a in arr[start+1:len(arr)]: if a < min...
''' You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of water connected vertically, horizontally or diagonally. The size of the pond is the total number of connected water cells. Write a me...
"""module queue""" from typing import List class Queue: """ Thread-safe, memory-efficient, maximally-sized queue supporting queueing and dequeueing in worst-case O(1) time. """ def __init__(self, length: int = 0): self.queue: List[int] = [] self.max_size = length def push(self...
''' aaa ''' a = [1,2,3,4,5,6,7,8] for x in a: if x % 2 == 1: print(x) b = a[0:len(a):3] print(b)
name = input("What is your name? ") age = input("How old are you? ") city = input("Where are you live? ") print("This is {0}.".format(name)) print("It is {0}.".format(age)) print("S(he) live in {0}.".format(city))
n1 = int(input("enter number 1: ")) n2 = int(input("enter number 2: ")) n3 = int(input("enter number 3: ")) largest = 0 a = [n1,n2,n3] for n in a: if n > largest: largest = n print(largest)
class MyClass: # Atributos (propiedades) de MyClass name = "My class" x = 10 y = ["My", "Class"] # Operaciones(Metodos/Funciones) de MyClass def printName(name): print(name) # Crear objeto # MyClass c = new MyClass() --- JAVA # Todos los atributos y metodos los va tener (C) # Declar...
def ordenamientoPorMezcla(unaLista): print("Dividir ", unaLista) if len(unaLista) > 1: mitad = len(unaLista)//2 mitadIzquierda = unaLista[:mitad] mitadDerecha = unaLista[mitad:] ordenamientoPorMezcla(mitadIzquierda) ordenamientoPorMezcla(mitadDerecha) i = 0 ...
# Rectangle Information. # This program displays information about a rectangle drawn by the user. # Input: 2 mouse clicks for the opposite corners of a rectangle. # Output: Draw the rectangle. #Print the perimeter and area of the rectangle. # Formulas: #area = (length)(width) perimeter = 2(length + w...
#-*- coding:utf-8 ''' Created on 2020. 10. 29. @author: user ''' # Ex03_dict_내이름 student = {} # {'kim':'10', 'park':'20'} while True : print() num = int(input('메뉴번호(1:출력, 2:입력, 3:검색, 4:삭제, 5:수정, 6:종료 => ')) if num == 1 : if len(student) != 0 : for i,j in student.items(): ...
#-*- coding:utf-8 ''' Created on 2020. 10. 21. @author: user ''' # Ex01_file f = open('file.txt','w') f.write('apple\nbanana') f.close() f2 = open('file.txt','r') str = f2.read() print('str:',str) f2.close() import os print(os.getcwd()) print(os.listdir('.')) def filetype(fpath): print(fpath,':',end='') ...
from collections import namedtuple from DirectedAcyclicGraph import DAG as DAG class Graph(): class Edge(): """Edge class represented by the vertices and weights. Easily printable and comparable.""" def __init__(self, startVertex, nextVertex, weight=0): self.startVertex = startVertex ...
#!/usr/bin/python import os import sys def handle_file(filename, outname): outname += ".txt"; if not os.path.exists(outname): print "%s -> %s" % (filename, outname); os.system("xsltproc 2554/download/XML/Scripts/justTheWords.xsl %s > %s" % (filename, outname)); def traverse_dir(dirname, o...
#basic sieve from collections import defaultdict def create_list(): return [] cmps = defaultdict(create_list) #Understand why defaultdict is used here def generate_primes(): v=2 while True: yield v cmps[v*v].append(v) v+=1 while v in cmps: for f in cmps[v]: cmps[v+f].append(f) ...
#reading files - use open() #r means that it only wants to read the file employee_file = open("employees.txt", "r")#store open function in a variable for employee in employee_file.readlines(): print (employee)#using the for loop you are printing out the entire array employee_file.close()#generally you want o...
''' Created on Apr 21, 2014 In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem. Here are data files describing three graphs: graph #1; graph #2; graph #3. The first line indicates the number of vertices and edges, respectively. Each subsequent line describes an edg...
# import the Flask class from the flask module from flask import Flask, render_template, redirect, url_for, request import json import requests import base64 import sqlite3 from sqlite3 import Error # create the application object my_service = Flask(__name__) # use decorators to link the function to a url @my_servi...
# %% x = 2 y = 3 z = x + y # %% z = z + x + y def f1(x): return x ** 2 def f2(x): return x ** 3 if __name__ == "__main__": f1(2) f2(3)
#!/usr/bin/python import numpy as np def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net...
""" Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of words 'quick', 'brown', 'the', 'fox', a...
""" Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2...
def mad(x,y): if(x == y): return print("They are Equal") else: return print("They are not Equal") a = int(input("Enter A Number = ")) b = int(input("Enter B Number = ")) c = mad(a,b)
# Greatest of the three Numbers a=int(input("Enter A Value = ")) b=int(input("Enter B value = ")) c=int(input("Enter C Value = ")) def greatest(x,y,z): if(x>y and x>z): print("X is the Greatest Number among all",x) elif(y>x and y>z): print("Y is the Greatest Number among all",y) elif(z>x a...
""" What is tuple? * Tuple is immutable sequence object in python * immutable means we can't manipulate the data once tuple object in created * tuple is almost equal to list object, except mutable behaviour * We can access elements/Items from tuple by using index position(tuple sequence object) Operations: * Read ...
""" Python is general purpose 1) scripting,(done) 2) procedural(inprogres) 3) object oriented programming """ """ What is function? * Function is block of organized code that could be execute when we call function * function having arguments/paramater to pass input data while calling function * required argumnets...
""" functional programming in python: Map filter reduce """ """ 1) map(func, iter): map takes function object and iterable as arguments """ # convert all chars to upper case data = ['badra', 'satys', 'mani'] # o/p : ['BADRA', "SATYS", "MANI"] out = [] for name in data: cap_latter = name.upper() out.append(...
import csv from datetime import datetime # helper functions to convert to python objects def parse_time(str_time): return datetime.strptime(str_time, '%H:%M:%S').time() def parse_date(str_date): return datetime.fromisoformat (str_date) # can be re ued in entire module TRADING_START_TIME = parse_time('09:30...
import time from math import sqrt, log from collections import defaultdict #Recursive Memoization: print("Recursive Memoization:") m1_start_time = time.time() max_check = 1000000 max_count = 0 start_max = 0 records = {} def CollatzLength(start, num, count = 1): if num == 1: records[start] = count return count ...
import time #Direct List Comprehension print("Direct List Comprehension:") m1_start_time = time.time() multiples = [x for x in range(1,1000) if ((x % 3 == 0) or (x % 5 == 0))] print("Answer: " + str(sum(multiples)) + "; Time: " + str(time.time() - m1_start_time)) #Sum Formula print("\nSum Formula:") m2_start_tim...
# Santiago Landaverde # 1856681 palindrome= input() x = 0 y = len(palindrome)-1 result = True while x < y: if palindrome[x] == ' ': x += 1 elif palindrome[y] == ' ': y -= 1 elif palindrome[x]!=palindrome[y]: result = False break else: x += 1 ...
from math import sqrt #返回一个有关 personl 与 person2 的基于距离的相似Jt伴价 def sim distance(prefs,personl,person2): # 得到 shared items 的列在 def sim_distance(prefs,person1,person2): # 得到 shared items 的列在 si ={ } for item in prefs[person1] : if item in prefs [person2]: si[item]=1 # 如果两者没有共同之处 . 则返回 O if len(si)==O: retur...
#!/usr/local/bin/python #Created on 2/12/13 __author__ = 'Juan Ugalde' import sys from collections import defaultdict #This are functions involved in reading files def read_genome_list(input_file): """ Function used to read the genome list. The output is a dictionary with the genome list (fasta_prefix -> n...
import string from ciphers import Cipher class Atbash(Cipher): '''Encrypts and decrypts messages using the Atbash Cipher. Formed by taking the alphabet and mapping it to its reverse, so that the first letter becomes the last letter, the second letter become the second to last letter, ...
import sys from pydub import AudioSegment from pydub.playback import play # take audio mp3 a first argument from command line print ("Usage: python change_pitch.py input.wav output.wav frequency") sound = AudioSegment.from_file(sys.argv[1], format="wav") # shift the pitch up by half an octave (speed will increase pro...
# create a guess variable guess = input("What's my favorite food? ") # condition to validate user input if guess == "cookies": print("Yep! So amazing!") else: print("Yuck! That's not it!") print("Thanks for playing!")
a = 10 b = 20 c = a+b def MakeListWithBracket(strList): lenth = len(strList) if strList[0]=="[" and strList[lenth-1]=="]": strList = strList.replace("[" , "") strList = strList.replace("]" ,"") newList = strList.split(" ") else: print("wrong syntax") return newList def...
# -*- coding: utf-8 -*- from datetime import timedelta def get_tuesday(dt): # 获取参数所在周的周二 wd = dt.weekday() if wd == 0: return (dt + timedelta(days=1)).date() else: return (dt - timedelta(days=wd - 1)).date()
# coding=utf-8 ''' Problem 35 17 January 2003 The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? ...
# coding=utf-8 ''' Problem 34 03 January 2003 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' import math facts = [math.factorial(i) for i in ra...
#!/usr/bin/env python import math # Level 1 def longest_palindrome_substring(string): strlen, best, pos = len(string), 0, 0 for i in range(1, strlen): for lower, upper, curlen in [(i - 1, i + 1, 1), (i, i + 1, 0)]: while lower >= 0 and upper < strlen and string[lower] == string[upper]: lower, u...
import numpy import sys """ Convolutional neural network implementation using NumPy. An article describing this project is titled "Building Convolutional Neural Network using NumPy from Scratch". It is available in these links: https://www.linkedin.com/pulse/building-convolutional-neural-network-using-numpy-from-...
from typing import List, Tuple, Any def main(): min_max = [] with open("input.txt") as f: for line in f: elems = line.split() int_elems = [int(elem) for elem in elems] min_max.append(process_line(int_elems)) with open("output.txt", mode='w') as f: for mi...
import numpy as np import matplotlib.pyplot as plt from celluloid import Camera #a = [int(x) for x in input("Enter number").split()] #print(a) def gradient_descent(x,y): m_curr = b_curr = 0 learning_rate = 0.001 iterations = 1000 cost_lst = [] i_lst = [] n=len(x) fig=plt.figure() camer...
#!/usr/bin/env python3 # -*-encoding:utf-8 -*- __author__ = 'mxu2' L=[2,8,3,50] L.sort() print(L) a="123kljkoi908jkfdd" print(a[::-1]) string = '' #string1 = raw_input('Enter a string:') string1 = 'this is a test' list1 = string1.split(' ') list2 = list1[::-1] for x in range(0,len(list2)): string += list2[x] +...
from typing import Tuple, Dict, List, Any def rankings_change(home_rank: float, away_rank: float, home_score: int, away_score: int, is_neutral_venue: bool = False, is_rwc: bool = False) -> Tuple[float, float]: """ THe change in rankings for both teams for a given match result. :param h...
class Survey: #survey is a 3d array #level one contains questions #level two contains individual questions and types #level three contains the types questions = ["nico","ji"] def parse_questions(self,qusetions): for x in questions: #x=individual questions and their types ...
# -*- coding: utf-8 -*- """ Created on Mon Aug 31 19:41:45 2020 @author: Daniel """ import error class Op(): def __init__(self, op, left, right): self.op = op self.left = left self.right = right class Func(): def __init__(self, method, parameters, loc=None, builtin=False, returns=Fals...
import collections s = input() t = input() loop = len(s) s_col = collections.Counter(s) t_col = collections.Counter(t) # print("s_col", s_col) s_l = sorted(s_col.values()) # print(len(s_col)) # print("s_l", s_l) # print("t_col", t_col) t_l = sorted(t_col.values()) # print("t_l", t_l) # print(len(t_col)) if s_l == t_l: ...
# 書く文字の変換が1対1対応でないと、スワップはできない # 書いてどういう時にダメなのかやってみる? # 各処理を分割してやってみる s = input() t = input() # 変換逆変換の表を作る trans_in = [-1] * 26 # 下の入力方式において、0はa→aで使う trans_out = [-1] * 26 # 文字→asciiコード・・・ord・・・ordだと10進数変換してくれるみたいね # asciiコード→文字・・・chr for i in range(len(s)): a = ord(s[i]) - ord("a") b = ord(t[i]) - ord("a") ...
from prime_num import prime_num from collections import OrderedDict def factoring(n): result = prime_num(n) print(result) loop_len = len(result) pf = OrderedDict() for i in range(0, loop_len): num = 0 while 1: if n % result[i] == 0: print(n) ...
############# import turtle from turtle import * turtle.colormode(255) import random import math #list of balls ball_list = [] ball_index = 0 turtle.tracer(0) #this class defines the border class SquaredBorder(Turtle): def __init__(self, top_left_x, top_left_y, length): Turtle.__init__(self) self.to...
import csv import os class PharmacyRecordParser(object): '''An object of this class is responsible for parsing an input pharmacy record file. Parameters ---------- file_path: str The path to the input file. ''' DELIMITER = ',' QUOTE_CHAR = '"' def __init__(self, file_pat...
""" 207. 课程表 你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1 。 在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] ,表示如果要学习课程 ai 则 必须 先学习课程 bi 。 例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1 。 请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false 。 示例 1: 输入:numCourses = 2, prerequisites = [[1,0]] 输出:true 解...
def make_incrementor(n): print(n) return lambda x: x class Xman(): def __init__(self, *args, **kwargs): self.args = args def connect(self, fn, n): fn(n) # print(make_incrementor) xman = Xman() # x = make_incrementor(1) xman.connect(make_incrementor, 'r') # make_incrementor('d')
m=int(input("dati m:")) for m in range(0,m+1,+2): if m!=0: print(m)
class Calculator: def __init__(numbers, num1, num2): numbers._num1 = num1 numbers._num2 = num2 def add(numbers): return numbers._num1 + numbers._num2 def subtract(numbers): return numbers._num1 - numbers._num2 def multiply(numbers): return numbers._num1 * numbers._num2 def division(numbers): return...
class nameChecker def __init__(name, name1): name._name1 = name1 enterName(name){ name = input("Enter your name: ") } checkName(name){ if name.startswith("t","T"): print("Name okay") else: print("Enter a name that begins with t") name = input("Enter your name: ") } checkLength(name){ if len(name) < 3: ...
name = input("Enter your name: ") tees = "t", "T" if name.startswith(tees): print("Name okay") if len(name) < 3: print("Too short") elif len(name) > 6: print("Too long") else: print("YEA BOI") else: print("Enter a name that begins with t") name = input("Enter your name: ")
words = ['bat', 'ball', 'yarn','basket', 'badminton' ] words.sort() print(words[0]) print(words[len(words)-1]) if('badminton' in words): print('true') else: print('false') words[len(words)-1] = 'beach' print(words)
a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a // b) print(a % b) for i in range(1, a//b): print(i)
vowels = {'a', 'e', 'i', 'o', 'u'} text = set(input("Please enter some text")) text = text.difference(vowels) print(text)
powers = [] for power in range(15, -1, -1): powers.append(2 ** power) print(powers) x = int(input("Please enter a number: ")) printing = False for power in powers: bit = x // power if bit != 0 or power == 1: printing = True if printing: print(bit, end='') x %= power
a=list(input()) a.sort() a=a[:-3] s = map(str, a) s = ''.join(s) s = int(s) print(s)
premium_cost = 125.00 def ground_shipping(weight): if weight <= 2: return 1.50*weight+20 elif weight > 2 and weight <= 6: return 3.00*weight+20 elif weight > 6 and weight <= 10: return 4.00*weight+20 else: return 4.75*weight+20 print(ground_shipping(8.4)) def drone_shipping(weight): if weigh...
# 標準出力 print('hello world') name = input('名前を入力してください') print(name) age = 18 # format関数 print('私の名前は={}, 年齢は{}'.format(name, age)) # 複数の変数に値を入力 a = b = "ok" print(a, b)
#!/usr/bin/python import psycopg2 # note that we have to import the Psycopg2 extras library! import psycopg2.extras import sys def main(): conn_string = "host='localhost' dbname='company' user='postgres' password='123change'" # print the connection string we will use to connect print "Connecting to da...
from Tkinter import * class Collision(object): def __init__(self, cx, cy, r, power,width=2): self.cx = cx self.cy = cy self.r = r self.power = power self.width = width def draw(self, canvas): r = self.r canvas.create_oval(self.cx-r,self.cy-r,self.cx+r,self...
import chess import time from players import player_human, player_minimax, player_random COLOR_TO_STRING = {chess.WHITE : "White", chess.BLACK : "Black"} class ChessManager: def __init__(self, white_player, black_player): self.board = chess.Board() self.white_player = white_player self.b...
list = [1,2,3] a=[] def total(): sum = 0 for i in list: sum=sum+i return sum def actual(n): for i in list: list1=n//i a.append(list1) b = total() actual(b) print(a)
s1 = 'geeks' s2= 'geeks for geeks' s3= s2.split(' ') print(s3) for i in range (len(s3)): if s3[i] == s1: print('string found at', i)
s ="i am muskan" def printeven(s): s1 = s.split(' ') for i in s1: if len(i)%2==0: print(i) printeven(s)
def outer(): print("inside outer function") def inner(): print("inside inner function") return inner m = outer() print(m) m()
list = [25,2,5,1,2,17,8,10] for i in range (len(list)-1): m_min=i for j in range (i+1,len(list)): if list[j]<list[m_min]: m_min=j if list[i]!=list[m_min]: list[i],list[m_min]=list[m_min],list[i] print(list)
# calculator in Python(v0.4) def add(num1, num2): return num1 + num2 def sub(num1, num2) Return num1 - num2 def mul(num1, num2) return num1 * num2 def div(num1, num2) return num1 / num2 def mod(num1, num2): return num1%num2 def sqr(number): return number ** 0.5 # main number = int(input("Enter a number: ")) ...
# -*- coding: utf-8 -*- def my_var(): a = int(42) print("%s est de type %s" % (a, a.__class__)) a = "42" print("%s est de type %s" % (a, a.__class__)) a = "quarante-deux" print("%s est de type %s" % (a, a.__class__)) a = float(42.0) print("%s est de type %s" % (a, a.__class__)) a = ...
# -*- coding: utf8 -*- """Neural network implementation for Python, uses logistic function as an activation function. Creates simple two layered neural network, which can be used f. e. to text recognition. Used in SnakeReader project (to recognize letters)""" from numpy.oldnumeric import * ##I am using matrix impleme...
# Заданиен 1 # Создайте словарь с количеством элементов не менее 5-ти. # Поменяйте местами первый и последний элемент объекта. # Удалите второй элемент. Добавьте в конец ключ «new_key» со значением «new_value». # Выведите на печать итоговый словарь. # Важно, чтобы словарь остался тем же (имел тот же адрес в памяти). d ...
"""Reverse the words in a string in place. eg. 'Hello I am Ray' becomes 'Ray am I Hello'""" def word_reversal(str): my_lst = str.split(" ") for i in range(len(my_lst)/2): my_lst[i], my_lst[-1-i] = my_lst[-1-i], my_lst[i] return " ".join(my_lst) print word_reversal("Hello I am Ray's friend")
class Node(object): def __init__(self, data=None, next=None): self.data = data self.next = next class Queue(object): def __init__(self): self.head = None self.tail = None def enqueue(self, data): new_node = Node(data) if not self.head: self.hea...
"""Implement an algorithm to determine if a string has unique characters. What if you cannot use additional data structures.""" def unique_chars(str): my_set = set() for item in str: my_set.add(item) if len(str) == len(my_set): return True else: return False
from random import randint playing = True attempts = 0 random_num = randint(1, 100) while playing: try: user_input = int(input("guess the number ")) attempts += 1 if user_input < random_num: print("go higher") elif user_input == random_num: ...
""" A class that allows you to peek into the future of the iterator """ class IteratorPeek: def __init__(self, iter): self.iter = iter self.buffer = [] def __iter__(self): return self def next(self): if self.buffer: return self.buffer.pop(0) ...
import random numbers = "0123456789" while 1: try: num_count = int(input("Hoeveel 'burgerservicenummers' wil je genereren? : ")) for a in range(0,num_count): # aantal opgevraagde bsn-nummers bsn_num = "" for a in range(0, 9): # lengte van de bsn-nummer ...
S = 0 people = int(input("Сколько вам нужно билетов?: ")) people_list = [i for i in range(people)] for identify_age in people_list: age = int(input("Возраст посетителя?: ")) if 0 <= age < 18: print("Стоимость билета для данного возраста:", 0, "рублей") S += 0 elif 18 <= age < 25: pr...
def fact(n): res = None if type(n) is not int: raise TypeError try: n = int(n) except (ValueError, TypeError): print('arg {} is not an integer or negative'.format(n)) else: if n < 0: raise ValueError elif n == 0: return 1 else: res = n * fact(n - 1) return res
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): """ Radix sort, you can see the explanation follow the links. https://www.cs.usfca.edu/~galles/visualization/RadixSort.html And here is a java solution in leetcode's discuss: https://leetcode.com/discuss/53636/radix-sort-soluti...
''' 693. Binary Number with Alternating Bits Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary...
''' 82. Remove Duplicates from Sorted List II Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3 ''' ''' ALGORITHM: 1. Iterate on the list ...