text stringlengths 5 121k |
|---|
def main():
print('This program sorts a list of cards by rank and suit')
filename = input('Enter a file name: ')
listOfCards = sortCards(filename)
score = checkScore(listOfCards)
print(score)
def sortCards(filename):
infile = open(filename, 'r')
listOfCards = []
for line in infile:
... |
import math
def main():
print('The program calculates the distance between two points.')
x1, y1, x2, y2 = eval(input('Enter two points x1, y1, x2, y2:'\
'(separate by commas) '))
distance = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
print('The dist... |
from graphics import *
def main():
print('The program draws a archery target.')
win = GraphWin('Archery Window', 400, 400)
blue = Circle(Point(200, 200), 100)
blue.setFill('blue')
red = Circle(Point(200, 200), 75)
red.setFill('red')
green = Circle(Point(200, 200), 50)
... |
def main():
print('The program calculates Fibonacci number.')
n = eval(input('How many numbers do you want?(>2) '))
f1 = 1
f2 = 1
for i in range(2, n):
fibo = f1 + f2
f1 = f2
f2 = fibo
print('Your Fibonacci number is', fibo)
main()
|
from graphics import *
def main():
print('The program draws the bar chart with Student Name and')
print('Score in horizontal.')
fileName = input('Give the file name: ')
inFile = open(fileName, 'r')
total = 0
total = eval(inFile.readline())
win = GraphWin('Student\'s Sc... |
def main():
print('The program encrypts a message by Caesar cipher.')
infileName = input('Enter the origin file name: ')
outfileName = input('Where do we put the secret message: ')
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')
for line in infil... |
from graphics import *
from gpa import Student, makeStudent
from button import Button
def main():
win = GraphWin('Students Sort', 400, 400)
win.setCoords(0, 0, 4, 5)
input1, input2, bList = drawInterface(win)
while True:
p = win.getMouse()
for b in bList:
if b.clicked(p):
... |
def main():
print('The program returns a sequence of Syracuse number from the first input.')
x = int(input('Enter your number: '))
while x != 1:
if x % 2 == 0:
x = x // 2
else:
x = 3 * x + 1
print(x, end=', ')
if __name__ == '__main__':
... |
import random
filename = "poem.txt"
def get_file_lines(filename):
read_poem = open(filename, 'r')
return read_poem.readlines()
def lines_printed_backwards(lines_list):
lines_list = lines_list[::-1]
for line in lines_list:
print(line)
print("*********************************************... |
import numpy as np
import matplotlib.pyplot as plt
N = 5
eggs_received = (100000, 150000, 100000, 50000, 150000)
year = (2014, 2015, 2016, 2017, 2018)
ind = np.arange(N)
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(ind, eggs_received, width, color='r', yerr=year)
eggs_hatched = (80000, ... |
class Dictionary:
def __init__(self):
self.dictionary = {}
with open("./dictionaries/english_words_94k.txt", "rb") as eng_words:
for word in eng_words:
try:
self.dictionary[word.decode("utf-8").strip()] = True
except UnicodeDecodeE... |
from urllib.request import urlopen
from io import StringIO
import csv
data = urlopen("http://pythonscraping.com/files/MontyPythonAlbums.csv").read().decode("ascii", "ignore")
dataFile = StringIO(data)
csvReader = csv.reader(dataFile)
for row in csvReader:
print("The album is: " + row[0] + " and the year is: " + ... |
def sq(z):
print(z**2)
sq(3)
sq(5)
def myFunctionName(firstName, lastName):
print("My Name is", firstName, lastName)
|
b = input()
count = 0
k = 0
for i in b:
if i == "H" or i == "Q" or i == "9":
print("YES")
exit()
print("NO")
|
from operator import itemgetter
sorted_lst_west = []
sorted_lst_east = []
west_server_lst = []
east_server_lst = []
output_lst = []
server_dict = {
"large": 1,
"xlarge": 2,
"2xlarge": 4,
"4xlarge": 8,
"8xlarge": 16,
"10xlarge": 32
}
def get_costs(instances, hours = 0, cpus = 0, price = 0):
for k, v in instanc... |
print("I")
for row in range(7):
for col in range(5):
if (row ==0):
print("*", end=" ")
elif (row in {1,2,3,4}) and (col ==2):
print("*", end=" ")
elif (row ==5) and (col in{0,2}):
print("*", end=" ")
elif (row ==6) and (col ==1):
... |
a=45
if(a>3):
print("Value of a is greater than 3")
elif(a>6):
print("Value of a is greater than 7")
else:
print("Value of a is not greater than 3 or 7") |
a="Soham"
b="42"
c=4081.12
print(a)
print(b)
print(c)
print(a+" "+b)
print(type(c))
print(type(a)) |
"""
When you physically exercise to strengthen your heart, you
should maintain your heart rate within a range for at least 20
minutes. To find that range, subtract your age from 220. This
difference is your maximum heart rate per minute. Your heart
simply will not beat faster than this maximum (220 - age).
When e... |
num = int(input("input:"))
result = []
for ii in range(1, num+1):
if ii % 5 == 0 and ii % 3 == 0:
result.append(ii)
elif ii % 5 != 0 and ii % 3 != 0:
result.append(ii)
print(len(result)) |
"""
juc2/examples/example_06.py
Draw a bunch of rectangles and move them around at random. ^_^
"""
import random
from juc2 import art, Stage
HEIGHT = 40
WIDTH = 100
stage = Stage(height=HEIGHT, width=WIDTH)
rectangles = list()
for i in range(30):
d, x, y = random.randint(3, 8), random.randint(10, WIDTH-10),... |
def countingSort(array):
size = len(array)
output = [0] * size
count = [0] * 10
for i in range(size):
count[array[i]] += 1
for i in range(1, 10):
count[i] += count[i-1]
i = size - 1
while i >= 0:
output[count[array[i]] - 1] = array[i]
... |
"""
Created on Wed Jul 21 11:43:34 2021
@author: palash
"""
def existsInTree(root, value):
if root is None:
return False
else:
leftExist = existsInTree(root.left, value)
rightExist = existsInTree(root.right, value)
return root.data == val or leftExist or rightExist
|
def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
if array[j] > array[j+1]:
(array[j], array[j+1]) = (array[j+1], array[j])
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print("Sorted array is: ")
print(data)
|
import copy, math
Vertices = int(input('enter Number of Vertices: '))
k_bound = int(input('enter k_bound or enter 0: '))
if k_bound == 0:
k_bound = math.ceil(0.36 * Vertices)
my_file = list(open("graph_sample.txt", 'r'))
edge = []
for line in my_file:
edge.append(line)
edge = [x.strip() for x in edge]
graph... |
print("Digite as idades")
idade = int(input())
soma = 0
cont = 0
if idade < 0:
print("IMPOSSIVEL CALCULAR")
else:
while idade > 0:
soma = soma + idade
cont = cont + 1
idade = int(input())
media = soma / cont
print(f"Media = {media:.2f}") |
x: int
y: int
i: int
x = 0
y = 5
for i in range(x,y):
print(i)
|
""" A side view from west to east through Olympus Mons. This will allow to extract meaningful insights regarding the smoothness of a surface and visualize its topography."""
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
from utils import save_fig
y_coord = 202
im = Image.open("images/mola_1024x512_... |
points = 0
playerOne = 0
playerTwo = 0
point = [0, 15, 30, 40]
playerOne = {
"zero": 0,
"fifteen": 15,
"thirty": 30,
"forty": 40,
"name": "playerOne"
}
class Player:
def __init__(self, score):
self.score = score
def setear_score(self, score):
self.score = score
playerOne... |
"""
Created on Thursday Dec 11 15:19:00 2018
@author: dbaleeds
A script to render data to acceptable thresholds for output
"""
import pandas as pd
import csv
import re
threshold = 5
placeholder = '<5'
truncateColumns = ["question1","question2","question3","question4","question5","question6","question7","question... |
import numpy as np
data_ipl =np.genfromtxt(path,delimiter =',',dtype='str',skip_header=True)
matches = data_ipl[:,0]
print(len(set(matches)))
team_1 = set(data_ipl[:,3])
team_2 = set(data_ipl[:,4])
print(team_1)
print(team_2)
all_teams =team_1.union(team_2)
print("the set of all the team palyed ",all_teams)
ext... |
"""
1,2,3,5,8,13,........
"""
"""
题1:
循环打印输入的月份的天数(使用continue实现)
- 要有判断输入的月份是否错误的语句
"""
def InputDate():
while True:
year = int(input("请输入年:"))
month = int(input("请输入月:"))
monthLis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
if month in monthLis:
... |
from math import sqrt
def factors(n):
myList = []
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
if (i != n/i):
myList.append(i)
myList.append(n // i)
else:
myList.append(i)
return sorted(myList)
def solve(N, D... |
def knapsackProblem(weight, value, capacity):
maxWt = [ [0 for x in range(weight)] for x in range(weight)]
|
stu_avg = float(input("Please enter student's average: "))
while(stu_avg < 0 or stu_avg > 100):
print("Invalid average! Please enter a valid " +
"average between 0 - 100:")
stu_avg = float(input("Please enter student's " +
"average: "))
num_days_missed = int(in... |
def factorial(num):
result = 1
for i in range(result, (num + 1)):
result = result * i
return result
print(factorial(5)) |
import operator
while True:
node, edge = input().strip().split(' ');
node, edge = [int(node), int(edge)];
if (node == 0 and edge == 0):
break;
sorted_edge = {};
for i in range(edge):
x, y, z = input().strip().split(' ');
x, y, z = [int(x), int(y), int(z)];
sorted_e... |
import turtle
t= turtle.Turtle()
def square(t):
jn = turtle.Screen()
jn.bgcolor("lightyellow")
jn.title("Quadrado")
for i in range (4):
t.forward(50)
t.left(90)
square(t)
|
class clone:
def nova_lista(uma_lista):
""" Essa funcao faz uma copia da lista dada e modifica a copia dobrando os valores dos seus elementos.
"""
clone_lista = uma_lista[:]
for (i, valor) in enumerate(clone_lista):
novo_elem = 2 * valor
clone_lista[i] = novo... |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree(object):
def __init__(self):
self.root = None
def set_root(self,data):
self.root = Node(data)
def insert(self,data):
if self.root is None:
... |
from two_sum import Solution
import unittest.test.test_program
class TestProgram(unittest.TestCase):
def test_1(self):
self.assertEqual(Solution().two_sum(([3,5,-4,8,11,1,-1,6],10), [-1, 11]))
def test_2(self):
self.assertEqual(Solution().two_sum([3,5,-4,8,11,1,-1,6,1,5,-9,-4,-6.6,8],19), [8... |
def get_nth_fib1(n):
if n == 2:
return 1
elif n == 1:
return 0
else:
return get_nth_fib1(n - 1) + get_nth_fib1(n - 2)
def get_nth_fib2(n, mem={1: 0, 2: 1}):
if n in mem:
return mem[n]
else:
mem[n] = get_nth_fib2(n - 1, mem) + get_nth_fib2(n - 2, mem)
... |
def gaussian2DblurOperator(n,sigma,truncate):
r'''
Returns a 2D Gaussan blur operator for a n x n sized domain
Constructed as a tensor product of two 1d blurs of size n.
See gaussian1DblurOperator for an example of how to perform a
2D Gaussian blur that is typically faster than constructing and
... |
def order_lists_asc(temp_list):
new_list = []
count = 0
loop_time = len(temp_list)
while count < loop_time:
new_list.append(min(temp_list))
temp_list.remove(min(temp_list))
count += 1
print(new_list)
first_list = [999, 333, 2, 8982, 12, 45, 77, 99, 11]
order_lists_asc(first_l... |
def front_back1(word) :
if len(word) > 1 :
words = list(word)
words.insert(0, words.pop(len(words)-1))
words.insert((len(words)-1), words.pop(1))
word1 = ""
return word1.join(words)
else :
return word
print(front_back1('clarusway'))
print(front_back1('a'))
print... |
'''
#Instance Variablesm -- Later, these will be loaded through reading blockchain.txt
#For now, this will start with 3 blocks in it -- in production, it will contain the entire blockchain
blockchain = [{"To":3,"From":0,"Amount":1},{"To":5,"From":0,"Amount":5},{"To":5,"From":3,"Amount":0.15}]
'''
import hashlib
import ... |
'''
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
two pointers
low high
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof
著作权归领... |
''''
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def permute(self, nums):
"""
:type nums: List... |
'''
给定一个二叉搜索树的根节点 root,返回树中任意两节点的差的最小值。
示例:
输入: root = [4,2,6,1,3,null,null]
输出: 1
解释:
注意,root是树节点对象(TreeNode object),而不是数组。
给定的树 [4,2,6,1,3,null,null] 可表示为下图:
4
/ \
2 6
/ \
1 3
最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/prob... |
f = open("divyam.txt", "rt")
content = f.readline()
content += f.readline()
print(content)
f.close()
|
d1 = {}
print(type(d1))
d2 = {"Divyam": "test", "test2": "testing", "tech": "guru", "dict": {"a": "dicta", "b": "dictb"}}
print(d2)
print(d2["Divyam"])
print(d2["dict"]["b"])
d2["added"] = "newlyAdded"
print(d2)
d2[420] = "I am 420"
print(d2)
del d2[420]
print(d2)
d3 = d2
del d3["added"]
print... |
list1 = ["Divyam", "Kumar", "Singh"]
for item in list1:
print(item)
list2 = [["divyam", 23], ["kumar", 36], ["singh", 33]]
for item, weight in list2:
print(item, weight)
dict1 = dict(list2)
print(dict1)
for item in dict1:
print(item)
for item, weight in dict1.items():
print(item, weight)
|
i = 0
while i < 43:
print(i)
i = i + 1
|
userInput = int(input("Please enter 0-6: "))
if userInput == 1:
print("Monday")
elif userInput == 2:
print("Tuesday")
elif userInput == 3:
print("Wednesday")
elif userInput == 4:
print("Thursday")
elif userInput == 5:
print("Friday")
elif userInput == 6:
print("Saturday")
elif userInput == 0:
... |
import numbers
import os
gameBoard = [['1','2','3'],
['4','5','6'],
['7','8','9']]
def printGameBoard(gameBoard):
board = """
? | ? | ?
---+---+---
? | ? | ?
---+---+---
? | ? | ?
... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
def scrape_NBA_team_data(years = [2017, 2018]):
final_df = pd.DataFrame(columns = ["Year", "Team", "W", "L",
"W/L%", "GB", "PS/G", "PA/G",
"SRS", ... |
def fib (limit) :
a,b=0,1
while (a<=limit):
yield a
a,b=b,a+b
def list_fib(limit) :
list = []
num=fib(limit)
for nu in num:
list.append(nu)
return list
if __name__ == "__main__":
assert list_fib(20) == [0, 1, 1, 2, 3, 5,... |
class A:
def __init__(self) -> None:
super().__init__()
self.mike = "Mike"
self.name = "Class A"
class B:
def __init__(self) -> None:
super().__init__()
self.bob = "bob"
self.name = "Class B"
class C(A, B):
def __init__(self) -> None:
sup... |
import numpy as np
import cv2
img = np.zeros((512,512,3), np.uint8)
img = cv2.rectangle(img,(384,0),(510,128),(0,255,0),5)
img = cv2.circle(img,(447,63),63,(255,0,0),-1)
ing = cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
img = cv2.line(img,(0,0),(511,511),(0,0,255),5)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.pu... |
import numpy as np
import numpy as np
import cv2
from math import *
import colorsys
from random import randint
import sys
def basicScale(Sx, Sy, Sz):
"""
Input: Sx and Sy floats
are the horizontal and
and vertical scaling factors; center of scale
is at the origin of the Coordinate S... |
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
print(bytes_to_int(256))
|
maximum = 10
releve = int(input())
if releve == 0:
print("Pas de pluie aujourd'hui")
elif releve > maximum :
maximum = releve
print("Nous avons un nouveau record")
else:
print("Pas de nouveau record")
print("Maximum retenu :", maximum) |
def valid_subsquares(grid):
for row in range(0, 9, 3):
for col in range(0,9,3):
temp = []
for r in range(row,row+3):
for c in range(col, col+3):
if grid[r][c] != 0:
temp.append(grid[r][c])
if any(i < 0 and i > 9 for i in temp):... |
import sys
import heapq
def simplify_parent_list(parent, start, end):
new = []
current = end
while current != -1:
new.append(current)
current = parent[current]
return list(reversed(new))
def path(graph, start, end=None):
return path_and_value(graph, start, end)[0]
def value(gra... |
"""
Created on Wed Mar 7 12:41:02 2018
@author: pyh
"""
'''
This class is for creating database and table easier by using pymysql
'''
import pymysql
class mysql_data:
def __init__(self,user_name,password):
self.conn=pymysql.connect(host='127.0.0.1',
port=3306,
user=us... |
def fun_my(filename):
with open(filename,'r')as file:
words=file.read().split()
max_len=len(max(words,key=len))
return [word for word in words if len(word)==max_len]
print(fun_my('new.txt'))
|
print("IN VERSION 3")
x=input("Enter the name or num")
print(x)
print(type(x))
print("After type casting")
b=int(input("Enter the item u want to print:"))
print(b)
print(type(b))
|
'''
Efetuar a leitura de três valores (variáveis A, B e C) e apresentar
os valores dispostos em ordem crescente
'''
a = int(input('Entre com o primeiro número: '))
b = int(input('Entre com o segundo número: '))
c = int(input('Entre com o terceiro número: '))
if a < b and b < c:
print(a, b, c)
elif a < b and b > ... |
class Admin:
instance = None
def __init__(self):
if Admin.instance is None:
Admin.instance = self
else:
raise Exception("Only once created an object you can go with that instance")
@staticmethod
def get_instance():
if Admin.instance is None:
A... |
"""
Contains functions to run tasks in parallel, be it through threads or processes.
Usage: Parallel.execute_n(iterable, operation, argument_constructor)
Parallel.execute_nm(outer_iterable, inner_iterable, operation, argument_constructor)
Parallel.spawn_process(operation, argument_list)
Parallel... |
import csv
def read_books():
fp = open('books.csv', 'r', newline='\n')
reader = csv.reader(fp, delimiter=",")
next(reader)
database = []
for each_book in reader:
book = {
each_book[1]:{
"isbn": each_book[0],
"author": each_book[2],
... |
import random
import sys
SOLUTION = random.randint(1,10)
def intro():
print("--------------------------------------")
print("Hello, Welcome to Number Guessing Game")
print("--------------------------------------\n")
def game():
try:
tries = 1
number_chosen = int(input("Please pick a n... |
import statistics as stat
import random
def calculate(lists):
for i in range(1,n):
lists.append(random.randint(1,r))
meanlist=stat.mean(lists)
medList=stat.median(lists)
stddev=stat.stdev(lists,meanlist)
return meanlist, medList, stddev
if __name__ == '__main__':
li... |
import sys
dirFichero = sys.argv[2]
fichero = open(dirFichero, 'w')
if len(sys.argv) != 3:
fichero.write("Error, se debe introducir dos un argumento de entrada\n")
else:
campos = []
campos = sys.argv[1].split('=')
if (len(campos) != 2) or (campos[0] != "nombre"):
fichero.write("Error, mal introducidos... |
def bubbleSort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(n-i-1):
if(arr[j] > arr[j+1]):
swapped = True
arr[j], arr[j+1] = arr[j+1],arr[j]
if(not swapped):
break
|
"""
Created on Thu Feb 8 09:33:02 2018
@author: hyh
"""
def add(a,b,f = abs):
return f(a)+f(b)
c=add(1,2)
print(c)
def f(x):
return x**2
list2 = list(map(f,[1,2,3,4]))
list3 = list(map(str,[1,2,3,4]))
from functools import reduce
def fn (x,y):
return 10*x+y
print(reduce(fn,[1,2,3,4]))
print('------... |
"""
Created on Sat Feb 10 11:42:39 2018
@author: hyh
"""
' a test module '
__author__ = 'Michael Liao'
import sys
def test():
args = sys.argv
if len(args)==1:
print('Hello, world!')
elif len(args)==2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments!')
if __na... |
import math
a=int(input("Enter the factorial number"))
print(math.factorial(c))
|
import balle
class Grille:
size = 0
step = 0
default = "0"
tab = []
def __init__(self, size, step):
self.size = size
self.step = step
def createTab(self, caractere):
self.default = caractere
tab = []
m = 0
while m < (self.size/self.step)**2:
... |
s = 'Life is too short, You need Python'
print(s.find('short'))
print()
s = 'Eighty percent of $ucce$$ is Showing up.'
s = s.replace('$', 's')
print(s)
print()
s = 'Life is too short, You need Python'
print(s.split())
print() |
def mergeSort(arr):
if len(arr)>1:
mid = len(arr)//2
left_array = arr[:mid]
right_array = arr[mid:]
mergeSort(left_array)
mergeSort(right_array)
i = 0
j = 0
k = 0
while i<len(left_array) a... |
def area_of_triangle(base, height):
area = base * height / 2
print("The area is {}cm²".format(area))
def main():
print("")
print("This program calculates the area of a triangle")
print("")
print("Please input the base and height")
print("")
base_from_user_str = ... |
class Node:
def __init__(self):
self.child = {}
self.isEnd = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
... |
import string
alphaArr = list(string.ascii_lowercase)
def print_rangoli(size):
for i in range(size - 1, 0, -1):
print(("-".join(alphaArr[i: size][:: - 1] + alphaArr[i + 1: size])).center((4 * size) - 3, "-"))
for i in range(1, size):
print(("-".join(alphaArr[i: size][:: - 1] + al... |
def areaOfSphere(radius):
area=4/3 * 3.14 * (radius**2)
return area
a=int(input ())
area=areaOfSphere(5)
print(area)
def perfect(number):
sum=0
for i in range(1,number):
if number%i is 0:
sum=sum+i
if sum == number:
return number
else:
... |
"""
Created on 2018/3/29
@Author: Jeff Yang
"""
from collections import OrderedDict
user_dict = OrderedDict()
user_dict["b"] = "Jack"
user_dict["a"] = "Bob"
user_dict["c"] = "Tom"
print(user_dict)
print("========")
user_dict = OrderedDict()
user_dict["b"] = "Jack"
user_dict["a"] = "Bob"
user_dict["c"] = "Tom"
print... |
import multiprocessing as mp
import random
import string
output = mp.Queue()
def rand_string(length, output):
""" Generates a random string of numbers, lower- and uppercase chars. """
rand_str = ''.join(random.choice(
string.ascii_lowercase
+ string.ascii_uppercase... |
num = int(input("Enter our number"))
num1 = num
arms_num = 0
while num>0:
arms_num = arms_num+(num%10) ** 3
num=num//10
if arms_num==num1:
print("Armstrong")
else:
print("Not Armstrong")
|
class Button(object):
def __init__(self, topleft, bottomright, text, color, outline, function, data, size=" 30"):
self.text = text
self.bg = color
self.outline = outline
self.callback = function
self.topleft = topleft
self.bottomright = bottomright
self.stat... |
class Card:
_suits = ("Heart", "Diamond", "Club", "Spade")
_ranks = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
def __init__(self, suit, rank):
if suit in self._suits:
self._suit = suit
if rank in self._ranks:
self._rank = rank
@property
def suit(self... |
def confusion():
name = input("Enter a name: ")
print(name[::-1].title())
def almost_hangman():
word = input("First player, enter the text: ")
guessed = "*" * len(word)
letter = " "
while not letter == "0":
for i, c in enumerate(word):
if c.... |
def average_value_1a():
i = 0
total = 0
while True:
user_input = input("Input a number or 'q' to quit: ")
if user_input.lower() == 'q':
break
else:
i += 1
total += float(user_input)
print(f"Average is {total / i:.2f}")
def av... |
def chat():
while (True):
UserInput = ""
ChatBot_Name = "zaki"
ChatBot_Name_Error = "console"
UserInput = str.lower(input("guest: "))
import pyfiglet
textascii = pyfiglet.figlet_format("test")
if UserInput == "quit" or UserInput == "end":
print(ChatBot_Name + ": bye thanks us... |
class BilleteraElectronica:
def __init__(self, identificador, nombres, apellidos, CI, PIN):
self.identificador=identificador
self.nombres=nombres
self.apellidos=apellidos
self.CI=CI
self.PIN=PIN
self.recargas=[]
self.consumos=[]
self.balance... |
import math
import pandas as pd
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def distance(a,b):
x_term = int(a.x) - int(b.x)
y_term = int(a.y) - int(b.y)
return math.sqrt((x_term * x_term) + (y_term * y_term))
def min_distance(click, star_catalogue):
star_nam... |
import os
from distutils.dir_util import copy_tree
from PIL import Image, ImageTk
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import tkinter as tk
'''
def change_pic(path):
root.photo = ImageTk.PhotoImage(Image.open(path))
vlabel.configure(image=root.photo)
print("updated")
'''
def s... |
def countApplesAndOranges(s, t, a, b, apples, oranges):
total_apples = 0
total_oranges = 0
max_len = 0
if len(apples) >= len(oranges):
max_len = len(apples)
else:
max_len = len(oranges)
for i in range(max_len):
if i < len(apples):
if apples[i] + a >= s... |
import sys
import datetime
'''
In cli mode, run python3 wikipedia.py <search-term> <log-file-name>
for example, python3 wikipedia.py "india" "log2.txt"
In interactive mode, run python3 wikipedia.py
'''
def wikipedia_search(keyword, file_name):
keyword = keyword.replace(' ', '%20')
url = "https://en.wikipedia... |
from LinkedList_def.LinkedList import LinkedList;
LList=LinkedList()
LList.insertStart(1)
LList.insertStart(2)
LList.insertStart(3)
LList.insertStart(5)
LList.insertEnd(8)
LList.insertEnd(13)
LList.insertEnd(21)
LList.insertEnd(34)
LList.insertEnd(55)
LList.insertEnd(89)
print("---------------------------------... |
def prime(a):
if (a<2):
return False
for x in range(2,a):
if(a%x==0):
return False
return True
def fibo(n):
a=[1,1]
n1=1
n2=1
for x in range(n-2):
n1,n2=n2,n1+n2
a.append(n2)
return a
def main():
n=int(input("enter number"))
f=fibo(n)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.