text
stringlengths
37
1.41M
# Import pyfiglet from pyfiglet import figlet_format # Import the colored module from the termcolor package from termcolor import colored # Store the available colors in a lighter-weight tuple rather than a list valid_colors = ("red", "green", "yellow", "blue", "magenta", "cyan", "white") def print_art(message, color...
import unittest from array123 import array123 class UnitTests(unittest.TestCase): def test_1_1_2_3_1_returns_true(self): actual = array123([1, 1, 2, 3, 1]) expected = True self.assertEqual( actual, expected, 'Expected calling array123() with "[1, 1, 2, 3, 1]" to return "True"'...
import unittest from max_end3 import max_end3 class UnitTests(unittest.TestCase): def test_1_2_3_returns_3_3_3(self): actual = max_end3([1, 2, 3]) expected = [3, 3, 3] self.assertEqual( actual, expected, 'Expected calling rotate_left3() with [1, 2, 3] to return [3, 3, 3]') ...
#Import the REQUESTS package import requests # Define a URL to request url = "http://www.npr.org" # Write the response response = requests.get(url) print(f"your request to {url} came back with the status code {response.status_code}") print(response.text)
import unittest from in1to10 import in1to10 class UnitTests(unittest.TestCase): def test_5_and_false_returns_true(self): actual = in1to10(5, False) expected = True self.assertEqual( actual, expected, 'Expected calling in1to10() with 5 and False to return "True"') def test...
import unittest from make_chocolate import make_chocolate class UnitTests(unittest.TestCase): def test_4_1_9_returns_4(self): actual = make_chocolate(4, 1, 9) expected = 4 self.assertEqual( actual, expected, 'Expected calling make_chocolate() with [4, 1, 9] to return "4"') ...
#!/usr/bin/env python3 #open the new sequence file and print it opSeq = open('Python_06.seq.txt', 'r') print(opSeq.read()) #the Python_06.seq.txt contains reverse complements in the format seqName\tsequence\n #to save the above sequences to a file in unix easily, can just run this .py script and redirect to a new f...
#!/usr/bin/env python3 #download specialized re functions import re #open, read, and print the Python07 fasta file #fastofile =open("Python_07.fasta","r") #print(fastofile.read()) #fastofile.close() #what type is fastofile? #print(type(fastofile)) #yuck its an IO, lets make it a string fastofile = open('Python_0...
import re class Extractor: def __init__ (self, dataFile, filename): self.dataFile = dataFile # Data file to be processed self.filename = filename # Name of the file currently being processed self.list_results = [] # List of results to be filled by the extractor def get_data...
# given name, family name, email, phone # a - add new person # l - list all people # q - quit # f - find people (search through names + email) # w - write info to disk # r - read info from disk # blog.lerner.co.il (reduce fun) #!/usr/bin/env python addresses = [ ['yue', 'gong', 'ygong@vmware.com', 1333], ['yang', ...
#!/usr/bin/env python x = 10 def firstlast(x): print "value %d" % x # firstlast('abc') => 'ac' # firstlast([1,2,3]) => [1,3] # firstlast((1,2,3)) => (1,3)
#!/usr/bin/python def triangles(N): L1 = [1,1] L0 = [1] L = [] i = 2 for i in range(2, N): L.append(1) j = 1 for j in range(N-1): L.append(L1[j-1] + L1[j]) L.append(1) L0 = L1 L1 = L for l in L1: print(l) if __name__ == '__main__': triangles(5)
class SchoolMember: def __init__(self, name, age): self.name = name self.age = age print '''initialize the school member''' def tell(self): print "name is %s, age is %d" % (self.name, self.age) class Teacher(SchoolMember): def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) s...
#!/usr/bin/env python def main(): n = 999 for i in range(n*n, 1, -1): if not is_palindrome(str(i)): continue for j in range(n+1, 1, -1): if i % j == 0 and i / j <= n: print("{} x {} = {}".format(int(i/j), j, i)) return def is_palindrome(...
n=int(input("Enter the number of elements to be printed : ")) a,b=0,1 print("The fibonacci numbers are:",end='') print(a,b,end=' ') sum=0 for i in range(n-2): sum=a+b a=b b=sum print(sum,end=' ')
""" Project Secondus Goal: Find out what aspects of a player affect their success the most (find correlations). Process: Calls an API I made to read csv data, train a neural net, and return its weights. Then, uses the weights to determine how important each input variable is and graphs them usi...
def house() width = int(input("enter width")) length = int(input("enter length")) area = width * length print(area)
y=int(input()) sum=0 while(y>0): sum=sum+y y=y-1 print(sum)
n=int(input()) temp=n r=0 while(n>0): dig=n%10 r=r*10+dig n=n//10 if(temp==r): print("yes") else: print("no")
# def hello(): # print("Hello World") # # # hello() # # # def say_hello(name): # print(f"Hi {name}") # # # say_hello("Bob") # # # def double(number): # return 2 * number # # # result = double(3) # print(result) def str_combine(name1, name2): return f"{name1} {name2}" print(str_combine("Kazuma", "Tak...
#============================================================================== # THIS CODE IMPLEMENTS THE THIRD QUIZ FROM INDTRODUCTION TO DATA ANALYSIS COURSE # AUTHOR : GUILHERME CARVALHO PEREIRA # SOURCE: INDTRODUCTION TO DATA ANALYSIS COURSE...UDACITY COURSE #===================================================...
from turtle import * def draw_a_square(): for i in range(4): forward(100) left(90) # draw_a_square() # mainloop() def draw_an_equaliteral_triangle(): for i in range(2): forward(100) left(120) forward(100) # draw_an_equaliteral_triangle() # mainloop() def pentagon(): for i in...
import time import os from pynput.keyboard import Key, Controller def Timer(time_in_seconds): os.system('cls' if os.name == 'nt' else 'clear') while time_in_seconds: print(time_in_seconds) time_in_seconds = time_in_seconds - 1 time.sleep(1) os.system('cls' if os.name == 'nt' el...
from functools import reduce from partB import * import random from re import * if __name__ == "__main__": print("hello world") def foo(flag): """ This is a fucking function for HW0 :param flag: boolean bullshit :return: int """ if flag: print(1) else: print(0) foo(Fa...
import numpy as np puzzle = [[1, 0, 0, 0, 0, 0, 0, 0, 9], [0, 0, 3, 0, 9, 0, 0, 0, 7],[0, 0, 0, 0, 2, 8, 5, 1, 0], [3, 0, 6, 5, 7, 0, 0, 0, 0], [0, 0, 1, 0, 0, 3, 6, 0, 0], [4, 7, 0, 6, 1, 0, 0, 0, 0], [0, 6, 0, 0, 3, 0, 0, 0, 0],[0, 0, 0, 8, 0, 0, 0, 5, 0],[7, 0, 0, 0, 0, 5, 1, 0, 2]] order = (3,3) def possible(arr...
def addition(num, num2): return int(num) + int(num2) num = input("enter number 1:") num2 = input("enter number 2:") total = addition(num,num2) if(total%2): print(total) print("your number is odd") else: print(total) print("your number is even")
import stypes class Matcher: VERBOSE = False def __init__(self, name, matchf): self.name = name self.matchf = matchf def _return(self, val, depth=0): if self.VERBOSE: result = "SUCCEEDED" if val else "FAILED" print "-"*depth+"MATCH "+result+":", self.name ...
#Creating the graph manually #The graph is the same used in Chapter 4.1 (page 533) of the book "Algorithm II" vertex_list = [[6,2,1,5], [0], [0], [5,4], [5,6,3], [3,4,0], [0,4], [8], [7], [10,12,11], [9], [9,12], [11,9]] #List used to mark visited vertex marked_list = [False, False, False, False, False, False, False,...
from random import shuffle class Quicksort(): ''' Quicksort is a recursive program that sorts a subarray a[lo..hi] by using a partition() method that puts a[j] into position and arranges the rest of the entries such that the recursive calls finish the sort. ''' def sort(self, a): ''' ...
class HashTable: def __init__(self): self.size = 13 self.n = 4 self.count = 0 self.load = 0.75 self.table = [] for i in range(0, self.size): self.table.append([]) def __nextPrime(self): self.size = 2**self.n -1 self.n += 1 def __h...
""" UC Berkeley CS 61B: https://www.youtube.com/watch?v=G5QIXywcJlY&list=PL4BBB74C7D2A1049C&index=34 Wikipedia: https://en.wikipedia.org/wiki/Splay_tree Also see http://www.cs.usfca.edu/~galles/visualization/SplayTree.html. We do splay at the end of each operation because we might have found a very deep part of the tr...
#!/usr/bin/python3 """This module contains a function called print_square(), that prints a square with the character # """ def print_square(size): """ Args: size (int): is the size length of the square. """ if type(size) is not int: raise TypeError('size must be an integer') elif ...
#!/usr/bin/python3 """This module contains a class called Rectangle""" BaseGeometry = __import__('7-base_geometry').BaseGeometry class Rectangle(BaseGeometry): """Class rectangle that inherits from BaseGeometry (7-base_geometry.py)""" def __init__(self, width, height): self.integer_validator('width', ...
#!/usr/bin/python3 """This module returns the key with the highest score.""" def best_score(a_dictionary): """The function gets the highest value of the keys in a dictionary. args: a_dictionary. Dictionary to be used """ if a_dictionary is not None: try: return(max(a_dictionary, key=a...
#!/usr/bin/python3 """This module contains a function called append_after that inserts a line of text to a file, after each line containing a specific string """ def append_after(filename="", search_string="", new_string=""): """ Args: filename (str): file to be opened and used. search_string ...
#!/usr/bin/python3 for numbers in range(99): print("{} = {}".format(numbers, hex(numbers)))
import pyperclip class Account: ''' Class generates new instances of contacts ''' account_list = [] #empty list of accounts # Init method up here def save_account(self): ''' save_account method saves account object into account_list ''' Account.account_list.a...
friends =["Joseph","Glenn","Sally"] for fr in friends: print("Happly new year:", fr) print("Done!")
count=0 sum=0 print("Before", count, sum) for value in [9,41,12,3,74,15]: count=count+1 sum=sum+value print(count, sum, value) print("After",count, sum, sum/count)
# coding: utf-8 str1 = "Hello" str2 = "there" bob = str1 + str2 bob apple = input("Enter:") x=apple -10 x fruit = banana fruit = "banana" letter = fruit[1] letter x=3 w=fruit[x-1] w zot ="abc" print(zot[5]) print(len(fruit)) index =0 while index < len(fruit): letter = fruit[index] print(index,letter) index ...
for numbers in range(0,151,1): print(numbers) for selectedNumber in range(5, 1001,1): if( selectedNumber % 5 == 0 ): print(selectedNumber) for counting in range(1, 101, 1): if(counting % 10 == 0): print("Coding Dojo") elif(counting % 5 == 0): print("Coding") els...
import asyncio, time async def download_data(destination, delay): await asyncio.sleep(delay) print(f'Downloaded data from {destination}') async def main(): print('Download data sequentially') t1 = time.perf_counter() await download_data('Tokyo', 10) await download_data('Munich', 2) t2 = ti...
#========================================================================== def print_matrix(*args): #-------------------------------------------------------------------------- if len((args)) == 1: a = args[0] format = "%7.2f" else: a = args[0] format = args[1] print('Matr...
# けんしょう先生のお菓子配り a = int(input()) b = int(input()) c = a % b if c == 0: print(c) else: print(b - a % b)
#python -c " from __future__ import print_function; import re;import sys; datepat=re.compile(r'(\d+)[/-]?(\d+)[/-]?(\d+)\D' r'([01][0-9]):([0-5][0-9])'); [print(datepat.sub(r'\2/\3/\1T\4:\5',ln) if datepat.search(ln) else '' )for ln in sys.stdin if ' ' in ln ] #python pythonRegTemplate.py < log.txt...
""" Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall! Example For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHeig...
""" Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on. You are given an array of positive integers - the weights of the people. Return an array of two integers, ...
#This general_search.py is the most important part of the code #In this file it has all 3 algorithms #I use a heap for priority queuing from heapq import heappop, heappush import Create_Puzzle #From the prompt you can deduce that if your puzzle is of size 15 or 25 if Create_Puzzle.Size_of_Puzzle == 9: diameter =...
# str.format () ' ' ' El método format del objeto str ejecuta una operación de formato en una string. El string en el cual ' ' ' ' ' ' este método es llamado puede contener texto o campos de sustitución delimitados por llaves {}.' ' ' # Ejemplo print('Hola, {}!'.format('Antonio')) ' ' ' Cada campo de sustitución {} ...
def sum_of_first_n_number(n): ans = (n*(n+1)) / 2 print(ans*ans) return int(ans*ans) def sum_of_first_n_number_squre(n): mul = n*(n+1)*((2*n)+1) print(mul) print(mul/n) ans = (n*(n+1)*(2*n+1)) / n print(ans) return ans def solve(n): first_diff = sum_of_first_n_number(n) s...
lst = [1,3,4,1,1,5,4,6,2,2,7,9,5,5] stack = [] ans = [] stack.append(lst[0]) print(stack) for i in range(1,len(lst)-1,1): print(lst[i]) while len(stack) > 0: #print(2) top = stack[-1] print(top) if lst[i]>top: print("inside if") stack.pop() st...
def binary_search(nums,target): high = len(nums) low = 0 while low < high: import pdb;pdb.set_trace() mid = int(high/2) if nums[mid] == target: return mid else: if target>nums[mid]: low = mid elif target<nums[mid]: ...
#!/usr/bin/env python # coding: utf-8 def calculate_determinant(list_of_lists): n = len(list_of_lists) for i in range(n-1): if len(list_of_lists[i+1]) != len(list_of_lists[i]): return None if n != len(list_of_lists[0]): return None if n == 1: return list_of_lists[0]...
#question: Countdown - Create a function that accepts a number as an input. Return a new array that counts down by one, from the number (as arrays 'zero'th element) down to 0 (as the last element). For example countDown(5) should return [5,4,3,2,1,0]. def countdown(start): return list(range(start,0,-1)) #Print...
import time import numpy as np from scipy import signal def fib(n): ''' x,y = 0,1 result = [] while x < n: result.append(x) #a,b = b, a+b z = x + y x = y y = z #temp = b #b = a+b #a = temp ''' t = np.linspace(1, 1, number-3) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 15 13:22:53 2019 @author: KL2KL """ import groups def printBoard(board): print(board['11'] + '|' + board['12'] + '|' + board['13'] + '|' + board['14'] + '|' + board['15'] + '|' + board['16'] + '|' + board['17'] + '|' + board['1...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation #initializing my figure fig1 = plt.figure() #some initial conditions i=1 m=0 n=0 #My potential:setting up 100 points, going from 1 to 18 V=np.linspace(0,0, num=100) #setting up 100 points, going from 0 to 100 xes =np.linspac...
import random import os import time class Card: def __init__(self, suit, value, card_value): self.suit = suit self.value = value self.card_value = card_value def clear(): os.system("clear") def print_cards(cards, hidden): s = "" for card in cards: s = s + "\t ______...
def d_to_y(col): return col.map(lambda x: int(x[:4])) # Date to years function - works on application date and publication date in one def date_to_year(df): if 'appln_filing_date' in df.columns: df.appln_filing_date = df.appln_filing_date.map(lambda x: int(x[:4])) df.rename(columns={'appln_fi...
#!/usr/bin/env python3 from newsdb import get_articles, get_popular_author, get_errors import datetime print("Please choose from these questions:") print("1 - What are the most popular three articles of all time?") print("2 - Who are the most popular article authors of all time?") print("3 - On which days did more tha...
# nom, prix, ingrédients, végétarienne class Pizza: def __init__(self, nom, prix, ingredients, vegetarienne=False): self.nom = nom self.prix = prix self.ingredients = ingredients self.vegetarienne = vegetarienne def Afficher(self): veg_str = "" if self.vegetari...
class Pizza: nom = "" ingredients = "" prix = 0.0 vegetarienne = False def __init__(self, nom, ingredients, prix, vegetarienne): self.nom = nom self.ingredients = ingredients self.prix = prix self.vegetarienne = vegetarienne def get_dictionary(self): re...
# Dictionary samples - dictionnaries personne = { "prenom" : 'Toto' , "taille" : 1.80 , "age" : 50 } print(personne) print("Prénom de cette personne: " + personne['prenom']) # Ajout d'une <k,V> - un simple str personne['profession'] = "informaticien" print(personne) # Ajout d'une <k,V> - un tuple personne['hobbies']...
def RSum(start, sum, count, d, n): if sum == n: #print(l) return count + 1 if sum > n or start > int(pow(n, 1/d))+1: return count count = RSum(start+1, sum, count, d, n) #l.append(start) count = RSum(start+1, sum + pow(start, d), count, d, n) #l.pop() return count ...
# TUPLE x = [ (1, ['a', 'b', 'c'], 3), (4, 5, 6) ] x[0][1][2] = 'Andi' x[0][1].append('d') x = tuple(x) x[0][1][2] = 'Budi' x[0][0] = 'Caca' #tidak bisa karena dalam tuple print(x) # set/himpunan # 1. no indexing # 2. duplicate elements not allowed # 3. set adalah variabel, tapi variabelnya harus elemen imm...
#!/usr/bin/python n = int(input("How many terms in the sequence?")) n1 = 1 n2 = 1 i = 0 if n <= 0: print('Please enter a positive integer') elif n <= 1: print('Fibonacci Sequence:') print(n1) else: print('Fibonacci Sequence:') while i < n: print(n1, end= ',') n1, n2 = n2, n1+n2 ...
""" A stack is a data structure whose primary purpose is to store and return elements in Last In First Out order. 1. Implement the Stack class using an array as the underlying storage structure. Make sure the Stack tests pass. 2. Re-implement the Stack class, this time using the linked list implementation as th...
test_array = [-4, 3, -9, 0, 4, 1 ] array_length = len(test_array) positive_numbers = 0 negative_numbers = 0 zero_numbers = 0 for x in test_array: if x > 0: positive_numbers = positive_numbers + 1 elif x < 0: negative_numbers = negative_numbers + 1 elif x == 0: zero_numbers = zero_...
#!/usr/bin/python2 # -*- coding: utf8 # auteur:<atfield2501@gmail.com> # Fleur de Vie... Ou autre chose. import turtle import random turtle.getcanvas().postscript(file="Caglio-Fleur-d-Vie.eps") # Enregistrement de la figure final dans un fichier. unique=turtle.Turtle() # Deffi...
"""A video player class.""" from .video_library import VideoLibrary import random class VideoPlayer: """A class used to represent a Video Player.""" def __init__(self): self._video_library = VideoLibrary() self.videoPlayin = False self.videoPaused = False self.cu...
def processLine(str): """ Process row Line :param str: A line sentence :return: List contains " " """ tmp = list(str) result = "" for i in range(len(tmp)): if tmp[i].isalnum() is False: tmp[i] = " " for i in tmp: result += i return result.split(" ")
import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM import keras # TODO: fill out the function below that transforms the input series # and window-size into a set of input/output pairs for use with our RNN model def window_transform_series(series,windo...
# -*- coding: utf-8 -*- # # aggregate.py # simplestats # "Aggregating data into bins or other approximations." _eps = 1e-8 def bins_by_data(data, n): """ Puts the data into n sorted bins. Where n does not divide the length of the data directly, distributes the remainder as evenly as possible. Retu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 18 09:23:59 2019 @author: chance """ import matplotlib.pyplot as plt nums =[25,37,33,37,6] labels =["High-school","Bachelor","Master","Ph.d","Others"] # use matplot plt.pie(x=nums,labels=labels) plt.show()
string = "UDDDUDUU" num = len(string) def countingValleys(n,s): sea_level = 0 valley_count = 0 splitString = list(s) for i in range(0,num): if splitString[i] == "U": sea_level += 1 if sea_level == 0: valley_count += 1 elif splitString[i] == "D": ...
from name_function import get_formatted_name while True: print("Enter a 'q' for exit any time:") firtname = input("Enter your first name:") if firtname == 'q': break lastname = input("Enter your last name:") if lastname == 'q': break fullname = get_formatted_name(firtname, lastn...
prompt = "Enter a topping, and we'll add it in," prompt += "\nEnter quit to exit.>" active = True while active: topping = input(prompt) if topping == 'quit': active = False else: print("\tOk, we'll add %s on the pizza." % topping.upper())
favorite_numbers = { 'xumin': 3, 'liuyuxuan': 100, 'jipson': 7, 'Shelly': 33, 'tonada': 23 } for name, number in favorite_numbers.items(): print(name.title() + "'s favorite number is " + str(number) + ".")
print("Give me two numbers, and I'll divide it.") print("Enter a 'q' to exit") while True: first_number = input("Enter first number:") if first_number == 'q': break second_number = input("Enter second number:") if second_number == 'q': break try: result = int(first_number...
from stacks_and_queues import Node, Stack def test_stack_push(): colors = Stack() colors.push('red') assert colors.top.data == 'red' def test_stack_push_two(): colors = Stack() colors.push('red') colors.push('blue') assert colors.top.data == 'blue' def test_stack_push_two_return_first...
class Node(): def __init__(self, data): self.data = data self.nxt = None class Stack(): """ """ top = None empty = 'Empty Stack' def push(self, new_data): """ """ new_node = Node(new_data) if self.top is None: self.top = new_node ...
from tree import BinarySearchTree, BinaryTree, Node def test_emoty_tree(): """ Can successfully instantiate an empty tree """ tree = BinaryTree() assert tree.root is None def test_single_root_node(): """ Can successfully instantiate a tree with a single root node """ tree = Binar...
list1=input("enter list:") print "the elements are:" for i in range(len(list1)): print list1[i]
a=input("enter a=") b=input("enter b=") c=a/b d=a%b print "quotient is ",c,"and remainder is ",d
n=input("enter number") for i in range(0,n+1): m=i*i if(m==n): print n," is a perfect square" break else: print n," is not a perfect square"
c=input("enter value in degree celsius") f=(1.8*c)+32 print c," DegreeCelcius in Fahrenheit is ",f,"F"
import math def s(x): z=math.radians(x) print "the sine value of ",x," in radian is:",z,",in degree:",math.degrees(z) return def c(y): v=math.cos(y) print "the cosine value of ",y," in radian is:",v,",in degree:",math.degrees(v) return a=input("enter number:") s(a) c(a)
# 选择排序 def chooseSort(a): for i, val in enumerate(a): min = i for j in range(i + 1, len(a)): if a[min] > a[j]: # 找到最小位置的下标 min = j a[i], a[min] = a[min], a[i] # 交换首位和最小位 # 插入排序 def insertSort(a): for i, val in enumerate(a): for j in range(i, 0, -1)...
# Zad_2 # Napisz program, który obliczy kwotę należną za zakupiony towar w oparciu o cenę za kg i liczbę produktów. Wszystkie onformacje wypisz na konsolę. cena = float(input('Podaj cenę za kg: ')); liczba = float(input('Podaj liczbę produktów: ')); wynik = cena*liczba print('Cena produktu wynosi ', wynik, 'zł') print(...
from employee import Employee from manager import Manager from developer import Developer import datetime # ============================================================================= print('\n') print('-' * 100) print('Employee Class Example') print('-' * 100) print('\n') # Instantiating Instances emp_1 = Employee...
history_class = {"Clancy": {"hw_grades": [10, 10, 9, 9], "exam_grades": [94, 91, 97], "participation": 10}, "Reba": {"hw_grades": [8, 9, 8, 10], "exam_grades": [89, 90, 94], "participatio...
# -*- coding: utf-8 -*- import sys input = sys.argv print input[1] flist = [0, 1] i = 1 while flist[i] < int(input[1]): flist.append(flist[i] + flist[i-1]) i += 1 print flist
from urllib.request import * from json import * import time def get_json(url): ''' Function to get a json dictionary from a website. url - a string''' with urlopen(url) as response: html = response.read() print('Loading' + '.' + '.') htmlstr = html.decode("utf-8") return ...
def binary_value(val1, val2): bin1, bin2 = bin(val1)[2:], bin(val2)[2:] if len(bin1) > len(bin2): higher = len(bin1) bin2 = (len(bin1) - len(bin2)) * "0" + bin2 else: higher = len(bin2) bin1 = (len(bin2) - len(bin1)) * "0" + bin1 print bin1, bin2 value = "" for i in range(higher): if int(bin1[i]) and...
def MDC(a, b): if (b == 0): return a else: return MDC(b, a % b) def conversor_binario_decimal(binario): soma = 0 for i in range(len(binario)): potencia = abs(i - len(binario)) - 1 if (int(binario[i]) == 1): valor = 2 ** potencia soma += valor ...
def busca_binaria(seq, search): right = len(seq) left = 0 previous_center = -1 if search < seq[0]: return -1 while 1: center = (left + right) / 2 candidate = seq[center] if search == candidate: return seq.index(search) if center == previous_center: return - 2 - center elif search < cand...
def get_tamanho_camiseta(i): if i == 0: tamanho = "P" elif i == 1: tamanho = "M" else: tamanho = "G" return tamanho n = int(raw_input()) while True: if n == 0: break brancas, vermelhas = [[], [], []], [[], [], []] for i in range(n): nome = raw_input() cor, tamanho = map(str, raw_input().split()) ...
from random import randint a = [randint (1,60),randint (1,60),randint (1,60), randint (1,60),randint (1,60) ,randint (1,60)] b = [] for value in a: while value in b: value = randint(1, 6) b.append(value) print (b)
''' 집합 자료형: 중복을 허용하지 않고 순서가 없음 1. 리스트나 문자열을 이용하여 초기화: set() 함수 이용 2. {}에 ,로 구분하여 초기화 가능 3. 데이터 조회나 수정에 있어서 0(1)이라는 시간복잡도를 가짐 ''' # set([]), {} a = set([1, 1, 2, 3]) print(a) b = {4, 5, 5, 6} print(b)
''' 논리연산자: 논리 값 사이의 연산을 수행 1. a and b: a와 b가 모두 True일 때 True반환 2. a or b: a나 b중에 하나라도 True면 True반환 3. not a: a가 False면 True, True면 False를 반환 ''' a = int(input("정수를 입력해주세요: ")) if a<=50 and a>=0: print("0이상 50이하의 정수를 입력하셨군요!.")