text stringlengths 37 1.41M |
|---|
def get_str(str1):
character = str1[0]
str1 = str1.replace(character, '$')
str1 = character + str1[1:]
return str1
if __name__ == "__main__":
string_made = input('Enter the string: ')
print(get_str(string_made)) |
name_list = ['Sudarshan', 'Niku', 'Suraj', 'Swapnil']
def find_john(name_list):
for i in name_list:
if i == 'John':
return i
return "Not found"
print(find_john(name_list))
|
d1 = {'Apple': 1, 'Banana': 2, 'Orange': 3}
d2 = {'Queen': 4, 'King': 5, 'Prince': 6, 'Princess': 7}
dict3 = d1.copy()
dict3.update(d2)
print(dict3) |
paragraph = "tar rat arc car elbow below state taste cider cried dusty got hurt my chin"
paraSplit = paragraph.split()
def findAnagram(paraSplit):
dict = {}
for word in paraSplit:
key = ''.join(sorted(word))
if key in dict.keys():
dict[key].append(word)
else:
di... |
d1 = {0: 1, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 15, 7: 20}
def check_key_presence(d1, k):
if k in d1:
print('Key is present.')
else:
print('key is not present.')
check_key_presence(d1, 2)
check_key_presence(d1, 3)
check_key_presence(d1, 5)
check_key_presence(d1, 11)
check_key_presence(d1, 6)
che... |
#!/usr/bin/python3.6
def plus(a, b):
return a + b
def minus(a, b):
return a - b
def durchschnitt(a, b):
return (a + b) / 2
def gleiches_vorzeichen(a, b):
return (a >= 0 and b >= 0) or (a < 0 and b < 0)
while True:
a = float(input('Erste Zahl: '))
b = float(input('Zweite Zahl: '))
op = i... |
for i in range(10):
print(i)
for c in "Hallo":
print(c)
for line in open("lyrics.txt"):
print(line.strip())
for zahl in [1, 2, 3, 4, 5]:
print(zahl)
for index, wort in enumerate(['Habe', 'nun', 'ach'], 1):
print(f"Das {index}. Wort ist { wort }.")
|
def print_2(eins, zwei):
print(eins, zwei)
def print_1(eins):
print(eins)
def print_nichts():
print('Nichts')
print_2('Zwiebelnsauce', 'Bratwurst')
print_1('Eule')
print_nichts()
vorname = 'Marco'
nachname = 'Schmalz'
print_2(vorname, nachname)
# Speziell in Python
print_2(zwei=nachname, eins=vorname)... |
liste = [1, 2, 3, 4, 5, 6]
print("Zweites Element:", liste[1])
print(liste[1:3])
print(liste[1:])
print(liste[-1])
print(liste[:3])
print('anna'[2])
print('anna'[1:3])
|
#!/usr/bin/python3
import csv
filename = 'mitglieder.csv'
for mitglied in csv.DictReader(open(filename)):
# Frage: Wie lauten die Emailadressen der Mitglieder die noch nicht
# bezahlt haben?
print(mitglied['Vorname'], mitglied['Nachname'])
# Idealer Output: "Vorname1 Nachame1" <email1@example.com>, "Vo... |
def isPalindrome(word):
for index in range(len(word) // 2):
if word[index] != word[-index-1]:
return False
return True
def isPalindromRekursiv(word):
if len(word) <= 1: # simple Fälle
return True
else:
if word[0] != word[-1]:
return False
else:
... |
for i in range(10): # for (int i=0; i<10; i++) {}
print(i)
print("-" * 20)
for i in range(1, 11, 2):
print(i)
|
#!/usr/bin/python3
import csv
import datetime
heute = datetime.date.today()
file = open('../team.csv')
reader = csv.DictReader(file)
entries = list(reader)
lehrlinge = []
for entry in entries:
if 'Lehre' in entry['Gruppen'].split(', '):
lehrlinge.append(entry)
for lehrling in lehrlinge:
datumsliste... |
cantidadNumeros = 0
numerosSumatoria = 0
resultado = 1
print("en este programa haremos la division de la cantidad de numeros que tu quieras")
cantidadNumeros = int(input("Cuantos numeros deseas dividir?"))
for i in range(1,cantidadNumeros + 1):
numerosSumatoria = int(input("ingresa el valor"))
if(i == 1):
... |
def is_equilateral(a, b, c):
return a == b == c
def is_isosceles(a, b, c):
return a == b or b == c or c == a
def is_scalene(a, b, c):
return a != b and b != c and c != a
a = input('Enter the length of the first side: ')
b = input('Enter the length of the second side: ')
c = input('Enter the length of the... |
# Car Assignment
class Car:
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if price > 10000:
self.tax = "15%"
else:
self.tax = "12%"
def displayAll(self):
... |
# For Loop Basic 1
# 1. Basic - Print all the numbers/integers from 0 to 150
for num in range(0, 151):
print(num)
# 2. Multiples of five - Print all the multiples of 5 from 5 to 1,000,000
for five in range(0, 100001):
if(five % 5 == 0):
print(five)
# 3. Counting, the Dojo Way - Print integers 1 to 10... |
# Insertion Sort
arr = [4,3,2,10,12,1,5,6]
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print(arr)
return arr
insertionSort(arr)
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list
if __name__ == '__main__':
n = int (input ().strip ())
arr = list (map (int, input ().strip ().split ()))
print (sorted (set (arr))[-2])
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/the-minion-game
def minion_game(s):
# your code goes here
vowels = 'AEIOU'
kevsc = 0
stusc = 0
slen = len (s)
for i in range (slen):
if s[i] in vowels:
kevsc += (slen - i)
else:
stusc += (slen... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/designer-door-mat
N, M = map(int,input().split())
for i in range(1,N,2):
print (('.|.' * i).center (M, '-'))
print ('WELCOME'.center (M, '-'))
for i in range(N-2,-1,-2):
print (('.|.' * i).center (M, '-'))
|
#!/usr/bin/env python3
def jump_clouds (c):
x = len (c)
j = 0
i = 0
while i < (x - 1):
if i + 2 < x and c[i + 2] == 0:
i += 2
j += 1
elif i + 1 < x and c[i + 1] == 0:
i += 1
j += 1
return j
_ = input ()
c = list (map (... |
#!/usr/bin/env python3
from collections import Counter
_ = input ()
stock = Counter (input ().strip ().split ())
pairs = 0
for n in stock.values ():
pairs += int (n / 2)
print (pairs)
|
#https://www.acmicpc.net/problem/2580
import sys
def search(board,i,j):
count=[0]*10
#row
for k in range(9):
count[board[i][k]]+=1
#column
for k in range(9):
count[board[k][j]]+=1
#square
x=i//3
y=j//3
for n in range(3):
... |
#https://www.acmicpc.net/problem/2581
def isPrime(x):
if x==1:
return False
for d in range(1,int(x**0.5)):
if x==d+1:
continue
if x%(d+1)==0:
return False
else:
return True
N=int(input())
M=int(input())
sum=0
min=10001
for x in range(N,M+1):
if i... |
#https://www.acmicpc.net/problem/1193
import math
def get_order(X,group):
max_order=(group*(group+1))/2
return group+X-max_order
X=int(input())
sol=(-1+(1+8*X)**0.5)/2
group=math.ceil(sol)
order=get_order(X,group)
if group%2==0:
print('%d/%d'%(order,group+1-order))
else:
print('%d/%d'%(group+1-order,... |
import urllib.request
from bs4 import BeautifulSoup as BS
def fetch_poem():
'''Fetch Shakespeare poems from MIT site (http://shakespeare.mit.edu/)
and writes them into a file poem_name.txt for example The Sonnets.txt
Also return a dictionary with poem name as key and the poem as value'''
poems = { "A Lover's Com... |
# Ref link: https://www.youtube.com/watch?v=0DnG0Kc9M2E
def diagonal_matrix_traversal(mat, rows, cols):
if not mat or not mat[0]:
return []
diagonals = [[] for i in range(rows + cols - 1)]
for i in range(rows):
for j in range(cols):
diagonals[i + j].append(mat[i][j])
res = d... |
def check_array_rotation(arr, size):
if size == 0:
return 0
min = 0
for i in range(1, size):
if arr[i] < arr[min]:
min = i
return min
size = int(input())
arr = [int(element) for element in input().split()] [ : size]
print(check_array_rotation(arr, size))
|
# Second Largest in array
# You have been given a random integer array/list(ARR) of size N.
# You are required to find and return the second largest element present in the array/list.
# If N <= 1 or all the elements are same in the array/list then return -2147483648 or -2 ^ 31.
# (It is the smallest value for the rang... |
# Swap Alternate
# You have been given an array/list(ARR) of size N. You need to swap every pair of alternate elements in the array/list.
# You don't need to print or return anything, just change in the input array itself.
# Input Format :
# The first line contains an Integer 't' which denotes the number of test cases... |
# 1 2 3 4 5
# 2 2 3 4 5
# 3 3 3 4 5
# 4 4 4 4 5
# 5 5 5 5 5
#for taking input from user
n=int(input())
#loop for rows
for i in range(1,n+1):
#loop for colunmns
for j in range(1,n+1):
if j<=i:
print(i,end="")
else:
print(j,end="")
print() |
import sys
import re
def main(path_to_file):
regex = r"\w+|\S"
output = []
with open(path_to_file, 'r') as in_file:
for line in in_file:
sentence = []
for match in re.finditer(regex, line, re.MULTILINE | re.UNICODE):
sentence.append(match.group())
if(len(sentence) > 0):
output.append(sentence)
p... |
# Jake Carpenter
# CS 21, Fall 2018
# Program: tennis
from random import random
# plays a single game
def play_game(prob_a):
a=0
b=0
points = ['0','15','30','40']
# plays the game until someone wins or it goes into deuce
while a<=3 and b<=3 and (a!=3 or b!=3):
# see who won th... |
TICKET_PRICE = 10
SERVICE_CHARGE = 2
tickets_remaining = 100
def calculate_price(num):
return (num * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining >= 1:
print("There are {} tickets remaining.".format(tickets_remaining))
name = input("Please type your name: ")
print("Hello, {}!!".format(name... |
# coding=utf-8
dineromensual=int(input("Dinero mensual a guardar\n"))
years = int(input("Años a guardar\n"))
#Inicializacion de los 12 meses
meses = []
for mes in range(12):
meses.append(mes)
interes = 1.035
dineromes = []
dinerosininterez = (dineromensual*12) * years
dineroconinterez = 0
for _ in range(len(me... |
Entrada = []
Contador_paginacao = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
while True:
valor_entrada = int(input("Digite a páginação: "))
if valor_entrada in Entrada:
Contador_paginacao[valor_entrada - 1] = Contador_paginacao[valor_entrada - 1] + 1
print(Entrada)
print(Contador_paginacao)... |
#!/usr/bin/env python
class isy(object):
def __init__(self,y,m,d):
print 'now is',y,m,d
if y%100==0:
if y%400==0:
print 'yes'
else:
print 'no'
elif y%4==0:
print 'yes'
else:
print 'no'
a=isy(2004,1,1)
|
def function1(x, y):
big, small = (x, y) if x > y else (y, x)
leaves = big % small
if not leaves == 0:
return function1(small, leaves)
else:
return small
print(function1(-165, -3))
|
def max_array(array):
max = 0
for e in array:
if e > max:
max = e
return max
def min_array(array):
min = 2000000
for e in array:
if e < min:
min = e
return min
if __name__ == "__main__":
array = [2,3,4,5,6,7,78,321,2,12,1,2]
print(max_array(array... |
# lambda expressions
from functools import reduce
# lambda syntax:
# lambda param: action(param)
# my_list = [1, 2, 3]
# def multiply_by2(item):
# return item*2
# def only_odd(item):
# return item % 2 != 0
# def accumulator(acc, item):
# print(acc, item)
# return acc + item
# print(list(map(lambd... |
# Frequency Counter - sameFrequency
# Write a function called sameFrequency. Given two positive integers, find out if the two numbers have the same frequency of digits.
# Time Complexity Should be O(N)
############### METHOD 01 ###############
from collections import Counter
def sameFrequency(num1, num2):
return Co... |
# Sliding Window
# This pattern involves creating a window which can either be array or number from one position to another.
# Depending on a certain condition, the windows either increases or closes (and a new window is created)
# Very useful for keeping track of a subset of data in an array/string etc
# Example
# Wr... |
# Sliding Window - maxSubarraySum
# Given an array of integers and a number, write a function called maxSubarraySum which finds the maximum sum of a subarray with the length of the number passed to the function.
# Note that a subarray must consist of consecutive elements from the original array. In the first example b... |
# ---------------------- PROBLEM 08 (RANDOM) ----------------------------------#
# Write a function called maxSubarraySum which accepts an array of integers and
# a number called n. The function should calculate the maximum sum of n consecutive
# elements in the array.
# Sample input: [1, 2, 5, 2, 8, 1, 5], 2
# Sampl... |
class Graphs:
def __init__(self):
self.adjacencyList = {}
def addVertex(self, vert):
if vert not in self.adjacencyList:
self.adjacencyList[vert] = []
return self.adjacencyList
def addEdge(self, vert_01, vert_02):
self.adjacencyList[vert_01].append(vert_02)
self.adjacencyList[vert_02].append(vert_01)
... |
# Write a function called someRecursive which accepts an array and a callback. The function returns true if a single value in the array returns true when passed to the call back. Otherwise it returns False.
def isOdd(num):
if num % 2 != 0: return True
def isEven(num):
if num % 2 == 0: return True
def someRecursive(... |
# Strings - Non Repeating Character
def non_repeating(stri):
count = {}
for i in range(len(stri)):
char = stri[i]
if char in count:
count[char] += 1
else:
count[char] = 1
for char in stri:
if count[char] == 1:
return char
return None
print(non_repeating('aabcb')) # c
print(non_repeating('xxyz')) #... |
# Write a recursive function called flatten which accepts an array of arrays and returns a new array with all values flattened.
def flatten(arrs):
if arrs == []:
return arrs
if isinstance(arrs[0], list):
return flatten(arrs[0]) + flatten(arrs[1:])
return arrs[:1] + flatten(arrs[1:])
print(flatten([1,2,3,[4,5]]... |
# Applications (Its a FIFO Data Structure):
# Queue of any kind | Background Tasks | Uploading Resources | Printing / Task Processing
# Big O of Queues - Insertion - O(1) | Removal - O(1) | Searching - O(N) | Access - O(N)
class Node:
def __init__(self, val):
self.val = val
self.next = None
class Queue:
def __i... |
# Write a recursive function called capitalizeWords. Given array of words, return a new array containing each word capitalized.
################# METHOD 01 #################
def capitalizeWords(arr, result=[]):
if len(arr) == 0: return result
result.append(arr[0].upper())
return capitalizeWords(arr[1:], result) |
# Write a function called ProductofArray which takes in an array of numbers and returns the product of them all.
def ProductofArray(arr):
if len(arr) == 0: return 1
return arr[0] * ProductofArray(arr[1:])
print(ProductofArray([1,2,3])) # 6
print(ProductofArray([1,2,3,10])) # 60 |
# Factorial
# Write a function which accepts a number and returns the factorial of that number. A factorial is the product of an integer and all the integers below itl e.g. factorial four is equal to 24. factorial zero is always 1.
def factorial(num):
if num == 0: return 1
return num * factorial(num-1)
print(factori... |
# Anagrams
# he goal of this exercise is to write some code to determine if two strings are anagrams of each other.
# An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
# For example:
# "rat" is an anagram of "art"
# "alert" is an anagram of "alter"
# "Slot machin... |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, val):
newNode = Node(val)
if self.root is None:
self.root = newNode
return self
currentNode = self.root
while True:
if newNode.val > ... |
# Write a recursive function called fib which accepts a number and returns the nth number in the Fibonacci sequence. Recall that the Fibonacci sequence is the sequence of whole numbers 1,1,2,3,5,8....which starts with 1 and 1, and where every number thereafter is equal to the sum of the previous two numbers.
def fib(n... |
"""
Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе.
"""
try:
b_attribute = b'attribute'
except Exception as exc:
print("Не удалось записать в байтовом виде", b_attribute)
try:
b_class = b'класс'
except Exception as exc:
print("Не удалось записать ... |
'''
Created on 2013-2-26
@author: yannpxia
'''
def Sum_Square_Difference(num):
list=[]
for i in range(1,num + 1):
difference = Sum_and_square(i) - Squar_and_sum(i)
list.append(difference)
return list
def Squar_and_sum(num):
sum = 0
for i in range(1,num+1):
sum = sum + i*i ... |
# return the length of list
a = [1, 2, 3, 5, 8]
print(len(a))
print(max(a))
print(min(a))
print(sorted(a))
print(list(reversed(a)))
print(a)
|
# Code to implement a B-tree
# Programmed by Hugo Chavez
# Last modified February 12, 2019
import math
class BTree(object):
# Constructor
def __init__(self,item=[],child=[],isLeaf=True,max_items=5):
self.item = item
self.child = child
self.isLeaf = isLeaf
if max_... |
class Undirected_Graph_Adjlist_Hashtable:
def __init__(self):
self.graph = {}
self.nodeNum = 0
def add_vertex(self,node):
if node not in self.graph:
self.graph[node] = []
self.nodeNum += 1
else:
raise "Conflict Node"
def add_edge... |
from tkinter import messagebox
from views.GUI.withdraw_interface import WithdrawInterface
class WithdrawController():
'''
Controller class for the WithdrawInterface view.
Attributes:
main_controller: a reference to the main controller object
withdraw_interface: the view thi... |
# JAGGED ARRAYS
# Playing arround with Python to create a jagged array class
class JaggedArray():
def __init__(self, rows=1):
if isinstance(rows, int) and rows > 0:
self.rows = rows
self.jArray = []
for i in range(self.rows):
self.jArray.append([])
... |
"""
Напишите функцию, которая возвращает все варианты комбинаций членов списков, переданных на вход.
Пример:
pairwise([1, 2, 3], ['a'], [True, False]) = [
[1, 'a', True],
[1, 'a', False],
[2, 'a', True],
[2, 'a', False],
[3, 'a', True],
[3, 'a', False]
]
"""
import json
from typing import List... |
"""
В магазине продается неограниченное количество плинтусных реек с длинами 1,2,…,n. Вы хотите купить некоторый набор реек,
чтобы получить суммарную длину L.
Разрешается чтобы в вашем наборе были рейки имеющие одну и ту же длину. Какое минимальное количество реек нужно, чтобы
получить длину L?
Формат входных данных
Е... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def fibby():
a,b = 0,1
yield a
yield b
while True:
a,b = b,a+b
yield b
N = input()
kk = fibby()
print(map(lambda x:x**3,[kk.next() for x in range(N)]))
|
my_tuple = tuple()
print(my_tuple)
my_tuple = ()
print(my_tuple)
rndm = ("M. Jackson", 1958, True)
print(rndm)
("self_taught",)
dys = ("1984", "Brave new World", "Fahrenheit 451")
print(dys[1])
#dys[1] = "Handmaid's Tale"
print("1984" in dys)
print("Handmaid's Tale" not in dys)
my_dict = dict()
... |
import torch
import torch.nn.functional as F
class Net(torch.nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)
def forward(self,x):
x = F.re... |
#A+BのAの部分を入力してもらう
input_numberA = input('数値を入力してください: ')
while not input_numberA.isdigit():
input_numberA = input('数値を入力してください: ')
numberA = int(input_numberA)
input_while = ' '
answer = numberA
while input_while != 'end':
print(answer)
print("1, +\n2, -\n3, ×\n4, ÷ ")
#演算記号の選択をしてもらう
input_symbo... |
hvelho = ''
ivelho = 0
mulheres = 0
sidade = 0
for c in range(1, 4):
print('---- {}° PESSOA ----'.format(c))
n = input('NOME: ')
i = int(input('IDADE: '))
s = input('SEXO [M/F]: ').strip().lower()
sidade = sidade + i
if c == 1 and s == 'm':
hvelho = n
ivelho = i
... |
n = 1
while n != 0:
n = int(input('Digite um valor: '))
print('FIM')
c = 2
while c <= 20:
print(c)
c = c + 1 |
ano = int(input('Digite o ano aqui: '))
r = ano % 4
t = ano % 100
y = ano % 400
import datetime
print(datetime.date.today().year)
if r == 0 and t != 0 and y == 0:
print('O ano é bissexto')
else:
print('O ano não é bissexto') |
j = ('n', 'b', 'w', 'c', 'i', 't', 'a', 'n', 'f', 'j')
print(j[0:6])
print(j[-1:-5: -1])
print(sorted(j))
print(j.index('c')) |
lista = []
apareceu = False
while True:
v = int(input('Digite um valor: '))
if v in lista:
print('Valor duplicado. Não adicionado')
else:
lista.append(v)
print('Valor adicionado com sucesso.')
if v == 5:
apareceu = 'sim'
resp = input('Deseja continuar?')
... |
print('Gerador de PA:')
print('=-' * 20)
p = int(input('Primeiro termo:'))
r = int(input('Razão da PA:'))
cont = 0
while cont <= 10:
print('{} >> '.format(p), end = '')
p = p + r
cont += 1
print('PAUSA')
t = 1
while t > 0:
t = int(input('Quantos termos a mais você quer mostrar? '))
ncon... |
print('-'*40)
print(' JOGO NA MEGA SENA ')
print('-'*40)
jogos = int(input('Quantos jogos você quer que eu sorteie? '))
print('-+'*3, f'SORTEANDO {(jogos)} JOGOS', '-+'*3,)
import random
from time import sleep
lista = []
aux = []
for b in range(0, jogos):
while len(aux) < 6:
n =... |
def reverseLinkedListInRange(head, start, end):
'''
Given the head node of a Linked List and a start and end index, reverse the order of the nodes between the start and end
indicies.
Example:
head -> 1 -> 2 -> 3 -> 4 -> 5, start = 2, end = 4. Result => head -> 1 -> 4 -> 3 -> 2 -> 5
'''
curr... |
class WordDictionary(object):
'''
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or ".".
A "." means it can represent any one letter.
... |
#!/usr/bin/python
#coding:utf-8
from string import Template
#3-1
print '#3-1'
#3-2
print '#3-2'
format = "Hello, %s, %s enough for ya?"
values = ('world','Hot')
print format % values
format = "Pi with three decimals: %.3f"
from math import pi
print format % pi
s = Template('$x, glorious $x!')
print s.substitute(x='... |
import re
#getting the text the file "two cities"
text = open("two_cities.txt",encoding='utf-8').read().replace('\n','')
#getting the total length of the text for the loop
text_length = len(text)
#deleting anything but letters and spaces(" ")
i = 0
while i < (text_length):
if (not((text[i] == " ") or (re.match("... |
def add(x, y):
return x+y
def subtract(x, y):
return x-y
def multiply(x, y):
return x*y
def divide(x, y):
return x/y
print(" Welcom to Tandemloop Simple Calculator.")
while True:
operation = input("Enter operation(add subtract divide multiply): ")
if operation in ('add', 'subtract', 'divide',... |
'''Given a 32-bit signed integer, reverse digits of an integer.'''
class Solution:
def reverse(self, x: int) -> int:
import math
if -math.pow(2,31) < x < math.pow(2,31)-1:
if x > 0:
result = int(str(x).rstrip('0')[::-1])
if result < math.pow... |
#!/bin/python
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return "Student object (name: %s)" % self.name
__repr__=__str__
def print_score(self):
print("%s: %s" % (self.name, self.score))
bart = St... |
def expect(xDistribution, function):
xvals = list(xDistribution.keys())
prob = list(xDistribution.values())
outputlist = [function(xvals[j]) * prob[j] for j in range(len(prob))]
expectation = sum(outputlist)
return expectation
##################################################
# ... |
#!/usr/local/bin/python3
"""
Let's play Blackjack!
Blackjack game using deckofcardsapi.com
"""
import random
import requests
from pprint import pprint
"""
TODO (Done) Start new game
Create new deck and set number of players
TODO (Done) Reshuffle function
Reshuffle existing deck
TODO (Don... |
#!/bin/python3
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)... |
# Complete the solve function below.
def solve(s):
words = s.split(" ")
temp = []
for word in words:
if word != '':
word = list(word)
word[0] = word[0].upper()
word = "".join(word)
temp.append(word)
s = " ".join(temp)
print(s)
r... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the camelcase function below.
def camelcase(s):
from collections import Counter
dc = Counter(s)
new_dict = dict()
for key, value in dc.items():
if str(key).isupper():
new_dict[key] = value
s =... |
"""
This script builds and runs a graph with miniflow.
There is no need to change anything to solve this quiz!
However, feel free to play with the network! Can you also
build a network that solves the equation below?
(x + y) + y
"""
from miniflow import *
t, u, v, w, x, y, z = Input(), Input(), Input(), Input(), I... |
#Phonebook using Hash Table#
#"defaultdict" is first imported from the collections
from collections import defaultdict
count=0 #for checking table size
class HashTable:
def __init__ (self, size):
self.HashT... |
"""
dlib test.
This was used for learning how to used dlib for face key-point detection.
Not final result of project.
Used tutorials:
http://www.paulvangent.com/2016/08/05/emotion-recognition-using-facial-landmarks/
http://www.paulvangent.com/2016/04/01/emotion-recognition-with-python-opencv-and-a-face-dataset/
by __... |
def preference():
answer = input("hi, do you wanna play a game?: ")
if answer == "yes":
print("schweet!")
from time import sleep
sleep(1.4) # Time in seconds
print("i knew you would make the right choice")
from time import sleep
sleep(1.2) # Time in seconds
... |
import pickle
import random
class TweetGenerator:
def __init__(self):
self.transition_dict = {}
self.loaded = False
def load_generator(self, filename):
"""
Prep the generator by specifying the markov chain's transition probabilities.
:param filename: file location of ... |
from collections import deque
def main():
n = int(input())
words = {input(): set() for _ in range(n)}
m = int(input())
for _ in range(m):
a, b = input().split()
words[a].add(b)
words[b].add(a)
colors = {}
q = deque()
for start in words.keys():
if s... |
#!/usr/bin/env python3
"""
Small method just to help me with small tasks.
"""
import os
import argparse
from PIL import Image
def crop_image(file_path, padding, dest_path=None):
"""Crop Image"""
try:
image = Image.open(file_path)
image = image.crop((padding, padding, image.size[0] - paddi... |
import curses
from random import randint
curses.initscr()
curses.noecho()
curses.curs_set(0)
win = curses.newwin(20,60,0,0) #y,x not x,y
win.keypad(1)
win.border(0)
win.nodelay(1)
snake = [(4,10),(4,9),(4,8)]
food = (10,20)
ESC = 27
key = curses.KEY_RIGHT
score = 0
win.addch(food[0],food[1],"O")
while key!=ESC:
... |
from tkinter import *
from functools import partial
import random
class Menu:
def __init__(self):
# Formatting variables
background_color = "deep sky blue"
# Menu frame
self.menu_frame = Frame(width=10, bg=background_color, pady=10)
self.menu_frame.grid()
# Qui... |
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans = []
def backtrack(S = '', left = 0, right = 0):
if len(S) == 2 * n:
ans.append(S)
return
if left < n:
... |
def removeDuplicates(nums,val):
length = len(nums)
if length == 0:
return 0
point = 0
for i in range(0,len(nums)):
if nums[i] != val: #如果相等,point不动,先赋值再前进
nums[point] = nums[i]
point += 1
return point,nums
print(removeDuplicates([1,2,2,3,4,6,7,2],2))
|
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic = {}
for value in nums:
if value in dic:
return True
else:
dic[value] = 1
return False
def c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.