text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
#the above just indicates to use python to intepret this file
# ---------------------------------------------------------------
#This mapper code will input a line of text and output <word, 1>
#
# ---------------------------------------------------------------
import sys #a pytho... |
from collections import deque
def main():
d = deque()
for _ in range(int(input())):
num_cubes = int(input())
cubes = input().split()
smol = int(cubes[0])
for cube in cubes:
d.append(int(cube))
if int(cube) < smol:
smol = int(cube)
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict
def main():
occurence = OrderedDict()
for _ in range(int(input())):
word = input()
if word in occurence:
occurence[word] += 1
continue
occurence[word] = 1
... |
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
# map()传入的第一个参数是func,即函数对象本身。由于结果a是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
def func(x):
return x*x
l = [1,2,3,4,5,6,7]
a = map(func, l)
print(list(a))
|
'''
An event is a simple synchronization object;
the event represents an internal flag, and threads
can wait for the flag to be set, or set or clear the flag themselves.
event = threading.Event()
# a client thread can wait for the flag to be set
event.wait()
# a server thread can set or reset it
event.set()
event.c... |
import queue
q = queue.Queue(maxsize=3) # 先进先出
q1 = queue.LifoQueue() # 后进先出
q2 = queue.PriorityQueue() # 存储时可设置优先级
q.put("d1")
q.put("d2")
q.put("d3")
# q.put("d4", block=False, timeout=5) #放多了就会卡住
print(q.qsize())
print(q.get())
print(q.get())
print(q.get())
# print(q.get()) 如果取空了,这里就会等待
# print(q.get(block=F... |
"""
implementing code to filter csv file based on requested columns
"""
import pandas as pd
import os
def filter_csv(return_as="json"):
"""
Filter down our data to something displayable based on parameters from the main page.
:param return_as: json or numpy (default json)
:returns: the filtered da... |
import os
import csv
election_data_csv = os.path.join("..", "PyPoll", "election_data.csv")
print ("Election Results")
print ("-----------------------------------------")
# This function will RETURN A LIST that contains the UNIQUE VALUES that appeared in the CANDIDATES COLUMN of the CSV
def unique(candidates_list):
... |
import random
from phrase import Phrase
import sys
class Game:
def __init__(self):
self.missed = 0
self.phrases = [Phrase('My dog ate my homework'),
Phrase('I love sushi'),
Phrase('Coding is hard'),
Phrase('Carell Baskin killed her husband'),
... |
def first_not_repeating_character(s):
hashtable = {}
non_repeating = []
for char in s:
if char in hashtable:
hashtable[char] += 1
if char in non_repeating:
non_repeating.remove(char)
else:
hashtable[char] = 1
non_repeating.... |
def main():
number = int(input("Insert a number:\t"))
if(is_prime(number)):
print(f"{number} is a prime number.")
else:
print(f"{number} isn't a prime number.")
def is_prime(num):
if(num < 2):
return 0 #all numbers < 2 are not prime numbers
count = num - 1
whi... |
import csv
import re
import sqlite3
import json
def isfloat(value):
"""Check if provided argument is float.
Parameters:
value - value to check
"""
try:
float(value)
return True
except ValueError:
return False
def read_data_from_file(file_path):
"""Read data fr... |
def Printdetail(name):
return f"My name is {name}"
def add(a, b):
return a+b+5
def Printname(name):
return f"My name is {name}"
def sum1(a, b):
return a+b+5
# print(Printdetail("Abhay"))
# o = add(5,5)
# print(o)
if __name__ == '__main__':
print(Printname("Abhay"))
a = sum1(5,3)
print(a... |
def searcher():
import time
letter1 = "This is the letter for the Abhinav Namdeo"
letter2 = "This is the letter for the Ashutosh Namdeo"
letter3 = "This is the letter for the Abhishek Namdeo"
letter4 = "This is the letter for the Manju Namdeo"
time.sleep(3)
while True:
# text = inpu... |
food = []
for i in range(5):
inp = input("Enter the Food Name\n")
food.append(inp)
print("Reverse by inbuilt python method")
foodwithreverse = food
foodwithreverse.reverse()
print(foodwithreverse)
print("----------------------------------------------------")
print("Reverse by Slicing")
foodwithslicing = food
fo... |
print("Enter Your First Number")
num1 = input()
print("Enter Your Second Number")
num2 = input()
sum = int(num1) + int(num2)
print("Your Total Sum Is", int(sum)) |
first=int(input("fill first number:"))
second=int(input("fill second number:"))
print(first,"+",second,"=",first+second)
print(first,"-",second,"=",first-second)
print(first,"*",second,"=",first*second)
print(first,"/",second,"=",first/second)
|
import os
def main():
continua = True
pesos = []
vertice = []
while continua:
os.system('clear')
print "[*] 1 - Adicionar vertice"
print "[*] 2 - Adicionar arestas com os pesos"
print "[*] 3 - Rodar algoritmo de Kruskal"
print "[*] 4 - Sair\n\n"
op = raw_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next_node = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
... |
import time
import platform
t1 = time.time()
print('time t1:{}'.format(t1))
time.sleep(1)
# for i in range(1, 10):
# system = platform.system()
# time.sleep(100)
# print(system + str(i))
t2 = time.time()
print('time t2:{}'.format(t2))
print('time consumed:{}'.format(t2 - t1))
t1 = time.time()
print('time ... |
from random import shuffle, random, randint
from math import floor
# constants
GENERATION_COUNT = 1000
POPULATION_COUNT = 1000
SATURATION_PERCENTAGE = 0.8
MUTATION_PROBABILITY = 0.9
# Cities
cities = ["Brighton", "Bristol", "Cambridge", "Glasgow", "Liverpool", "London", "Manchester", "Oxford"]
distances = [
[0,1... |
largest = None
print('Before:', largest)
for i in [3, 41, 41, 9, 74, 15]:
if largest is None or i > largest:
largest = i
print('Largest:', largest)
|
smallest = None
print('Before:', smallest)
for i in [3, 41, 41, 9, 74, 15]:
if smallest is None or i < smallest:
smallest = i
print('Largest:', smallest)
|
cel = input("Enter Celsius Temperature: ")
far = float(cel)*(9/5) + 32
print("Fahrenheit Temperature:", far)
|
def main_menu():
print("1. List of Elements")
print("2. Learn about Elements")
print("3. Add Elements")
print("4. Combine Elements")
print("5. Exit Program")
a = True
while a:
selection = int(input("Enter a # corresponding to what you would like to do:"))
if selection == 1:
... |
import random
min = 0
max = 12
no_of_tries = 3
t = 1
secret = random.choice(range(min, max+1))
print("can you guess my number" + "\n")
while True:
guess = input("try: ")
try:
guess = int(guess)
except:
print("try a number instead")
break
if guess == secret:
print("score! you guessed my number.")
... |
# print("你好 中国!")
# print("你好 世界!")
# print("你好 博文!")
'''a = 2
b = 3
print(a+b)'''
# user = 924823387
# password = 111111
# print(user,password)
# name ="小明"
# age = 18
# sex = True
# hight = 1.75
# weinht = 75
# a = int(input("请输入单价:"))
# a = 25
# b = 10
# print("%d元,%f" % (a,b))
# name = str(input("输入你的名字:"))
# s... |
#program for formating dates
from datetime import datetime
import re#library for regular expression
import fileinput
for line in fileinput.input():
n = re.split("[\/\- ]", line.strip())#to split the input
#first check if the input has three values for day, month and year
if(len(n)!=3):
print(n,"invalid input"... |
from random import choice
from string import ascii_uppercase
def make_grid(height, width):
return {(row, col): choice(ascii_uppercase)
for row in range(height)
for col in range(width)}
def neighbours_of_position(row, col):
return ((row - 1, col - 1), (row - 1,col), (row - 1, col + 1),
(row, col - 1), ... |
import math
from sympy import Point, Circle, intersection
import matplotlib.pyplot as plt
def signal_strength_to_distance(signal, freq):
"""
Calculates the distance in meters, given the signal strength in decibels and frequency in Ghz
Arguments:
signal {float} -- [Signal strength in decibals]
Keyword Arg... |
#!/usr/bin/env python
"""
Shape related functions.
"""
__author__ = "Song Huang"
import numpy as np
from scipy.spatial import Delaunay
from scipy.spatial import ConvexHull
__all__ = ['alpha_shape', 'convex_hull', 'concave_hull']
def alpha_shape(points, alpha, only_outer=True):
'''Compute the alpha shape (conca... |
number , asalMi = int(input("Sayı giriniz: ")), True
for i in range(2,number):
if number%i == 0: asalMi = False, print(str(number)+" sayısı Asal Değil, " + str(i) +" sayısına bölünüyor.") ; break
if asalMi == True: print(str(number)+" Sayı Asal") |
# -*- coding: utf-8 -*-
sayi = int(input("Sayı giriniz: "))
if sayi > 0:
print("Girdiğiniz sayı Pozitifir.")
elif sayi < 0:
print("Girdiğiniz sayı Negatifir.")
else:
print("Girdiğiniz sayı Sıfırdır.") |
import sys
from typing_extensions import final
liste = [7,'gurkan',0,3,"6"]
for x in liste:
try:
print("Number: " + str(x))
result = 1/int(x)
print("Result: " + str(result))
except ValueError:
print(str(x) + " bir sayı değil")
except ZeroDivisionError:
print(str(x)+... |
import random
win_num = random.randint(1,100)
print("Enter Your Number between 1 - 100")
coins = input("Enter Your Coins : ")
print("You Earned A Free Coin ;)")
ask = input("Enter your Guessing Number : ")
guess = 1
if "." in coins or "." in ask:
print("You Losed all of your Coins,who said that to you Huh?"... |
import re
passwordChanged = False
while passwordChanged == False:
print('Please type a strong pasword')
uInput = input()
#check length
if len(uInput) < 8:
print ('A strong password has at least 8 chracters')
else:
pass
#check for a capital
capitalRegex = re.compile(r'[ABCDEFGHIJKLMNOPQRST... |
def estCondicional01 ():
#Definir variables y otros
print ( "Ejemplo estructura Condicional en Python" )
montoP = 0
#Datos de entrada
cantidadX = int ( input ( "Ingrese la cantidad de lapices:" ))
#Proceso
si cantidadX > = 1000 :
montoP = cantidadX * 0.80
otra cosa :
montoP = cantidadX... |
#!/usr/bin/python3.4
import string
def to_rot13(dat_in) :
maj_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
min_chars = "abcdefghijklmnopqrstuvwxyz"
dat_out = ""
# Analise and replace MAJ chars
z = int(0)
# Select char[n] from the input
for a in dat_in :
y = int(0)
base_placement ... |
'''
def is_phone_number(text): #415-554
if len(text) != 12:
return False # correct size check
for i in range(0, 3):
if not text[i].isdecimal():
return False # area code check
if text[3] != '-':
return False # dash check
if i in range(4, 7):
if not text[i].isd... |
import math
class Circle:
def __init__ (self, centerX = 0.0, centerY = 0.0, radius = 0.0):
self.centerX = centerX
self.centerY = centerY
self.radius = radius
def getCenter(self):
return (self.centerX, self.centerY)
def setCenter(self, x, y):
self.center... |
from basicgraph import *
from bfs import *
# return True if there should be an edge between nodes for word1 and word2
# in the word graph. Return False otherwise
#
def shouldHaveEdge(word1, word2):
result = False
# Step 1: make this function correct
if len(word1) == len(word2):
indexDif =... |
from basicgraph import *
# CS1210 Spring 2020. Discussion section 8. April 15-17, 2020
#
# Complete steps 1, 2.1, 2.2, and 2.3 so that
# buildWordGraph(somefilename) will return a graph with words from somefilename as Nodes
# and an edge between each pair of Nodes that represents two words that differ in exactly... |
class Solution:
def naive_isPerfectSquare(self, num: int) -> bool:
if num == 1:
return True
else:
digits = len(str(num))
biggest_number = int('9' * ((digits // 2) + 1)) if digits > 1 else num // 2
for i in range(biggest_number, 0, -1):
... |
import random
import sys
import math
class DECK():
def __init__(self):
self.new_deck()
def new_deck(self):
self.cards = []
for val in ['A','2','3','4','5','6','7','8','9','T','J','Q','K']:
for suit in ['H','D','S','C']:
self.cards.append(val+suit)
random.shuffle(self.cards)
def get_card(self):
... |
#print(20 / 3)
#print(20 % 3)
#print (20 // 3)
def required_boxes(a,b):
answer=a//b
remainder=a%b
if remainder>0:
return answer+1
else:
return answer
boxes_needed1 = required_boxes (20,25)
boxes_needed2 = required_boxes (20,3)
print("1.", "Boxes:", boxes_needed1)
print("2.... |
# Group of friends from all over the country are planning a trip
# together in New york. They will all arrive on the same day and
# leave on the same day and they would like to share transportation
# to and from the airport so as to minimize the cost for the trip.
import time
import random
import math
from datetime imp... |
# 1. Update Values in Dictionaries and Lists:
x = [[5, 2, 3], [10, 8, 9]]
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'}
]
sports_directory = {
'basketball': ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer': ['Messi', 'Ronaldo', 'Rooney']
}
... |
import tempfile
#temp files are looked for in environment variables: TMPDIR, TEMP, TMP
#On windows, C:\TEMP, C:\TMP, \TEMP, and \TMP.
print("Temp dir location--> ", tempfile.gettempdir())
# if you want to write text data into a temp file,
# we need to create the tempfile using the w+t mode
# instead of the default.
#m... |
import random as rand
import pygame
rows, cols = input("Enter X and Y size of board: ").split(' ')
boardsize = int(rows)*int(cols)
bombAmount= input("Your board has " + str(boardsize) + " cells, how many bombs do you want? ")
rows, cols, bombAmount = int(rows), int(cols), int(bombAmount)
celldim = 20
margin = 1
... |
a = 5
c = a ** 3 # c: 125
b = 'Sangkeun'
print(b[0:3:2]) # 'Sn'
print(b[1:5]) # 'angk'
print(b[:3]) # 'San'
print(b + ' Kim') # 'Sangkeun Kim'
d = 5.123
e = 987654321123456789123456
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import random
from hmap.sockets import AbstractSocket
class LocalSocket(AbstractSocket):
"""
Interacts with other sockets on the same thread and process. LocalSocket is
not thread-safe and is intended for testing purposes: spoofing up
interac... |
# name=["n","i","t","i","n"]
# rev=1
# x=name
# y=[]
# while rev<=len(name):
# r=(name[-rev])
# y.append(r)
# rev=rev+1
# print(y)
# if(y==name):
# print("palindrome name")
# else:
# print("not palindrome name")
# main_str=["A","B"]
# user=int(input("enter the value"))
# i=0
# while i<len(main_str)... |
# def calculator(num1,num2,operation):
# if operation=="addition":
# return(num1+num2)
# elif operation=="substration":
# return (num1-num2)
# elif operation=="multiple":
# return(num1*num2)
# elif operation=="modolus":
# return(num1%num2)
# elif operation=="division"... |
# def sum_and_avg(k):
# a=int(input("enter the num"))
# b=int(input("enter the num"))
# c=int(input("enter the num"))
# i=0
# sum=0
# while i<k:
# sum=sum+a+b+c
# a=a+1
# print(sum)
# i=i+1
# sum_and_avg(10)
# def add_numbers(number_x,number_y):
# number_sum=number_x... |
# def number(a):
# i=1
# while i<=a:
# if i%2==0:
# print(i,"this is even num")
# else:
# print(i,"this is not even num")
# i=i+1
# number(10) |
heroes = {}
command = input()
while not command == 'End':
current_command_info = command.split()
current_command = current_command_info[0]
hero_name = current_command_info[1]
if current_command == 'Enroll':
if hero_name in heroes.keys():
print(f"{hero_name} is already enr... |
tanks = input().split(', ')
commands_count = int(input())
def index_range(index, length):
return 0 <= index < length
for i in range(commands_count):
args = input().split(', ')
command = args[0]
if command == 'Add':
tank_name = args[1]
if tank_name in tanks:
pr... |
number = int(input())
string_text = str(number)
string=list(string_text)
def sum_even_sum_odd(num):
even_sum = 0
odd_sum = 0
for index in string:
index = int(index)
if index % 2 == 0:
even_sum += index
elif index % 2 != 0:
odd_sum += index
... |
text = input()
for char in text:
new_char = ord(char) + 3
print(chr(new_char), end='')
|
def repeat(string, n):
result = ''
for i in range(0, n):
result += string
return result
text = input()
count = int(input())
print(repeat(text, count))
|
file_name = input().split("\\")[-1]
name = file_name.split('.')[0]
extension = file_name.split('.')[1]
print(f"File name: {name}")
print(f"File extension: {extension}")
|
price_ratings = [int(el) for el in input().split()]
point = int(input())
item = input()
rating = input()
left_items = price_ratings[:point]
right_items = price_ratings[point + 1:]
sum_left = 0
sum_right = 0
if rating == 'positive':
sum_left += sum([num for num in left_items if num > 0])
sum_ri... |
from collections import Counter
color_name_ph = dict() # {color: {name : ph} }
d = dict() # {color_name : ph}
colors = {}
in_line = input()
while in_line != "Once upon a time":
dwarfName, dwarfHatColor, dwarfPhysics = in_line.split(" <:> ")
dwarfPhysics = int(dwarfPhysics)
if (dwarfHatColor,... |
data = input()
count = 0
command = input().split()
while not command[0] == 'Finish':
if command[0] == 'Replace':
current_char = command[1]
new_char = command[2]
data = data.replace(current_char, new_char)
print(data)
elif command[0] == 'Cut':
start = int(comma... |
shops = input().split()
number_commands = int(input())
for num in range(number_commands):
command = input().split()
if command[0] == 'Include':
shop = command[1]
shops.append(shop)
elif command[0] == 'Visit':
shop_to_remove = command[1]
shop_numbers = int(command[2... |
data = input()
companies = {}
while not data == 'End':
company, employee = data.split(' -> ')
if company not in companies:
companies[company] = []
if employee not in companies[company]:
companies[company].append(employee)
data = input()
companies = sorted(companies.items()... |
store = {}
while True:
tokens = input().split('->')
if tokens[0] == 'END':
break
else:
command = tokens[0]
name = tokens[1]
if command == 'Add':
what = tokens[2].split(',')
if name not in store:
store[name] = what
... |
health = 100
bitcoins = 0
dungeons_rooms = input().split('|')
is_won = True
for i in range(len(dungeons_rooms)):
room = dungeons_rooms[i]
data = room.split()
command = data[0]
number = int(data[1])
if command == 'potion':
temp = health
health += number
healed = ... |
line = input()
courses = {}
while line != 'end':
args = line.split(' : ')
course_name = args[0]
student_name = args[1]
if course_name not in courses:
courses[course_name] = []
courses[course_name].append(student_name)
line = input()
sorted_courses = dict(sorted(course... |
import hashlib
import checkutil
filename = input('Input file location: ')
checkmd5 = input('Input MD5 to check (Leave blank to ignore):')
checksha1 = input('Input SHA1 to check (Leave blank to ignore):')
try:
file = open(filename, 'rb')
except FileNotFoundError as e:
print('Cannot find file.')
print('Prog... |
# A. Словарь синонимов
n = int(input())
d1 = {}
d2 = {}
for _ in range(n):
tmp = input().split()
d1[tmp[0]] = tmp[1]
d2[tmp[1]] = tmp[0]
word = input()
print(d1[word] if word in d1 else d2[word])
|
# D. Уравнение с корнем
a = int(input())
b = int(input())
c = int(input())
if c < 0:
print("NO SOLUTION")
else:
if a == 0:
if c*c == b:
print("MANY SOLUTIONS")
else:
print("NO SOLUTION")
else:
xtmp = (c*c-b)
print(xtmp//a if xtmp%a == 0 else "NO SOLUTION")
|
# F. Очень легкая задача
from math import lcm
#def lcm(a, b):
# return abs(a*b) // gcd(a, b)
N, x, y = tuple(map(int, input().split()))
res = min(x,y) # first copy
xylcm = lcm(x,y)
qnt_of_copies_for_xylcm_sec = xylcm//x + xylcm//y
res += (N-1)//qnt_of_copies_for_xylcm_sec*xylcm
rest = (N-1)%qnt_of_copies_for_xyl... |
marks=[1,3,5,2,8,10,1]
max_marks=marks[0]
for i in range(6):
if(max_marks<marks[i+1]):
max_marks=marks[i+1]
print(max_marks)
|
def k_largest(arr, k):
arr.sort(reverse = True)
for i in range(k):
print (arr[i])
# Driver program
arr = [5, 1, 3, 6, 8, 2, 4, 7]
# n = len(arr)
k = 3
k_largest(arr, k)
|
count_items = 0
number_of_items = int(input("Please enter the number of items"))
while number_of_items <0:
number_of_items = int(input("Invalid number of items. Please enter the number of items"))
prices_of_items = []
while number_of_items > count_items:
price_of_item = float(input("Please enter the price of ea... |
#Lab #5
#Due Date: 09/21/2018, 11:59PM
########################################
#
# Name:Daniel Melo Cruz
# Collaboration Statement: I did not ask for help
#
########################################
class SodaMachine:
'''
Creates instances of the class ... |
## Uninformed and informed searches
## Mustafa Sadiq
################################# Imports ###############################
import random as rand
import numpy as np
from collections import deque
import heapq
from math import sqrt
####################### Make maze ##############################
def make_maze(dim, ... |
import datetime
# här importerar jag nu tidens tid
while True:
# Här sätter jag en loop som loopar varje gång det är sant
DT = datetime.datetime.now()
pernum = input("Skriv ditt personnummer ÅÅÅÅMMDD: ")
# Här så sätter jag en input så att man kan skriva det den frågar efter
DTpers = DT.strptime(pernum, '%Y... |
from experiments import utility
def run_experiment():
"""
Experiment II: Noam Chomsky --> https://en.wikipedia.org/wiki/Noam_Chomsky
"""
noam_context='Avram Noam Chomsky (born December 7, 1928) is an American linguist, philosopher, cognitive \
scientist, historian, social critic, and political activist. ... |
# Python Activity
#
# Fill in the code for the functions below.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# # Part A.
def array_2_dict(emails, contacts):
counter = 0
for i in emails:
contacts[list(contacts.keys())[counter]] = i
counter... |
import numpy as np
from scipy import stats
x=int(input())
sum1 = 0
arr=list(map(int, input().split()[:x]))
for i in range(x):
sum1 = sum1+arr[i]
print(sum1/x)
print(np.median(arr))
m=stats.mode(arr)
print(int(m[0]))
|
"""This example lets you dynamically create static walls and dynamic balls
"""
__docformat__ = "reStructuredText"
import pygame
import pymunk
from pymunk import Vec2d
X, Y = 0, 1
### Physics collision types
COLLTYPE_DEFAULT = 0
COLLTYPE_MOUSE = 1
COLLTYPE_BALL = 2
def flipy(y):
"""Small hack to convert chipmu... |
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
quit()
screen.fill... |
def removeElement(nums, val):
if len(nums)==0:
return nums
j=0
i=j+1
while i<len(nums):
if nums[j] == val and nums[i] == val:
i+=1
elif nums[j] == val and nums[i] != val:
nums[i], nums[j] = nums[j], nums[i]
j+=1
... |
# Sorting Algorithm Naive approach : Bubble Sort
#Create a randomized array of length 'length' and range 0,maxint
from random import randint
import logging
import os
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
def create_random_array(length=10, maxint=50):
try :
return [randint(0, maxint) for _... |
def pascal(i,j):
if j==i or j==1:
return 1
else:
return pascal(i-1, j-1) + pascal(i-1,j)
pascal(10,5)
class Solution:
def pascal(self, row, col):
if row == col or col == 1:
return 1
else:
return self.pascal(row-1, col-1) + self.pascal(row-1, c... |
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right, self.next = None, None, None
# level order traversal using 'next' pointer
def print_level_order(self):
nextLevelRoot = self
while nextLevelRoot:
current ... |
# Merge Sort
from random import randint
def create_random_array(length=10, maxint=50):
return [randint(0, maxint) for _ in range(length)]
new_array = create_random_array(length=3, maxint=50)
print(new_array)
# class sorting():
# def __init__(algorith_name = None, array_length=10, randomized=True):
# self.algorith... |
# todo : This is for Help in tabulate table
from tabulate import tabulate
head= ["Row1","Row2","Row3"]
# assign data
mydata = [{'a', 'b', 'c'},{12, 34, 56},{'Geeks', 'for', 'geeks!'}]
# display table
print(tabulate(mydata,headers=head,tablefmt="psql"))
exit()
# todo : This is our Project Tabulate part
from t... |
#Question 1
print("Python 3 uses parenthesis around print statements. Python 2 does not.")
#Question 2
x = [0, 1, 2, 3, 4, 5, 6]
print(x[2])
#Question 3
y = x[::-1]
print(y)
#Question 4
z = x[1::2]
print(z)
#Question 5
#Original Code
#x = 99
#if(x > 0) is True
#print('x is positive')
x = 99
if(... |
# By: Malane Lieng and Gregorio Lopez
# Part 1
# Question 1
print("Question 1")
print("Python 3 uses parenthesis to print out text while Python 2 does not use parenthesis to print text.")
# Question 2
print("Question 2")
x = [0, 1, 2, 3, 4, 5, 6]
print(x[2])
# Question 3
print("Question 3")
x.reverse()
... |
"""Module which imports mathematical functions"""
import math
class CreateSphere:
"""Class which creates a sphere based on object's composed elements"""
def calculate_volume(self):
"""Calculates the volume with the radius given"""
return (4 / 3) * math.pi * self.radius ** 3
def calculate... |
#Homework 2
#Author: Donald Jalving
#EGR 400 Full Stack Development in Python
#Question 2 (Iterating Through Lists)
x = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9 ,10, 11], [12, 13, 14, 15]];
for i in range(len(x)):
print(*x[i], sep = ' & ')
|
def add(num1:int, num2:int)->int:
return num1+num2
if __name__ == "__main__":
assert add(1, 2) == 3
assert add(-1, 1) == 1
|
from turtle import *
from paddle import Paddle
from barrier import Barrier
from ball import Ball
import time
screen = Screen()
screen.bgcolor("black")
screen.setup(width=600, height=600)
screen.title("Break-out Game")
paddle = Paddle()
barrier = Barrier()
ball = Ball()
screen.listen()
screen.onkey(fun=paddle.go_righ... |
''' Even number between 1 and 100'''
i=1
while i <= 100:
if i%2 == 0:
print i
i=i+1
# Generate Fibonacci series upto 10
a,b = 0,1
print a,b
for i in range(0,15):
c = a+b
a,b=b,c
print c
|
class Employee:
"""Class to represent an employee """
def __init__( self , first , last ):
"""Employee Constructor takes first and last name """
self.firstName = first
self.lastName = last
def __str__( self ):
return "{} {}".format( self.firstName , self.lastName )
class HourlyWorker( Employee ):
""" C... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 12 20:54:01 2018
@author: joykumardas
"""
from collections import deque
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def add(node, root):
if root is None:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 21:57:00 2018
@author: joykumardas
"""
class Fraction:
def __init__( self, num, deno ):
self.numerator , self.denominator = Fraction.reduce( num , deno )
@classmethod
def reduce( cls , top , bottom ):
co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.