blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
73219c63946768b4458c9c4c9f30639a83829d19
|
AndyLaneOlson/LearnPython
|
/Ch3TurtleShapes.py
| 863
| 4.28125
| 4
|
import turtle
#Set up my turtle and screen
wn = turtle.Screen()
myTurtle = turtle.Turtle()
myTurtle.shape("turtle")
myTurtle.speed(1)
myTurtle.pensize(8)
myTurtle.color("blue")
myTurtle.penup()
myTurtle.backward(400)
myTurtle.pendown()
#Make the turtle do a triangle
for i in range(3):
myTurtle.forward(100)
myTurtle.left(120)
#Move the turtle to a new spot
myTurtle.penup()
myTurtle.forward(200)
myTurtle.pendown()
#Make the turtle create a square
for i in range(4):
myTurtle.forward(100)
myTurtle.left(90)
myTurtle.penup()
myTurtle.forward(200)
myTurtle.pendown()
#Make the turtle create a hexagon
for i in range(6):
myTurtle.forward(60)
myTurtle.left(60)
myTurtle.penup()
myTurtle.forward(200)
myTurtle.pendown()
#Make the turtle create an octagon
for i in range(8):
myTurtle.forward(50)
myTurtle.left(45)
wn.mainloop()
| false
|
c0994074084e337bba081ca44c37d2d4d8553f8f
|
xtom0369/python-learning
|
/task/Learn Python The Hard Way/task33/ex33_py3.py
| 368
| 4.15625
| 4
|
space_number = int(input("Input a space number : "))
max_number = int(input("Input a max number : "))
i = 0
numbers = []
while i < max_number:
print(f"At the top i is {i}")
numbers.append(i)
i = i + space_number
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
| true
|
27d0745e6199185dc5b1fb8d9739b2d0226fd606
|
letaniaferreira/guessinggame
|
/game.py
| 1,554
| 4.1875
| 4
|
"""A number-guessing game."""
# greet player
# get player name
# choose random number between 1 and 100
# repeat forever:
# get guess
# if guess is incorrect:
# give hint
# increase number of guesses
# else:
# congratulate player
import random
name = raw_input("Welcome, what is your name? ")
greeting = "Hello, %s, do you want to play a guessing game? " %(name)
print greeting
best_score = ""
def number_game():
random_number = random.randint(1,100)
user_guess = 0
count = 0
while user_guess != random_number:
user_guess = raw_input("Guess a number from 1 to 100: ")
try:
user_guess = int(user_guess)
#break
except ValueError:
print("Oops! That was an invalid number. Rounding number.")
user_guess = int(float(user_guess))
print user_guess
if user_guess > random_number:
print "Your guess is too high!"
count += 1
elif user_guess < random_number:
print "Your guess is too low!"
count += 1
elif user_guess < 1 or user_guess > 100:
print "Please enter a number between 1 and 100."
count += 1
else:
print "Well done, %s, You found the number in %s trials!" %(name,count)
return count
number_game()
# keep track of best score
greeting = raw_input("Would you like to play another round: ")
if greeting == 'yes':
number_game()
# if count < best_score:
else:
print "goodbye"
| true
|
567566abb3fad5fb82f4944fb222941988bf8fc8
|
vokoramus/GB_python1_homework
|
/Homework__1/HW1-4.py
| 458
| 4.25
| 4
|
'''4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.'''
n = int(input("Введите n: "))
max_char = n % 10
while n > 0:
last_chr = n % 10
if last_chr > max_char:
max_char = last_chr
n //= 10
print("max =", max_char)
| false
|
1532020913bb3d12e049d871a9d544fb0d5f4abc
|
KD4/TIL
|
/Algorithm/merge_two_sorted_lists.py
| 1,227
| 4.1875
| 4
|
# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
# splice 꼬아 잇다
# 주어준 링크드리스트 두 개를 하나의 리스트로 만들어라. 두 리스트의 노드들을 꼬아서 만들어야한다.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = None
result = None
while l1 is not None or l2 is not None:
if l2 is None or (l1 is not None and l1.val < l2.val):
if result is None:
result = l1
cur = l1
l1 = l1.next
else:
cur.next = l1
cur = l1
l1 = l1.next
else:
if result is None:
result = l2
cur = l2
l2 = l2.next
else:
cur.next = l2
cur = l2
l2 = l2.next
return result
| true
|
b6364e51af1472c1eec2b3bef4e9aa5d68f4e2e4
|
CHuber00/Simulation
|
/Sprint-1-Python_and_Descriptive_Statistics/Deliverables/MoreCalculations.py
| 2,014
| 4.25
| 4
|
"""
Christian Huber
CMS 380, Fall 2020 / Sprint 1 / MoreCalculations
This script reads a text file's values and calculates and prints
the mean, median, variance, and standard deviation.
"""
from math import sqrt
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
def mean(x):
"""
Calculate and return the mean of input list x
"""
return sum(x) / len(x)
def median(x):
"""
Calculate and return the median of input list x
"""
values.sort()
# Calculate mean for middle indexes for even set
# Averaging middle two indexes
if(len(x)%2==0):
return ((x[int(len(x)/2)]+x[int(len(x)/2)-1])/2)
# Referencing the middle index of uneven set
else:
return(x[(int(len(x)/2))])
def variance(x):
"""
Calculate and return the variance of input list x
"""
m = mean(x)
# Create an array with the value of each (element - mean)^2
v = [((i-m)**2) for i in x]
return mean(v)
def sDeviation(x):
"""
Calculate and return the standard Deviation of
input list x
"""
return sqrt(variance(x))
values = []
# Read all data from the file into value list
with open("data.txt") as f:
data = f.readlines()
for line in data:
# Remove trailing whitespace
line = line.strip()
values.append(float(line))
dataMean = mean(values)
dataMedian = median(values)
dataVariance = variance(values)
dataSDeviation = sDeviation(values)
# Use matlibplot to output boxplot and histogram to pdf
plt.figure()
plt.boxplot(values)
plt.title("Data.txt Values visualization in Boxplot")
plt.xlabel("Data")
plt.ylabel("Values")
plt.savefig("MoreCalculationsBoxplot.pdf", bbox_inches = "tight")
plt.figure()
plt.hist(values,20)
plt.title("Data.txt Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.savefig("moreCalculationsHistogram.pdf", bbox_inches = "tight")
| true
|
0779044e55eb618e79e6cc91c7d8d59e614713dc
|
yamiau/Courses
|
/[Udemy] Web Scraping with Python - BeautifulSoup, Requests, Selenium/00 Data Structures Refresher/List Comprehension 2.py
| 777
| 4.21875
| 4
|
'''Nested lists'''
carts = [['toothpaste', 'soap', 'toilet paper'], ['meat', 'fruit', 'cereal'], ['pencil', 'notebook', 'eraser']]
#or
person1 = ['toothpaste', 'soap', 'toilet paper']
person2 = ['meat', 'fruit', 'cereal']
person3 = ['pencil', 'notebook', 'eraser']
carts = [person1, person2, person3]
print(carts)
for value in carts:
print(value)
#print(my_list[row][column])
'''2D list'''
my_matrix = []
#range(start inclusive, stop exclusive, step)
for row in range(0, 25, 5):
row_list = []
for column in range(row, row+5):
row_list.append(column)
my_matrix.append(row_list)
print(my_matrix)
for row in my_matrix:
print(row)
'''Using list comprehension'''
new_matrix = [[column for column in range(row, row+5)] for row in range(0,25,5)]
print(new_matrix)
| true
|
16ab5543da15a3db9c80b7526c55e3745eadf2af
|
lithiumspiral/python
|
/calculator.py
| 1,196
| 4.25
| 4
|
import math
print('This calculator requires you to enter a function and a number')
print('The functions are as follows:')
print('S - sine')
print('C - cosine')
print('T - tangent')
print('R - square root')
print('N - natural log')
print('X 0- eXit the program')
f, v = input("Please enter a function and a value ").split(" ")
v = float(v)
while f != 'X' and f != 'x':
if f == 'S' or f == 's' :
calculation = math.sin(v)
print('The sine of your number is ', calculation)
elif f == 'C' or f == 'c' :
calculation = math.cos(v)
print('The cosine of your number is ', calculation)
elif f == 'T' or f == 't' :
calculation = math.tan(v)
print('The tangent of your number is ', calculation)
elif f == 'R' or f == 'r' :
calculation = math.sqrt(v)
print('The square root of your number is ', calculation)
elif f == 'N' or f == 'n' :
calculation = math.log10(v)
elif f == 'X' or f == 'x' :
print('Thanks for using the calculator')
if f != 'X' and f != 'x':
f, v = input("Please enter a function and a value ").split(" ")
v = float(v)
print('Thanks for using the calculator')
| true
|
d508ae43c03ea8337d2d5dcfeb3ccfc75555df4d
|
Emma-2016/introduction-to-computer-science-and-programming
|
/lecture15.py
| 1,958
| 4.34375
| 4
|
# Class - template to create instance of object.
# Instance has some internal attributes.
class cartesianPoint:
pass
cp1 = cartesianPoint()
cp2 = cartesianPoint()
cp1.x = 1.0
cp2.x = 1.0
cp1.y = 2.0
cp2.y = 3.0
def samePoint(p1, p2):
return (p1.x == p2.x) and (p1.y == p2.y)
def printPoint(p):
print '(' + str(p.x) + ', ' + str(p.y) + ')'
# shallow equality -- 'is': given two things, do they point to exactly the same reference? (object)
# deep equality -- we can define. (value)
class cPoint():
#def __init__(self, x, y): create an instance, use 'self' to refer to that instance
#when call a class, it create an instance with all those internal attributes. __init__ create a pointer to that instance.
#You need access to that, so it calls it, passing in self as the pointer to the instance.
#That says, it has access to that piece of memory and now inside of that piece of memory, I can do thing like:
#define self.x to be the value passed in for x. That is create a variable name x and a value associated with it.
#self will always point to a particular instance
def __init__(self, x, y):
self.x = x
self.y = y
self.radius = math.sqrt(self.x * self.x + self.y * self.y)
self. angle = math.atan2(self.y, self.x)
def cartesian(self):
return (self.x, self.y)
def polar(self):
return (self.radius, self.angle)
def __str__(self): #print repretation
return '(' + str(self.x) + ', ' + str(self.y) + ')'
def __cmp__(self, other):
return cmp(self.x, other.x) and cmp(self.y, other.y)
#data hidding - one can only access instance values through defined methods. Python does not do this.
# operator overloading
class Segment():
def __init__(self, start, end):
self.start = start
self.end = end
def length(self):
return ((self.start.x - self.end.x) ** 2 + (self.start.y - self.end.y) ** 2) ** 0.5
#in fact, one should access the value through a defined method.
| true
|
3f835498966366c4a404fc4eb00725bbca57fee9
|
fredssbr/MITx-6.00.1x
|
/strings-exercise2.py
| 304
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 10 19:59:32 2016
@author: frederico
"""
#Exercise 2 - Strings
str1 = 'hello'
str2 = ','
str3 = 'world'
print('str1: ' + str1)
print('str1[0]: ' + str1[0])
print('str1[1]: ' + str1[1])
print('str1[-1]: ' + str1[-1])
print('len(str1): ' + str(len(str1)))
| false
|
00ce7ddd2e3fe18691908492ddd2de4ebde05559
|
ckceddie/OOP
|
/OOP_Bike.py
| 878
| 4.25
| 4
|
# OOP Bike
# define the Bike class
class bike(object):
def __init__ (self , price , max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print "bike's price is " + str(self.price)
print "maximum speed : " + str(self.max_speed)
print "the total miles : "+str(self.miles)
return self
def ride(self):
print "Riding : "
self.miles += 10
print "the miles is "+str(self.miles)
return self
def reverse(self):
print "Reversing : "
self.miles -= 5
print "the miles is "+str(self.miles)
return self
# create instances and run methods
bike1 = bike(99.99, 12)
bike1.displayInfo()
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2=bike(1000,20)
bike2.displayInfo()
| true
|
6b20406d423409b7a977d67e670b61022f4f0976
|
ehpessoa/Python
|
/Automate-The-Boring-Stuff-With-Python/Chapter 03 - Functions/the_collatz_sequence.py
| 329
| 4.4375
| 4
|
#! python3
# the_collatz_sequence.py - Take user input num and prints collatz sequence
def collatz(num):
print(num)
while num != 1:
if int(num) % 2:
num = 3 * num + 1
else:
num = num // 2
print(num)
user_num = input('Enter a number ')
collatz(user_num)
| false
|
6604cf3f68749b72d0eeb22a76e03075d2b87a02
|
jkbstepien/ASD-2021
|
/graphs/cycle_graph_adj_list.py
| 1,087
| 4.125
| 4
|
def cycle_util(graph, v, visited, parent):
"""
Utility function for cycle.
:param graph: representation of a graph as adjacency list.
:param v: current vertex.
:param visited: list of visited vertexes.
:param parent: list of vertexes' parents.
:return: boolean value for cycle function.
"""
visited[v] = True
for u in graph[v]:
if not visited[u]:
parent[u] = v
cycle_util(graph, u, visited, parent)
elif visited[u] and parent[u] != v:
return True
return False
def cycle(graph, s=0):
"""
Function determines whether graph has a cycle.
:param graph: graph as adjacency list.
:param s: starting vertex.
:return: boolean value.
"""
n = len(graph)
visited = [False] * n
parent = [False] * n
return cycle_util(graph, s, visited, parent)
if __name__ == "__main__":
G = [[1, 3], [2, 0], [3, 1], [4, 0], [3]]
G2 = [[1, 3], [2, 0], [1], [4, 0], [3]]
G3 = [[1, 2], [2, 0], [0, 1]]
print(cycle(G))
print(cycle(G2))
print(cycle(G3))
| true
|
830aaaa0664c6d8f993de0097927ff4c385c6d4e
|
okipriyadi/NewSamplePython
|
/SamplePython/samplePython/Modul/memcache/_01_Using_memcache.py
| 1,261
| 4.21875
| 4
|
"""
kesimpuan sementara saya, memcache digunakan untuk menyimpan sebuah value di memori cache
sehingga program lain bisa mengambil value tersebut dengan cara mencari key yang telah ditetapkan
coba lihat value di file ini bisa didapatkan oleh file _02_test.py
It's fairly simple. You write values using keys and expiry times. You get values using keys.
You can expire keys from the system. Most clients follow the same rules.
You can read the generic instructions and best practices on the memcached homepage.
<http://www.danga.com/memcached>
If you really want to dig into it, I'd look at the source. Here's the header comment:
"""
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set("some_key", "Some value")
value = mc.get("some_key")
print "value 1", value
mc.set("another_key", 3)
value = mc.get("another_key")
print "value 2", value
mc.delete("another_key")
value = mc.get("another_key")
print "value 3", value
"""
mc.set("key", "1") # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")
key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)
# we now have obj, and future passes through this code
# will use the object from the cache.
"""
| false
|
d93db45bbff954b5957cf7d8b62363877c7b0e84
|
okipriyadi/NewSamplePython
|
/SamplePython/build_in_modul/_04_getattr.py
| 678
| 4.5625
| 5
|
"""
Objects in Python can have attributes. For example you have an object person,
that has several attributes: name, gender, etc. You access these attributes
(be it methods or data objects) usually writing: person.name, person.gender,
person.the_method(), etc.
But what if you don't know the attribute's name at the time you write the program?
For example you have attribute's name stored in a variable called gender_attribute_name
"""
class Hello_world():
def __init__(self):
self.Pariabel = "saya orang sunda"
def saja(self):
print "pulangkan saja "
a = Hello_world()
b = getattr(a, "Pariabel")
print b
c = getattr(a, "saja")
c()
| false
|
f08bd170328ec6dc4ca3c8da2f3d8e2af7af5891
|
okipriyadi/NewSamplePython
|
/SamplePython/build_in_modul/_01_zip.py
| 358
| 4.125
| 4
|
"""
built-in zip berfungsi untuk iterasi yang menghasilkan satu-ke satu. return nya berupa tuple.
contoh zip([1, 2, 3, 4], ['a', 'b', 'c', 'f']) menghasikan
"""
a = zip([1, 2, 3, 4], ['a', 'b', 'c', 'f'])
for i in a :
print i
print "a = " , a
b = zip([1, 2], ['a', 'b', 'c', 'f'])
print "b =",b
c = zip([1, 2, 3, 4], ['a', 'b', 'c'])
print "c =", c
| false
|
cf4bf216fd03c9acaff05038fe3f204902ddd216
|
anmolparida/selenium_python
|
/CorePython/FlowControl/Pattern_Stars.py
| 758
| 4.125
| 4
|
"""
Write a Python program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
def pattern_star_right_arrow_method1(n):
print('pattern_star_right_arrow_method1')
for i in range(n + 1):
print("* " * i)
for j in range(n - 1, 0, -1):
print("* " * j)
pattern_star_right_arrow_method1(5)
def pattern_star_right_arrow_method2(n):
print('pattern_star_right_arrow_method2')
for i in range(n):
for j in range(i):
print('* ', end=' ')
print('')
for i in range(n, 0, -1):
for j in range(i):
print('* ', end=' ')
print('')
pattern_star_right_arrow_method2(5)
| false
|
5512e04c4832ad7b74e6a0ae7d3151643747dd8c
|
anmolparida/selenium_python
|
/CorePython/DataTypes/Dictionary/DictionaryMethods.py
| 1,181
| 4.28125
| 4
|
d = {'A': 1, 'B' : 2}
print(d)
print(d.items())
print(d.keys())
print(d.values())
print(d.get('A'))
print(d['A'])
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict)
"""
Removing elements from Dictionary
"""
print('\nRemoving elements from Dictionary')
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
squares[4] = 16
print(squares)
# removes last item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# print(squares) # Throws Error
"""
setdefault
"""
person = {'name': 'Phill', 'age': 22}
age = person.setdefault('age')
print('person = ',person)
print('Age = ',age)
| true
|
6a655da9e2fefbfaa7a77ce652b6af6755ae1e95
|
surenthiran123/sp.py
|
/number.py
| 330
| 4.21875
| 4
|
n1=input();
n2=input();
n3=input();
Largest = n1
if Largest < n2:
if n2 > n3:
print(n2,"is Largest")
else:
print(n3,"is Largest")
elif Largest < n3:
if n3 > n2:
print(n3,"is Largest")
else:
print(n2,"is Largest")
else:
print(n1,"is Largest")
| false
|
946d183421857c5896636eac5dcaa797091cb87a
|
aboyington/cs50x2021
|
/week6/pset6/mario/more/mario.py
| 480
| 4.15625
| 4
|
from cs50 import get_int
def get_height(min=1, max=8):
"""Prompt user for height value."""
while True:
height = get_int("Height: ")
if height >= min and height <= max:
return height
def print_pyramid(n):
"""Print n height of half-pyramid to console."""
for i in range(1, n+1):
print(" "*(n-i) + "#"*i + " "*2 + "#"*i)
def main():
height = get_height()
print_pyramid(height)
if __name__ == "__main__":
main()
| true
|
2b233d93ef2101f8833bbff948682add348fde63
|
djanibekov/algorithms_py
|
/inversion_counting.py
| 2,025
| 4.21875
| 4
|
inversion_count = 0
def inversion_counter_conquer(first, second):
"""[This function counts #inversions while merging two lists/arrays ]
Args:
first ([list]): [left unsorted half]
second ([list]): [right unsorted half]
Returns:
[tuple]: [(first: merged list of left and right halves, second: #inversions)]
"""
i = 0
j = 0
length_of_first = len(first)
length_of_second = len(second)
inversion_count = 0
merged = []
#? looking for number of particular inversion
while (i < length_of_first) and (j < length_of_second):
if (first[i] > second[j]):
inversion_count += length_of_first - i
merged.append(second[j])
j = j + 1
else:
merged.append(first[i])
i = i + 1
#! extra check whether element is left
while i < len(first):
merged.append(first[i])
i = i + 1
while j < len(second):
merged.append(second[j])
j = j + 1
return merged, inversion_count
def list_divider_divide(array):
"""[This function divides the input list/array in to two parts recursively
by divide and conquer method till the base case.]
Args:
array ([list]): [given input]
Returns:
[int]: [final answer of the question "How many inversions did list hold?"]
[list]: [the sorted array/list of two derived lists "left" and "right"]
"""
length = len(array)
if(length == 1):
return array, 0
mid = length // 2
left = list_divider_divide(array[:mid])
right = list_divider_divide(array[mid:])
#? inversion_count holds the sum of all particular #inversion
merged, particular_inversions = inversion_counter_conquer(left[0], right[0])
inversion_count = particular_inversions + left[1] + right[1]
return merged, inversion_count
f_name = open("IntegerArray.txt")
integers = []
for integer in f_name:
integers.append(int(integer))
print(list_divider_divide(integers)[1])
| true
|
63ca4f68c05708f2482045d06775fa5d7d22ea55
|
loudan-arc/schafertuts
|
/conds.py
| 1,574
| 4.1875
| 4
|
#unlike with other programming languages that require parentheses ()
#python does not need it for if-else statements, but it works with it
fake = False
empty = None
stmt = 0
f = 69
k = 420
hz = [60, 75, 90, 120, 144, 240, 360]
if k > f:
print(f"no parentheses if condition: {k} > {f}")
if (k > f):
print(f"with parentheses if condition: {k} > {f}")
if not k==hz[5]:
print(f"variable {k=}, not {hz[5]}")
#not can be used in place of != inequality
#or just evaluating if a statement is false and accept it if false
#for fstrings in pythong, using {var_name=}
#will print the variable name with the actual value of it directly'
#you must include the = sign
#otherwise it will just print value, period
#-------------------
#CONDITIONALS
if fake == False:
print(f"Fake == {fake}, empty == {empty}")
#evalutes to print the fact that it is false
if not empty:
print("empty will also evaluate to False")
#while empty is strictly set to None, which means using "if empty == None"
#will be skipped by the program
#if you use "if not empty"
#it will like on the above example, try to evaluate to false
#and None will evaluate to False in this specific way, so it will print
#the statement, it will not skip
if stmt == 0:
print("0 is also false")
else:
print("True bruh")
#What evals to False:
# * any variable = False
# * any variable = None
# * any variable = 0
# * any variable = '', (), [] which is an empty list or tuple
# * any variable = {} empty dict
#-------------------
#LOOPING
| true
|
4afceabb3673acbe934061dd9888d06e0457a152
|
dark5eid83/algos
|
/Easy/palindrome_check.py
| 330
| 4.25
| 4
|
# Write a function that takes in a non-empty string that returns a boolean representing
# whether or not the string is a palindrome.
# Sample input: "abcdcba"
# Sample output: True
def isPalindrome(string, i=0):
j = len(string) - 1 - i
return True if i >= j else string[i] == string[j] and isPalindrome(string, i + 1)
| true
|
7ce3fe03de726250fbad7573e0f6a12afa5fcc4a
|
AshishKadam2666/Daisy
|
/swap.py
| 219
| 4.125
| 4
|
# Taking user inputs:
x = 20
y = 10
# creating a temporary variable to swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
| true
|
ef3a0ab8ca46680697e312f31094b9ce455a37bb
|
Choe-Yun/Algorithm
|
/LeetCode/문자열 다루기/02.Reverse_String.py
| 746
| 4.15625
| 4
|
### 문제
# Write a function that reverses a string. The input string is given as an array of characters s.
# 문자열을 뒤집는 함수를 작성해라. 인풋값은 배열이다
### Example 1
# Input: s = ["h","e","l","l","o"]
# Output: ["o","l","l","e","h"]
###### code
from typing import List
# 투 포인터를 이용한 스왑 방식
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# 파이싼의 reverse() 함수를 이용한 방식
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()
| false
|
bb155d4d67a7611506849ea6160074b6fec2d01f
|
kalpitthakkar/daily-coding
|
/problems/Jane_Street/P5_consCarCdr.py
| 1,420
| 4.125
| 4
|
def cons(a, b):
def pair(f):
return f(a, b)
return pair
class Problem5(object):
def __init__(self,
name):
self.name = name
# The whole idea of this problem is functional programming.
# Use the function cons(a, b) to understand the functional
# interface required to write functions car(f) and cdr(f).
# car/cdr takes a function as input => as cons(a,b) returns a
# function. The returned function takes a function as input,
# which has two arguments like cons => this inner function
# like cons can be made by us according to whether it is called
# from car or cdr.
def solver_car(self, f):
def first(x, y):
return x
return f(first)
def solver_cdr(self, f):
def last(x, y):
return y
return f(last)
def __repr__(self):
return "Problem #5 [Medium]: " + self.name + "\nThis problem was asked by Jane Street"
if __name__ == '__main__':
p = Problem5('Return first element of pair using car and second using cdr')
print(p)
x = cons(2, cons(cons(3, 4), 5))
car = getattr(p, 'solver_car')
cdr = getattr(p, 'solver_cdr')
print("Input: x = cons(2, cons(cons(3, 4), 5))")
print("Solution from solver for car function: car(x) = {}".format(car(x)))
print("Solution from solver for cdr function: cdr(cdr(x)) = {}".format(cdr(cdr(x))))
| true
|
11b8b5e7175b685c7f3718409d22ce34322dbb11
|
mariagarciau/EntregaPractica3
|
/ejercicioadivinar.py
| 1,884
| 4.125
| 4
|
"""
En este desafío, probamos su conocimiento sobre el uso de declaraciones
condicionales if-else para automatizar los procesos de toma de decisiones.
Juguemos un juego para darte una idea de cómo diferentes algoritmos para el mismo
problema pueden tener eficiencias muy diferentes.
Deberás desarrollar un algoritmo que seleccionará aleatoriamente un número entero
entre 1 y 15.
El usuario deberá ser adivinando, deberemos permanecer en la condición hasta
encontrar el número seleccionado.
Además nos deberá dar una pista( si es mayor o menor) en cada intento.
Ahora desarrolla el código para un número del 1 al 300, sabiendo que no deberías
necesitar más de 9 intentos.
"""
import random
numeroRandom = random.randint(1,15)
numeroIntroducido = int(input("Introduzca un número entre 1 y 15: "))
while numeroIntroducido != numeroRandom:
if numeroRandom < numeroIntroducido:
print("El número que debe adivinar es menor")
numeroIntroducido = int(input("Introduzca un número entre 1 y 15: "))
elif numeroRandom > numeroIntroducido:
print("El número que debe adivinar es mayor")
numeroIntroducido = int(input("Introduzca un número entre 1 y 15: "))
print("Has acertado el número")
numeroRandom2 = random.randint(1,300)
numeroIntroducido2 = int(input("Introduzca un número entre 1 y 300: "))
intentos : int
intentos = 1
while numeroIntroducido2 != numeroRandom2:
intentos +=1
if intentos>9:
break
elif numeroRandom2 < numeroIntroducido2:
print("El número que debe adivinar es menor")
numeroIntroducido2 = int(input("Introduzca un número entre 1 y 300: "))
elif numeroRandom2 > numeroIntroducido2:
print("El número que debe adivinar es mayor")
numeroIntroducido2 = int(input("Introduzca un número entre 1 y 300: "))
if intentos<9:
print("Has acertado el número")
| false
|
84f2c41dd849d194eb1bbdbb5abc97ae9f05bfcd
|
trishajjohnson/python-ds-practice
|
/fs_1_is_odd_string/is_odd_string.py
| 974
| 4.21875
| 4
|
def is_odd_string(word):
"""Is the sum of the character-positions odd?
Word is a simple word of uppercase/lowercase letters without punctuation.
For each character, find it's "character position" ("a"=1, "b"=2, etc).
Return True/False, depending on whether sum of those numbers is odd.
For example, these sum to 1, which is odd:
>>> is_odd_string('a')
True
>>> is_odd_string('A')
True
These sum to 4, which is not odd:
>>> is_odd_string('aaaa')
False
>>> is_odd_string('AAaa')
False
Longer example:
>>> is_odd_string('amazing')
True
"""
abcs = list('abcdefghijklmnopqrstuvwxyz')
count = 0
word = word.lower()
for letter in word:
idx = abcs.index(letter) + 1
count += idx
if count % 2 == 1:
return True
else:
return False
# Hint: you may find the ord() function useful here
| true
|
1991e34b3272b9374e485fb49abe10f2adfb7b3b
|
smirnoffmg/codeforces
|
/519B.py
| 303
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
n = int(raw_input())
first_row = map(int, raw_input().split(' '))
second_row = map(int, raw_input().split(' '))
third_row = map(int, raw_input().split(' '))
print [item for item in first_row if item not in second_row]
print [item for item in second_row if item not in third_row]
| true
|
42e25fed3a11b28f2bd4eb5070ce2ff7034eeda1
|
sanapplegates/Python_qxf2_exercises
|
/bmi.py
| 288
| 4.28125
| 4
|
#calculate the bmi of user
#user height in kg
print("Enter the user's weight(kg):")
weight = int(input())
#user height in metres
print("Enter the user's height(metre) :")
height = int(input())
#Body Mass Index of user
bmi = weight/(height*height)
print("bmi of user:",bmi)
| true
|
7f200a512c5821b826df1a6eec5259ef91484125
|
nahuelv/frro-soporte-2019-11
|
/practico_01_cvg/ejercicio_08.py
| 547
| 4.21875
| 4
|
"""
Definir una función superposicion() que tome dos listas y devuelva True si tienen al
menos 1 miembro en común o devuelva False de lo contrario. Escribir la función
usando el bucle for anidado.
"""
lista_1 = ["a", "b", "c"]
lista_2 = ["b", "d", "e"]
def superposicion (lista1, lista2):
for i in range (0, len(lista1)):
for j in range (0, len(lista2)):
if lista1[i]==lista2[j]:
return True
return False
assert superposicion(["a","b"],["f","b"]) == True
print(superposicion(lista_1, lista_2))
| false
|
b88a715b7625b1b27f47e9cb6098e00e8e616f7e
|
lexruee/project-euler
|
/problem_9.py
| 326
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc
"""
def main():
#TODO
pass
if __name__ == '__main__':main()
| true
|
91e717e2422ba6a54dcfef0de4292846b9fd1832
|
Laavanya-Agarwal/Python-C2
|
/Making functions/countWords.py
| 271
| 4.3125
| 4
|
def countWords():
fileName = input('Enter the File Name')
file = open(fileName, 'r')
noOfWords = 0
for line in file:
words = line.split()
noOfWords = noOfWords + len(words)
print('The number of words is ' + str(noOfWords))
countWords()
| true
|
3c54aa7bc9815de81888d9b40085067fa1cf218a
|
keryl/2017-03-24
|
/even_number.py
| 467
| 4.25
| 4
|
def even_num(l):
# first, we will ensure l is of type "list"
if type(l) != list:
return "argument passed is not a list of numbers"
# secondly, check l is a list of numbers only
for n in l:
if not (type(n) == int or type(n) == float):
return "some elements in your list are not numbers"
# else find even numbers in it
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
| true
|
8bd5806dd9b01c9eb90592e7239e8662ae9f1af5
|
danny237/Python-Assignment3
|
/insertion_sort.py
| 541
| 4.1875
| 4
|
"""Insertion Sort"""
def insertion_sort(list1):
"""function for insertion sort"""
for i in range(1, len(list1)):
key = list1[i]
j = i-1
while j >=0 and key < list1[j] :
list1[j+1] = list1[j]
j -= 1
list1[j+1] = key
return list1
# user input
print('Enter list of number seperated by comma.')
print('Example: 1,2,3')
list_arr = [int(i) for i in input().strip().split(',')]
sorted_arr = insertion_sort(list_arr)
print(f'Sorted list: {sorted_arr}')
| true
|
adfba4e45bc9ec9707eeda09767bfde152600426
|
reachtoakhtar/data-structure
|
/tree/problems/binary_tree/diameter.py
| 776
| 4.125
| 4
|
__author__ = "akhtar"
def height(root, ans):
if root is None:
return 0
left_height = height(root.left, ans)
right_height = height(root.right, ans)
# update the answer, because diameter of a tree is nothing but maximum
# value of (left_height + right_height + 1) for each node
ans[0] = max(ans[0], 1 + left_height + right_height)
return 1 + max(left_height, right_height)
def find_diameter(root):
"""
Find the diameter of a binary tree with given root.
:param BTreeNode root: The root of the tree.
:return: the diameter of the tree.
:rtype: int
"""
if root is None:
return 0
# This will store the final answer
ans = [-99999999999]
height(root, ans)
return ans[0]
| true
|
93c12f6ced3ca1b9d99a490e6e3e7d6551dbd58f
|
hector81/Aprendiendo_Python
|
/Bucles/Hexagono.py
| 625
| 4.125
| 4
|
numero = 0
cuadrado = ''
# bucle para poner numero correto
while numero < 1 :
# ponemos el numero
numero = int(input('Escribe el número '))
print()
if numero < 1:
print('El número debe ser positivo')
else:
numeroArriba = numero
while numeroArriba < ((numero*2) + 3):
for i in range(0, ((numero*2)-1)):
if i < numero:
cuadrado = cuadrado + ' '
else:
cuadrado = cuadrado + 'x'
print(cuadrado)
cuadrado = ''
numeroArriba = numeroArriba + 2
| false
|
b9d59b5bd22207e7d7188fdfffa92f5acbccd82f
|
hector81/Aprendiendo_Python
|
/CursoPython/Unidad7/Ejercicios/ejercicio_II_u7.py
| 1,171
| 4.53125
| 5
|
'''
Lambda y map()
map() es una función incorporada de orden superior que toma una función e iterable como entradas, y
devuelve un iterador que aplica la función a cada elemento de la iterable. El código de abajo
usa map() para encontrar la media de cada lista en números para crear los promedios de la lista.
Haz una prueba para ver qué pasa.
Reescribe este código para ser más conciso reemplazando la función media por una expresión lambda
definida dentro de la llamada a map()
'''
''' SOLUCION SIN FUNCION LAMBDA '''
numeros = [
[56, 13, 93, 45, 18],
[59, 83, 16, 75, 43],
[49, 59, 93, 83, 62],
[41, 72, 56, 10, 87]
]
def promedio(num_list):
return sum(num_list) / len(num_list)
medias = list(map(promedio, numeros))
print(medias)
''' SOLUCION CON FUNCION LAMBDA '''
#Expresión lambda para realizar la solución al mismo problema.
promedio1 = lambda numeros : sum(numeros) / len(numeros) # lambda parametro return formula
medias1 = list(map(promedio1, numeros)) # a la funcion map le pasamos como parametros la funcion y la lista
print(medias1)
| false
|
08be952345411637b829e6af9f3ff91c745225cd
|
hector81/Aprendiendo_Python
|
/CursoPython/Unidad5/Ejemplos/ejemplo3_if_else_anidados.py
| 1,063
| 4.125
| 4
|
'''
Durante el trimestre, un estudiante debe realizar tres exámenes. Cada examen tiene una calificación
y la nota total que recibe el estudiante es la suma de las dos mejores calificaciones.
Escribe un programa que lea las tres notas y determine cuál es la calificación total que recibirá el
estudiante.
Solamente hay tres casos posibles y son excluyentes, por lo que se usarán dos decisiones anidadas para
verificar dos casos, y el tercero será la cláusula else.
'''
# Cálculo de calificación final
nota1 = int(input('Cual es la nota de tu primer examen: '))
nota2 = int(input('Cual es la nota de tu segundo examen: '))
nota3 = int(input('Cual es la nota de tu tercer examen: '))
# aquí añadimos 2 comparaciones que concatenadas con and obliga a que las dos sean verdaderas para que if
# sea verdad
t = 0
if nota1 >= nota3 and nota2 >= nota3:
t = nota1 + nota2
else:
if nota1 >= nota2 and nota3 >= nota2:
t = nota1 + nota3
else:
t = nota2 + nota3
print(f'Su calificación total es: {t}')
| false
|
0c8d83c250fa1300cde1e30bade521711b00199c
|
hector81/Aprendiendo_Python
|
/Integer/Introducir_Pares.py
| 396
| 4.125
| 4
|
def introducirNumero():
while True:
try:
x = int(input("Por favor ingrese un número par: "))
return x
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
numero = 0
while numero%2 == 0:
numero = introducirNumero()
if numero%2 != 0:
print("El numero era impar")
| false
|
a5084140a8d49079bcbac4d8d6cc2cb27721ebab
|
hector81/Aprendiendo_Python
|
/Excepciones/Ejercicio2_texto_ruta_OSError.py
| 1,117
| 4.125
| 4
|
'''
EJERCICIOS EXCEPCIONES
2. Programa que itere sobre una lista de cadenas de texto que contienen nombres
de fichero hasta encontrar el primero que existe (OSError) [Pista: crear nuestra
propia función, existe_fichero(ruta), que devuelve True o False]
'''
# buscar fichero = Ejercicio2_texto_ruta_OSError.py
def introducirNombreFichero():
while True:
try:
fichero = input(f"Por favor ingrese un nombre de fichero: ")
if fichero != '':
print(f"El fichero buscado es " + fichero)
return fichero
break
except ValueError:
print(f"Oops! No era válido. Intente nuevamente...")
def existe_fichero(fichero):
while True:
try:
with open(fichero,"r") as ficheroBuscar:
print(f"Fichero encontrado")
break
except OSError:
print(f"Fichero ' {fichero} ' no existe")
finally:
print(f"Operación terminada")
break
fichero = introducirNombreFichero()
existe_fichero(fichero)
| false
|
9570e6bbbe210122e6a2611d19622fabafac0777
|
hector81/Aprendiendo_Python
|
/CursoPython/Unidad6/Soluciones/ejercicio_I_u6 (2).py
| 637
| 4.3125
| 4
|
"""Diseña un programa que genere un entero al azar y te permita introducir números para saber si aciertas dicho número.
El programa debe incluir un mensaje de ayuda y un conteo de intentos.
"""
import random
num = int(input("Introduce un número del uno a l diez: "))
aleatorio = random.randint(1,10)
while num != aleatorio:
if num < aleatorio:
print(f"El numero {num} es demasiado pequeño")
num = int(input("Introduce otro"))
elif num > aleatorio:
print(f"El numero {num} es demasiado grande")
num = int(input("Introduce otro"))
print(f"Enhorabuena has acertado el num es {aleatorio}")
| false
|
8c72ee9e300534e48b4f7ff9adad76e665e758b5
|
hector81/Aprendiendo_Python
|
/CursoPython/Unidad7/Ejemplos/funcion_nonlocal.py
| 558
| 4.15625
| 4
|
'''
Si el programa contiene solamente funciones que no contienen a su vez funciones, todas las variables
libres son variables globales. Pero si el programa contiene una función que a su vez contiene una
función, las variables libres de esas "subfunciones" pueden ser globales (si pertenecen al programa
principal) o no locales (si pertenecen a la función).
'''
def myfunc1():
x = "John"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1())
# devuelva la variable que está dentro de la subfuncion
| false
|
3cd870efac96ad2866c909ef969caf5acc2830d1
|
hector81/Aprendiendo_Python
|
/CursoPython/Unidad9/Ejemplos/clase_metodo_operador_matematico.py
| 557
| 4.375
| 4
|
class Punto():
"""Clase que va representar un punto en un plano
Por lo que tendrá una coordenada cartesiana(x,y)
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, otro):
""" Devuelve la suma de ambos puntos. """
return Punto(self.x + otro.x, self.y + otro.y)
def __sub__(self, otro):
""" Devuelve la resta de ambos puntos. """
return Punto(self.x - otro.x, self.y - otro.y)
p = Punto(3,4)
q = Punto(2,5)
print(p - q)
print(p + q)
| false
|
7a165c4d007d1ba99dc4024e658e26bcc7dbee5d
|
hector81/Aprendiendo_Python
|
/Listas/Ordenacion_listas.py
| 729
| 4.40625
| 4
|
'''
ORDENACIÓN DE LISTAS
'''
x = [8, 2, 3, 7, 5, 3, 7, 3, 1]
print(x)
print(f"1. El mayor número de la lista ")
print(f"{max(x)}")
print(f"2. El menor número de la lista ")
print(f"{min(x)}")
print(f"3. Los tres mayores números de la lista ")
lista = sorted(x, reverse=True)
print(lista[0:3])
print(f"4. El mayor de los tres primeros números de la lista")
print(f"{max(x)}")
print(f"5. El menor de los cuatro últimos números de la lista ")
print(f"{min(x[len(x)-4:len(x)])}")
print(f"6. La suma de los cinco mayores números de la lista ")
print(f"{sum(lista[0:5])}")
print(f"7. La suma de los tres menores números de la lista")
print(f"{sum(x[len(lista)-3:len(lista)])}")
print(lista)
| false
|
a43ddbb034d53912e38c51fc663c49e12520f22f
|
hector81/Aprendiendo_Python
|
/CursoPython/Unidad4/Ejemplos/listas_funciones.py
| 996
| 4.40625
| 4
|
''' funciones_listas '''
x = [20, 30, 40, 50, 30]
y = [20, "abc", 56, 90, "ty"]
print(len(x)) # devuelve numero elemento lista x
print(len(y)) # devuelve numero elemento lista x
#max y min solo funcionan con listas numéricas
print(max(x)) # maximo de la lista x
# ERROR # print(max(y)) # maximo de la lista y
print(min(x)) # MINIMO de la lista x
# ERROR # print(min(y)) # MINIMO de la lista y
''' FUNCION SUMA funcionan con listas numéricas '''
print(sum(x)) # sumaria todos los elementos de la lista x
# ERROR # print(sum(y)) # sumaria todos los elementos de la lista y
''' OPERADORES Y CONCATENADORES '''
c = x + y # me devuelve la concatenacion de ambas listas
print(c)
d = x * 3 # me devuelve 3 veces la misma lista en una sola lista
print(d)
''' BUSQUEDA in devuelve valores booleanos'''
print(23 in x)# me pregunta si 23 está en la lista x, y devuelve true o false
print(30 in x)# me pregunta si 23 está en la lista x, y devuelve true o false
| false
|
7915e90dd431cedcd1820486783a299df813b0b9
|
SoumyaMalgonde/AlgoBook
|
/python/sorting/selection_sort.py
| 654
| 4.21875
| 4
|
#coding: utf-8
def minimum(array, index):
length = len(array)
minimum_index = index
for j in range(index, length):
if array[minimum_index] > array[j]:
minimum_index = j
return minimum_index
def selection_sort(array):
length = len(array)
for i in range(length - 1):
minimum_index = minimum(array, i)
if array[i] > array[minimum_index]:
array[i], array[minimum_index] = array[minimum_index], array[i]
if __name__ == "__main__":
entry = input("Enter numbers separated by space: => ")
array = [int(x) for x in entry.split()]
selection_sort(array)
print(array)
| true
|
3b68f1f217fd64cc0428e93fbfe17745c664cb2e
|
SoumyaMalgonde/AlgoBook
|
/python/maths/jaccard.py
| 374
| 4.1875
| 4
|
a = set()
b = set()
m = int(input("Enter number elements in set 1: "))
n = int(input("Enter number elements in set 2: "))
print("Enter elements of set 1: ")
for i in range(m):
a.add(input())
print("Enter elements of set 2: ")
for i in range(n):
b.add(input())
similarity = len(a.intersection(b))/len(a.union(b))
print("Similarity index: {} ".format(similarity))
| true
|
df7feb3e68df6d0434ed16f02ce3fcf0fd1dbf99
|
SoumyaMalgonde/AlgoBook
|
/python/maths/Volume of 3D shapes.py
| 2,970
| 4.1875
| 4
|
import math
print("*****Volume of the Cube*****\n")
side=float(input("Enter the edge of the cube "))
volume = side**3
print("Volume of the cube of side = ",side," is " ,volume,)
print("\n*****Volume of Cuboid*****\n")
length=float(input("Enter the length of the cuboid "))
breadth=float(input("Enter the breadth of the cuboid "))
height=float(input("Enter the height of the cuboid "))
volume=length * breadth * height
print("Volume of the cuboid of length = ",length,", breadth = ",breadth,", height = ",height," is " ,volume)
print("\n*****Volume of cone*****\n")
radius = float(input("Enter the radius of the cone "))
height = float(input("Enter the height of the cone "))
volume = round((((math.pi)*(radius**2)*height)/3),2)
print("Volume of cone of radius = ",radius,", height = ", height, " is ", volume)
print("\n*****Volume of right circular cone*****\n")
radius = float(input("Enter the radius of the right circular cone "))
height = float(input("Enter the height of the right circular cone "))
volume = round((((math.pi)*(radius**2)*height)/3),2)
print("Volume of right circular cone of radius = ",radius,", height = ", height, " is ", volume)
print("\n*****Volume of a prism*****\n")
base_length = float(input("Enter the length of the base "))
base_breadth = float(input("Enter the breadth of the base "))
height = float(input("Enter the height of the prism"))
base_area = base_length * base_breadth
volume = base_area * height
print("Volume of prism of base area =",base_area,", height = ",height, " is ",volume)
print("\n*****Volume of different types of pyramid*****\n")
apothem = float(input("Enter the apothem length of the pyramid "))
base = float(input("Enter the base length of the pyramid "))
height = float(input("Enter the height of the pyramid "))
volume_square = ((base**2)*height)/3
volume_triangle = (apothem * base * height)/6
volume_pentagon = (5 * apothem * base * height)/6
volume_hexagon = apothem * base * height
print("\nVolume of a square pyramid of base = ",base,", height = ",height, " is ", volume_square)
print("Volume of a triangular pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_triangle)
print("Volume of a pentagonal pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_pentagon)
print("Volume of a hexagonal pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_hexagon)
print("\n*****Volume of Sphere*****\n")
radius = float(input("Enter the radius of the sphere "))
volume = round((4 * (math.pi) * (radius**3))/3)
print("Volume of the sphere of radius = ",radius," is ",volume)
print("\n*****Volume of circular cylinder*****\n")
radius = float(input("Enter the radius of the circular cylinder "))
height = float(input("Enter the height of the circular cylinder "))
volume = round((math.pi) * (radius**2) * height)
print("Volume of the circular cylinder of radius = ",radius,", height = ",height," is ",volume)
| true
|
bb114c561547aa3adbcf855e3e3985e08c748a01
|
SoumyaMalgonde/AlgoBook
|
/python/sorting/Recursive_quick_sort.py
| 834
| 4.1875
| 4
|
def quick_sort(arr, l, r): # arr[l:r]
if r - l <= 1: # base case
return ()
# partition w.r.t pivot - arr[l]
# dividing array into three parts one pivot
# one yellow part which contains elements less than pivot
# and last green part which contains elements greater than pivot
yellow = l + 1
for green in range(l+1, r):
if arr[green] <= arr[l]:
arr[yellow], arr[green] = arr[green], arr[yellow]
yellow += 1
# move pivot into place
arr[l], arr[yellow - 1] = arr[yellow - 1], arr[l]
quick_sort(arr, l, yellow-1) # recursive calls
quick_sort(arr, yellow, r)
return arr
print("Enter elements you want to sort: ")
array = list(map(int, input().split()))
sorted_array = quick_sort(array, 0, len(array))
print("Sorted array is: ", *sorted_array)
| true
|
edb2d3e1a9f09ce94933b8b223af17dda52143a3
|
SunshinePalahang/Assignment-5
|
/prog2.py
| 327
| 4.15625
| 4
|
def min_of_3():
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
if a < b and a < c:
min = a
elif b < a and b < c:
min = b
else:
min = c
return min
minimum = min_of_3()
print(f"The lowest of the 3 numbers is {minimum}")
| true
|
34a2bfbe98dfb42c1f3d2a8f444da8e49ca04639
|
PaxMax1/School-Work
|
/fbi.py
| 1,610
| 4.25
| 4
|
# a322_electricity_trends.py
# This program uses the pandas module to load a 3-dimensional data sheet into a pandas DataFrame object
# Then it will use the matplotlib module to plot comparative line graphs
import matplotlib.pyplot as plt
import pandas as pd
# choose countries of interest
my_countries = ['United States', 'Zimbabwe','Cuba', 'Caribbean small states', "Cameroon", "Burundi"]
# Load in the data with read_csv()
df = pd.read_csv("elec_access_data.csv", header=0) # header=0 means there is a header in row 0
# get a list unique countries
unique_countries = df['Entity'].unique()
# Plot the data on a line graph
for c in unique_countries:
if c in my_countries:
# match country to one of our we want to look at and get a list of years
years = df[df['Entity'] == c]['Year']
# match country to one of our we want to look at and get a list of electriciy values
sum_elec = df[df['Entity'] == c]['Access']
plt.plot(years, sum_elec, label=c,)
plt.ylabel('Percentage of Country Population')
plt.xlabel('Year')
plt.title('Percent of Population with Access to Electricity')
plt.legend()
plt.show()
# CQ1- A countrys access to electricity can affect its access to computing innovations because computers require electricity and power to opperate.
# If you don't have electricity to run a computer, than you can't use your computer and have access to it's innovations.
# CQ2- Analyzing data like this can affect global change because we can see what countrys have issues in the world so that other countrys that are more advanced can help get them up on their feet.
| true
|
c275468117aa43e59ac27afd391e463d0983a979
|
gevishahari/mesmerised-world
|
/integersopr.py
| 230
| 4.125
| 4
|
x=int(input("enter the value of x"))
y=int(input("enter the value of y"))
if(x>y):
print("x is the largest number")
if(y>x):
print("y is the largest number")
if (x==y):
print("x is equal to y")
print("they are equal")
| true
|
d76dfe561f9111effed1b82da602bf6df98f2405
|
AdmireKhulumo/Caroline
|
/stack.py
| 2,278
| 4.15625
| 4
|
# a manual implementation of a stack using a list
# specifically used for strings
from typing import List
class Stack:
# initialise list to hold items
def __init__(self):
# initialise stack variable
self.stack: List[str] = []
# define a property for the stack -- works as a getter
@property
def stack(self) -> List[str]:
return self._stack
# define a setter for the property
@stack.setter
def stack(self, new_stack: List[str]) -> None:
# ensure proper format
if isinstance(new_stack, List):
# assign private stack wit new value
self._stack = new_stack
else:
# improper input, deny and raise an error
raise ValueError("Must be a list of strings, i.e List[str]")
# push method adds to top of stack
def push(self, item: str) -> None:
if type(item) == str:
self.stack.append(item)
else:
raise ValueError("Must supply a string")
# pop method removes from top of stack
def pop(self) -> str:
# get top item
item: str = self.stack[-1]
# delete top item
del self.stack[-1]
# return top item
return item
# peek method retrieves the item at the top of the stack without removing it
def peek(self) -> str:
return self.stack[-1]
# size returns the number of elements in the stack
def size(self) -> int:
return len(self.stack)
# check if the stack is empty
def is_empty(self) -> bool:
return len(self.stack) == 0
# reverse method
def reverse(self) -> None:
# create a new stack
new_stack: Stack = Stack()
# iterate through current stack and push to new stack
while not self.is_empty():
new_stack.push(self.stack.pop())
# assign new_stack to old_stack
self.stack = new_stack.stack
# dunder methods -- kinda unnecessary here to be honest
# len works the same as size() above
def __len__(self) -> int:
return len(self.stack)
# repr returns a string representation of the stack
def __repr__(self) -> str:
string: str = ''
for item in self.stack:
str += item
return string
| true
|
8b7da9557874db581b38432a28b41f9058e9dadf
|
cpelaezp/IA
|
/1. Python/ejemplos/3.projects/1.contactos/contactoBook.py
| 831
| 4.15625
| 4
|
class Contacto:
def __init__(self, name, phone, email):
self._name = name
self._phone = name
self._email = email
class ContactoBook:
def __init__(self):
self._contactos = []
def add(self):
name = str(input("Ingrese el nombre: "))
phone = str(input("Ingrese el telefono: "))
email = str(input("Ingrese el email: "))
contacto = Contacto(name, phone, email)
self._contactos.append(contacto)
print('name: {}, phone: {}, email: {}'.format(name, phone, email))
def showAll(self):
for contacto in self._contactos:
_print_contato(contacto)
def _print_contato(self, _contacto):
print('name: {}, phone: {}, email: {}'.format(_contacto.name, _contacto.phone, _contacto.email))
| false
|
71021e7cf21f47c13df7be87afe4e169eb945ab5
|
jessicazhuofanzh/Jessica-Zhuofan--Zhang
|
/assignment1.py
| 1,535
| 4.21875
| 4
|
#assignment 1
myComputer = {
"brand": "Apple",
"color": "Grey",
"size": 15.4,
"language": "English"
}
print(myComputer)
myBag = {
"color": "Black",
"brand": "MM6",
"bagWidth": 22,
"bagHeight": 42
}
print(myBag)
myApartment = {
"location": "New York City",
"type": "studio",
"floor": 10,
"color": "white and wood"
}
print(myApartment)
myBreakfast = {
"cost": "5 dollars",
"drink": "pink drink",
"food": "egg and bacon",
"calorie": 500
}
print(myBreakfast)["food"]
#assignment 2
{
"name": "amy",
"location": "garden",
"genus": "flower",
"species": "rose",
"count": 5,
"spined": False
}
#assignment 3
print ("Welcome to New York City")
print ("Answer the questions below to create your story in NYC")
print ("-------------------------")
adjective1 = raw_input("Enter an adjective: ")
color1 = raw_input("What is your favorite color?: ")
country1 = raw_input("Which country you come from?: ")
number1 = raw_input("Enter any number between 1-100: ")
place1 = raw_input("Enter your favorite area in NYC: ")
person1 = raw_input("Enter your favorite movie star: ")
person2 = raw_input("Enter your favorite singer: ")
story = " I arrived New York City on a" + adjective1 + "day," \
"carrying a" + color1 + "suitcase which I bought in" + country1 + "." \
"It will take" + number1 + "minutes to my apartment, " \
"which located in" + place1 + "." \
"I fount out that" + person1 + "and" + person2 + "is my neighbor. " \
print(story)
| true
|
15774b26dae087e6ec683e676046c29d2009b904
|
devimonica/Python-exercises---Mosh-Hamedani-YT-
|
/4.py
| 490
| 4.5
| 4
|
# Write a function called showNumbers that takes a parameter called limit. It should
# print all the numbers between 0 and limit with a label to identify the even and odd numbers. For example,
# if the limit is 3, it should print:
# 0 EVEN
# 1 ODD
# 2 EVEN
# 3 ODD
# Solution:
def showNumbers(limit):
for number in range(0, limit+1):
if number % 2 == 0:
print(f'{number} EVEN')
else:
print(f'{number} ODD')
showNumbers(5)
| true
|
d5d3b540482b581ad95e5a4d4ab4e8dbcc1280fd
|
gninoshev/SQLite_Databases_With_Python
|
/delete_records.py
| 411
| 4.1875
| 4
|
import sqlite3
# Connect to database
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Order By Database - Order BY
c.execute("SELECT rowid,* FROM customers ORDER BY rowid ")
# Order Descending
c.execute("SELECT rowid,* FROM customers ORDER BY rowid DESC")
items = c.fetchall()
for item in items:
print(item)
# Close out connection
conn.close()
| true
|
5a0637856f9dddcb3d6667340def81e831361c7d
|
kaloyansabchev/Programming-Basics-with-Python
|
/PB Exam - 20 and 21 February 2021/03. Computer Room.py
| 755
| 4.25
| 4
|
month = input()
hours = int(input())
people_in_group = int(input())
time_of_the_day = input()
per_hour = 0
if month == "march" or month == "april" or month == "may":
if time_of_the_day == "day":
per_hour = 10.50
elif time_of_the_day == "night":
per_hour = 8.40
elif month == "june" or month == 'july' or month == "august":
if time_of_the_day == "day":
per_hour = 12.60
elif time_of_the_day == "night":
per_hour = 10.20
if people_in_group >= 4:
per_hour *= 0.9
if hours >= 5:
per_hour *= 0.5
price_per_person = per_hour
total_price = (price_per_person * people_in_group) * hours
print(f"Price per person for one hour: {price_per_person:.2f}")
print(f"Total cost of the visit: {total_price:.2f}")
| true
|
a818501d5eccec65ef65fe2d1cf461258ade1e99
|
kaloyansabchev/Programming-Basics-with-Python
|
/03 Conditional Statements Advanced Lab/11. Fruit Shop.py
| 1,773
| 4.125
| 4
|
product = input()
day = input()
quantity = float(input())
if day == "Saturday" or day == "Sunday":
if product == 'banana':
banana_cost = 2.70 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.25 * quantity
print(f'{apple_cost:.2f}')
elif product == 'orange':
orange_cost = 0.90 * quantity
print(f'{orange_cost:.2f}')
elif product == 'grapefruit':
grapefruit_cost = 1.60 * quantity
print(f'{grapefruit_cost:.2f}')
elif product == 'kiwi':
kiwi_cost = 3.00 * quantity
print(f'{kiwi_cost:.2f}')
elif product == 'pineapple':
pineapple_cost = 5.60 * quantity
print(f'{pineapple_cost:.2f}')
elif product == 'grapes':
grapes_cost = 4.20 * quantity
print(f'{grapes_cost:.2f}')
else:
print('error')
elif day == "Monday" or day == "Tuesday" or day == "Wednesday" or day == "Thruesday" or day == "Friday":
if product == 'banana':
banana_cost = 2.50 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.20 * quantity
print(f'{apple_cost:.2f}')
elif product == 'orange':
orange_cost = 0.85 * quantity
print(f'{orange_cost:.2f}')
elif product == 'grapefruit':
grapefruit_cost = 1.45 * quantity
print(f'{grapefruit_cost:.2f}')
elif product == 'kiwi':
kiwi_cost = 2.70 * quantity
print(f'{kiwi_cost:.2f}')
elif product == 'pineapple':
pineapple_cost = 5.50 * quantity
print(f'{pineapple_cost:.2f}')
elif product == 'grapes':
grapes_cost = 3.85 * quantity
print(f'{grapes_cost:.2f}')
else:
print('error')
else:
print("error")
| false
|
3b46d280e7581cb9cf36098bf3375b126a9305b7
|
i-fernandez/Project-Euler
|
/Problem_004/problem_4.py
| 862
| 4.21875
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 19:32:24 2020
@author: israel
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(number):
st = str(number)
size = len(st)
for i in range(0,int(size/2)):
if (st[i] != st[size-i-1]):
return False
return True
# Comprueba si es divisible por dos numeros de tres digitos
def is_divisible(n):
for i in range(999,100,-1):
if n%i == 0:
r = int(n/i)
st = str(r)
if len(st) == 3:
print(f'Eureka: {n} = {i} * {r}')
return True
return False
max_val = 999*999
cont = True
while cont:
for i in range(max_val,100,-1):
if is_palindrome(i) and is_divisible(i):
cont = False
break
| false
|
bb2ff59d2062a5b6ab007782f05653c2fd7fb1c1
|
Ramya74/ERP-projects
|
/Employee.py
| 1,296
| 4.25
| 4
|
employees = [] #empty List
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Display all employee")
print("5. Change a employee name in the list")
print("6. exit")
ch = int(input("Enter your choice: "))
if ch is None:
print("no data present in Employees")
elif ch == 1:
#Add employee
name = input("Enter name: ")
employees.append(name)
#in one line
#employees.append(input("Enter name: "))
elif ch == 2:
#Delete employee
print(employees)
print("Choose name from this: ")
name = input("Enter name to delete: ")
employees.remove(name)
elif ch == 3:
#Search employee
name = input("Enter name you want to search: ")
if name in employees:
print(name + " is in the list")
else:
print(name + " not in the list")
elif ch == 4:
#Display employee
#print("---['r','t']---like output")
#print(employees)
for i in range(0,len(employees)):
print(i+1,".",employees[i])
i+=1
elif ch== 5:
#Change a employee name in the list
name = input("Enter the name: ")
index = employees.index(name)
new_name = input("Enter new name: ")
employees[index] = new_name
#employees[employees.index(name)] = input("Enter new name: ")
elif ch == 6:
#Exit
break;
else:
print("Invalid Choice")
| true
|
36987ff25b32b7f90e4fdcddbb0e8067acdbd4ec
|
saubhagyav/100_Days_Code_Challenge
|
/DAYS/Day61/Collatz_Sequence.py
| 315
| 4.34375
| 4
|
def Collatz_Sequence(num):
Result = [num]
while num != 1:
if num % 2 == 0:
num = num/2
else:
num = 3*num+1
Result.append(num)
return Result
if __name__ == "__main__":
num = int(input("Enter a Number: "))
print(Collatz_Sequence(num))
| false
|
5491efb3841bc753f8de6fff6b0f5233c132a805
|
saubhagyav/100_Days_Code_Challenge
|
/DAYS/Day22/Remove_Duplicates_in_Dictionary.py
| 364
| 4.21875
| 4
|
def Remove_Duplicates(Test_string):
Test_list = []
for elements in Test_string.split(" "):
if ((Test_string.count(elements) > 1 or Test_string.count(elements) == 1) and elements not in Test_list):
Test_list.append(elements)
return Test_list
Test_string = input("Enter a String: ")
print(*(Remove_Duplicates(Test_string)))
| true
|
f2f47ab9d8e116d43c619e88b3db0807b4d658f9
|
saubhagyav/100_Days_Code_Challenge
|
/DAYS/Day10/String_Palindrome.py
| 203
| 4.1875
| 4
|
def Palindrome(Test_String):
if Test_String == Test_String[::-1]:
return True
else:
return False
Test_String = input("Enter a String: ")
print(Palindrome(Test_String))
| true
|
816b1917aa477d70f2ce4c30323d811ae7896bde
|
saubhagyav/100_Days_Code_Challenge
|
/DAYS/Day18/Remove_Keys_from_Dictionary.py
| 387
| 4.1875
| 4
|
def Remove_Keys(Test_dict, Remove_Value):
return {key: value for key, value in Test_dict.items() if key != Remove_Value}
N_value = int(input("Enter n: "))
Test_dict = {}
for i in range(N_value):
key = input("Key: ")
Value = int(input("Value: "))
Test_dict[key] = Value
Remove_Value = input("Which Key to Delete: ")
print(Remove_Keys(Test_dict, Remove_Value))
| false
|
ab24f06d7a40626bf37222236b0ad610637171bb
|
yuttana76/python_study
|
/py_dictionary.py
| 563
| 4.125
| 4
|
phonebook = {
'John':999,
'Jack':888,
'Jill':777
}
print(phonebook)
#Interating
for name,tel in phonebook.items():
print('%s has phone number is %s' %(name,tel))
#Delete item
print('Delete item')
del phonebook['Jill']
print(phonebook)
#Update and Add item
print('Update and Add item')
phonebook.update({'AAA':222})
phonebook.update({'Jack':555})
print(phonebook)
if "Jack" in phonebook:
print('Hi Jack your phone number is %s' %(phonebook['Jack']) )
if "Jill-x" in phonebook:
print('Jill-x here.')
else:
print('Jill-x not here.')
| false
|
73d106223ed6a7d1b8435d731bf0ac076927484e
|
britannica/euler-club
|
/Week33/euler33_smccullars.py
| 2,818
| 4.125
| 4
|
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __eq__(self, other):
return self.numerator == other.numerator and self.denominator == other.denominator
def __str__(self):
return '{}/{}'.format(self.numerator, self.denominator)
def simplify(self):
# check for a common prime factor -- since we are only interested in two digit numbers,
# we can stop checking when x * n > 99 (where x and n is prime). if x == 2 (aka the
# smallest prime), n cannot be more than 47.
for p in (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47):
if self.numerator % p == 0 and self.denominator % p == 0:
simpler_fraction = Fraction(int(self.numerator/p), int(self.denominator/p))
return simpler_fraction.simplify()
return self
# bad simplification means "transform the fraction's numerator and denominator into strings,
# find a shared digit, remove the shared digit from those strings, and then use those strings
# to make a new fraction"
def bad_simplify(self):
for x in str(self.numerator):
for y in str(self.denominator):
if x == y and x != '0':
digit_cancelled_numerator = int(str(self.numerator).replace(x, '', 1))
digit_cancelled_denominator = int(str(self.denominator).replace(x, '', 1))
return Fraction(digit_cancelled_numerator, digit_cancelled_denominator)
return None
curious_fractions = []
# we want all two digit numerators
for numerator in range(10, 100):
# we want a two digit denominator, but it must be larger than the numerator for the
# fraction to be less than 1
for denominator in range(numerator+1, 100):
raw_fraction = Fraction(numerator, denominator)
mangled_fraction = raw_fraction.bad_simplify()
# prevent divide by zero errors
if mangled_fraction and mangled_fraction.denominator != 0:
if raw_fraction.simplify() == mangled_fraction.simplify():
curious_fractions.append(raw_fraction)
numerator_product = 1
denominator_product = 1
for fraction in curious_fractions:
numerator_product *= fraction.numerator
denominator_product *= fraction.denominator
solution_fraction = Fraction(numerator_product, denominator_product)
print(solution_fraction.simplify().denominator)
# --------------------------------------
# TLDR
# --------------------------------------
# raw --> mangled --> simplified
# 16/64 --> 1/4 --> 1/4
# 19/95 --> 1/5 --> 1/5
# 26/65 --> 2/5 --> 2/5
# 49/98 --> 4/8 --> 1/2
#---------------------------------------
# (1*1*2*1)/(2*5*5*4) == 2/200 --> 1/100
| false
|
d386360920ee5b5e08654d3e2c781148839fbdc9
|
scudan/TestPython
|
/com/refrencePython/function/FunctionT1.py
| 468
| 4.375
| 4
|
#可变参数函数
def concat(*args , sep ='/'):
return sep.join(args);
result = concat("earth","mars","venus");
print(result);
result1 = concat("earth","mars","venus",sep =".");
print(result1);
# 参数分拆
# *args 分拆 元祖
# **args 分拆 字典
list1 = list(range(3,6))
print(list1);
args = [3,6]
list2 = list(range(*args))
print(list2);
def make_inc(n):
return lambda x: x+n;
f= make_inc(42);
re = f(2);
print(re);
print(make_inc.__doc__)
| false
|
bb1a8090d3fc97546339037bbc0e9b06ff43b438
|
3point14guy/Interactive-Python
|
/strings/count_e.py
| 1,153
| 4.34375
| 4
|
# Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
#
# Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then keeps track of how many are the letter ‘e’. Your function should print an analysis of the text like this:
#
# Your text contains 243 alphabetic characters, of which 109 (44.8%) are 'e'.
import string # has sets of characters to use with 'in' and 'not in'
letters = string.ascii_lowercase + string.ascii_uppercase
strng = """The stump thunk the skunk stunk and the skunk thunk the stump stunk."""
def count(p):
#count characters, "e", and calc % "e"
counter = 0
e = 0
for char in p:
if char in letters:
counter = counter + 1
if char == "e" or char == "E":
e = e + 1
perc = e / counter * 100
return counter, e, perc
#returns a set
ans = count(strng)
print("Your text contains {} alphabetic characters, of which {} ({:.2}%) are 'e'.".format(ans[0], ans[1], ans[2]))
| true
|
11992691b92d6d74aa41fe6797f70f810ea3bfb9
|
3point14guy/Interactive-Python
|
/tkinter/hello_world_tkinter.py
| 1,249
| 4.15625
| 4
|
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
window = tk.Tk()
# my_label = ttk.Label(window, text="Hello World!")
# my_label.grid(row=1, column=1)
# messagebox.showinfo("Information", "Information Message")
# messagebox.showerror("Error", "My error message")
# messagebox.showwarning("WARNING!", "Warning message")
# answer = messagebox.askokcancel("QUESTION", "DO YOU WANT TO OPEN A FILE?")
# answer = messagebox.askretrycancel("Question", "Do you want to try again?")
# answer = messagebox.askyesno("Question", "Do you like Python?")
# answer = messagebox.askyesnocancel("Hey You!", "Continue playing?")
answer = simpledialog.askstring("input", "WHat is your first name?", parent=window)
if answer is not None:
print("Hello ", answer)
else:
print("hello annonymous user")
answer = simpledialog.askinteger("input", "What is your age", parent=window, minvalue=0, maxvalue=100)
if answer is not None:
my_label = ttk.Label(window, text="Wow, I am {} too!".format(answer))
my_label.grid(row=10, column=20)
else:
my_label = ttk.Label(window, text="Most people who feel old won't enter their age either.")
my_label.grid(row=10, column=20)
window.mainloop()
| true
|
da34092f0d87be4f33072a3e2df047652fb29cf3
|
sudj/24-Exam3-201920
|
/src/problem2.py
| 2,658
| 4.125
| 4
|
"""
Exam 3, problem 2.
Authors: Vibha Alangar, Aaron Wilkin, David Mutchler, Dave Fisher,
Matt Boutell, Amanda Stouder, their colleagues and
Daniel Su. January 2019.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
run_test_shape()
def run_test_shape():
""" Tests the shape function. """
print()
print('--------------------------------------------------')
print('Testing the SHAPE function:')
print('There is no automatic testing for this one; just compare it'
'to the expected output given in the comments:')
print('--------------------------------------------------')
print()
print('Test 1 of shape: n=5')
shape(5)
print()
print('Test 2 of shape: n=3')
shape(3)
print()
print('Test 3 of shape: n=9')
shape(9)
def shape(n):
####################################################################
# IMPORTANT: In your final solution for this problem,
# you must NOT use string multiplication.
####################################################################
"""
Prints a shape with numbers on the left side of the shape,
other numbers on the right side of the shape,
and stars in the middle, per the pattern in the examples below.
You do NOT need to deal with any test cases where n > 9.
It looks like this example for n=5:
11111*
2222*1
333*12
44*123
5*1234
And this one for n=3:
111*
22*1
3*12
And this one for n=9:
111111111*
22222222*1
3333333*12
444444*123
55555*1234
6666*12345
777*123456
88*1234567
9*12345678
:type n: int
"""
# ------------------------------------------------------------------
# DONE: 2. Implement and test this function.
# Some tests are already written for you (above).
####################################################################
# IMPORTANT: In your final solution for this problem,
# you must NOT use string multiplication.
####################################################################
for k in range(n):
for j in range(n - k):
print(k + 1, end='')
if k == 0:
print('*')
else:
print('*', end='')
for l in range(k):
if l == (k - 1):
print(l + 1)
else:
print(l + 1, end='')
# ----------------------------------------------------------------------
# Calls main to start the ball rolling.
# ----------------------------------------------------------------------
main()
| true
|
b2e763e72dd93b471294f997d2c18ab041ad665c
|
Evanc123/interview_prep
|
/gainlo/3sum.py
| 1,274
| 4.375
| 4
|
'''
Determine if any 3 integers in an array sum to 0.
For example, for array [4, 3, -1, 2, -2, 10], the function
should return true since 3 + (-1) + (-2) = 0. To make things simple,
each number can be used at most once.
'''
'''
1. Naive Solution is to test every 3 numbers to test if it is zero
2. is it possible to cache sum every two numberse, then see if the rest make zero?
Insight: we need enough "power" in the negative numbers to reduce the positive numbers.
Count up the negative numbers summed to see the maximum negative number.
Possibly create some sort of binary search tree, where all the sums are the roots? No
that wouldn't work.
'''
def sum_2(arr, target):
dict = {}
for i in range(len(arr)):
complement = target - arr[i]
if complement in dict:
return True
dict[arr[i]] = i
return False
def sum_3(arr):
arr.sort()
for i in range(len(arr)):
if sum_2(arr[:i] + arr[i+1:], -arr[i]):
return True
return False
test = [4, 3, -1, 2, -2, 10]
assert sum_3(test) == True
test = [4, -4, 0]
assert sum_3(test) == True
test = [4, -3, -1]
assert sum_3(test) == True
test = [0, 0, 1]
assert sum_3(test) == False
test = [0, 2, -1, -5, 20, 10, -2]
assert sum_3(test) == True
| true
|
5ebd4c91bd2fd1b34fbfdcff3198aef77ceb8612
|
CrazyCoder4Carrot/lintcode
|
/python/Insert Node in a Binary Search Tree.py
| 1,676
| 4.25
| 4
|
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
"""
Revursive version
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param node: insert this node into the binary search tree.
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if not root:
root = node
return root
if root.val > node.val:
if not root.left:
root.left = node
else:
self.insertNode(root.left, node)
return root
else:
if not root.right:
root.right = node
else:
self.insertNode(root.right, node)
return root
"""
Iteration version
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param node: insert this node into the binary search tree.
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if not root:
root = node
return root
cur = root
while cur:
if cur.val > node.val:
if cur.left:
cur = cur.left
else:
cur.left = node
break
else:
if cur.right:
cur = cur.right
else:
cur.right = node
break
return root
"""
Refined iteration version
"""
| true
|
0046fd9fa359ebfaa81b7fb40ecf2c5f6d278273
|
sfagnon/stephane_fagnon_test
|
/QuestionA/QaMethods.py
| 1,120
| 4.21875
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Verify if the two positions provided form a line
def isLineValid(line_X1,line_X2):
answer = True
if(line_X1 == line_X2):
answer = False
print("Points coordinates must be different from each other to form a line")
return answer
#Verify if the two positions provided form respectively the lower bound and the upper bound of #the line
def verifyLineCoordinates(line):
line_X1 = line[0]
line_X2 = line[1]
#Swap the line's bounds
if(line_X1 > line_X2):
temporary_point = line_X1
line_X1 = line_X2
line_X2 = temporary_point
print("Line Coordinates\' bounds have been swapped from X1 = "+str(line_X2)+" and X2 = "+str(line_X1)+ "\n Line is now: ("+str(line_X1)+","+str(line_X2)+")")
line = [line_X1,line_X2]
return line
#Check if a position bound belongs to a line interval (represented by its bounds)
def isValueInInterval(value,lower_bound,upper_bound):
answer = False
if((lower_bound<=value) and (upper_bound>=value)):
answer = True
return answer
| true
|
1916ef020df5cb454e7887d2d4bb051d308887e3
|
sammysun0711/data_structures_fundamental
|
/week1/tree_height/tree_height.py
| 2,341
| 4.15625
| 4
|
# python3
import sys
import threading
# final solution
""" Compute height of a given tree
Height of a (rooted) tree is the maximum depth of a node,
or the maximum distance from a leaf to the root.
"""
class TreeHeight:
def __init__(self, nodes):
self.num = len(nodes)
self.parent = nodes
self.depths = [0] * self.num
def path_len(self, node_id):
""" Returns path length from given node to root."""
parent = self.parent[node_id]
if parent == -1:
return 1
if self.depths[node_id]:
return self.depths[node_id]
self.depths[node_id] = 1 + self.path_len(self.parent[node_id])
return self.depths[node_id]
def compute_height(self):
""" Computes the tree height."""
return max([self.path_len(i) for i in range(self.num)])
'''
# original solution
def compute_height(n, parents):
# Replace this code with a faster implementation
max_height = 0
for vertex in range(n):
height = 0
current = vertex
while current != -1:
height += 1
current = parents[current]
max_height = max(max_height, height)
return max_height
'''
'''
# alternativ solution, explicit build tree and use recursiv compute_height,
# not use cache to store intermediate depth of node,not quick as original solution
def build_tree(root_node, nodes):
children = [
build_tree(child, nodes)
for child, node in enumerate(nodes)
if node == root_node
]
print(children)
return {'key': root_node, 'children':children}
def compute_height(tree):
return 1 + max((compute_height(child) for child in tree['children']), default=-1)
'''
def main():
'''
n = int(input())
parents = list(map(int, input().split()))
print(compute_height(n, parents))
'''
input()
nodes = list(map(int, input().split()))
tree = TreeHeight(nodes)
print(tree.compute_height())
# In Python, the default limit on recursion depth is rather low,
# so raise it here for this problem. Note that to take advantage
# of bigger stack, we have to launch the computation in a new thread.
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start()
| true
|
7cafa9fc6b348af6d2f11ad8771c5cca59b1bea7
|
irina-baeva/algorithms-with-python
|
/data-structure/stack.py
| 1,702
| 4.15625
| 4
|
'''Imlementing stack based on linked list'''
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def insert_first(self, new_element):
"Insert new element as the head of the LinkedList"
new_element.next = self.head
self.head = new_element
def delete_first(self):
"Delete the first (head) element in the LinkedList as return it"
if self.head:
deleted_element = self.head
temp = deleted_element.next
self.head = temp
return deleted_element
else:
return None
class Stack(object):
def __init__(self,top=None):
self.ll = LinkedList(top)
def push(self, new_element):
"Push (add) a new element onto the top of the stack"
self.ll.insert_first(new_element)
def pop(self):
"Pop (remove) the first element off the top of the stack and return it"
return self.ll.delete_first()
# Test cases
# Set up some Elements
e1 = Element(5)
e2 = Element(20)
e3 = Element(30)
e4 = Element(40)
# Start setting up a Stack
stack = Stack(e1)
# Test stack functionality
stack.push(e2)
stack.push(e3)
print(stack.pop().value) #30
print (stack.pop().value) #20
print (stack.pop().value) # 5
print (stack.pop())
stack.push(e4)
print (stack.pop().value)
| true
|
01ece2001beaf028b52be310a8f1df24858f4e59
|
amitesh1201/Python_30Days
|
/OldPrgms/Day3_prc05.py
| 579
| 4.375
| 4
|
# Basic String Processing : four important options: lower, upper, capitalize, and title.
# In order to use these methods, we just need to use the dot notation again, just like with format.
print("Hello, World!".lower()) # "hello, world!"
print("Hello, World!".upper()) # "HELLO, WORLD!"
print("Hello, World!".capitalize()) # "Hello, world!"
print("Hello, World!".title()) # "Hello, World!"
# Use the strip method remto remove white space from the ends of a string
print(" Hello, World! ".strip()) # "Hello, World!"
| true
|
f6c183fb7de25707619a330224cdfa841a8b44be
|
maryliateixeira/pyModulo01
|
/desafio005.py
| 229
| 4.15625
| 4
|
# Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e antecessor
n= int(input('Digite um número:'))
print('Analisando o número {}, o seu antecessor é {} e o sucessor {}' .format(n, (n-1), (n+1)))
| false
|
b9151241f8234f5c1f038c733a5d0ff46da376d3
|
louishuynh/patterns
|
/observer/observer3.py
| 2,260
| 4.15625
| 4
|
"""
Source: https://www.youtube.com/watch?v=87MNuBgeg34
We can have observable that can notify one group of subscribers for one kind of situation.
Notify a different group of subscribers for different kind of situation.
We can have the same subscribers in both groups.
We call these situations events (different kinds of situations) or channels.
This gives us the flexibility of how we notify subscribers.
"""
class Subscriber:
""" Sample observer. """
def __init__(self, name):
self.name = name
def update(self, message):
print('{} got message "{}"'.format(self.name, message))
class Publisher:
def __init__(self, events):
"""
We want to provide interface that allows subscribers to register for a specific event that the observable can announce.
So we modify a publisher to take several events and modify the subscriber attribute to
map event names to strings to dictionaries that then map subscribers to their callback function
"""
self.subscribers = {event: dict() for event in events}
def get_subscribers(self, event):
""" Helper method.
Look up for a given even the map of subscriber to the callback function.
"""
return self.subscribers[event]
def register(self, event, who, callback=None):
""" Change the way we insert the subscriber to our records of the callback."""
if callback is None:
# fallback to original method
callback = getattr(who, 'update')
self.get_subscribers(event)[who] = callback
def unregister(self, event, who):
del self.get_subscribers(event)[who]
def dispatch(self, event, message):
""" We keep the api interface fairly similar."""
for subscriber, callback in self.get_subscribers(event).items():
callback(message)
if __name__ == '__main__':
pub = Publisher(['lunch', 'dinner'])
bob = Subscriber('Bob')
alice = Subscriber('Alice')
john = Subscriber('John')
pub.register("lunch", bob)
pub.register("dinner", alice)
pub.register("lunch", john)
pub.register("dinner", john)
pub.dispatch("lunch", "It's lunchtime!")
pub.dispatch("dinner", "Dinner is served")
| true
|
e2ef440e9f140b93cb1adc8bf478baf2beae8fa3
|
timmichanga13/python
|
/fundamentals/oop/demo/oop_notes.py
| 1,389
| 4.25
| 4
|
# Encapsulation is the idea that an instance of the class is responsible for its own data
# I have a bank account, teller verifies account info, makes withdrawal from acct
# I can't just reach over and take money from the drawer
# Inheritance allows us to pass attributes and methods from parents to children
# Vehicles are a class that can carry cargo and passengers
# we wouldn't create vehicles, but we would create classes that inherit from our vehicle class:
# wheeled vehicles with wheels, aquatic vehicle that floats, winged vehicle that flies, living vehicles like a horse
# all require fuel, but it's different for each subclass
# multiple inheritance - a class can inherit from multiple classes
# Polymorphism - many forms, classes that are similar can behave similarly
# can have x = 34, y = 'hello!', z = {'key_a': 2883, 'key_b': 'a word!'}
# can find the length of each; len(x), len(y), len(z)
# each gives us a length, but differs based on the type of info (number of items, number of letters)
# Abstraction: an extension of encapsulation, we can hide things that a class doesn't need to know about
# a class can use methods of another class without needing to know how they work
# we can drive a car, fill tank with gas, might not be able to change oil but can take it somewhere to get oil changed
# can't make a car out of raw materials, but still know how to drive it
| true
|
95eaa4c8b527c0ac22bbd95dcfc30dad1fc836ad
|
notwhale/devops-school-3
|
/Python/Homework/hw09/problem6.py
| 973
| 4.1875
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Решить несколько задач из projecteuler.net
Решения должны быть максимально лаконичными, и использовать list comprehensions.
problem6 - list comprehension : one line
problem9 - list comprehension : one line
problem40 - list comprehension
problem48 - list comprehension : one line
Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
print(sum([_ for _ in range(1, 101)]) ** 2 - sum(map(lambda x: x**2, [_ for _ in range(1, 101)])))
| true
|
97d12c33b2d142eaf238ae867bf6324c08a02bf9
|
lanvce/learn-Python-the-hard-way
|
/ex32.py
| 1,033
| 4.46875
| 4
|
the_count=[1,2,3,4,5]
fruits=['apples','oranges','pears','apricots']
change=[1,'pennies',2,'dimes',3,'quarters']
#this fruit kind of fora-loop goes through a list
for number in the_count:
print(f"this is count {number}")
#same as above
for fruit in fruits:
print(f"A fruit of type :{fruit}")
#also we can go through mixed lists too
#noticed we have to use {} since we don't know what's in it
for i in change:
print(f"I go {i}")
#we can built lists,first start with an emoty one
elements=[]
#then use the range function to da 0 to 5 counts
for i in range(0,6):
print(f"Adding {i} to the list.")
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in range(1,100,10):
print(f"they are {i}")
elements.append(i)
elements.append('kugou')
elements.append('wangyiyun')
del elements[10]
print (elements)
print(len(elements))
#for i in elements:
# print(f"Elements was :{i}")
print(elements.count(1))
elements.reverse()
print (elements)
| true
|
ce5457678e0742d76a9e7935a257cd1af6e05617
|
RobertElias/PythonProjects
|
/GroceryList/main.py
| 1,980
| 4.375
| 4
|
#Grocery List App
import datetime
#create date time object and store current date/time
time = datetime.datetime.now()
month = str(time.month)
day = str(time.day)
hour = str(time.hour)
minute = str(time.minute)
foods = ["Meat", "Cheese"]
print("Welcome to the Grocery List App.")
print("Current Date and Time: " + month + "/" + day + "\t" + hour + ":" + minute)
print("You currently have " + foods[0] + " and " + foods[1] + " in your list.")
#Get user input
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
food = input("\nType of food to add to grocery list: ")
foods.append(food.title())
#Print and sort the list
print("Here is your grocery list: ")
print(foods)
foods.sort()
print("Here is you grocery list sorted: ")
print(foods)
#Shopping for your list
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
print("\nSimulating Grocery Shopping...")
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
buy_food = input("What food did you just buy: ").title()
foods.remove(buy_food)
print("Removing " + buy_food + " from the list...")
#The store is out of this item
print("\nCurrent grocery list: " + str(len(foods)) + " items")
print(foods)
no_item = foods.pop()
print("\nSorry, the store is out of " + no_item + ".")
new_food = input("What food would you like instead: ").title()
food.insert(0,new_food)
print("\nHere is what remains on your grocery list: ")
print(foods)
#New food
| true
|
dae536759b45c9c3db4f98695e57aa4aeb51c88d
|
RobertElias/PythonProjects
|
/Multiplication_Exponentiation_App/main.py
| 1,673
| 4.15625
| 4
|
print("Welcome to the multiplication/exponentiation table app.")
print("What number would you like to work with?")
# Gather user input
name = input("\nHello, what is your name: ").title().strip()
num = float(input("What number would you like to work with: "))
message = name + ", Math is really cool!!!"
# Multiplication Table
print("\nMultiplication Table for " + str(num))
print("\n\t 1.0 * " + str(num) + " = " + str(round(1*num, 4)))
print("\t 2.0 * " + str(num) + " = " + str(round(2*num, 4)))
print("\t 3.0 * " + str(num) + " = " + str(round(3*num, 4)))
print("\t 4.0 * " + str(num) + " = " + str(round(4*num, 4)))
print("\t 5.0 * " + str(num) + " = " + str(round(5*num, 4)))
print("\t 6.0 * " + str(num) + " = " + str(round(6*num, 4)))
print("\t 7.0 * " + str(num) + " = " + str(round(7*num, 4)))
print("\t 8.0 * " + str(num) + " = " + str(round(8*num, 4)))
print("\t 9.0 * " + str(num) + " = " + str(round(9*num, 4)))
#Exponent Table
print("\nExponent Table for " + str(num))
print("\n\t " + str(num) + " ** 1 = " + str(round(num**1,4)))
print("\t " + str(num) + " ** 2 = " + str(round(num**2, 4)))
print("\t " + str(num) + " ** 3 = " + str(round(num**3, 4)))
print("\t " + str(num) + " ** 4 = " + str(round(num**4, 4)))
print("\t " + str(num) + " ** 5 = " + str(round(num**5, 4)))
print("\t " + str(num) + " ** 6 = " + str(round(num**6, 4)))
print("\t " + str(num) + " ** 7 = " + str(round(num**7, 4)))
print("\t " + str(num) + " ** 8 = " + str(round(num**8, 4)))
print("\t " + str(num) + " ** 9 = " + str(round(num**9, 4)))
#Math is cool
print("\n" + message)
print("\t" + message.lower())
print("\t\t" + message.title())
print("\t\t\t" + message.upper())
| false
|
0cf8bac0a47bb1156eaaff40503bc1cdcadb50a1
|
RobertElias/PythonProjects
|
/Arrays/main_1.py
| 309
| 4.375
| 4
|
#Write a Python program to create an array of 5 integers and display the array items.
from array import *
array_num = array('i', [1,3,5,7,9])
for i in array_num:
print("Loop through the array.",i)
print("Access first three items individually")
print(array_num[0])
print(array_num[1])
print(array_num[2])
| true
|
83fb395b9fc573098d6fe9f258391a4eef07f0e9
|
RobertElias/PythonProjects
|
/Favorite_Teacher/main.py
| 2,539
| 4.46875
| 4
|
print("Welcome to the Favorite Teachers Program")
fav_teachers = []
#Get user input
fav_teachers.append(input("Who is your first favorite teacher: ").title())
fav_teachers.append(input("Who is your second favorite teacher: ").title())
fav_teachers.append(input("Who is your third favorite teacher: ").title())
fav_teachers.append(input("Who is your fourth favorite teacher: ").title())
#Summary of list
print("\nYour favorite teachers ranked are: " + str(fav_teachers))
print("You favorite teachers alphabetically are: " + str(sorted(fav_teachers)))
print("You favorite teachers in reverse are: " + str(sorted(fav_teachers, reverse=True)))
print("\nYour top Two favorite teachers are: " + fav_teachers[0] + " and " + fav_teachers[1] + ".")
print("Your next two favorite teachers are: " + fav_teachers[2] + " and " + fav_teachers[3] + ".")
print("Your last favorite teachers is: " + fav_teachers[-1])
print("You have a total of: " + str(len(fav_teachers)) + " favorite teachers.")
#Insert a new favorite teacher
fav_teachers.insert(0, input("\nOops, " + fav_teachers[0] + " is no longer you first favorite teacher. Who is your new Favorite Teacher: ").title())
#Summary of list
print("\nYour favorite teachers ranked are: " + str(fav_teachers))
print("You favorite teachers alphabetically are: " + str(sorted(fav_teachers)))
print("You favorite teachers in reverse are: " +
str(sorted(fav_teachers, reverse=True)))
print("\nYour top Two favorite teachers are: " +
fav_teachers[0] + " and " + fav_teachers[1] + ".")
print("Your next two favorite teachers are: " +
fav_teachers[2] + " and " + fav_teachers[3] + ".")
print("Your last favorite teachers is: " + fav_teachers[-1])
print("You have a total of: " + str(len(fav_teachers)) + " favorite teachers.")
#Remove a specific teacher
fav_teachers.remove(input("\nYou decide you no longer like a teacher. Who do we remove form the list: ").title())
#Summary of list
print("\nYour favorite teachers ranked are: " + str(fav_teachers))
print("You favorite teachers alphabetically are: " + str(sorted(fav_teachers)))
print("You favorite teachers in reverse are: " +
str(sorted(fav_teachers, reverse=True)))
print("\nYour top Two favorite teachers are: " +
fav_teachers[0] + " and " + fav_teachers[1] + ".")
print("Your next two favorite teachers are: " +
fav_teachers[2] + " and " + fav_teachers[3] + ".")
print("Your last favorite teachers is: " + fav_teachers[-1])
print("You have a total of: " + str(len(fav_teachers)) + " favorite teachers.")
| false
|
2dae568f69ab9c93d43fb38f7f5a776844bb5e3e
|
Isco170/Python_tutorial
|
/Lists/listComprehension.py
| 723
| 4.84375
| 5
|
# List Comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
# Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name
# Without list comprehension
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newList = []
# for x in fruits:
# if "a" in x:
# newList.append(x)
# print(newList)
# With list comprehension
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newList = [ x for x in fruits if "a" in x]
# Only accept items that are not "apple"
# newList = [x.upper() for x in fruits if x != "apple"]
newList = ['Hello' for x in fruits if x != "apple"]
print(newList)
| true
|
a315863eeb4b603354fc7f681e053554a35582fc
|
IonutPopovici1992/Python
|
/LearnPython/if_statements.py
| 276
| 4.25
| 4
|
is_male = True
is_tall = True
if is_male and is_tall:
print("You are a tall male.")
elif is_male and not(is_tall):
print("You are a short male.")
elif not(is_male) and is_tall:
print("You are not a male, but you are tall.")
else:
print("You are not a male.")
| true
|
3f4261421609d3248060d7b9d12de47ad8bac76d
|
becomeuseless/WeUseless
|
/204_Count_Primes.py
| 2,069
| 4.125
| 4
|
'''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
#attemp 1: for every number smaller than n+1, check if it is a prime. To check if a number p is a prime, see if it #divisible by the numbers smaller than p.
#Time Complexity : O(n**2)
#Space Complexity : O(1)
'''
cnt = 0
for i in range(1,n):
if self.isPrime(i):
cnt += 1
return cnt
def isPrime(self, x):
if x == 1:
return False
for i in range(2,x):
if x%i == 0:
return False
return True
'''
#attemp 2:To check if a number is p is a prime, we dont need to divide it by all the numbers smaller than p. Actually only
#the numbers smaller than p**1/2 would be enough.
#Time Complexity : O(n**1.5)
#Space Complexity : O(1)
'''
cnt = 0
for i in range(1,n):
if self.isPrime(i):
cnt += 1
return cnt
def isPrime(self, x):
if x == 1:
return False
i = 2
while i <= x**0.5:
if x%i == 0:
return False
i += 1
return True
'''
#attemp 3:When check if a number is a prime number, we will know for sure the multiples of the number are not prime numbers.
#Thus we dont need to check the multiples.
#Time Complexity : O(loglogn)
#Space Complexity : O(n)
if n < 3:
return 0
isPrime = [True]*n
isPrime[0] = isPrime[1] = False
for i in range(int(n**0.5) + 1):
if not isPrime[i]:
continue
j = i*i
while j< n:
isPrime[j] = False
j += i
return sum(isPrime)
| true
|
77665880cde79a8f833fb1a3f8dfe9c88368d970
|
codexnubes/Coding_Dojo
|
/api_ajax/OOP/bike/bikechain.py
| 1,120
| 4.25
| 4
|
class Bike(object):
def __init__(self,price,max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayinfo(self):
print "Here are your bike stats:\n\
Price: ${}\n\
Max Speed: {}\n\
Miles Rode: {}".format(self.price, self.max_speed, self.miles)
def ride(self):
self.miles += 10
print "Riding..."
return self
def reverse(self):
if self.miles >= 5:
self.miles -= 5
print "Reversing..."
else:
print "Can't reverse!"
return self
bike1 = Bike(200, "10mph")
bike2 = Bike(1000, "50mph")
bike3 = Bike(500, "38mph")
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
for i in range(0,3):
bike1.ride().ride().ride().reverse()
bike2.ride().reverse().reverse().reverse()
bike3.reverse().ride().reverse()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
for i in range(0,2):
bike1.reverse()
bike2.ride()
bike3.ride()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
| true
|
256f3e7cfe573c0bed1c8e5e62c6df1226d9cc79
|
AlenaGB/hw
|
/5.py
| 465
| 4.125
| 4
|
gain = float(input("What is the revenue this month? $"))
costs = float(input("What is the monthly expenses? $"))
if gain == costs:
print ("Not bad. No losses this month")
elif gain < costs:
print("It's time to think seriosly about cutting costs")
else:
print("Great! This month you have a profit")
staff = int(input("How many employees do you have?"))
profit = (gain - costs)/staff
print ("Your profit is ${:.2f} per person".format(profit))
| true
|
c619f9cd9cef317f81eab2637a5b454ef9c745e5
|
TwiggyTwixter/Udemy-Project
|
/test.py
| 309
| 4.15625
| 4
|
print("This program calculates the average of two numbers")
firstNumber = float (input({"What will the first number be:"}))
secondNumber = float (input({"What will the second number be:"}))
print("The numbers are",firstNumber, "and",secondNumber)
print("The average is: ", (firstNumber + secondNumber )/ 2)
| true
|
37899a51d576727fdbde970880245b40e7e5b7b4
|
dusanvojnovic/tic-tac-toe
|
/tic_tac_toe.py
| 2,430
| 4.125
| 4
|
import os
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
def print_board(board):
print(board[7] + ' |' + board[8] + ' |' + board[9])
print("--------")
print(board[4] + ' |' + board[5] + ' |' + board[6])
print("--------")
print(board[1] + ' |' + board[2] + ' |' + board[3])
def game():
play = "X"
count = 0
global board
for i in range(10):
os.system('cls')
print ("Welcome to the TicTacToe! Use your num keypad(1-9) to play.")
print_board(board)
choice = input(f"Player {play} it's your turn to play: ")
move = int(choice)
if board[move] != " ":
print("That field is not empty, please try again.")
continue
else:
board[move] = play
count += 1
if count >= 5:
# checking rows
if board[7] == board[8] == board[9] == play or \
board[4] == board[5] == board[6] == play or \
board[1] == board[2] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
# checking columns
elif board[7] == board[4] == board[1] == play or \
board[8] == board[5] == board[2] == play or \
board[9] == board[6] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
# checking diagonals
elif board[1] == board[5] == board[9] == play or \
board[7] == board[5] == board[3] == play:
os.system('cls')
print_board(board)
print (f"GAME OVER! The winner is {play} player!")
break
if count == 9:
os.system('cls')
print_board(board)
print ("GAME OVER! It's tied!")
break
if play == "X":
play = "O"
else:
play = "X"
if input("Do you want to play again? (Y)es or (N)o: ").upper() == "Y":
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
os.system('cls')
game()
else:
os.system('cls')
print("Goodbye")
game()
| true
|
f4247987858702440a4739dc84674cec373d9384
|
league-python-student/level0-module1-dencee
|
/_02_variables_practice/circle_area_calculator.py
| 1,345
| 4.53125
| 5
|
import turtle
from tkinter import messagebox, simpledialog, Tk
import math
import turtle
# Goal: Write a Python program that asks the user for the radius
# of a circle and displays the area of that circle.
# The formula for the area of a circle is πr^2.
# See example image in package to check your output.
if __name__ == '__main__':
window = Tk()
window.withdraw()
# Ask the user for the radius in pixels and store it in a variable
# simpledialog.askinteger()
num = simpledialog.askinteger("Enter a radius",None)
# Make a new turtle
Shivam = turtle.Turtle()
# Have your turtle draw a circle with the correct radius
# my_turtle.circle()
Shivam.circle(num)
# Call the turtle .penup() method
Shivam.penup()
# Move your turtle to a new x,y position using .goto()
Shivam.goto(100,80)
# Calculate the area of your circle and store it in a variable
# Hint, you can use math.pi
arnum = math.pi*num*num
# Write the area of your circle using the turtle .write() method
# my_turtle.write(arg="area = " + str(area), move=True, align='left', font=('Arial',8,'normal'))
Shivam.write(arg="area = " + str(arnum), move=True, align='left', font=('Arial',8,'normal'))
# Hide your turtle
Shivam.hideturtle()
# Call turtle.done()
turtle.done()
| true
|
6d63273b82815d33226d51ddf224e22434bbaded
|
WalterVives/Project_Euler
|
/4_largest_palindrome_product.py
| 975
| 4.15625
| 4
|
"""
From: projecteuler.net
Problem ID: 4
Author: Walter Vives
GitHub: https://github.com/WalterVives
Problem:
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
part1 = []
part2 = []
result = 0
for i in range(100,1000):
for j in range(100,1000):
multiplication = i * j
multiplication = list(str(multiplication))
if len(multiplication) == 6:
part1 = multiplication[0], multiplication[1], multiplication[2]
part2 = multiplication[3], multiplication[4], multiplication[5]
# Palindrome
if part1[::-1] == part2:
# List of numbers to int number
num = int("".join(multiplication))
# Add the largest palindrome product
if num > result:
# result
result = num
# Number 1
x = i
# Number 2
y = j
#print(i, "*", j, "=", result)
print(x, "*", y, "=", result)
| true
|
74914ed8c197d826a7c557c8a1fcd3c8e3c805aa
|
aryanirani6/ICS4U-Classwork
|
/example.py
| 866
| 4.5625
| 5
|
"""
create a text file with word on a number of lines
1. open the text file and print out 'f.read()'. What does it look like?
2. use a for loop to print out each line individually. 'for line in f:'
3. print our words only with "m", or some other specific letter.
"""
# with open("Some_file.txt", 'r') as f:
# print(f.read())
#2
#with open("Some_file.txt", 'r') as f:
# for line in f:
# print(line)
#3 to print the line it will give skip another line for each word
#4 with open("Some_file.txt", 'r') as f:
# for line in f:
# print(line.strip())
#4 print words only with m
#with open("Some_file.txt", 'r') as f:
# for line in f:
# if line.startswith("m"):
# print(line.strip())
#5 to check for both upper case and lower case letter
#with open("Some_file.txt", 'r') as f:
# for line in f:
# if line.lower().startswith("m"):
# print(line.strip())
| true
|
6798074572ee5e82a5da113a6ace75b4670ae00c
|
aryanirani6/ICS4U-Classwork
|
/classes/classes2.py
| 2,179
| 4.375
| 4
|
"""
name: str
cost: int
nutrition: int
"""
class Food:
""" Food class
Attributes:
name (str): name of food
cost (int): cost of food
nutrition (int): how nutritious it is
"""
def __init__(self, name: str, cost: int, nutrition: int):
""" Create a Food object.
Args:
name: name of food
cost: cost of food
nutrition: how nutritious it is
"""
self.name = name
self.cost = cost
self.nutrition = nutrition
class Dog:
""" Thing that goes ruff
Attributes:
breed (str): The dog's breed
name (str): The dog's name
happiness (int): The dog's happiness. Defualts to 100
"""
def __init__(self, breed: str, name: str):
""" Create a dog object.
Args:
breed: The breed of the dog
name: name of the dog.
"""
self.breed = breed
self.name = name
self.happiness = 100
def __str__(self):
return f"{self.happiness}, {self.name}"
def eat(self, food: Food):
""" Gets the dog to eat food.
increases dogs happiness by 10% of food eaten
Args:
food: The food for dog to eat.
"""
happiness_increase = food.nutrition * 0.1
self.happiness += happiness_increase
def bark(self):
""" Make the dog bark
"""
print("Ruff Ruff")
sausage = Food("Polish Sausage", 10, 100)
james = Dog("Husky", "James")
print(james)
print(james.happiness)
james.eat(sausage)
print(james.happiness)
james.bark()
"""if __name__ == "__main__":
main()
"""
""" Encapsulation
Basic definition: protecting your object's attributes.
"""
class Student:
def __init__(self, name: str, age: int):
self.name = name
self._age = age
def set_age(self, age: int):
if type(age) != int:
raise ValueError("Age must be an integer")
self._age = age
def age_in_5_years(self):
return self._age + 5
def get_age(self):
return self._age
s = Student("Sally", 15)
print(s.age_in_5_years())
print(s.get_age())
| true
|
7416e1c946d17374332e7e4ebabb09eb159aaa97
|
GribaHub/Python
|
/exercise15.py
| 967
| 4.5
| 4
|
# https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
# clear shell
def cls():
print(50 * "\n")
# backwards order (loop)
def backwards(text):
result=text.split(" ")
lnth=len(result)
j=range(lnth)
text=[]
for i in j:
text.append(result[lnth-i-1])
result=[]
result=" ".join(text)
return(result)
# backwards order (reverse)
def backwards2(text):
result=text.split(" ")
result.reverse()
result=" ".join(result)
return(result)
# main program
cls()
print("Words in backwards order:",backwards(input("Enter a string containing multiple words: ")))
print()
print("Words in backwards order:",backwards2(input("Enter a string containing multiple words: ")))
| true
|
dca9c5f3548711b16c7736adc0588fff766c95a1
|
kirubakaran28/Python-codes
|
/valid palindrome.py
| 359
| 4.15625
| 4
|
import re
def isPalindrome(s):
s = s.lower()
#removes anything that is not a alphabet or number
s = re.sub('[^a-z0-9]','',s)
#checks for palindrome
if s == s[::-1]:
return True
else:
return False
s = str(input("Enter the string: "))
print(isPalindrome(s))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.