text stringlengths 37 1.41M |
|---|
'''
problem statement: https://www.hackerearth.com/practice/algorithms/searching/linear-search/practice-problems/algorithm/monk-takes-a-walk/
'''
def isVowels(chr):
vowels = ['A', 'E', 'I', 'O', 'U' ,'a','e','i','o','u']
if chr in vowels:
return True
else:
return False
for t in range(in... |
print ("--Calculator--")
while True:
inp1 = input("Masukkan angka pertama: ")
inp2 = input("Masukkan angka kedua: ")
print ( "1 Bagi \n"
"2 Kali \n"
"3 Jumlah \n"
"4 Kurang\n"
"5 Exit")
op = input("Operator yang ingin digunakan? ")
if op == "1":
... |
real_user = 'harris'
real_pass = '1234'
tries = int(input("Berapa Kali Coba: "))
for tries in range(tries,0,-1):
print (f"Anda memiliki {tries} coba")
guess_user = input('Masukkan username: ')
guess_pass = input('Masukkan password: ')
if guess_user == real_user and guess_pass == real_pass:
pr... |
class A:
pass
class B:
pass
class C:
pass
class D(A):
pass
class E(A, B):
pass
class F(E, C):
pass
a, b, c, d, e, f = A(), B(), C(), D(), E(), F()
print((isinstance(a, A)))
print((isinstance(a, B)))
print((isinstance(a, C)))
print((isinstance(a, D)))
print((isinstance(a, E)))
print(... |
s = set([1, 2, 3])
t = set([3, 4, 5])
s.symmetric_difference_update(t)
t.symmetric_difference_update(s)
print(s)
print((s == t))
print((s == set([1, 2, 4, 5])))
print((s == set([1, 2, 3])))
|
import random
random.seed(0)
print("randint")
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print("randrange")
print(random.randrange(4, 9))
print(random.randrange(4, 9))
print(random.randrange(4... |
class A:
pass
a = A()
print((isinstance([], list)))
print((isinstance([], dict)))
print((isinstance([], str)))
print((isinstance([], tuple)))
print((isinstance([], A)))
print("---")
print((isinstance({}, list)))
print((isinstance({}, dict)))
print((isinstance({}, str)))
print((isinstance({}, tuple)))
print((isi... |
l = ["h", "e", "l", "l", "o"]
print((l.index("l")))
print((l.index("l", 2)))
print((l.index("l", 3)))
print((l.index("l", 2, 3)))
print((l.index("l", 3, 4)))
print((l.index("l", 2, -1)))
print((l.index("l", 2, -2)))
print((l.index("l", 3, -1)))
try:
print((l.index("l", 4)))
except ValueError as e:
print((repr... |
def helper(got, expect):
if got == expect:
print(True)
else:
print(False, expect, got)
print("\nstr.capitalize")
helper("hello world".capitalize(), "Hello world")
helper("HELLO WorlD".capitalize(), "Hello world")
print("\nstr.center")
helper("12345".center(7), " 12345 ")
helper("12345".center... |
def f(n):
for i in range(n):
yield i
g = f(5)
print((next(g)))
print((next(g)))
print((next(g)))
print((next(g)))
|
c = "squirrel"
time = 0
def x():
global time
time += 1
if time == 1:
b = "dog"
else:
b = "banana"
print((b, c))
def y(d):
a = "cat"
print((a, b, d))
def z():
for i in range(10 * time):
yield i, a, b, c, d
return z
... |
print(int())
print(type(int()))
# integers and long integers
print(int(123))
print(int(-123))
print(int(456))
print(int(-456))
# floating point
print(int(-1.1))
print(int(-0.9))
print(int(-0.1))
print(int(0.5))
print(int(0.9))
print(int(1.1))
# string
print(int("10"))
print(int(" -1234 "))
print(int("101", 0))
prin... |
l = [1, 2, 3, 4]
t = (1, 2, 3, 4)
d = {1: 2, 3: 4}
s = "1234"
print(list(zip()))
print(list(zip(l)), list(zip(t)), list(zip(d)), list(zip(s)))
print(list(zip(l, t)), list(zip(l, d)), list(zip(l, s)))
print(list(zip(t, d)), list(zip(t, s)))
print(list(zip(d, s)))
print(list(zip(l, t, s)))
print(list(zip(l, t, s, d)))... |
a = [1, 2, 3, 4, 5, 6]
b = [9, 9, 9]
a[1:5] = b
print(a)
mylist = ["a", "b", "c", "d"]
d = {"1": 1, "2": 2}
mylist[0:2] = d
print(mylist)
mylist[1:3] = "temp"
print(mylist)
mylist[:] = ["g", "o", "o", "d"]
print(mylist)
|
myList = [1, 2, 3, "foo", 4, 5, True, False]
print(myList.index("foo"))
print("foo" in myList)
print(myList.index(True))
print(2 in myList)
|
import sys
import json
def extract_tweets(tweet_file):
'''Function which return a list of tweets given a raw tweet txt file. '''
tweets = []
for line in tweet_file.readlines():
try:
tweet =json.loads(line)
tweet_text=tweet[u'text']
tweets.ap... |
import datetime
year = datetime.date.today().year
birth_year = input('What year were you born?')
print(int(year) - int(birth_year))
|
#!/usr/bin/python
mylist=['Das Wetter']
#mylist[2]='ist'
mylist.insert(2, 'ist')
mylist.insert(3, 'sehr')
mylist.append('schoen')
print(mylist) # Das Ergebnis? |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Creation: 07.04.2015
# Last Update: 07.04.2015
#
# Copyright (c) 2015 by Georg Kainzbauer <http://www.gtkdb.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free... |
#!/usr/bin/env python
from time import sleep
number = float(raw_input("Give me a number: "))
if number % 2 == 0:
print number**4
else:
print number
sleep (5) |
import re
from collections import defaultdict, Counter
class Coordinate:
def __init__(self, input_string = '', x = None, y = None):
if (x == None and y == None):
# Example: '220, 349'
regex = '(\d+), (\d+)'
(x,y) = re.findall(regex,input_string)[0]
self.x = i... |
"""
Hello freinds Today you will make a Tic-Tac-Toe;
Language:Python;
library:Tkinter;
Let's start...
"""
#First import everything from Tkinter.
from tkinter import *
"""
Now You are import messegabox from tkinter.
The messageboxes is used when any user is win
or
draw.
"""
from tkinter import messagebox
"""
rooms var... |
print("Welcome to the Simple Calculator")
num1 = input("Please enter your first number")
num2 = input("Please enter your second number")
Operation = input("Please select your operation : + - * /")
if Operation == "+" :
print(float(num1) + float(num2))
elif Operation == "-" :
print(float(num1) - float(num2))
eli... |
import math
class Shape:
def __init__(self, a=8, b=9):
self.set_params(a, b)
def set_params(self, a, b):
self._a = a
self._b = b
def get_a(self):
return self._a
def get_b(self):
return self._b
def __repr__(self):
return self.__class__.__name__ + "[... |
# en son yaptigim sey bu
import pygame
import sys
pygame.init()
WindowX = 1000
WindowY = 1000
gLength = WindowX / 6
windowSize = (WindowX, WindowY)
screen = pygame.display.set_mode(windowSize)
myriadProFont = pygame.font.SysFont("Myriad pro", 70)
helloWorld = myriadProFont.render("Hello Worldzzz", 1, (255, 0, 255)... |
"""
@author: Hensel
8/30/16
Assignment 8.4 : lists
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
The program should build a list of words. For each word on each line check to see if the word is already in the list,
if not append i... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 25 11:30:31 2016
@author: Hensel
Strings: Chapter 6
"""
#we can get at ant string character in a tring using an index specified in square brakets[]
# 0 is the 1st value of the string
fruit = 'banana'
letter = fruit[1] # 1 vaule is 2nd value in the string above or a
... |
#try and except practice from lecture 3.3 in week 5
#try and except pairs
astr = 'hello Bob'
try:
istr = int(astr)
except:
istr = -1
print 'Done', istr
#check an input value bellow
rawstr = raw_input('Enter a number:')
try:
ival = int(rawstr) #converts to intiger or blows up
except:
ival = -1
if i... |
"""
@author: Hensel
9/1/16
Chapter 10 Tuples!
"""
#Tuples are another kind of sequence that function much like a list
#they have elements which are indexed starting at 0
#Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string!
#Tuples are 'immutable' (unlike lists) ALSO cant sor... |
"""
@author Hensel
Chapter 9: word counting program
"""
name = raw_input('Enterfile:') #ask for file name
handle = open(name,'r') #ask file to open and read
text = handle.read() #read whole file newlines and all, put in variable 'text'
words = text.split() #go through whole string and split to list called 'words'
co... |
"""
@author: hensel
8/30/16
Chapter 8 worked Exercise: Lists
Source: https://www.coursera.org/learn/python-data/lecture/t8uFQ/worked-exercise-lists
goal:
debug a program
"""
#if program chokes on blank lines, use 'Gaurdian pattern!'
fhand = open('mbox-short.txt')
for line in fhand :
line = line.rstrip()
wo... |
from graphics import *
import random
from random import randint
def Randcolor():
'''generate random color'''
color=color_rgb( randint( 0, 255 ), randint( 0, 255 ), randint( 0, 255 ))
return color
class background:
def __init__(self, win, w, x):
'''create columns at the bottom'''
self.x... |
class Node(object):
"""defines attributes and methods for linked list node"""
def __init__(self, init_data):
self.data = init_data
self.next = None
class LinkedList(object):
"""defines attributes and methods for linked list class"""
def __init__(self, head=None):
self.head = head
def add(self, item):
... |
def compress_encode(my_string):
"""
given a string, output a compressed encryption string.
ex.
>>> astring = "abcccccde"
>>> compress(astring)
"ab5xcde"
"""
if len(my_string)<= 1:
return "need a string greater than 1 char"
out = ""
prev = my_string[0]
count = 1
for x in my_string[1:]:
if x == prev:... |
"""Is this word a palindrome?
>>> is_palindrome("a")
True
>>> is_palindrome("noon")
True
>>> is_palindrome("racecar")
True
>>> is_palindrome("porcupine")
False
Treat spaces and uppercase letters normally:
>>> is_palindrome("Racecar")
False
"""
def is_palindrome(word):
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def print_spiral(matrix):
top = 0
bottom = len(matrix)-1
left = 0
right = len(matrix[0]) -1
output = []
while True:
#print "left", left
#print "right", right
#print "top", top
#print "bottom",... |
"""Calculate possible change from combinations of dimes and pennies.
Given an infinite supply of dimes and pennies, find the different
amounts of change can be created with exact `num_coins` coins?
For example, when num_coins = 3, you can create:
3 = penny + penny + penny
12 = dime + penny + penny
21 = dim... |
# powerSet
#
# input: string
# output: array of strings
#
# input: 'abc'
# output: ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
#
#
def powerSet(input):
# char_lst = list(input)
# out_list = [[]]
# for char in char_lst:
# print "out: ", out_list
# out_list.extend([sublist +[char] fo... |
#
# Design and Build a Tic-Tac-Toe Game
#
# Board, 2 Players
#
# 1. Select player 1 (by default O)
# 2. Player makes move (action):
# -> evaluate if action is valid (check if space is empty)
# -> make move
# 3. Check if anyone (player who moved) has won
# 4. Switch Player (return to Step 1)
#
class Board(object)... |
def bracket_matching(astring):
"""
determines whether string has valid bracket matching.
input: string
output: boolean
example:
>>> bracket_matching("({[]}())")
True
>>> bracket_matching("(()])")
False
>>> bracket_matching("test{variable()}")
True
>>> bracket_matching... |
def zero_out(matrix):
# tracker lists to keep the columns and rows to zero out
columns_to_zero = [False] * len(matrix[0])
rows_to_zero = [False] * len(matrix)
for outer_idx, row in enumerate(matrix):
for inner_idx, cell in enumerate(row):
# if we find a zero. set the appropriate indicies in trackers to True
... |
def find_smallest_index(array, start_idx):
""" takes an array and a number start_idx
returns the index of the smallest value that occurs with index start_idx or greater.
"""
min_val = array[start_idx]
min_idx = start_idx
for x in range(min_idx+1, len(array)):
if array[x] <= min_val:
min_idx = x
min_val ... |
class Node(object):
def __init__(self, val=None):
self.value = val
self.leftChild = None
self.rightChild = None
def __repr__(self):
return "<value: {}, leftChild: {}, rightChild: {}>".format(self.value, self.leftChild, self.rightChild)
class BinarySearchTree(object):
def ... |
for char in "UMSS":
print (char)
for li in ['U','M','S','S']:
print(li)
T = ("Norah","Villarroel","UMS","2019")
for t in T :
print (T.index(t), t)
D = {"nombre": 'Norah', 'universidad':"UMSS"}
for k,v in D.items():
print(k,v)
for k in D:
print(k)
|
import random
import time
#Prompt 1
print("Welcome to Multiplication Game.")
print("You will be prompted to solve a math equation")
print("and you will need to answer within 3 seconds.")
#Prompt 2
ready = input('Are you ready to play(y/n)?:\n').lower()
score = 0
#Main Game Loop
while (ready == 'y' or ready == "yes"):... |
# 实现一个简单的商城购物系统
from bll import handles
from dal import shopping_goods_data
def shopping():
prompt = "您好,欢迎使用薯条橙子在线购物系统chipscoco,输入<>中对应的指令来使用购物系统:\n" \
"<1>:查看所有商品\n<2>:对商品按售价进行排序(asc表示升序,desc表示降序)\n" \
"<3>:添加商品到购物车\n<4>:查看购物车\n<5>:删除购物车指定商品\n<6>:下单结账\n<0>:退出系统"
commands = {1: h... |
"""
Project Euler
Problem 3
Largest prime factor
Aaron Mok
08/09/14
"""
import math
#Overflow error, method doesn't work
def largest_prime(num):
arr = [True] * num
root = math.sqrt(num)
root = math.ceil(root)
for i in range(2,root,1):
if arr[i] is True:
for j in range(... |
#!/usr/bin/python
import readline
def main():
stack = [];
while(True):
# Display stack and prompt for input
str_stack = " ".join([str(e).rstrip('0').rstrip('.') for e in stack])
prompt = "> %s " % str_stack if len(stack) else "> "
token = raw_input(prompt)
... |
import math
def verify_pyth_triplet():
# I. Structure the for loop to enforce the first Pythagorean requirement a < b < c
for a in range(1, 1000):
for b in range(a + 1, 1000):
csqr = a*a + b*b
# II. The second requirement c*c = a*a + b*b also checking csqr as a conditional from the preceeding variables saves... |
def pig_it(text):
tokens = text.split(" ")
output = " ".join(word[1:] + word[0] + "ay" if str(word).isalpha() else word for word in tokens)
return output
print(pig_it("Hello world !"))
|
def get_middle(s):
mid = int(len(s) / 2)
return s[mid] + s[mid + 1] if len(s) % 2 == 0 else s[mid + 1]
def binary_array_to_number(arr):
k = 2**(len(arr)-1)
output = 0
for x in arr:
output += k * x
k /= 2
return output
binary_array_to_number([0,0,1,0])
|
"""
This provide some common utils methods for YouTube resource.
"""
import isodate
from isodate.isoerror import ISO8601Error
from pyyoutube.error import ErrorMessage, PyYouTubeException
def get_video_duration(duration: str) -> int:
"""
Parse video ISO 8601 duration to seconds.
Refer: https://develo... |
import math, collections
SpaceVectorBase = collections.namedtuple('SpaceVector', 'x y z')
#SpaceTimeVectorBase = collections.namedtuple('SpaceTimeVector', 'x y z t')#Time is relative, so use a SpaceTimeVector to do an operation as if it was a particular, known, point in time.
class VectorMethods():
def __int__(se... |
import typing
class List(typing.NamedTuple):
"""
Monad implementation for list
"""
value: list
def is_empty(self) -> bool:
"""
Check if the list is empty
:return: True if the list is empty, False otherwise
"""
return not self.value
def map(self, func) -... |
#Ejercicio5_3 Palabra o frase palindroma
cadena = input("Digite una cadena: ")
#Quitar espacios en blanco
cadena = cadena.replace(" ","")
#Invertir la cadena
cadena2 = cadena[::-1] #Cadena Invertida
print(cadena2)
if cadena == cadena2:
print("La cadena es palindroma")
else:
print("La cadena no es palindroma... |
#Ejercicio5_1 Cadena más larga
cadena1 = input("Digite una cadena: ")
cadena2 = input("Digite una cadena: ")
if len(cadena1) > len(cadena2):
print(f"\nLa cadena más larga es: {cadena1}")
elif len(cadena2) > len(cadena1):
print(f"\nLa cadena más larga es: {cadena2}")
else:
print("\nAmbas cadenas son igual... |
#Ejercicio4_3 Insertar elementos y ordenarlos
lista = []
salir = False
while not salir:
numero = int(input("Digite un numero: "))
if numero == 0:
salir = True
else:
lista.append(numero)
lista.sort()
print(f"\nLista ordenada: \n{lista}")
|
#Ejercicio6_4 Factorial de un numero (Recursividad)
def factorial(num):
if num > 0:
resultado = num * factorial(num-1)
else:
resultado = 1
return resultado
valor = factorial(5)
print(valor)
|
from Date import *
myfile=open('birthdays.txt')
myfile=myfile.read()
myfile=myfile.split('\n')
myfile2=[]
for i in range(len(myfile)-1):
myfile2.append(myfile[i].split())
ed=Date(myfile2[0][0],myfile2[0][1],myfile2[0][2])
for i in range(1,len(myfile2)):
date=Date(myfile2[i][0],myfile2[i][1],myfile2[i][2])
... |
""" This is the skeleton for your lab 10. We provide a function
here to show the use of nose.
"""
import random
def closest1(L):
if len(L)<2:
return None, None
close1=abs(L[0]-L[1])
close2=L[0],L[1]
for i in range(len(L)):
for j in range(len(L)):
if i!=j and abs(L[i]-L... |
A=int(raw_input('Enter a value ==> '))
print A
print ''
print "Here is the computation:"
def reverse(A):
X=A%100%10*100+A%100/10*10+A/100
return X
B=reverse(A)
C=abs(B-A)
print max(A,B),"-",min(A,B),"=",C
D=reverse(C)
print C,"+",D,"=",C+D
if C+D==1089:
print "You see, I told you."
else:
print "Are you ... |
clubs = {'WRPI': set(['May', 'Coulson']), 'Red Army': set(['Simmons', 'Fitz']), \
'Poly': set(['May']), 'UPAC': set(['Skye', 'Hunter']) }
if __name__=='__main__':
name=raw_input('Name ==> ')
x=set()
y=set()
for key in clubs.keys():
if name in clubs[key]:
x.add(key)
else:
... |
import time
import matplotlib.pyplot as plt
def fib1(n):
if n==0:
return 0
if n==1:
return 1
return fib1(n-1)+fib1(n-2)
def fib2(n):
for i in range(0,n+1):
f.append(i)
for i in range(2,n+1):
f[i]=f[i-1]+f[i-2]
if __name__ == '__main__':
#... |
if __name__ == '__main__':
myfile=raw_input('File name => ')
print myfile
number=int(raw_input('How many names to display? => '))
print number
myfile=open(myfile)
myfile=myfile.read()
myfile=myfile.split()
myfile2=[]
for i in range(len(myfile)):
myfile2.append(myfile[i].split... |
def cap_value(mystr):
mystr=mystr.capitalize()
return mystr
def arrange_value(mylist):
mylist.sort()
myvals=[]
finished=False
while not finished:
newval=raw_input('Enter a value (stop to end) ==> ')
if newval=='stop':
finished=True
else:
newval=cap_value(newval)
myvals.... |
word=raw_input('Word ==> ')
letters=set(word)
X=[]
for letter in list(letters):
X.append((word.count(letter),letter))
X.sort(reverse=True)
for i in range(len(X)):
print '%s: %d'%(X[i][1],X[i][0]) |
#!/usr/bin/env python
import sys
import re
for line in sys.stdin:
line = line.strip()
name = line.split('\t')[0]
words = re.findall(r'\w+',line)
for word in words:
if word:
print '%s\t%s' % (word.lower(), name)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-02-25 19:39
# @Author : ZD Liu
class Solution:
def longestCommonPrefix(self, strs):
if len(strs) > 0:
commen_prefix = strs[0]
for e in strs:
com_len = len(commen_prefix)
len_e = len(e)
... |
def menu():
print('Option-1) Read a FASTA format DNA sequence file and make a reverse sequence file.')
print('Option-2) Read a FASTA format DNA sequence file and make a reverse complement sequence file.')
print('Option-3) Convert GenBank format to FASTA format file.')
op = input('Select the option: ')
... |
a = input("Enter a string: ")
print(f"Reversed string: {a[::-1]}")
|
a = int(input("Enter a integer: "))
b = int(input("Enter another: "))
if a > b:
print(f"{a} is greater than {b}.")
elif a < b:
print(f"{a} is less than {b}.")
else:
print(f"{a} is equal to {b}.")
|
"""
Smallest Multiple
https://projecteuler.net/problem=5
"""
def is_evenly_divisible(number):
for i in range(1, 21):
if number % i != 0:
return False
return True
def main():
i = 2
while i > 0:
if is_evenly_divisible(i):
print i
return
i +... |
"""
Special Pythagorean Triplet
https://projecteuler.net/problem=9
"""
import math
def is_pythagorean_triplet(a, b, c):
return (a ** 2) + (b ** 2) == (c ** 2)
def main():
# choose arbitrary max limits for a,b.
# this is a brute force method to try all combinations of a < b until you hit the
# one wh... |
"""
Summation of primes
https://projecteuler.net/problem=10
"""
import math
def is_prime(number):
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
return False
return True
def main():
max_limit = 2000000
primes = [n for n in range(2, max_limit+1) if is_prime(n)]... |
def partition(n, I=1):
yield (n,)
for i in range(I, n//2 + 1):
for p in partition(n-i, i):
yield (i,) + p
def partitions(n):
a = partition(n)
c = 0
for i in a:
c += 1
return c
a = partitions(100)
print(a) |
word = input()
spacing = ' ' * int(input())
print(*word, sep=spacing)
|
#!/usr/bin/env python
'''
Proyecto [Python]
Consulta de accidentes -Accidentología Vial-
---------------------------
Autor: Diego Farias
Version: 1.1
Descripcion:
Programa creado para generar una lista de fechas para consulta de archivo .csv de
registro de accidentes viales.
'''
__author__ = "Diego Farias"
__email_... |
import pickle
import re
import printascii
'''
def _isupper(str):
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
res = True
for i in range (len(str)):
if upper.find(str[i])<0:
res = False
break
return res
def level0():
res = 2
for i in range(37):
res = res * 2
... |
#!/bin/python3
import math
import os
import random
import re
import sys
import copy
#
# Complete the 'crosswordPuzzle' function below.
#
# The function is expected to return a STRING_ARRAY.
# The function accepts following parameters:
# 1. STRING_ARRAY crossword
# 2. STRING words
#
def crosswordPuzzle(crossword, w... |
class Test(object):
def __init__(self):
self.name = 'abc'
def __enter__(self):
print("created")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("exit")
def test(self):
print(self.name)
print('before')
test = Test()
test.test()
print('af... |
class MinHeap():
__data = []
__size = 0
def push(self, val):
self.__data.append(val)
self.__size += 1
self.__ascend()
return
def size(self):
return self.__size
def pop(self):
temp = self.__data[0]
self.__data[0] = self.__data[self.__size-1]
... |
#Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
def ex_3(a, b, c):
z = [a, b, c]
z.remove(min(a, b, c))
return sum(z)
def ex_3_use():
print(ex_3(4, 1, 9)) |
#Funcion para convertir las letras en números
def convertir(letra): #Utilicé una lista para representar el tablero del juego, esta me permite almacenar
lista = ['A', 'B', 'C', 'D'] #tanto valores enteros (1, 2, 3 y 4) como caracteres (A, B, C y D). No podríamos hacer esto
... |
from typing import List
import pandas as pd
from pandas import DataFrame
from sklearn.utils import resample
def balance(frame: DataFrame, label: str, amount: float) -> DataFrame:
"""
:param frame: Data which should be balanced for a label
:param label: label name for which data should be balanced
:pa... |
#by Kenzin Igor
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
def electricity_bill_v1():
print("Electricity Bill Estimator V1.0")
cents_per_kwh = float(input("Enter Cents per kWh: "))
use_in_kwh = float(input("Enter Daily use in kWh: "))
days = float(input("Enter Billing Days"))
total = (use_in_kwh*(ce... |
"""
CP1404/CP5632 - Practical Solution
Broken program to determine score status
Update: FIXED
by Kenzin Igor
"""
# todo: Fix this!
# Update: FIXED
#Update: From Week 1's source code instead of printing the output i have returned the statement
def fixed_solution(score):
if(0 < score < 50):
return "Bad"
... |
#by Kenzin Igor
numbers = [3,1,4,1,5,9,2]
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(numbers[3:4])
print(5 in numbers)
print(7 in numbers)
print("3" in numbers)
print(numbers + [6, 5, 3])
# Change the first element of numbers to "ten"
print(numbers)# Change the last element of nu... |
import unittest
from stacks_queues.p32 import Stack
class TestStack(unittest.TestCase):
def setUp(self) -> None:
self.stack = Stack()
def test_push(self):
"""
stack << 1 << 4
stack.arr should contain two elements, 1 and 4
:return: void
"""
self.stack.... |
import unittest
from recursivity.p6 import towers_of_hanoi
class TestTowersOfHanoi(unittest.TestCase):
def test_move(self):
"""
Input:
stack1: [3, 2, 1]
stack2: []
stack3: []
Output:
stack1: []
stack2: []
stack3: [3, ... |
"""
Minimal Tree: Given a sorted (increasing order) array with unique integer elements,
write an algorithm to create a binary search tree with minimal height.
Source: Cracking the Coding Interview: 189 Programming Questions and Solutions
by Gayle Laakmann McDowell
"""
class Node:
def __init__(self, data: int):
... |
"""
Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a
binary search tree. You may assume that each node has a link to its parent.
Source: Cracking the Coding Interview: 189 Programming Questions and Solutions
by Gayle Laakmann McDowell
"""
class Node:
def __ini... |
import unittest
from graphs.p4_1 import Node
from graphs.p4_1 import route_exists
class TestRouteExists(unittest.TestCase):
def setUp(self) -> None:
"""
Create graph:
1: 2, 4
2: 3
3: 4
4: 5
5: _
:return: void
"""
n1 = Node(1)
... |
def h(s):
if len(s)<2:
return True
elif s[0]!=s[-1]:
return False
else:
return h(s[1:-1])
if __name__=='__main__':
s=input("请输入一个整数")
if h(s):
print("这个数是回文数")
else:
print("这个数不是回文数")
|
def ctof(c):
# 3 operations
return c*9/5 + 35
def mysum(x):
# 1
total = 0
# 1x
for i in range(x):
# 2x
total += i
return total
# num ops = 1 + 3*x |
def gentest():
yield 1
yield 2
# a = gentest()
# b = gentest()
# print(next(a))
# print(next(a))
# print(next(b))
# print(a.__next__())
def genFib():
fibn_1 = 1 #fib(n-1)
fibn_2 = 0 #fib(n-2)
while True:
# fib(n) = fib(n-1) + fib(n-2)
next = fibn_1 + fibn_2
yield next
... |
def applyToEach(L, f):
"""Apply the function to each element in the list"""
for i in range(len(L)):
L[i] = f(L[i])
def fib(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return fib(n-1) + fib(n-2)
def factorial(n):
result = 1
for i in range(1, n+1):
... |
a=int(input("Enter 1 for Even\n Enter 2 for odd\n"))
if(a==1):
b=2
elif(a==2):
b=3
else:
print("Wrong input -1")
for i in range(1,100):
if(i%b==0):
print(i)
|
nome = input("Digite um nome: ")
y = len(nome)
while y != 0:
print("%s" %nome[0:y])
y = y-1
|
#!/usr/bin/env python3
#
# connections.py is responsible for converting a connection string
# in URI form to component parts for MySQL or SQLite3 databases.
#
import os
from urllib.parse import urlparse
class ConnectionInfo:
'''ConnectionInfo provides a means to parse a URI containing a
DB connection and s... |
"""
This script start the generation of random TestBench, it ask how many testbench
to generate
"""
import generator
print("inserisci il numero di test da generare")
num = int(input())
while(num>0):
print("Sto generando")
generator.generate()
num = num -1
input("Premi per terminare")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.