text stringlengths 37 1.41M |
|---|
#This is a simple guess the password example program counting the tryouts of guessing the right word
p = "IlovePython"
x = ""
count=0
while x != p:
x = input("Password: ")
print(count)
count=count+1
print ("Congratulations, the password is right!")
|
class Integer(object):
def __init__(self, number, p):
self.number=number
self.p=p
def display(self):
if self.p:
print self.number
else:
print (self.number - self.number - self.number)
class NegativeInteger(Integer):
def __init__(self, number):
super(NegativeInteger, self).__init__(number... |
# maps a variables values based on old range and new range linearly
# source: https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
def variable_mapping(value, from_low, from_high, to_low, to_high):
"""
maps a variables values based on old range and new range linea... |
"""
A Baby class and functions that use/test it.
Authors: Dave Fisher, David Mutchler, Vibha Alangar, Matt Boutell,
Mark Hays, Amanda Stouder, Derek Whitley, their colleagues,
and PUT_YOUR_NAME_HERE.
""" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE.
import random
def main():
""" Runs the te... |
#]pzGhαXAbϥΤؤPXᥬC
#]pG_@k10630819\yu
#v覡G mWХܢwDӷ~ʢwۦP覡
from turtle import *
#define funtion
def eight(s):
for i in range(8):
forward(s)
left(360/8)
def six(s):
for i in range(6):
forward(s)
left(60)
def five(s):
for i in range(5):
forward(s)
left(360/5)
def flower1(s):
... |
def insertion_sort(arr):
for i in range(1, len(arr)):
value = arr[i]
j = i
while j > 0 and arr[j-1] > value: # while j > 0 and arr[j-1] > arr[i]
arr[j] = arr[j-1] # arr[j] is set to arr[j-1]
j += -1 # increment j by -1
arr[j] = value # arr[j] is set to arr[i]
re... |
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return ("%s of %s" %(self.rank, self.suit))
class CardDeck:
def __init__(self):
self.deck = []
for suit in ['clubs', 'diamonds', 'hearts', 'spades']:
for rank in ['A', '2', '3', '4', '5', '6', '7', '8', '... |
#application form for users (part 1) and collecting them (part 2)
#part 1
current_year = 2020
minimum_age = 14
maximum_age = 61
print("This is your application form please insert your data")
name = input("Please, enter your name : ")
surname = input("Please, enter your surname : ")
year = input("Please, enter the year... |
#-------------------------------------------------------------------------------
# Name: tsp_chromosome
# Purpose:
#
# Author: aaron
#
# Created: 17/04/2011
# Copyright: (c) aaron 2011
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import random... |
import re
class Solution:
def get_check_digit(self, input):
check = re.match("[0-9]-[0-9]{2}-[0-9]{6}-[a-z]$", input)
if check:
i = 0
# while(i<9):
total = 0
i = 1
for pos in input:
if pos.isdecimal():
... |
#!/usr/bin/env python
import numpy as np
def warmUpExercise(*args, **kwargs):
# warmUpExercise Example function in python
# warmUpExercise() is an example function that returns the 5x5 identity matrix
# ============= YOUR CODE HERE ==============
# Instructions: Return the 5x5 identity matrix
# In ... |
# string permutation in lexicographically order with repetition of characters in the string
def permute(input):
count_map = {}
for ch in input:
if ch in count_map.keys():
count_map[ch] = count_map[ch] + 1
else:
count_map[ch] = 1
keys = sorted(count_map)
str = []... |
"""
Problem Statement
=================
Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array
such that the integers in the subsequence are in increasing order.
Complexity
----------
* Time Complexity: O(n^2)
* Space Complexity: O(n)
Video
-----
* http... |
"""
Problem Statement
=================
Given two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find the length of the longest common
subsequence.
Video
-----
* https://youtu.be/NnD96abizww
Complexity
----------
* Recursive Solution: O(2^n) (or O(2^m) whichever of n and m is larger).
* Dynamic P... |
"""
Problem Statement
=================
Given the number of nodes N, in a pre-order sequence how many unique trees can be created? Number of tree is exactly
same as number of unique BST create with array of size n. The solution is a catalan number.
Complexity
----------
* Dynamic Programming: O(n^2)
* Recursive Solut... |
"""
Problem Statement
=================
Given a positive integer N, count all the numbers from 1 to 2^N, whose binary representation does not have consecutive
1s.
This is a simple application of fibonacci series.
Video
-----
* https://www.youtube.com/watch?v=a9-NtLIs1Kk
Complexity
----------
* Runtime Complexity:... |
#dijkstra's algorithm
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/DijkstraShortestPath.java
from priorityqueue import PriorityQueue
from graph import Graph
import sys
def shortest_path(graph, sourceVertex):
min_heap = PriorityQueue(True)
distance = {}
pare... |
"""
Problem Statement
=================
Given different dimensions and unlimited supply of boxes for each dimension, stack boxes on top of each other such that
it has maximum height but with caveat that length and width of box on top should be strictly less than length and width
of box under it. You can rotate boxes a... |
#Graph class
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Graph.java
class Graph(object):
def __init__(self, is_directed):
self.all_edges = []
self.all_vertex = {}
self.is_directed = is_directed
def add_edge(self, id1, id2, weight=0):
... |
"""
Problem Statement
=================
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find the kth ugly number.
Complexity
----------
* Time Complexity O(n)
* Space C... |
string=""
for x in range(1,10):
string=""
for y in range(1,x+1):
if str(y) == "1":
string = string + (str(y) + "*" + str(x) + "=" + str(x*y))
else:
string = string + "\t" + (str(y) + "*" + str(x) + "=" + str(x*y))
print(string)
squares=[value**2 for value in range(1,11)]
print(squares)
print(squares[-2... |
def main():
#escribe tu código abajo de esta línea
n=int(input())
c=1
suma=0
numero=0
while c<=n:
numero=float(input())
suma+=numero
promedio=suma/n
c+=1
print(promedio)
if __name__=='__main__':
main()
|
# This reads in a users height and weight and calulates their BMI
# Author: Eddie Callan (G00398815)
# The line below looks for the user to input their height and saves it in variable 'height' as an integer
height = int(input("Please enter your height in centimeters: "))
# The line below looks for the user to input ... |
#give input like this :[2,4,32,1]
def mergesort(lst):
n = len(lst)
if n == 1 or n == 0:
return lst
else:
length = n//2
A = lst[:length]
B = lst[length:]
A = mergesort(A)
B = mergesort(B)
i, j = 0, 0
lst = []
while i < len(A) and j < len... |
# Author:Chris Rios
# Finds the specified file type, either .mp3, .flac, .wav, or all 3, and copies it to a speicfied folder.
import sys
import re
import os
import shutil
music_list={}
def folder_crawler(dir_name,file_type):
'''Explores all folders and sub folders for the speicified file type, composes a diction... |
input_word = input('Enter Word: ')
if 'e' in input_word:
print('Yes')
else:
print('No') |
known_users = ['Gande', 'Emma', 'Nabem', 'Jude', 'Blessing', 'Avalumun']
while True:
user_name = input('What is your Name: ').capitalize()
print(f'Hi! {user_name} welcome to Travis')
#Check if user is in the list
if user_name in known_users:
print(f'Hello, {user_name}')
#Ask U... |
from random import randrange
import time
'''
Snow animation
Snow is simply the `#` symbol here. Half of the snow moves at 1 char
per frame, while the other half moves at 0.5 chars per frame. The
program ends when all the snow reaches the bottom of the screen.
The viewing area is 80x25. It puts 100 snow flakes to outp... |
import sys
sys.stdin = open("input_data", "r")
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def start():
cases = int(input())
while cases > 0:
# list for points
points = []
N = int(input())
# creating all the po... |
#!/usr/bin/env python3
from itertools import product
A = input().split()
n = int(input())
## lazy hack over itertools
def main0():
S0 = ' '
for P in product(A,repeat=n):
S = ''.join(P)
d = 0
while d<n and S[d]==S0[d]:
d += 1
for i in range(d+1,n):
pri... |
#!/usr/bin/env python3
def temple(H):
if len(H)%2==0:
return False
for i in range(len(H)//2+1):
if not H[i]==H[-1-i]==i+1:
return False
return True
def main():
S = int(input())
for _ in range(S):
N = int(input())
H = list(map(int,input().split()))
... |
#!/usr/bin/env python3
import rosalib
# NB: the statement explains "Why Are We Counting Modulo 134,217,727?
# (...) however, if we count modulo a large prime number"
# yet 2^27-1 = 134217727 is not prime... (-_-)
def Levenstein_align(u,v):
m,n = len(u),len(v)
T = [[max(i,j) for j in range(n+1)] for i in ... |
#!/usr/bin/env python3
# Greedy approach in O(sqrt(n))
# Key observations:
# - It is always "optimal" to "upgrade" (buy new machines/workers)
# as soon as possible: If the optimal requires to buy k ressources, then
# there is clearly a way to achieve this optimal by buying progressively
# the k ressources as... |
#!/usr/bin/env python3
# Comme vu dans INOD, ajouter une feuille a un arbre binaire non-enracine,
# c'est choisir une arete, ajouter un nouveau noeud interne au milieu
# et y connecter la nouvelle feuille. On avait n-2 noeuds internes pour n>=3
# feuilles, donc 2n-2 sommets et donc 2n-3 aretes.
# Donc b(n+1) = (2*n-3)... |
#!/usr/bin/env python3
import rosalib
def pdist(A,B):
assert(len(A)==len(B))
return sum(int(A[i]!=B[i]) for i in range(len(A)))/len(A)
def main():
L = rosalib.parse_fasta()
for i in range(len(L)):
print(' '.join(str(pdist(L[i][1],L[j][1])) for j in range(len(L))))
main()
|
#!/usr/bin/env python
import sys
win = {0:False, 1:False}
def progdyn(n):
if n not in win:
win[n] = not progdyn(n-2) or (n>2 and not progdyn(n-3)) or (n>4 and not progdyn(n-5))
return win[n]
def main():
T = int(sys.stdin.readline())
for _ in xrange(T):
n = int(sys.stdin.readline())
... |
#!/usr/bin/env python
import sys
from math import sqrt
# probleme "easy" car un lien est donne dans l'enonce vers :
# http://math.stackexchange.com/questions/124408/finding-a-primitive-root-of-a-prime-number
# les racines primitives sont les generateurs de (Z/nZ)* (d'ordre phi(n))
# s'il en existe, alors (Z/nZ)* est... |
#!/usr/bin/env python3
def is_pal(S):
return S==S[::-1]
def pal_index(S):
s = len(S)
for i in range(s//2):
if S[i]!=S[s-i-1]:
if is_pal(S[:i]+S[i+1:]):
return i
elif is_pal(S[:s-i-1]+S[s-i:]):
return s-i-1
return -1
return -1
... |
#!/usr/bin/env python3
# Rajouter une feuille a un arbre binaire non-enracine, c'est
# choisir une arete, ajouter un nouveau noeud interne au milieu
# et y connecter la nouvelle feuille.
# On ajoute donc exactement 1 noeud interne par nouvelle feuille.
# Pour n = 1 ou 2 on a 0 noeud interne.
# Pour n = 3 on a exacteme... |
#!/usr/bin/env python3
from itertools import groupby
Uniq = list(range(1,8))+list(range(6,0,-1))
def rainbow(A):
return A==A[::-1] and [G[0] for G in groupby(A)]==Uniq
def main():
T = int(input())
for _ in range(T):
N = int(input())
A = list(map(int,input().split()))
print('ye... |
#!/usr/bin/env python3
# pb 10040 on UVa, 2201 on Archive
# Duval's algorithm (1988) to generate Lyndon words of size <=n in lex order
# https://en.wikipedia.org/wiki/Lyndon_word
def lyndon(n):
w = [0]*n
l = 1
yield '0'
while True:
for i in range(l,n):
w[i] = w[i%l]
l = n
... |
#!/usr/bin/env python3
def hist_max_rect(H):
H.append(0)
S = []
res = 0
for i in range(len(H)):
x = i
while S and H[i]<=S[-1][1]:
x,h = S.pop()
# an interval of height h starts at x and ends at i-1
res = max(res,h*(i-x))
S.append((x,H[i])) # a... |
#!/usr/bin/env python3
def main():
N = int(input())
S = input()
# recursively removing "()" from S
R = []
for s in S:
if s==')' and len(R)>0 and R[-1]=='(':
R.pop()
else:
R.append(s)
# R = ")" * a + "(" * b with a+b even
a = R.count(')')
b = le... |
#!/usr/bin/env python3
# https://en.wikipedia.org/wiki/Euler's_criterion
# for p an odd prime, a coprime to p (i.e. not a multiple of p here)
def euler_criterion(a,p):
return pow(a,(p-1)//2,p)==1
def main():
T = int(input())
for _ in range(T):
A,M = map(int,input().split())
if A==0 or M==... |
#!/usr/bin/env python3
# Method used here:
# 1. Use one LALIGN web interface to discover the pattern
# http://www.ebi.ac.uk/Tools/psa/lalign/nucleotide.html
# http://fasta.bioch.virginia.edu/fasta_www2/fasta_www.cgi?rm=lalign&pgm=lald
# 2. Append the discovered pattern to the FASTA input and use this script
# to count... |
#!/usr/bin/env python3
# Appelons PAA(n) une permutation 3-anti-arithmetique de taille n
# et SAA une suite finie (qcq) 3-anti-arithmetique.
# Une SAA le reste (clairement) si l'on :
# - supprime des elements ;
# - ajoute une constante a tous les elements ;
# - multiplie tous les elements par une constante.
# Pour ... |
#!/usr/bin/env python
import sys
# we simply want to count the number of iterations of the loop nest
# an iteration is determined by 1 <= i1 < i2 < ... < ik <= n
# with i2-i1 >= 1, i3-i2 >= 2, i4-i3 >= 3, ...
# let us do a simple translation:
# let j1 = i1, j2 = i2 > j1,
# j3 = i3-1 > j2 so that i3-i2 >= 2 becomes j... |
#!/usr/bin/env python3
# Si l'on considere les arbres binaires non-enracines a n feuilles etiquetees,
# alors en retirant la n-ieme feuille et en choisissant son pere comme racine,
# on obtient, sans doublon, tous les arbres binaires enracines a n-1 feuilles
# etiquetees.
# Ou reciproquement, on obtient les arbres non... |
#!/usr/bin/env python3
import rosalib
# pretty naive and lazy approach here, yet good enough
# (for sure there are more efficient and still relatively simple
# approaches using string hashing)
# see also https://en.wikipedia.org/wiki/Longest_common_substring_problem
# for a really good approach using suffix trees
d... |
import numpy as np
import matplotlib.pyplot as plt
def exponential_growth(x0, k, dt, N):
X = [x0]
for _ in range(N):
X.append(X[-1]*(1+k*dt))
return X
def eplot(x0, k, dt, N):
X = np.linspace(0, N*dt, 1000)
Y = x0*np.exp(k*X)
plt.plot(X, Y)
X = np.arange(0, (N+0.1)*dt, dt)
Y = ... |
# Code_snippets
///A. Find out number of digits in a number using python
Method 1
///
no=float(input("enter the number"))
digits=0
while(n!=0):
n=n//10
digits+=1
print("number of digits are",digits)
//Method 2:
no=int(input())
print(Len(str(no))) //convert int to string
|
#! /usr/bin/python3
import sys
lines = sys.stdin.readlines()
l, w, n, r = [int(i) for i in lines.pop(0).split()] #parse input values
ns = {}
reachable = {}
counter = 1
for li in lines:
ns[counter] = [int(i) for i in li.split()] #save coordinates of cranes into dictionary
reachable[counter] = []
counter += ... |
n=5
while n> 0 :
print(n)
n = n-1
print("it is done") |
import string
LOWER_LETTERS = string.ascii_lowercase
def isPalindrome(string):
def normalize_string(string):
string = string.lower()
ans = ''
for letter in string:
if letter in LOWER_LETTERS:
ans += letter
return ans
def isPal(string):
... |
def user_numbers():
integers = input("Enter 10 integers: ").split()
return [int(number) for number in integers]
numbers = user_numbers()
def calculation(numbers):
odd_numbers = [number for number in numbers if number % 2 != 0]
return max(odd_numbers)
x = calculation(numbers)
print(x)
|
#Sum the values of the hand (ie the number of letters available to use).
#We will use this info as a check to see when we need to end the game (ie, no more letters to use)
def calculateHandlen(hand):
return sum(hand.values())
def updateHand(hand, word):
hand_copy = hand.copy()
for letter in word:
... |
example = open('circle.py', 'a')
for i in range(2):
name = input("Enter name: ")
example.write(name)
example.close()
# file = 'pi_digits.py'
# with open(file) as f_object:
# lines = f_object.readlines()
# for line in lines:
# print(line.strip())
|
#monthly_payment is not passed into this function
def calculate_ending_balance(balance, annualInterestRate, monthly_payment):
month = 1
while month <= 12:
unpaid_balance = balance - monthly_payment
monthly_interest_rate = annualInterestRate / 12.0
new_balance = unpaid_balance + (month... |
import random
import matplotlib.pyplot as plt
from itertools import islice
import numpy as np
#Ejercicio 1
def modulo(x):
modulo = 2**32
multiplicador = 1013904223
incremento = 1664525
return (x*multiplicador + incremento) % modulo
def random_generator(cantidad):
numeros = []
x = 96102
f... |
''' Q.1- Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class. '''
import math as m
class Circle:
'''class to get area and circumference of a circle using the radius'''
def __init__(self,r):
self.radius=r
def getArea(s... |
#Exercises
#Exercise 1
print('hello\n\thello\n\t\thello')
#Exercise 2
print('OrangeAcademy \n'*20)
#Exercise 3
x=float(1)
y=float(2.8)
z=float("3")
w=float("4.2")
"""print(x)
print(y)
print(z)
print(w)"""
print(x,y,z,w,sep='10')
#to have 10 between the value
#Exercise 4
number1=input("Enter the first numbe... |
import csv
with open("Resources/election_data.csv" , "r") as fh:
import csv
csvpath = ("Resources/election_data.csv")
with open(csvpath, newline="") as csvfile:
csv_reader =csv.reader(csvfile, delimiter=",")
csv_headers = next(csv_reader, None)
#print (f"CSV Header: {csv_headers}"
# print headi... |
import re
from urllib.parse import urlparse
def validate_url(url):
"""
Validate an HTTP(S) URL
Helper for use with Colander that validates a URL provided by a user as a
link for their profile.
Returns the normalized URL if successfully parsed else raises a ValueError
"""
parsed_url = ur... |
import time
def invest(amount, rate, years):
for year in range(years):
amount += amount * (rate/100)
print(f'year {year+1}: ${amount:.2f}')
def main():
while True:
try:
amount = float(input('Amount for investment: '))
rate = float(input('Rate of investment (%): '))
... |
import time
while True:
nums = input('Enter integers separate by space: ').strip().split()
try:
nums = [int(num) for num in nums]
print (f'The sum of integers equals: {sum(nums)}')
break
except ValueError:
print('Invalid input format')
continue
time.sleep(3)
|
import time
print('Task_1')
weight = 0.2
animal = 'newt'
#stdout using only string concatenation
print(str(weight) + ' kg is the weight of the ' + animal + '.')
time.sleep(3)
print('\nTask_2')
#stdout using format method
print('{} kg is the weight of the {}.'.format(weight, animal))
time.sleep(3)
print('\nTask_3')
... |
import time
def factorial(num):
global fact_count
fact_count += 1
if num <= 1:
return 1
return num * factorial(num - 1)
num = int(input("Enter a non negative number: "))
fact_count = 0
start = time.time()
factorial(num)
stop = time.time()
print("The answer is", factorial(num)... |
'''
CN-codedemy-script-8.Loops-10.Your-Hobbies.py
Worked Oct 20, 2016
'''
hobbies = []
for i in range(3)
hobbies.append(raw_input("What are your hobbies:")
# print list when done (after 3 input)
# will print something like this: ['music', 'movies, ' books']
print hobbies
|
'''
Codecademy - Learn basic Pyhon https://www.codecademy.com/learn/python
Assignment: Battleship
File: battleship.py
'''
# Create a square board size 5, load all cells with O (letter O upper case)
board = []
for x in range(0,5):
board.append(["O"*5]
# print board to see
def print_board(board): # "board" arg is a ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 20:54:14 2018
@author: akansal2
"""
#importing libraries
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
#function for calculating distance
#Euclidean Distance
def dist1(a,b):
return np.linalg.norm(a-b)
#cosine ... |
#Criando a matriz
matriz= []
def criando_matriz (dimensao_matriz):
for i in range (dimensao_matriz):
matriz.append([0]* dimensao_matriz )
return matriz
#Lendo a matriz
def lendo_matriz(matriz,dimensao_matriz):
for i in range (dimensao_matriz):
for j in range(dimensao_matriz):
print('Pos... |
"""
pipe.py 管道通信
注意:
1. 管道通信只能应用于一个父子进程中
2. 管道对象在父进程中创建,子进程通过copy父进程代码获取管道
"""
from multiprocessing import Process,Pipe
"""
# 创建管道
fd1,fd2 = Pipe()
def app1():
print("启动app1,请登录")
print("请求app2 授权")
fd1.send("app1 请求登录") # 写入管道
data = fd1.recv()
if data == ("David",123):
print("... |
"""
栈模型的链式存储
"""
class StackError(Exception):
pass
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "该节点是%s" % (self.value)
# 第一种方法:
# 该种类每次调用添加或删除方法都需要遍历链表,得到最后一个元素,
# 相比第二种方法更复杂,麻烦
"""
class LStack:
def __init__(self):... |
"""
multiprocessing模块创建进程
1.编写进程函数
2.生产进程对象
3.启动进程
4.回收进程
"""
import multiprocessing as mp
from time import sleep
def fun01():
print("开始进程1")
sleep(3)
print("子进程结束")
def fun02():
print("开始进程2")
sleep(5)
print("父进程结束")
# 创建进程对象
p1 = mp.Process(target=fun01)
p1.start() # ... |
def quick_sort(alist):
if len(alist) < 2:
return alist
first = alist[0]
alist.remove(first)
left,right = [],[]
for i in alist:
if i > first:
right.append(i)
else:
left.append(i)
res = quick_sort(left) + [first] + quick_sort(right)
return res
... |
word = list("cookies")
# print(word)
joined_word = "".join(word)
new_word = []
for char in word[:2:-1]:
new_word.append(char)
print(new_word)
print(word)
# word.reverse()
# print(word)
# print(joined_word)
|
# from torch.nn import CrossEntropyLoss
from .sup_single import *
from abc import abstractmethod
class ClassificationTrainer(SupSingleModelTrainer):
"""this is a classification trainer.
"""
def __init__(self, logdir, nepochs, gpu_ids, net, opt, datasets, num_class):
super(ClassificationTrainer,... |
# lesson3
# Задание №3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
i = 1
array = []
num = int(input('Сколько элементов массива Вы хотите ввести? (ввдите целое положительно число): '))
while i <= num:
array.append(input('Введите {} целое число: '.format(i)))
i += ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 10 15:51:01 2017
@author: Gubynator
"""
def reverseseq(n):
ReverseSequence = []
for number in range(n, 0 , -1):
ReverseSequence.append(number)
return ReverseSequence
def reverseseq(n):
return list(range(n, 0, -1)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 11:56:17 2018
@author: kaidenbillings
"""
def print_header():
print("Think of a number between 1 and 100")
print("I'm going to try to guess your number")
print("Tell me if my guess is correct by entering yes, lower or higher")
#... |
#!/usr/bin/python2
# class test:
# def __init__(self):
# self.count = 1
# self.cost = None
# def test(self,cost=lambda x:1):
# self.cost = cost
# print cost
for i in range(1000):
print "hello there" |
def IsYearLeap(year):
# if the year number isn't divisible by four, it's a common year;
if year % 4 != 0:
return False
# otherwise, if the year number isn't divisible by 100, it's a leap year;
elif year % 100 != 0:
return True
# otherwise, if the year number isn't divisible by 400, i... |
"""
Estimated time
10-15 minutes
Level of difficulty
Easy/Medium
Objectives
Familiarize the student with:
using the if-elif-else statement;
finding the proper implementation of verbally defined rules;
testing code using sample input and output.
Scenario
As you surely know, due to some astronomical reasons, years may... |
#input a float value for variable a here
a = float(input("Enter a float: "))
#input a float value for variable b here
b = float(input("Enter another float: "))
#output the results of addition, subtraction, multiplication and division
print("addition: a + b = ", a + b)
print("subtraction: a - b = ", a - b)
print("multip... |
initial_cost = int(input('Enter the initiation fee: $'))
monthly_cost = int(input('Enter the monthly fee: $'))
length = int(input('Enter how many months you\'d like to calculate for: '))
annual_cost = int(input('Enter the annual cost: $'))
total_cost = []
for num in range(length + 1):
if num == 0:
total_cost.ap... |
why=raw_input('Hey')
print 'Do you like X-TREME ROLLER COASTERS?!'+' '+why
myname='Mrs.Kipling'
print myname=='Mrs.Kipling'
print 6>=1
l=18
if(l!=18):
print 'l is less than 16'
else:
print'l is less than 16'
|
import turtle
t=turtle.Pen()
t.pensize(110)
red=1
green=0.5
blue=1
for i in range(1,10):
t.color(red,green,blue)
t.forward(200);
t.right(100);
t.forward(200);
t.right(100);
red=red - 0.1
green=0.5
blue=1
t.color(1,1,0)
t.up()
t.right(48)
t.forward(135)
t.down()
t.pensize(50)
t.circle(15)... |
# GIVEN
# Is that user enter guess secret number.
# Required
#to tell the user whether their number was too large or small.
# to tell number of tries
# Algorithm
# import random
# n = random.randint(1, 50) guess = int(input("Enter an integer from 1 to 50: "))
# while n != "guess"
#if guess < n: print ("gu... |
# this program calculates molecular weight of a carbohydrate
def mol_weight():
h = int(input("Enter the number of hydrogen atoms: "))
o = int(input("Enter the number of oxygen atoms: "))
c = int(input("Enter the number of carbon atoms: "))
hw, cw, ow = 1.00794, 12.0107, 15.9994
m_weight = h * hw + o * ... |
import math
def pizzaArea(r):
a = r*r * math.pi
return a
def pizzaCost(a, p):
cpcm = p / a
return cpcm
def main():
diameter = float(input("Enter diameter of the pizza: "))
price = float(input("Enter price of the pizza: "))
area = pizzaArea(diameter)
cost_per_sqcm = pizzaCost(area, pr... |
def break_digits_apply_luhns(my_str):
first_list = [int(my_str[j]) for j in range(0, len(my_str), 2)]
second_list = [int(my_str[j]) for j in range(1, len(my_str), 2)]
for j in range(len(second_list)):
second_list[j] = 2 * second_list[j]
for j in range(len(second_list)):
if ... |
#leap years
def main():
year = int(input("Enter year: "))
if year % 4 == 0:
if year in list(range(100, year + 1, 100)):
if year % 400 ==0:
print("This is leap year")
else:
print("This ain't no leap year!")
else:
print... |
# this program determines the distance to a lightning strike based on
# the time elapsed between the flash and the sound of thunder
def lightning_strikes_twice():
t = int(input("Enter number of seconds passed since the lightning: "))
sos = 1100
distance_in_feet = t * sos
distance_in_miles = round(distan... |
def plane():
x1, y1 = eval(input("Enter coordinates separated by comma: "))
x2, y2 = eval(input("Enter coordinates separated by comma: "))
slope = (y2 - y1) / (x2 - x1)
print()
print("----------------------")
print("Slope is", slope)
print()
print()
print()
input("Press<E> to quit")
plane() |
def fibonacci(n):
a, b = 1, 1
for j in range (n - 2):
a = a + b
b = a - b
return a
def main():
numero = int(input("Enter n-th number you'd like displayed: "))
print("Your number is", fibonacci(numero))
main()
|
def numSum(n):
x = 1
for j in range(2, n+1):
x = j + x
return x
def cubSum(n):
x = 1
for j in range(2, n+1):
x = j*j*j + x
return x
def main():
n = int(input("Enter final number (n): "))
print()
print(numSum(n))
print()
print(cubSum(n))
main()
... |
# this program prints the sum of numbers defined by user
def average():
lops = int(input("Enter how many numbers to be summed: "))
sum = 0
print()
for n in range(lops):
n = int(input("Enter a number: "))
sum = sum + n
average = sum / lops
print()
print("---------------------")
print("The averag... |
#quizz_grades
def main():
grades = ["F", "D", "C", "B", "A"]
ui = int(input("Enter quizz score: "))
if ui < 60:
print(grades[0])
elif ui in range(60, 70):
print(grades[1])
elif ui in range(70, 80):
print(grades[2])
elif ui in range(80, 90):
print(grades[3])
e... |
'''
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
'''
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anythin... |
class FizzBuzzer:
@staticmethod
def run_for(number):
if not isinstance(number, int):
raise Exception("not a number")
number = int(number)
if number % 15 == 0:
return 'fizzbuzz'
elif number % 3 == 0:
return 'fizz'
elif number % 5 == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.