blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b665de980d5eabb27854c138cd7fa2d17f822d28 | DDParkas/Lista-de-exercicios-Python | /1-Estrutura-sequencial/7.py | 287 | 4.1875 | 4 | # Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
altura = float(input('Digite a altura do quadrado: '))
largura = float(input('Digite a largura do quadrado: '))
area = altura * largura
print('O dobro da area e:', area * 2) | false |
e8afbd7e8a2193301fedc822c2d5bb84665cefc5 | iagsav/AS | /T2/Gornushenkova/2.2p.py | 354 | 4.25 | 4 | def arithmetic(a,b,c):
if (c=='+') | (c=='-') | (c=='/') | (c=='*'):
case={
'+': a+b,'-': a-b,'*': a*b,'/': a/b,
}
print(case[c])
else:
print("Unknown operation")
a = int(input("Enter firs num"))
b = int(input("Enter second num"))
c = input("Choose operation: +,-,/,*")
arithmetic(a,b,c)
| false |
adf22dafd8c29cb0c905ca70612396c5a6518598 | wmillar/ProjectEuler | /102.py | 1,564 | 4.125 | 4 | '''
Three distinct points are plotted at random on a Cartesian plane, for which
-1000 <= x, y <= 1000, such that a triangle is formed.
Consider the following two triangles:
A(-340,495), B(-153,-910), C(835,-947)
X(-175,41), Y(-421,-714), Z(574,-645)
It can be verified that triangle ABC contains the origin, whereas triangle
XYZ does not.
Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text
file containing the co-ordinates of one thousand "random" triangles, find the
number of triangles for which the interior contains the origin.
NOTE: The first two examples in the file represent the triangles in the
example given above.
'''
def getPoints():
points = []
f = file('triangles.txt', 'r')
for line in [map(int, line.split(',')) for line in f.readlines()]:
points.append(map(lambda i: tuple(line[i:i + 2]), range(0, 6, 2)))
return points
def getB(p1, p2):
return p1[1] - float(p2[1] - p1[1]) / (p2[0] - p1[0]) * p1[0]
def getSides(points):
sideDict = {'L':[], 'R':[]}
for p in points:
if p[0] < 0:
sideDict['L'].append(p)
else:
sideDict['R'].append(p)
return sorted(sideDict.values(), key=lambda x: len(x))
def opposites(L):
return L[0] > 0 and L[1] < 0 or L[1] > 0 and L[0] < 0
def containsOrigin(points):
vertex, points = getSides(points)
if not vertex:
return 0
b = [getB(vertex[0], p) for p in points]
if opposites(b) or 0 in b:
return 1
return 0
print sum(map(containsOrigin, getPoints()))
| true |
ce769b84943a8b819c1447d90ed02e1e8232e3f6 | wmillar/ProjectEuler | /001.py | 425 | 4.28125 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
def arithSum(n):
return n * (n + 1) / 2
def arithSumMult(m, n):
return arithSum(n // m) * m
def multSum(a, b, n):
return arithSumMult(a, n) + arithSumMult(b, n) - arithSumMult(a * b, n)
print multSum(3, 5, 999)
| false |
cb2a8bcaf5a1d5984fbd72e94c1efb91f0795f58 | Karthikzee/Python | /rps1.py | 911 | 4.25 | 4 | #rock paper scissors game
#calling random module for choosing a string from tuple using .choice function
import random
a = ["rock", "papers", "scissors"]
u = "you win"
l = "you lose"
#loop to play again and again
while True:
#player will type in their desired option
p = input("enter rock or papers or scissors")
#contional statement to quit
if p == "q":
print("thanks for playing")
quit()
#computer will choose in random
com = random.choice(a)
print("you chose", p, "computer chose", com)
#comparing player and compter options and displaying who wins
if p == com:
print("its a tie")
elif p == "rock" and com == "scissors":
print(u)
elif p == "papers" and com == "rock":
print(u)
elif p == "scissors" and com == "papers":
print(u)
elif p == "scissors" and com == "rock":
print(l)
elif p == "rock" and com == "papers":
print(l)
elif p == "papers" and com == "scissors":
print(l) | true |
98b63efbb9d96162c9dc7aa734037acfd71fe25b | Karthikzee/Python | /rpscore.py | 1,163 | 4.25 | 4 | #rock paper scissors game
#calling random module for choosing a string from tuple using .choice function
import random
a = ["rock", "papers", "scissors"]
w = "you win"
l = "you lose"
u = 0
c = 0
count = 0
#loop to play again and again
while count < 6:
#player will type in their desired option
p = input("enter rock or papers or scissors")
#contional statement to quit
if p == "q":
print("thanks for playing")
quit()
#computer will choose in random
com = random.choice(a)
print("you chose", p, "computer chose", com)
#comparing player and compter options and displaying who wins
if p == com:
print("its a tie")
elif p == "rock" and com == "scissors":
print(w)
u = u+1
elif p == "papers" and com == "rock":
print(w)
u = u+1
elif p == "scissors" and com == "papers":
print(w)
u = u+1
elif p == "scissors" and com == "rock":
print(l)
c = c+1
elif p == "rock" and com == "papers":
print(l)
c = c+1
elif p == "papers" and com == "scissors":
print(l)
c = c+1
print ("Your score ", u, "computers score is", c)
count = count + 1
if count == 6:
if u > c:
print("You win the game")
else:
print("Computer wins the game") | true |
16713082a338687c2a0d888b19a79c2dc2bf0f40 | charlieob/code | /python/samples/closure/closure1.py | 436 | 4.21875 | 4 | #
# See http://stackoverflow.com/questions/36636/what-is-a-closure
#
# Example showing three different variable scopes available in the closure:
# (1) parameter of function that creates the closure (a)
# (2) local variable of the creating function
# (3) parameter of the closure function when it is called
#
def outer(a):
b = 'variable in outer()'
def inner(c):
print a,b,c
return inner
f = outer('test')
f(1)
| true |
e726ecf4f92b4c0f6419e029b6e1d740c56179e6 | charlieob/code | /python/samples/iterators.py | 853 | 4.4375 | 4 | '''
Some sample code to understand how iterators work.
Invoking an iterator only works once - when it gets
to the end it raises the StopIteration exception and
just keeps doing that.
'''
it = iter([1,2,3,4])
print list(it)
print list(it) # empty because the iterator has already been used/exhausted
it = iter(range(10,14))
print it
li = list(it)
print li
print li # not exhausted because li is not an iterator
for i in li: print i,
print
print str(li) # that is really just a string it's printed
it = iter(range(20,24))
print it.next()
print it.next()
print it.next()
print it.next()
#print it.next() # that would cause an exception and script exit
it = iter(range(30,34))
while 1:
try:
print it.next()
except:
print 'oops, one too many'
break
print list(it)
print it.next() # this will fail and exit
| true |
41778696bcf05ebc7747184c1f1066eccf0931d4 | BerkanR/Programacion | /Codewars/Extract the message.py | 1,517 | 4.125 | 4 | # The local transport authority is organizing an online picture contest. Participants must take pictures of transport
# means in an original way, and then post the picture on Instagram using a specific hashtag.
# The local transport authority needs your help. They want you to take out the hashtag from the posted message. Your
# task is to implement the function
# def omit_hashtag(message, hashtag):
# Examples
# * ("Sunny day! #lta #vvv", "#lta") -> "Sunny day! #vvv" (notice the double space)
# * ("#lta #picture_contest", "#lta") -> " #picture_contest"
# Notes
# When multiple occurences of the hashtag are found, delete only the first one.
# In C, you should modify the message, as the function returns a void type. In Python, you should return the answer.
# There can be erroneous messages where the hashtag isn't present. The message should in this case stay untouched.
# The hashtag only consists of alphanumeric characters.
def omit_hashtag(message, hashtag):
if hashtag in message:
return (message.replace(hashtag, "", 1))
else:
return message
assert (omit_hashtag("Sunny day! #lta #vvv", "#lta")) == "Sunny day! #vvv", "Extracto erróneo"
assert (omit_hashtag("#lta #picture_contest", "#lta")) == " #picture_contest", "Extracto erróneo"
assert (omit_hashtag("#lta #picture_contest #lta", "#lta")) == " #picture_contest #lta", "Extracto erróneo"
assert (omit_hashtag("Hello #world", "#jeff")) == "Hello #world", "Debería funcionar si el hashtag no está en el mensaje" | true |
6f708eebb648554cbf32dad52a8be58d3cbefa3b | BerkanR/Programacion | /Codewars/Remove the minimum.py | 1,473 | 4.4375 | 4 | # The museum of incredible dull things
# The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up
# with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest
# rating.
# However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a
# program that tells her the ratings of the items after one removed the lowest one. Fair enough.
# Task
# Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple
# elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty
# array/list.
# Don't change the order of the elements that are left.
# Examples
# remove_smallest([1,2,3,4,5]) = [2,3,4,5]
# remove_smallest([5,3,2,1,4]) = [5,3,2,4]
# remove_smallest([2,2,1,2,1]) = [2,2,2,1]
def remove_smallest(numbers):
if numbers == []:
return []
else:
numbers.remove(min(numbers))
return numbers
assert (remove_smallest([])) == [], "Resultado incorrecto para []"
assert (remove_smallest([1, 2, 3, 4, 5])) == [2, 3, 4, 5], "Resultado incorrecto para [1, 2, 3, 4, 5]"
assert (remove_smallest([5, 3, 2, 1, 4])) == [5, 3, 2, 4], "Resultado incorrecto para [5, 3, 2, 1, 4]"
assert (remove_smallest([1, 2, 3, 1, 1])) == [2, 3, 1, 1], "Resultado incorrecto para [1, 2, 3, 1, 1]" | true |
92c6895428dbc011cde7261831ed656e5979a58b | UniqueDavid/Python | /day5/demo-class.py | 566 | 4.25 | 4 | #python的类和实例
#类是抽象的模板,实例是具体的对象
class Student(object):
pass
bart=Student()
#给类赋一个值
bart.name='Bart Simpson'
print(bart.name)
#可以把一些必要的属性定义在类里面
class Teacher(object):
#这里的第一参数永远是self,表示创建的实例本身
def __init__(self,name,salary):
self.name=name
self.salary=salary
#可以对于内部的属性进行封装
def print_info(self):
print("name:%s salary:%s"%(self.name,self.salary))
adam=Teacher('Adam Jhson',8500)
print(adam.salary)
adam.print_info() | false |
d2f75d8ce02c67f41b2957de294b2a08ec95530b | manchuran/isPointInRectangle | /isIn2.py | 2,917 | 4.40625 | 4 | def area_of_triangle(first_vertix,second_vertix,third_vertix):
'''
Calculates area of triangle using three vertices
Returns: area of triangle
'''
# Calculate area of triangle from three vertices
x1, y1 = first_vertix[0], first_vertix[1]
x2, y2 = second_vertix[0], second_vertix[1]
x3, y3 = third_vertix[0], third_vertix[1]
return abs(x1*(y2-y3) + x2*(y3-y1)+x3*(y1-y2))/2
def area_of_rectangle(first_vertix,second_vertix):
'''
Calculates area of rectangle using two corner vertices
Returns: area of rectangle
'''
# Calculate area of rectangle from two vertices (parallel to axes)
x1, y1 = first_vertix[0], first_vertix[1]
x2, y2 = second_vertix[0], second_vertix[1]
B = abs(x1 - x2)*abs(y1 - y2)
return B
def isIn2(firstCorner=(0,0), secondCorner=(0,0), point=(0,0)):
'''
Checks if point is in rectangle
Returns: True if point is in rectangle; False otherwise
'''
# Determine if point is inside rectangle
x, y = point[0], point[1]
a1, b1 = firstCorner[0], firstCorner[1]
a3, b3 = secondCorner[0], secondCorner[1]
# Establish four vertices of Rectangle
a2, b2 = a1, b3
a4, b4 = a3, b1
# Treats edge case. Establish if rectangle is a line and point is outside of this line
if b1==b3:
if b1==b3==y:
if (a1<=x<=a3) or (a1>=x>=a3):
return True
else:
return False
else:
return False
elif a1==a3:
if a1==a3==x:
if (b1<=y<=b3) or (b1>=y>=b3):
return True
else:
return False
else:
return False
# Calculate area of individual triangles
A1 = area_of_triangle((a4,b4),(a1,b1),(x,y))
A2 = area_of_triangle((a1,b1),(a2,b2),(x,y))
A3 = area_of_triangle((a2,b2),(a3,b3),(x,y))
A4 = area_of_triangle((a3,b3),(a4,b4),(x,y))
area_of_4_triangles = abs(A1 + A2 + A3 + A4)
area_rectangle = area_of_rectangle(firstCorner, secondCorner)
if area_of_4_triangles == area_rectangle:
return True
return False
def header():
print('-'*20+'-'*12*3)
print('{:^20}|{:^12}|{:^12}|{:^12}'.format('rectangle','point','calculated','given'))
print('-'*20+'-'*12*3)
if __name__ == '__main__':
list_of_points = [[(1,2), (3,4), (1.5, 3.2), 'True'], [(4,3.5), (2,1), (3, 2), 'True'],
[(-1,0), (5,5), (6,0), 'False'], [(4,1), (2,4), (2.5,4.5), 'False'],
[(1,2), (3,4), (2,2), 'True'], [(4,5), (1,1.5), (4.1,4.1), 'False'], [(2,2),(4,3),(3,3), 'True'],
[(2,1),(-3,3),(1,1), 'True']]
header()
for item in list_of_points:
args = item[:3]
print('{:<20}{:^14}{:^14}{:^9}'.format(str(item[:2]),
str(item[2]),str(isIn2(*args)), item[3]))
| true |
be89dbb3cffe9f2fbbd2ab458763cce07d95b089 | amelia678/python-104 | /n_to_m.py | 461 | 4.3125 | 4 | #what i've got:
#the abilty to ask user for start/end loop values
#what i want:
# to create a loop with user's start/end input
#how to i get:
#create a while loop that starts at user's start number and ends at end integer
start_number = int(input("Enter a number to start the loop"))
end_number = int(input("Enter a number to end the loop"))
while start_number <= end_number:
print(start_number)
start_number = start_number + 1
print() | true |
2fd0039e71ce6423844668f6677e11d10d58df41 | asadmoosvi/automate-the-boring-stuff-solutions | /chap07/date_detection.py | 1,479 | 4.28125 | 4 | import re
import sys
def is_leap_year(year: int) -> bool:
if year % 4 == 0:
if year % 100 != 0:
return True
else:
if year % 400 == 0:
return True
return False
date_regex = re.compile(
r'''(
(0[1-9]|[12][0-9]|3[01])/
(0[1-9]|1[012])/
([12]\d{3})
)''',
re.VERBOSE
)
test_date = input('Enter a test date: ')
mo = date_regex.search(test_date)
if not mo:
print(':: Invalid date format.')
sys.exit(1)
else:
valid_date = True
invalid_reason = ''
day, month, year = (int(x) for x in mo.groups()[1:])
is_leap = is_leap_year(year)
if month == 2:
if is_leap:
if day > 29:
valid_date = False
invalid_reason = 'Feb can have at most 29 days in a leap year.'
else:
if day > 28:
valid_date = False
invalid_reason = 'Feb can have at most 28 days in a non-leap year.'
if month == 4 or month == 6 or month == 9 or month == 11:
if day > 30:
valid_date = False
invalid_reason = 'This month can have at most 30 days.'
else:
if day > 31:
valid_date = False
invalid_reason = 'This month can have at most 31 days.'
if valid_date:
print(f':: {test_date} is a valid date.')
sys.exit(0)
else:
print(f':: {test_date} is an invalid date.')
print(f'::: Reason: {invalid_reason}')
sys.exit(2)
| false |
3456191404ebd27728f9fde604e16ac8fabec6ad | jbell1991/code-challenges | /challenges/leetcode/height_checker/height_checker.py | 397 | 4.25 | 4 | def height_checker(heights):
# sort list of heights from low to high
expected = sorted(heights)
# counter
counter = 0
# iterate over both the heights and expected
for height, expect in zip(heights, expected):
# if values do not match
if height != expect:
# increment counter by 1
counter += 1
# return counter
return counter
| true |
fc09b636ce6e436db9166a6b086dd4a7317f8bcb | jbell1991/code-challenges | /challenges/leetcode/reverse_vowels/reverse_vowels.py | 757 | 4.1875 | 4 | def reverse_vowels(s):
# list of vowels
vowels = "aeiouAEIOU"
# convert string to list
string_list = list(s)
# empty list to store matching vowels
matches = []
# iterate over the list of characters
for char in string_list:
# if character in vowels
if char in vowels:
# add it to another list
matches.append(char)
# reverse the list
matches.reverse()
# iterate over the list again
for i, char in enumerate(string_list):
# if char in vowels
if char in vowels:
# replace it with char at 0th index position
string_list[i] = matches[0]
# pop 0th index from list
matches.pop(0)
return "".join(string_list)
| true |
775c5df0179fed54475be04a1c0988eaa39864bc | jbell1991/code-challenges | /challenges/leetcode/steps_to_zero/steps_to_zero.py | 489 | 4.40625 | 4 | def steps_to_zero(num):
# steps
steps = 0
# while num is not equal to zero
while num != 0:
# if the num is even
if num % 2 == 0:
# divide it by two
num = num / 2
# increment steps by one
steps += 1
# if the num is odd
else:
# subtract one
num = num - 1
# increment steps by one
steps += 1
# once loop is exited return steps
return steps
| true |
f8e9eaf1175babfb8ee82b8aaa87279a338a84b4 | mtaylor62831/algorithms_data_structures_scripts | /intro_ds/merge_sort2.py | 2,423 | 4.21875 | 4 | def merge_sort(list, startIndex = 0, endIndex = None):
"""
Sorts the list in ascending order.
Returns a new sorted list.
Divide: find the midpoint of the list and divide into sublists.
Conquer: Recursively sort the sublists created in previous step.
Combine: Merge sorted sublists created in previous step.
This version doesn't use the [:N] slice operation becuase it runs slower than O(n)
"""
#if the length of the list is 0 or 1 it's already sorted
if len(list) <= 1:
return list
#once we get down to a single item we need to return it in a list
#unclear to me if this solves the runtime issue
#tradeoff seems to be creating a bunch of little arrays
if startIndex == endIndex:
sublist = []
sublist.append(list[startIndex])
return sublist
if endIndex == None:
endIndex = len(list) -1
midpoint = (endIndex - startIndex) // 2 + startIndex
#as long as there are more than 1 items in the sublist, split again
if startIndex <= midpoint:
leftList = merge_sort(list, startIndex, midpoint)
#once we have a viable list update the start position
#startIndex += len(leftList)
if midpoint + 1 <= endIndex:
rightList = merge_sort(list, midpoint + 1, endIndex)
#Handle the sort and merge for sublists
sortedList = []
leftIndex = 0
rightIndex = 0
while leftIndex < len(leftList) and rightIndex < len(rightList):
leftVal = leftList[leftIndex]
rightVal = rightList[rightIndex]
if leftVal < rightVal:
sortedList.append(leftVal)
leftIndex += 1
else:
sortedList.append(rightVal)
rightIndex += 1
while leftIndex < len(leftList):
leftVal = leftList[leftIndex]
sortedList.append(leftVal)
leftIndex += 1
while rightIndex < len(rightList):
rightVal = rightList[rightIndex]
sortedList.append(rightVal)
rightIndex += 1
return sortedList
def verify_sorted(list):
"""
Verified that a list is sorted in ascending order. Returns true or false.
"""
n = len(list)
if n == 0 or n == 1:
return True
return list[0] < list[1] and verify_sorted(list[1:])
mylist = [3, 1, 14, 5, 6, 4]
sortlist = merge_sort(mylist)
print(verify_sorted(mylist))
print(verify_sorted(sortlist))
print(sortlist) | true |
62e47f6d7ad7af4c7c12e39a1f15fc1604453b7a | Zia-/Mathematical-Code-Solutions | /src/12.wave-array.py | 786 | 4.3125 | 4 | """
author: Dr. Mohammed Zia
https://www.linkedin.com/in/zia33
Problem Statement:
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
more: https://practice.geeksforgeeks.org/problems/wave-array-1587115621/1
"""
def wave_arr(n):
"""
Generate wave array
"""
try:
mid_idx = len(n) // 2
for i in range(mid_idx):
if (n[2*i] < n[2*i+1]):
n[2*i], n[2*i+1] = n[2*i+1], n[2*i]
return n
except Exception as e:
print(e)
if __name__ == '__main__':
# n = [1,2,3,4,5]
n = [2,4,7,8,9,10]
print(wave_arr(n)) | true |
b52bca642447cd01771d8ab0ed270554799fa4f5 | Zia-/Mathematical-Code-Solutions | /src/7.stock-buy-and-sell.py | 1,335 | 4.3125 | 4 | """
author: Dr. Mohammed Zia
https://www.linkedin.com/in/zia33
Problem Statement:
The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum.
Note: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0.
more: https://practice.geeksforgeeks.org/problems/stock-buy-and-sell-1587115621/1
"""
def stock_buying_selling_days(A):
"""
Get when to buy or cell the stock
"""
try:
buy_idx = []
sell_idx = []
len_A = len(A)
for i in range(len_A):
if (i == 0):
if (A[i] < A[i+1]):
buy_idx.append(i)
elif (i == len_A-1):
if (A[i-1] < A[i]):
sell_idx.append(i)
elif (A[i-1] > A[i] and A[i] < A[i+1]):
buy_idx.append(i)
elif (A[i-1] < A[i] and A[i] > A[i+1]):
sell_idx.append(i)
return (buy_idx, sell_idx)
except Exception as e:
print(e)
if __name__ == '__main__':
N = 7
A = [100, 180, 260, 310, 40, 535, 695]
print(stock_buying_selling_days(A)) | true |
1ffe1910aab11ef0582b23781382e1ac10c74847 | oran2527/holbertonschool-machine_learning | /math/0x00-linear_algebra/8-ridin_bareback.py | 954 | 4.21875 | 4 | #!/usr/bin/env python3
""" matrix multiplication """
def mat_mul(mat1, mat2):
""" function to multiply two matrices """
cursize1 = []
cursize2 = []
newmat = []
add = 0
finalmat = []
cursize1 = matrix_shape(mat1)
cursize2 = matrix_shape(mat2)
if cursize1[1] == cursize2[0]:
for i in range(0, len(mat1)):
for w in range(0, len(mat2[0])):
for m in range(0, len(mat2)):
add = add + mat1[i][m] * mat2[m][w]
newmat.append(add)
add = 0
finalmat.append(newmat)
newmat = []
return finalmat
else:
return None
def matrix_shape(matrix_sub):
""" matrix to define a matrix """
size = []
try:
size.append(len(matrix_sub))
size.append(len(matrix_sub[0]))
size.append(len(matrix_sub[0][0]))
return size
except Exception as ex:
return size
| false |
9d65613a6ab7aaf16d3714ed8b76362ee91252aa | ky-koz/pythonProjects | /CodingDrills/drill122/drill122_func.py | 2,074 | 4.15625 | 4 | #
# Python: 3.8.0
#
# Author: Kyla M. Kozole
#
# Purpose: The Tech Academy- Python Course, Drill 122, For this drill,
# you will need to write a script that creates a GUI with a button widget
# and a text widget. Your script will also include a function that when it
# is called will invoke a dialog modal which will allow users with the
# ability to select a folder directory from their system. Finally, your
# script will show the user’s selected directory path into the text field.
#
#
# - Python 3 and the Tkinter module
# - askdirectory() method from the Tkinter module
# - a function linked to the button widget so that once the button
# has been clicked will take the user’s selected file path retained
# by the askdirectory() method and print it within your GUI’s text widget.
#
#
# imports
from tkinter import *
import tkinter as tk
from tkinter import messagebox
import tkinter.filedialog
import sqlite3
import os
import drill122_main
import drill122_gui
fileDialog = tkinter.filedialog
def center_window(self, w, h):
# get user's screen w x h
screen_width = self.master.winfo_screenwidth()
screen_height = self.master.winfo_screenheight()
# calc x and y coords to paint the app centered on the user's screen
x = int((screen_width/2) - (w/2))
y = int((screen_height/2) - (h/2))
centerGeo = self.master.geometry('{}x{}+{}+{}'.format(w, h, x, y))
return centerGeo
'''
def getDir(self):
varDir = fileDialog.askdirectory()
varDir = StringVar(root)
directoryName = StringVar()
# print(varDir)
self.get.insert(varDir)
# return self.get()
# directoryName.set(varDir)
'''
def getDir(self):
varDir = fileDialog.askdirectory()
if varDir:
self.txt_browse1.insert(INSERT,varDir)
def ask_quit(self):
if messagebox.askokcancel("Exit program", "Okay to exit application?"):
# this closes app
self.master.destroy()
os._exit(0)
if __name__ == "__main__":
pass
| true |
b5f38f360de5af43b445263fdb0c9e446e604dd3 | bsangars/BCI | /BubbleSort.py | 586 | 4.34375 | 4 | # Bubble Sort for an Array.
def BubbleSort(Array):
def swap(i,j):
Array[i],Array[j] = Array[j],Array[i]
n=len(Array)
swapped =True
x= -1
while swapped:
swapped=False
x=x+1
for i in range(1,n-x):
if Array[i-1]>Array[i]:
swap(i-1,i)
swapped=True
return Array
SampleArray =[2,1,2.5,1.1,6,4,7,5.5,7.1,10, 8,9,9.9]
TextArray =['1Alpha','AArin','Ja1ck','Charlie','Bingo','Jil9l','Zebra','Debra','Dustin']
BubblesortedArray =BubbleSort(TextArray)
print(BubblesortedArray)
| false |
0b9335d94150e81c191fcb3fb1948b9675751b55 | Peter-Leimer/Simulations | /BubbleSort_test.py | 743 | 4.46875 | 4 | def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
arr2 = []
arr3 = [94, 56, 81]
bubbleSort(arr)
bubbleSort(arr2)
bubbleSort(arr3)
print ("Sorted array 1 is:")
print (arr)
print ("Sorted array 2 is:")
print (arr2)
print ("Sorted array 3 is:")
print (arr3)
#for i in range(len(arr)):
# print ("%d" %arr[i]),
| false |
68f288a49bfebff5056598075fc823ad306ba03a | Loisa-Kitakaya/resources | /resource/import_test.py | 851 | 4.34375 | 4 | # firs imprt the file
# then from the file import the class
# after importing class make object that can use the methods in the class.
# NOTE: After importing the file and then the class within the file (imagine that the class has physically moved into this file and you can see it). Then create an object from the class and now you can call a method with the object.
import class_import_test
import example_class
from class_import_test import importTest
from example_class import exampleClass
ver = importTest() # here is where you make object from the class, that will use the methods in the class.
ver.test("Loisa") # here is where you use the object to call the method in the class importTest.
ver2 = ver.test("Loisa") #here you assign the method to a variable then print the variable.
print (ver2)
ver3 = exampleClass()
ver3.thisMethod() | true |
00c35697133644c45c8ad466a414fe2f0693b318 | Loisa-Kitakaya/resources | /resource/DiceRollingSimulator.py | 2,647 | 4.8125 | 5 | """ The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
Concepts to keep in mind:
Random
Integer
Print
While Loops """
import random # here we have imported the random module to generate the random number.
import author # here we have imported the author module to print the author of this program.
import datetime
print ("\n")
author.signature() # here we call the method "signature" which displays the name of the author of this program.
print ("\n")
print ("This program simulates the rolling of die and stores the dice rolls on an external log file. \n")
print ("The location for the log file is: /home/freedom/Desktop/Python/Files/dicerolls.txt \n")
print ("To quit the program, type 'quit' when you are prompted to roll the dice. \n")
while 1: # we use a while loop to the process of rolling the dice infinitely until the user wishes to stop.
print ("\nDo you want to roll the dice? ['yes' or 'quit']")
answer = input(">>> ") # the user prompts the program if they want to roll the dice (this process will be repeated until the user wishes to quit).
print ("\n")
dice_roll = random.randint(1,6) # here we use the module random and call the "randint" method which generates a random intager, and from our specified values for the method... the intager value is between 1-6. the value is then stored in the variable "dice_roll".
if answer == "yes": # here we use an if function to control the repeating process that prompts for the rolling of the dice.
print (dice_roll)
elif answer == "quit":
print ("Exiting simulation...")
break
else:
print ("Wrong input, try again. \n")
dice_result = str(dice_roll) #here we convert the randomly generated intager into a string and save it in the variable "dice_result".
date = datetime.datetime.now()
date2 = str(date)
dicerolls = open ("/home/freedom/Documents/Python/logs/dicerolls.txt", "a") # here we create an object that opens a file and writes on it.
dicerolls.writelines("\n")
dicerolls.writelines(date2)
dicerolls.writelines("\tProgram run successfuly\n.")
dicerolls.close() # here we close the file. | true |
7dab75a62cd8624a675e1926944234e64af10ad0 | Loisa-Kitakaya/resources | /resource/password.py | 744 | 4.34375 | 4 | # A small program that prompts for the user password, saves it, checks again if the password is correct.
pass_list = []
password = input("Enter your new password: ")
print ("\n") # This will print a blank line (next line).
pass_list.append(password) # This will append/add the input in variable "password" to the sequence list "pass_list".
print ("You will need to confirm your password.")
confirm_password = input("Re-enter your new password: ")
print ("\n")
if confirm_password in password: # This if function checks to see if the new password (confirm_password) is same as the one in list pas_list.
print ("Yep! That is the correct password.")
else:
print ("Nope! The password you have entered is not the same one you entered before.") | true |
aa1cd8333f921166cf6c3841ae4304699867203f | Loisa-Kitakaya/resources | /resource/file_object_one.py | 634 | 4.34375 | 4 | # This program creates and writes to a textfile.
file_object = open("/home/freedom/Desktop/Python/Files/greetings.txt", "w") # This is how you create a file; by specifying its creation location, then detailing the action that shall be performed of it.
file_object.write("Hello world! Good morning!") # This is how you perform the action that wass earlier detailed (writing on the file).
file_object.close() # You muxt always close the file after creating and writing on it.
say_hi = "import_modules.greetings()"
file_object = open("/home/freedom/Desktop/Python/Files/say_hi.txt", "w")
file_object.write(say_hi)
file_object.close() | true |
3243fb2999d2fec467e9e3a20fbe6ca8b13ac149 | rahul-tuli/APS | /Problems/Bipartite Graphs/bipartite_graphs.py | 1,865 | 4.1875 | 4 | def bipartite_graphs(n: int, m: int, d: int, D: int) -> str:
"""
Finds if a graph with the given property is available or not.
:param n: The number of vertices on each part of the bipartite graph.
:param m: The total number of edges.
:param d: The minimum degree of any vertex v.
:param D: The maximum degree of any vertex v.
:return: A string of m lines where each line is of the form 'u v'
denoting an edge between u and v if such a graph is possible
else -1.
"""
# If the total number of edges, m, is
# less than n * d (i.e. minimum # edges that could be made) or
# more than n * D (i.e. maximum # edges that can be made),
# No such graph exists.
if m < n * d or m > n * D: return '-1'
# Vars to hold
# min_deg = equally distributing the edges among all vertices (i.e. m // n).
# remaining = the number edges still to be made after each vertex has
# degree = min_deg.
# res -> to hold the string representation of the bipartite graph.
min_deg, remaining, result = *divmod(m, n), []
# For each vertex numbered from 1 to n,
for vertex in range(n):
# Make the degree of each vertex min_deg,
for deg in range(min_deg):
result.append(f'{vertex + 1} {(vertex + deg) % n + 1}')
# Make the remaining edges.
for vertex in range(remaining):
result.append(f'{vertex + 1} {(vertex + min_deg) % n + 1}')
# return the result
return '\n'.join(result)
def main():
"""
Driver function.
:return: None
"""
# For all the test cases,
for _ in range(int(input())):
# Get the input,
n, m, d, D = map(int, input().split())
# Solve for possible graphs.
result = bipartite_graphs(n, m, d, D)
# Output the result.
print(result)
if __name__ == '__main__':
main()
| true |
f508ddf0211a69054454bb9d25c504395abe6867 | rahul-tuli/APS | /Problems/String Similarity/string_similarity.py | 1,988 | 4.125 | 4 | def stringSimilarity_brute_force(s) -> int:
"""
Trivial implementation of the Z-function.
:param s: The string whose similarity is to be found with it's suffixes.
:return: The sum of string's similarity with all it's suffixes.
"""
# Length of s.
n = len(s)
# Z-Array, where z[i] == len(longest_common_prefix(s, suffix(s, i))).
z = [0] * n
for i in range(1, n):
# Keep incrementing z[i] till mismatch or end of string.
while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1
# return the sum(z) + n
# where n accounts for when i = 0 i.e. s == suffix(s, i = 0)
return sum(z) + n
def stringSimilarity(s) -> int:
"""
Efficient implementation of the Z-function.
:param s: The string whose similarity is to be found with it's suffixes.
:return: The sum of string's similarity with all it's suffixes.
"""
# Length of s.
n = len(s)
# l, r to hold the indices of the right-most segment match.
# Z-Array, where z[i] == len(longest_common_prefix(s, suffix(s, i))).
l, r, z = 0, 0, [0] * n
for i in range(1, n):
# if i < r, use an min(r - i + 1, z[i - l]) as an initial approximation.
if i <= r: z[i] = min(r - i + 1, z[i - l])
# if i > r, compute z[i] trivially.
while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1
# Update l, r to hold the indices of the right-most segment match.
if i + z[i] - 1 > r: l, r = i, i + z[i] - 1
# return the sum(z) + n
# where n accounts for when i = 0 i.e. s == suffix(s, i = 0)
return sum(z) + n
def main():
"""
Driver function.
:return: None
"""
# For every test case
for _ in range(1, int(input()) + 1):
# Get the input string.
s = input()
# Find the sum of the string's similarity with all it's suffixes.
result = stringSimilarity(s)
# Output the result.
print(result)
if __name__ == '__main__':
main()
| true |
fe963870d5d390349b74af6258597571f9d25080 | misseyri/django5 | /Algorithm_Section/sorting/insertion_sort.py | 603 | 4.25 | 4 | def insertion_sort(arr: list) -> list:
for i in range(1, len(arr)):
if arr[i-1] < arr[i]:
print("hellp")
continue
else:
for j in range(i-1, -1, -1):
print("bye: ", j)
print("i: ", i)
if arr[j] < arr[i]:
print("salam")
temp = arr.pop(i)
arr.insert(j, temp)
break
temp = arr.pop(i)
arr.insert(0, temp)
return arr
# print(list(range(0, -1, -1)))
print(insertion_sort([10, 2, 3, 15, -1, 0]))
| false |
bbe8ca0d6351812707987bc2031b020f94937cef | Leonardo-KF/Python3 | /ex033.py | 835 | 4.125 | 4 | n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
n3 = int(input('Digite o terceiro numero: '))
# tentiva inicial
'''if n1 >= n2 and n1 >= n3:
print(f'O maior numero é: {n1}')
if n2 >= n1 and n2 >= n3:
print(f'O maior numero é: {n2}')
if n3 >= n1 and n3 >= n2:
print(f'O maior numero é: {n3}')
if n1 <= n2 and n1 <= n3:
print(f'E o menor numero é: {n1}')
if n2 <= n1 and n2 <= n3:
print(f'E o menor numero é: {n2}')
if n3 <= n1 and n3 <= n2:
print(f'E o menor numero é: {n3}')'''
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
maior = n3
if n1 > n3 and n1 > n2:
maior = n1
if n2 > n3 and n2 > n1:
maior = n2
print(f'O menor valor digitado foi {menor}\nE o maior digitado foi {maior}')
| false |
e39237bb88d993d02ff82ac005713fc43479fb52 | vivekmatta/Python_Projects | /math_problems.py | 1,638 | 4.25 | 4 |
def quotient():
print("What two numbers would you like to divide? ")
answer1 = int(input())
answer2 = int(input())
quotient = answer1 / answer2
print(str(answer1) + " / " + str(answer2) + " = " + str(quotient))
def subtraction():
print("What two numbers would you like to subtract? ")
answer1 = int(input())
answer2 = int(input())
subtraction = answer1 - answer2
print(str(answer1) + " - " + str(answer2) + " = " + str(subtraction))
def addition():
print("What two numbers would you like to add? ")
answer1 = int(input())
answer2 = int(input())
addition = answer1 + answer2
print(str(answer1) + " + " + str(answer2) + " = " + str(addition))
def multiplication():
print("What two numbers would you like to subtract? ")
answer1 = int(input())
answer2 = int(input())
multiplication = answer1 * answer2
print(str(answer1) + " * " + str(answer2) + " = " + str(multiplication))
def run():
print("What operation would you like to do? ")
operator = input()
if operator == "addition" or operator == "Addition":
addition()
if operator == "subtraction" or operator == "Subtraction":
subtraction()
if operator == "division" or operator == "Division":
division()
if operator == "muliplication" or operator == "Multiplication":
multiplication()
"""
print("Would you like to do another operation? yes or no? ")
answer = input()
if answer == "yes":
run()
if answer == "no":
break
"""
run()
| false |
7cfb8bfac92e7adfb2d632e1cc63d7355d26050a | ytk1216/PyDailychallenge | /number_of_times.py | 701 | 4.15625 | 4 | # Create a function that calculates how many times an integer can be
# divided by another given integer. If the answer of resulting
# divisions does not result in an integer, that division is not counted
# towards the number of times. As an example:
# If n is 10 and divisor is 3, since in the first division 10/3 doesn't
# return an integer, this division doesn't count towards the number
# of times and therefore its number of times should be 0.
# def divisions(n, divisor):
# return number_of_times
def divisions(n, divisor):
number_of_times = 0
while n%divisor == 0:
n = int(n/divisor)
number_of_times += 1
return number_of_times
print(divisions(24,2))
| true |
3f1dc9a1c4ba33821c595666893486b350435eae | A-khateeb/Full-Stack-Development-Path | /Python/PCC/Chapter6/Person.py | 312 | 4.21875 | 4 | person = {"fname":"Afeef","lname":"Khateeb","age":27,"city":"Jerusalem"}
print("Person's First name is : " + str(person['fname'].title()))
print("Person's Last name is : " + str(person['lname'].title()))
print("Person's age is : " + str(person['age']))
print("Person's City is : " + str(person['city'].title()))
| false |
82ae0033cdb3e8f10a426e7fc1af6469c97fefd2 | A-khateeb/Full-Stack-Development-Path | /Python/main/LPTHW2.py | 532 | 4.21875 | 4 | #Prints the string I will now count my chickens
print("I will now count my chickens")
print("Hens", 25.00+30.00/6.00)
print("Roosters",100.00-25.00*3.00%4.00)
print("I will count the eggs")
print(3.00+2.00+1.00-5.00+4.00%2.00-1.00/4.00+6.00)
print("is it true that 3+2<5-7?")
print(3.00+2.00<5.00-7.00)
print("What is 3+2",3.00+2.00)
print("What is 5-7",5.00-7.00)
print("Oh that's why it is false")
print("Is it greater", 5.00>2.00)
print("Is it greater than or equal", 5.00>=-2.00)
print("Is it less than or equal",5.00<=-2.00)
| true |
396d6c67882858efd60b895d4237403c36baf039 | A-khateeb/Full-Stack-Development-Path | /Python/SmallProject/Regular Expression.py | 390 | 4.21875 | 4 | import re
phone_number_reg = re.compile(r'(\d\d\d-)\?\d\d\d-\d\d\d\d')
print("Please enter a Phone number")
mo = phone_number_reg.search(input())
print("The Phone number that is found is : "+mo.group())
print(mo.group(0))
print(mo.group(1))
#print(mo.group(2))
print(mo.groups())
###areacode , mainNumber , extention = mo.groups()
#print(areacode)
#print(mainNumber)
#print(extention)
### | false |
e3377639e07a141b3eb6c50e7fdf25164e288dea | A-khateeb/Full-Stack-Development-Path | /Python/PCC/Chapter5/Stages_of_life.py | 356 | 4.1875 | 4 | age = 20
if age < 2:
print("The person is a baby")
elif age <= 2 and age < 4 :
print("The person is a toddler")
elif age <= 4 and age < 13 :
print("The person is a kid")
elif age <= 13 and age < 20:
print("The person is a teenager")
elif age <= 20 and age <65 :
print("The person is adult")
else:
print("The person is an elder")
| true |
0499688b3a2bb0401ec59ebde9ac98bf1c5ffb4e | A-khateeb/Full-Stack-Development-Path | /Python/PCC/Chapter4/number.py | 591 | 4.15625 | 4 | for values in range(1,6):
print(values)
numbers = list(range(1,6))
print(numbers)
print(numbers[0])
print(numbers[1])
print(numbers[2])
print(numbers[3])
print(numbers[4])
#numbers[5]
#numbers[6]
#Even Numbers
even_numbers = list(range(2,11,2))
print(even_numbers)
#Square Numbers
squares = []
for value in range(1,11):
# square = value**2
# square = square+square
squares.append(value**2)
print(squares)
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
sq = [val**2 for val in range(1,11)]
print("Squares are equal to = "+str(sq))
| true |
b847abf97e703a3ab140a01950b869046e2896bf | A-khateeb/Full-Stack-Development-Path | /Python/SmallProject/Dictionaries.py | 623 | 4.28125 | 4 | name_birthday = {"Ahmad": "Apr 1", "Mohammad":"Sep 11 ", "Afeef": "10 July"}
while True:
print("Type the name of your friend (blank to stop)")
name = input()
if name == '':
break
if name in name_birthday:
print("The birthday of your friend is : "+name_birthday[name])
else:
print("The name does not exist "+ name)
print("What is "+ name+"'s birth date")
bday = input()
name_birthday[name] = bday
print(name_birthday)
print("It is now saved in the database")
| true |
a4df637e422dafdf80097936bc9e4bb7ccdc1cae | darylm20/Daryl-Mawere-CP1404-Pracs | /prac_04/quick_picks.py | 732 | 4.125 | 4 | import random
NUMBERS_PER_LINE = 6
MINIMUM = 1
MAXIMUM = 45
def main():
no_quick_picks = int(input("How many quick picks would you like? "))
while no_quick_picks < 0:
print("Does not compute! Please pick a number greater than 0 (zero)")
no_quick_picks = int(input("How many quick picks would you like? "))
for a in range(no_quick_picks):
quick_pick = []
for b in range(NUMBERS_PER_LINE):
number = random.randint(MINIMUM, MAXIMUM)
while number in quick_pick:
number = random.randint(MINIMUM, MAXIMUM)
quick_pick.append(number)
quick_pick.sort()
print(" ".join("{:2}".format(number) for number in quick_pick))
main() | true |
20b189ba1fbb197946c664413c271c59ecfff93e | dipenich2019/scholarshp | /env/sql_strings.py | 1,641 | 4.28125 | 4 | # imports sqlite
import sqlite3
# connects it to the books-collection database
conn = sqlite3.connect('sqlite3_database.db')
# creates the cursor
c = conn.cursor()
# execute the query which creates the table called books with id and name #as the columns
# executes the query which inserts values in the table
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (23, '£15000','A trip to NewYork plus Cash' ) ")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (24, 'Flight Tickets','Plus $5000 Spending Money' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (25, '£4000','50% Reduction in Tuition Fees' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (26, '£25000','Research Grant From Microsoft' ) ")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (27, '£2000','University Allowance' ) ")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (28, '£7000','PostGraduate Scholarship' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (29, '£10000','IBM Masters Grant' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (30, '£26000','UN Scholarship allowance' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (31, '£2000','Maintenance allowance' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (32,'£7000','Alumni Award' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (33,'£82000','A Job with Facebook' )")
c.execute("INSERT INTO Present (ID,GIFT, DESCRIPTION)VALUES (34,'£17000','Google Award' )")
# commits the executions
conn.commit()
# closes the connection
conn.close()
| true |
fccbd3300cfa761105ebe147f2b68d3da529cc71 | 7ecapilot/py-learning | /src/Quiz1bQ7.py | 341 | 4.1875 | 4 | import math
def polygon_area(num_sides, side_length):
numerator = 0.25 * num_sides * side_length ** 2
denominator = math.tan(math.pi / num_sides)
result = numerator / denominator
return result
number_of_sides = 7
side_length = 3
print (number_of_sides)
print (side_length)
area = polygon_area(number_of_sides, side_length)
print (area) | true |
58728c61430ac876c3761cabee02aabd15772fcf | ahmed6262445/8-Puzzle-Python-AI | /src(1)/board.py | 2,041 | 4.125 | 4 | from random import randint
# from numpy import reshape
from time import sleep
class Board():
def __init__(self, length: int, breadth: int, board: list = [] ):
"""
Parameters:
length (int) : It sets the length of the board
breadth (int): It sets the breadth of the board
Members:
lenght (int): Length of the board
breadth (int): Breadth of the board
board (list): Board itself (It is initialzed by -1 invalide spots)
"""
self.__length = length
self.__breadth = breadth
self.board = list()
self.initialize_board(board)
def initialize_board(self, board : list):
"""
Convertes the 1d List to 3d List
e.g.
[1, 2 , 3, 4, 5 ,6 , 7, 8, 0]
to
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8
"""
self.board = self.reshape_array(self.__length, self.__breadth, board)
def reshape_array(self,row: int, col: int, arr = []) -> list:
index = 0
return_list = []
for i in range(row):
temp_list = []
for j in range(col):
temp_list.append(arr[index])
index += 1
return_list.append(temp_list)
return return_list
def print_board(self) -> str:
"""
Returns a string of a printed board
"""
board = ""
for i in range(self.__length):
for j in range(self.__breadth):
board += str(self.board[i][j])
if j != 2:
board += " | "
board += "\n"
return board
def print_board(board) -> str:
"""
Returns a string of a printed board
"""
board_p = ""
for i in range(len(board)):
for j in range(len(board)):
board_p += str(board[i][j])
if j != 2:
board_p += " | "
board_p += "\n"
return board_p | true |
8b63120e0d44aa7b4f1010af7665d9fd918e4421 | Grigoreva2312/- | /task_9_4.py | 2,249 | 4.125 | 4 | # Задача 9. Вариант 4.
#Григорьева Я.В.
#1-50. Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать.
#Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет".
#Вслед за тем игрок должен попробовать отгадать слово.
# 18.04.2017
import random
word = ("помощник","меч","память","цветы","вознаграждение","солнце","вера")
varik=""
comp=random.choice(word)
quantity=5
attempt=1
print('у вас 5 попыток отгадать слово')
print("Угадайте заданное слово из ниже перечисленных")
print (word)
while varik != comp and quantity > 0:
if quantity == 5 :
if (input("Нужна ли Вам подсказка?")) == "да" :
print("Длина заданного слова = :",len(comp))
else :
if quantity <5:
if (input("Нужна ли Вам ещё подсказка?")) == "да" :
symbol=input(" Спросите у компьютера любую букву из алфавита, а он ответит, есть ли в слове эта буква: ")
if symbol in comp :
print("Вы угадали!Эта буква присутствует в слове")
else :
print ("Вы не угадали!Буква отсутвует")
quantity=quantity-1
varik=input("Попробуйте отгадать слово :")
print("Попытка :",attempt)
attempt=attempt+1
if varik==comp :
print("Да,именно так!Вы отгадали!")
else :
print('К сожалению,вы не угадали!!! Правильный ответ: ', comp )
input ('Нажмите Enter для выхода')
| false |
d40672d2f3cb30b0cff8b9bd8e547a655b0c2537 | arunatuoh/assignment-code | /anagram.py | 337 | 4.21875 | 4 | def anagram(str1,str2):
if len(str1)!=len(str2):
return 0
str1 = sorted(str1)
str2 = sorted(str2)
for i in range(0, len(str1)):
if str1[i] != str2[i]:
return 0
return 1
str1="arun"
str2="nura"
if anagram(str1,str2):
print("string is anagram")
else:
print("string is not anagram") | false |
635942cad1e73ead9f73d42b2a532407da8cefab | Adithyavj/PythonBasics | /sample_inheritance.py | 876 | 4.375 | 4 | class BaseClass:
def __init__(self):
print("Base inint")
def set_name(self, name):
self.name = name
print("Base Class set_name()")
class SubClass(BaseClass):
def __init__(self): #here this constructor overrides the constructor of base class Constructor Overriding
super().__init__() # if we want to call constructor of base class we use super()
print("SubClass inint")
def Welcome(self):
print("Welcome")
def set_name(self, name): #Method OverRiding base class and sub class has method of same name, the subclass method overrides the method of the base class
super().set_name(name)
self.name = name
print("Sub Class set_name()")
def display_name(self):
print("Name: " + self.name)
y = SubClass()
y.Welcome()
y.set_name("Adithya Vijay K")
y.display_name()
#Method OverRiding
| false |
9fa3b9bac4ef5e2ca66f2da287026a0bcd2b8c81 | Agbomadzi/Global-Python | /fib 3.py | 602 | 4.46875 | 4 | # Program to generate the Fibonacci sequence in Python
# The length of our Fibonacci sequence
length = 10
# The first two values
x = 0
y = 1
iteration = 0
# Condition to check if the length has a valid input
if length <= 0:
print("Please provide a number greater than zero")
elif length == 1:
print("This Fibonacci sequence has {} element".format(length), ":")
print(x)
else:
print("This Fibonacci sequence has {} elements".format(length), ":")
while iteration < length:
print(x, end=', ')
z = x + y
# Modify values
x = y
y = z
iteration += 1 | true |
45fdb2113dcb9aea21a25b5a0ead44f10577c593 | jasClem/CamelCase | /main.py | 648 | 4.15625 | 4 | __author__ = "Jason"
# DONE
from camelCase import *
# Import functions
def main():
camel_case_input = input("\nEnter words to camelCase (separated by spaces): ")
# Get user input for words to camelCase
words_to_camelcase = camel_case_input.split(' ')
# Separate the words by spaces
camel_case_words = [camel_case(each_word) for each_word in words_to_camelcase]
# Send words to turn into camelCase
camel_case_words[0] = camel_case_words[0].lower()
# Change first word to lowercase
output = "".join(camel_case_words)
# Remove spaces from words
print(output)
# Display camelCase words
main()
| true |
f376f93652ce589f11d39dab938c1dee36e260d3 | RadoslavGYordanov/hackerschool | /PracticePython/exercise11.py | 314 | 4.125 | 4 | import sys
import math
def is_prime(num):
for x in xrange(2,num):
if num%x==0:
return 0
return 1
if sys.version_info[0] >= 3:
num=int(input("Enter a number: "))
else:
num=int(raw_input("Enter a number: "))
if is_prime(num):
print("\nThe number is prime\n")
else:
print("\nThe number is not prime\n")
| true |
39e5c2f9daa6649b4b4b9313d6869e99af36e333 | K-Vaid/Python | /Basics/height_cal.py | 1,065 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 22 17:30:51 2018
@author: Kunal Vaid
Code Challenge
Name:
Height Calculator
Filename:
height_cal.py
Problem Statement:
Lets assume your height is 5 Foot and 11 inches
Convert 5 Foot into meters and
Convert 11 inch into meters and
print your total height in meters and
print your total height in centimetres also
Hint:
1 Foot = 0.3048 meters
1 inch = 0.0254 meters
1 m = 100 cm
"""
# Enter your height
foot, inches = list(map(float,input("Enter your height (like 5.11 (if it is 5 Foot and 11 inches)): ").split(".")))
# total height in foots
total_foot = foot * 0.3048
# total height in inches
total_inches = inches * 0.0254
# total height in meters
total_height_in_meters = total_foot + total_inches
# total height in centimeters
total_height_in_centimeters = total_height_in_meters * 100
print("Total Height in Meters is "+str(round(total_height_in_meters,2))+" m")
print("Total Height in Centimeters is "+str(round(total_height_in_centimeters,2))+" cm") | true |
f0e9711241fa4ffb7cfe2eaf48ddcdf153e16fc0 | K-Vaid/Python | /Basics/age_cal.py | 928 | 4.125 | 4 | """
Code Challenge
Name:
Age Calculator
Filename:
age_cal.py
Problem Statement:
Lets assume your age is 21 today
What would be your age after 5 years from today
How old were you 10 years back
Hint:
You need to add to calculate future age
You need to subtract to calculate your past age
"""
# Enter your age
user_age = int(input("Enter your age :"))
# Enter years after that you want to calculate your age
f_years = int(input("Enter the no. of years after, to calculate your age :"))
# Enter years before that you want to calculate your age
p_years = int(input("Enter the no. of years back, to calculate your age :"))
future_age = user_age + f_years
past_age = user_age - p_years
print ("Your current age is : {0}".format(user_age))
print ("Your age after {0} years will be : {1}".format(f_years,future_age))
print ("Your age before {0} years was : {1}".format(p_years,past_age)) | true |
6afd419520e80c3fd8e1c04307368c287c636702 | foooooooooooooooooooooooooootw/CP1404Prac | /prac 3/password_check.py | 464 | 4.25 | 4 | def main():
minimum_length = 8
password = get_password(minimum_length)
for i in range(len(password)):
print("*", end='')
def get_password(minimum_length):
password = input("Enter your password: ")
while len(password) < minimum_length:
print("Your password is too short.")
print("Minimum length is {} characters".format(minimum_length))
password = input("Enter your password: ")
return password
main()
| false |
2251f6b01a61412a4ba19191bb9b380e8af404a3 | vmirisas/Python_Lessons | /lesson13/part3/exercise3.py | 201 | 4.21875 | 4 | def float_average(*numbers):
sum = 0
for number in numbers:
sum += number
average = sum / len(numbers)
return average
print(f"average = {float_average(1,2,3,4,5,6,7,8,9,10)}") | true |
a7b89abf7fb261c519d431954e0c3ecdda42f8d7 | vmirisas/Python_Lessons | /lesson3/exercise5.py | 233 | 4.1875 | 4 | x = int(input("type an integer for x: "))
y = int(input("type an integer for y: "))
z = int(input("type an integer for z: "))
if x >= y and x >= z:
print(x)
if y >= x and y >= z:
print(y)
if z >= x and z >= y:
print(z) | false |
b7ca0e31a80c59fccb527378ff707d634ac6225c | vmirisas/Python_Lessons | /lesson5/exercise9.2.py | 319 | 4.3125 | 4 | number = int(input("type a number: "))
hidden_number = 4
while number != hidden_number:
if number <= hidden_number:
number = int(input("type a greater number: "))
elif number >= hidden_number:
number = int(input("type a lesser number: "))
if number == hidden_number:
print("found it")
| false |
fd3f43f302f57a5c6298d7c7bba0c3868696ef8e | vmirisas/Python_Lessons | /lesson17/part8/exercise10.py | 1,108 | 4.15625 | 4 | from math import sqrt
class Circle:
def __init__(self, c):
self.c = c
def __str__(self):
return f"x^2 + y^2 = {self.c}^2"
def __eq__(self, other):
return self.c == other.c
def __lt__(self, other):
return self.c < other.c
def __call__(self, x, y=None):
if y is None:
if isinstance(x, (int, float)):
if x < abs(self.c):
return (x, sqrt(self.c ** 2 - x ** 2)), (x, -sqrt(self.c ** 2 - x ** 2))
elif abs(x) == self.c:
return (x, 0)
else:
return None
else:
if isinstance(x, (int, float)):
if x ** 2 + y ** 2 < self.c ** 2:
print(f"({x}, {y}) is inside the circle")
elif x ** 2 + y ** 2 == self.c ** 2:
print(f"({x}, {y}) is on the circle")
else:
print(f"({x}, {y}) is out of the circle")
circle = Circle(5)
print(circle(3))
print(circle(5))
print(circle(7))
circle(1, 1)
circle(5, 0)
circle(5, 9)
| false |
ea1b059e08329d94c0df6ff8748e569609c58098 | thehimel/hackerrank-python | /src/split_join.py | 487 | 4.21875 | 4 | """
https://www.hackerrank.com/challenges/python-string-split-and-join/problem
>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings.
>>> print a
['this', 'is', 'a', 'string']
>>> a = "-".join(a)
>>> print a
this-is-a-string
Input:
this is a string
Output:
this-is-a-string
"""
def split_and_join(line):
return '-'.join(line.split())
if __name__ == '__main__':
line = 'this is a string'
result = split_and_join(line)
print(result)
| true |
90ee1ef62f47cf951ed24d237a9fbc138a884b2f | thehimel/hackerrank-python | /src/print_funcion.py | 531 | 4.3125 | 4 | """
https://www.hackerrank.com/challenges/python-print/
Read integer n from STDIN.
Without using any string methods, print the following:
123...n
Note that "..." represents the consecutive values in between.
Example
Input
n = 5
Output
12345
Constraints
1 <= n <= 150
Output Format
Print the list of integers from 1 through n as a string, without spaces.
Sample Input
3
Sample Output
123
"""
if __name__ == '__main__':
n = int(input())
# for (i=1; i<=n; i++)
for i in range(1, n+1):
print(i, end='')
| true |
4b868595379f64ca92ba0d2b2a2bb449d49843d5 | nambroa/Algorithms-and-Data-Structures | /LEGACY/sorting_algorithms/heap_sort.py | 1,637 | 4.21875 | 4 | """
HOW TO HEAP SORT
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. We then swap the root node with the last node and
delete the last node from the heap.
3. Repeat 1 and 2 steps while size of heap is greater than 1.
"""
# To heapify subtree rooted at index i.
# n is size of heap. FOR MAXHEAPS
def heapify(arr, arr_length, root_index):
largest = root_index # Initialize largest as root
left_child = 2 * root_index + 1 # left = 2*i + 1
right_child = 2 * root_index + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if left_child < arr_length and arr[root_index] < arr[left_child]:
largest = left_child
# See if right child of root exists and is
# greater than root
if right_child < arr_length and arr[largest] < arr[right_child]:
largest = right_child
# Change root with one of its childs, if they were bigger.
if largest != root_index:
arr[root_index], arr[largest] = arr[largest], arr[root_index] # swap
# Heapify the root again.
heapify(arr, arr_length, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" % arr[i]),
| true |
b86b0b8b70443fff10684ad6c9fc2563e73cf688 | nambroa/Algorithms-and-Data-Structures | /arrays/B_add_one_to_number/algorithm.py | 2,265 | 4.125 | 4 | # coding=utf-8
"""
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
EXAMPLE:
If the vector has [1, 2, 3], the returned vector should be [1, 2, 4], as 123 + 1 = 124.
NOTE: Certain things are intentionally left unclear in this question which you should practice asking the interviewer.
For example, for this problem, following are some good questions to ask :
Q : Can the input have 0’s before the most significant digit. Or in other words, is 0 1 2 3 a valid input?
A : For the purpose of this question, YES
Q : Can the output have 0’s before the most significant digit? Or in other words, is 0 1 2 4 a valid output?
A : For the purpose of this question, NO. Even if the input has zeroes before the most significant digit.
"""
# Question: Can the input contain invalid data? Structs, strings... Answer: NO. Input is always valid.
# Question: Can the input be None: Answer: YES. You should check it.
# IDEA: Algorithm steps are as follows:
# PRE: Check if input is None.
# A: Clean zeroes from the left from the input.
# B: Add 1 to the last digit. If the digit is 9, change it to zero and add 1 to the previous one
# EDGE CASE: If all numbers are 9, add one space at the beginning and put a 1 there, all other digits to 0.
def clean_zeroes_of_number(number):
for index, digit in enumerate(number):
if digit != 0:
return number[index:]
return number # If all digits are zeroes
def check_if_number_is_none(number):
if number is None:
raise ValueError("Number is None.")
def check_if_number_is_empty(number):
if len(number) is None:
raise ValueError("Number is empty.")
def add_one_to_number(number):
check_if_number_is_none(number)
check_if_number_is_empty(number)
new_number = clean_zeroes_of_number(number)
current_index = len(new_number) - 1
for digit in new_number[::-1]:
if digit != 9:
return new_number[:current_index] + [digit+1] + new_number[current_index+1:]
else:
new_number[current_index] = 0
current_index -= 1
return [1] + new_number
| true |
fa4f56a1c8c2b7fcb6d12e18dec82bf756054e07 | nambroa/Algorithms-and-Data-Structures | /recursion_dp_backtracking/D_power_set/algorithm.py | 1,204 | 4.34375 | 4 | """
Write a method to return all subsets of a set.
EXAMPLE: If input = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
QUESTIONS YOU SHOULD ASK:
+ Can I use custom classes?
+ In what datastruct will the input be? List
+ Can the set be empty? Yes, return [[]]
+ Can the input be None? Yes, raise exc.
+ Can the set contain anything other than integers? No
+ Can the set contain repeated numbers? No (CRUCIAL)
"""
"""
Caveat: new_subsets.extend(subsets) is O(|subsets|)
Complexity: (N * (2^N))
Explanation: A set S will have |2^N| subsets in a power set. Each iteration is, at worst, N.
"""
def _get_all_subsets_of(numbers):
if not numbers:
return [[]] # Base case.
else:
last_number = numbers[-1]
subsets = _get_all_subsets_of(numbers[0:len(numbers)-1])
new_subsets = []
for subset in subsets:
new_subsets.append(subset + [last_number])
new_subsets.extend(subsets)
return new_subsets
def get_all_subsets_of(numbers):
if numbers is None:
raise ValueError("Numbers are None.")
if len(numbers) == 0:
return [[]]
return _get_all_subsets_of(numbers)
| true |
4bd90e91cca4a6cad3ed73800e2222c5c2f654e8 | nambroa/Algorithms-and-Data-Structures | /strings/M_count_and_say/algorithm.py | 2,161 | 4.25 | 4 | """
Write a function to find the nth "count and say sequence" given an integer n.
The "count and say sequence" is a special recursive sequence. Here are some base cases:
N String to Print
1 1
2 1 1
3 2 1
4 1 2 1 1
Base case: n = 1 ---> print "1"
For n = 2 ---> Look at the previous string and write the number of times a digit is seen and the digit itself.
In this case, digit 1 is seen 1 time in a row, so print "1 1"
For n = 3 ---> Digit 1 is seen two times in a row, so print "2 1"
For n = 4 ---> Digit 2 is seen 1 time, then digit one is seen one time, print "1 2 1 1"
For n = 5 ---> Digit 1 is seen one time, then digit 2 is seen two times, then digit one is seen two times.
Print "1 1 1 2 2 1"
QUESTIONS YOU SHOULD ASK:
+ Can I use custom classes? Yes.
+ Will the input always be valid? No, it can be None
+ Can n be negative? No. Can it be zero? Yes, return 1.
"""
"""
Count and say is a recursive function, and you have to do all the steps (so no memoization for optimizing)
"""
def count_and_say(n):
if n is None or n <= 0:
raise ValueError('N is None or is lower than 1.')
# Base cases.
if n == 1:
return '1'
if n == 2:
return '11'
# Other cases: I can assume n is higher than 2. So it will always have 2 or more chars.
else:
previous_iteration = '11'
for i in range(2, n):
new_iteration = ''
current_char = previous_iteration[0]
amount_of_times = 1
for char in previous_iteration[1:]:
# Count the amount of times chars are seen. Print amount_of_times+char for each char.
# Then replace previous iteration with the result.
if char == current_char:
amount_of_times += 1
else:
new_iteration = new_iteration + str(amount_of_times) + current_char
current_char = char
amount_of_times = 1
new_iteration = new_iteration + str(amount_of_times) + current_char
previous_iteration = new_iteration
return previous_iteration
| true |
5d0f8b08fdf2e9d92045a947efaacfe041ea57c8 | nambroa/Algorithms-and-Data-Structures | /arrays/G_largest_number/algorithm.py | 2,105 | 4.3125 | 4 | """
Given a list of non negative integers, arrange them such that they form the largest number.
For example:
Given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
QUESTIONS YOU SHOULD ASK:
+ Is the input always going to be valid? Yes.
+ Can I get zeroes in the list? Yes.
+ Should I form the largest number with them or try to ignore them from the function? Use them to form it.
"""
from fractions import Fraction
"""
Since sorting in descending order doesn't work (because 34 > 9 but 9 appears first in the finished number), we need to
sort on a custom comparison A or B.
A) Given numbers X and Y, we append to form XY and YX, and then we compare. If XY > YX, then X should come first,
otherwise Y should come first.
B) Given a number X, we calculate it's fraction in relation to the number of digits it has. For example, if X=3, then
the fraction is 3/10^1 = 3/10. If X=30, the fraction is 30/10^2 = 30/100. In order to make 3 come before 30 as we
need, we subtract 1 from the denominator. That makes X=3 --> 3/9 and X=30 --> 30/99, such as 3/9 > 30/99. This
subtraction of 1 makes sure that all the cases of 3 vs 30 or 30 vs 300 always prioritize the number with the least
digit count.
It also makes the cases of 3 vs 31 or 3 vs 3i, with i > 3 favor the case of 3i as it should be. For example,
X=3 --> 3/9 and X=34 --> 34/99 such that 3/9 < 34/99. Of course this also means that 3 vs 3i will favor 3 with
i < 3. With i == 3 it doesn't matter, since they are "the same".
"""
def largest_number(numbers):
# Sort by the fraction method B)
numbers = sorted(numbers, key=lambda n: Fraction(n, (10 ** len(str(n)))-1), reverse=True)
i = 0
# This while is in place in case the array is full of zeroes. It will make answer just a '0' which is the
# largest number.
while i < len(numbers) - 1:
if numbers[i] != 0:
break
else:
i += 1
answer = ''.join(str(digit) for digit in numbers[i:])
return answer | true |
e8361b6d85b36b1e207ff49460ec5ca7e7bf8235 | nambroa/Algorithms-and-Data-Structures | /arrays/A_min_steps_in_infinite_grid/algorithm.py | 1,410 | 4.125 | 4 | """
You are in an infinite 2D grid where you can move in any of the 8 directions :
(x,y) to:
(x+1, y),
(x - 1, y),
(x, y+1),
(x, y-1),
(x-1, y-1),
(x+1,y+1),
(x-1,y+1),
(x+1,y-1)
You are given a sequence of points and the order in which you need to cover the points.
Give the minimum number of steps in which you can achieve it. You start from the first point.
EXAMPLE:
Input : [(0, 0), (1, 1), (1, 2)]
Output : 2
"""
# IDEA: Every new point can be achieved at, at worst, 1 step. So if the next point is different (IDC how), I will need
# and extra step. Repeat these for every new point.
# I'll assume points are always well-constructed. That is, they always have an x and a y coordinate.
def minimum_steps_to_traverse_grid(points):
steps_required = 0
if not points:
return steps_required
for i in range(len(points) - 1):
if points[i] != points[i+1]:
steps_required += 1
if points[-1] != points[-2]:
steps_required += 1
return steps_required
class Point(object):
def __init__(self, x, y):
if x is None or y is None:
raise ValueError("Point is missing coordinates x or y.")
self._x = x
self._y = y
def x(self):
return self._x
def y(self):
return self._y
def __ne__(self, other):
return self.x() != other.x() or self.y() != other.y()
| true |
b6d8ec7bfac2b28e5eff00317753b901dc9a5a4b | nambroa/Algorithms-and-Data-Structures | /arrays/H_wave_array/algorithm.py | 1,108 | 4.5 | 4 | """
Given an array of integers, sort the array into a wave like array and return it,
In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
EXAMPLE:
Given [1, 2, 3, 4]
One possible answer : [2, 1, 4, 3]
Another possible answer : [4, 1, 3, 2]
PLEASE NOTE:
If there are multiple answers possible, return the one thats lexicographically smallest.
So, in example case, you will return [2, 1, 4, 3]
QUESTIONS YOU SHOULD ASK:
+ Is the input always going to be valid? Yes.
+ Can I get zeroes or negatives in the list? Yes
+ Does the array come sorted? No
+ Can the list have repeated numbers? No
"""
def create_wave_list_from(numbers):
if not numbers or len(numbers) == 0:
raise ValueError("Numbers list is empty or otherwise invalid.")
numbers = sorted(numbers)
i = 0
# I want to iterate through all the numbers except the last one, which will be moved in the last iteration.
while i < len(numbers) - 1:
temp = numbers[i]
numbers[i] = numbers[i+1]
numbers[i+1] = temp
i += 2
return numbers
| true |
206a478a1115008865f3099eb3a1a1364ed49f2d | js-refresh/python-102 | /objects.py | 1,146 | 4.25 | 4 | # class examples
def introduce(first, last):
print(f'Introducing {first}, of house {last}!')
introduce('Arya', 'Stark')
# Callbacks
def greet(name):
print(f'Hello, {name}')
def depart(name):
print(f'Goodbye, {name}')
def interactTwice(name, action):
action(name)
action(name)
interactTwice('Molly', greet)
interactTwice('Molly', depart)
# What is an object?
# It's just a 'thing', bunch of data, plus, has methods for working with that data
# also callee attributes, properties, or state
# what's an example of an object?
# A cat has.... fur, lives, legs, claws, tail (i.e. these are objects)
# How is an object created?
# It is 'instantiated', it's an instance of an object
# 'Class' is like a blueprint, different than 'objects'
# Instantiate cat!, start with a class
class Cat:
# Class attibute
species = 'mammal'
# Initialize / Instance Attribute
def _init_(self, name, age):
self.name = name
self.age = age
gus = Cat('Gus', 8)
print(f'{self.name} is {self.age} years old.')
print('%s is %s years old' %(self.name, self.age))
# .format(gus.name, gus.age))
| true |
3e5fa5d0c4a49530370fee0d3060f96243bf4481 | Poligera/Turtle-Crossing-Game-with-Python-and-Turtle | /car_manager.py | 1,077 | 4.15625 | 4 | from turtle import Turtle
import random
COLORS = ["blue", "green", "red", "yellow", "orange", "purple", "brown", "grey"]
MOVE_INCREMENT = 5
MOVE_DISTANCE = 10
class CarManager:
"""Creates a car using a Turtle class and appends it to a list of cars.
The other two methods control car speed"""
def __init__(self):
self.all_cars = []
self.car_speed = MOVE_DISTANCE
def create_car(self):
# A counter to reduce frequency of cars appearing on the screen later on, so it's approx. 1 every 6 loops:
random_chance = random.randint(1, 6)
if random_chance == 1:
new_car = Turtle("square")
new_car.shapesize(1, 2)
new_car.penup()
new_car.color(random.choice(COLORS))
new_car.goto(300, random.randint(-250, 250))
self.all_cars.append(new_car)
def drive(self):
for car in self.all_cars:
car.back(self.car_speed)
def drive_faster(self):
self.car_speed += MOVE_INCREMENT
self.drive() | true |
9f8f585cb0a86cd34109750d993b578913be934b | AndreeaLoredanaIlie/algorithms | /Stacks_and_Queues/queue.py | 1,420 | 4.3125 | 4 | """
Implements a queue as a linked list
"""
class QueueNode(object):
def __init__(self, data):
# Node element, stores data and "pointer" to next Node.
self.data = data
self.next = None
class Queue(object):
def __init__(self):
self.last = None
self.first = None
# Remove the first item from the stack
def remove(self):
if self.first is None:
raise EmptyQueueException
self.first = self.first.next
if self.first is None:
self.last = None
# Add an item to the last of the stack
def add(self, item):
node = QueueNode(item)
if self.last is not None:
node.next = self.last
self.last = node
if self.first is None:
self.first = self.last
def printList(self):
temp_head = self.first
while temp_head is not None:
print(temp_head.data)
temp_head = temp_head.next
# Return the top of the queue
def peek(self):
if self.first is None:
raise EmptyQueueException
else:
return self.first.data
# Check if queue is empty
def is_empty(self):
return self.first is None
class EmptyQueueException(Exception):
pass
if __name__ == '__main__':
queue = Queue()
queue.add(1)
queue.add(4)
queue.add(6)
queue.printList()
print(queue)
| true |
460f22d4b8cb712191612460040a4f8bd5eb75c2 | WDB40/CIS189 | /Module5/src/average_scores.py | 1,081 | 4.15625 | 4 | """
Program: average_scores.py
Author: Wes Brown
Last date modified: 09/17/19
Purpose: Calculate the average from the list of values instead of passing each
"""
def average(score_list):
total = 0
num_values = len(score_list)
avg_score = -1
if num_values != 0:
for value in score_list:
total = total + value
avg_score = total / len(score_list)
else:
avg_score = 0
return avg_score
def get_test_scores():
INVALID_INPUT = -2
STOP = -1
user_input = 0
scores = []
while user_input != STOP:
try:
user_input = float(input("Enter a score (enter -1 to exit): "))
except ValueError:
user_input = INVALID_INPUT
if user_input != STOP and user_input != INVALID_INPUT:
scores.append(user_input)
return scores
if __name__ == '__main__':
last_name = input("Enter the last name: ")
first_name = input("Enter the first name: ")
avg_scores = average(get_test_scores())
print("%s, %s - %.2f" % (last_name, first_name, avg_scores))
| true |
6ca7ada6438dd1d3f13cfdd064bb4f5a4b967e07 | ArryJ/algorithms | /python/challenges/staircase.py | 821 | 4.375 | 4 | """
Problem Statement:
Your teacher has given you the task of drawing a staircase structure. Being an expert programmer, you decided to make a program to draw it for you instead. Given the required height, can you print a staircase as shown in the example?
Input:
You are given an integer N depicting the height of the staircase.
Output:
Print a staircase of height N that consists of # symbols and spaces. For example for N=6, here's a staircase of that height:
Example:
#
##
###
####
#####
######
Note: The last line has 0 spaces before it.
"""
def printStaircase(nLevels):
for level in range(nLevels):
normalizedLevel = level + 1
spaces = (' ' * (nLevels - normalizedLevel))
octothorpes = ('#' * normalizedLevel)
print(spaces + octothorpes)
printStaircase(6)
| true |
ae2409901c639361d22ab53e1538526edd2743be | AmandaRH07/AulaEntra21_AmandaHass | /Prof01/Aula08/listas/Lista_Exercicios.py | 1,043 | 4.53125 | 5 | # #**LISTAS E METODOS**
#
# **Indexação**
#
# É a forma usada para recuperar parte da lista usando indices.
#
# lista[ inicio : fim ]
#
# Inicio: Inicio da lista, começa com 0
# Fim: Fin da lista.
# Lembrando que pega o valor anterior.
# Comandos:
# lista.append() = adicionar na ultima posição
# lista.insert(index,elemento) = adicionar na posição escolhida
# ultimo = lista.pop() = retirar o ultimo elemento e retornar
# lista.remove() = remover o primeiro elemento indexado
# lista.sort() = ordenar os elementos da lista em order crescente
# lista.revert() = inverte os elementos da lista
lista = [6,7,8,9,10,11,12,13]
# Pegando o primeiro elemento
print(lista[0])
# Pegando o terceio elemento
print(lista[2])
# Pegando o último elemento
print(lista[-1])
# Pegar todos os números a partir do terceio elemento
print(lista[2:])
# Pegando o número 7 a 10
print(lista[1:5])
# Sabia que isso também funciona com strig!
texto = "Atirei o pau no gato"
print(texto[2])
print(texto[2:10])
| false |
ae7769224fca90c91bfe80817529a48fc53966b8 | AmandaRH07/AulaEntra21_AmandaHass | /Prof01/Aula10/exercicios/exercicio02.py | 933 | 4.375 | 4 | """Exercício 02
O id de um cliente é um código único (só aquela pessoa tem) composto
por números inteiros que inicia do número 1 e vai aumentando de 1 em 1 enquanto for necessário.
Exemplo:
id: 1
Nome: Dudu
id: 2
Nome: Marta
id: 3
Nome: Pedro
ATENÇÃO!!!!
O id é um número atribuido automáticamente! O cliente não escolhe o número. O seu programa deve fazer o cadastro deste id automaticamente.
Com isso, crie um cadastro de clientes que receba o id, nome e idade. Depois mostre os dados dos clientes individualmente.
(cadastre no minimo 4 clientes)
"""
lista_id = []
lista_nome = []
lista_idade = []
for i in range(4):
lista_id.append(i+1)
lista_nome.append(input("Digite o nome: "))
lista_idade.append(int(input("Digite a idade: ")))
print()
tamanho = len(lista_nome)
for i in range(tamanho):
print(f"""
Id: {lista_id[i]}
Nome: {lista_nome[i]}
Idade: {lista_idade[i]}
""")
| false |
c89c7457753c60f85a34ddce10f030e84194c645 | AmandaRH07/AulaEntra21_AmandaHass | /Prof01/Aula10/exercicios/exercicio03.py | 1,663 | 4.375 | 4 | """Exercício 03
3.1) Crie um programa que cadastre o id, nome, sexo e a idade de 5 clientes.
3.2) Depois mostre os dados dos 5 clientes.
3.3) Peça para que o usuário escolha um id de um cliente e mostre as informações deste cliente.
3.4) Crie um filtro que ao digitar um id de um cliente mostre as seguintes informações:
- Para menores de 17 anos: Entrada Proibida
- Para maiores de 17 anos: Entrada Liberada
- Para o sexo Feminino: 50% de desconto
- Para o sexo Masculino: 5% de desconto
"""
lista_id = []
lista_nome = []
lista_sexo = []
lista_idade = []
print("---------Cadastro do Cliente---------")
for i in range(1,6):
lista_id.append(i)
lista_nome.append(input("Digite o nome: "))
lista_sexo.append(input("Digite o sexo (M ou F): "))
lista_idade.append(int(input("Digite a idade: ")))
print()
tamanho = len(lista_id)
for i in range(tamanho):
print(f"""
Id: {lista_id[i]}
Nome: {lista_nome[i]}
Sexo: {lista_sexo[i]}
Idade: {lista_idade[i]}
""")
print("-----------Escolha de um ID-----------")
escolha_Id = int(input("Insira o ID para imprimir a informação dos clientes: "))
for i in range(tamanho):
if escolha_Id == lista_id[i]:
print(f"""
Id: {lista_id[i]}
Nome: {lista_nome[i]}
Sexo: {lista_sexo[i]}
Idade: {lista_idade[i]}
""")
if lista_idade[i] >= 18:
print("Entrada liberada")
else:
print("Entrada proibida")
if lista_sexo[i] == 'f' or lista_sexo[i] == 'f':
print("Desconto de 50%")
else:
print("Desconto de 5%")
print("-------------------------------") | false |
d692048ee8c1a524657f9e9fe9e9c73390b7c538 | Onana1/201Projects | /201/Homeworks/hw6/hw6_part2.py | 989 | 4.5625 | 5 | # File: hw6_part2.py
# Author: Nana Owusu
# Date: 11/21/16
# Section: 29
# E-mail: onana1@umbc.edu
# Description: This program draws a right triangle of a userInput height and
# userInput symbol that the triangle is made up of.
#############################################################
# recurTri() prints out lines of characters to make a right
# triangle
# Input: height; a userInteger that is the height of the triangle
# symbol; character that the triangle is made of
# line; string where the body of the triangle is printed
# Output: None;
def recurTri(height, symbol, line):
if height > 0:
recurTri(height - 1,symbol, line)
while len(line) < height:
line += symbol
print(line)
line = ""
def main():
triHeight = int(input("Please enter the height of the triangle: "))
triSymbol = input("Please enter the symbol to use: ")
triLine = ""
recurTri(triHeight, triSymbol, triLine)
main()
| true |
35f43c635fb00f654760f21e2f4a5419a0977311 | Onana1/201Projects | /201/Homeworks/hw3/hw3_part2.py | 584 | 4.375 | 4 | # File: hw3_part2.py
# Author: Nana Owusu
# Date: 9/28/17
# Section: 29
# E-mail: onana1@umbc.edu
# Description: This program ask the user for two numbers and computes the
# first number to the power of the second.
def main():
numFirst = int(input("Please enter the first number:"))
numSecond = int(input("Please enter the second number:"))
count = 1
numTotal = numFirst
while count < numSecond:
numTotal *= numFirst
count += 1
if numSecond == 0:
numTotal = 1
print(numFirst , "**" , numSecond , "=" , numTotal)
main()
| true |
45a4aefe526c1acc0b03594fdce77e6032d41bda | Onana1/201Projects | /201/Homeworks/hw6/hw6_part3.py | 817 | 4.40625 | 4 | # File: hw6_part3.py
# Author: Nana Owusu
# Date: 11/21/16
# Section: 29
# E-mail: onana1@umbc.edu
# Description: This program counts the number of ears and horns in a line of
# horses and unicorns.
#############################################################
# count() Takes in an integer and returns the total number of
# ears and horns.
# Input: length; userInput, length of the line
# Output: userTotal, total of ears and horns
def count(length):
if length == 0:
return 0
if length % 2 == 0:
return 2 + count(length-1)
else:
return 3 + count(length-1)
def main():
lineLength = int(input("How long is the line of equines? "))
numParts = count(lineLength)
print("In a line of " + str(lineLength) + ", there are " + str(numParts) + " ears and horns.")
main()
| true |
847f9cf8a320872f75cfb0cde57ab0f34a503b3c | Onana1/201Projects | /201/Homeworks/hw6/hw6_part1.py | 983 | 4.1875 | 4 | # File: hw6_part1.py
# Author: Nana Owusu
# Date: 11/21/16
# Section: 29
# E-mail: onana1@umbc.edu
# Description: This program calculates the summation of a number and stops at a
# second number that is userInput.
#############################################################
# numSummation() calculates the summation of a number and
# returns an integer
# Input: num; userInteger as the starting number
# base; userInteger as teh stopping number
# Output: userInteger; returns the sum of the summation
def numSummation(num,base):
if num == base:
return base
else:
return num + numSummation(num-1,base)
def main():
numFrom = int(input("Please input the number you want to sum from: "))
numDown = int(input("Please input the number you want to sum down to: "))
sumNum = numSummation(numFrom,numDown)
print("The summation from " + str(numFrom) + " to " + str(numDown) + " is "+ str(sumNum))
main()
| true |
59ba4fa5afb8906a037c1f049bf6468545006f6a | Onana1/201Projects | /201/Homeworks/hw6/hw6_part6.py | 989 | 4.3125 | 4 | # File: hw6_part6.py
# Author: Nana Owusu
# Date: 11/21/16
# Section: 29
# E-mail: onana1@umbc.edu
# Description: This program generates the levels of Pascal's triangle using
# recursion.
#############################################################
# getValidInput() gets a valid integer based on the users ranges
# Input: userNum; the integer being checked
# minimum; the minimum number that is allowed
# Output: userInt; integer above the minimium
def getValidInput():
#############################################################
# pascal() uses recursion to create each level of Pascal's
# triangle, reaching the requested height
# Input: currLevel; an int, the current level being created
# levelsToMake; an int, the number of levels requested
# levelList; a 2D list of ints, containing the levels
# as they are created
# Output: None (levelList is changed in place, and the updated
# levelList will be the same in main() )
def pascal():
def main():
main()
| true |
dd18ad5792c7b24999ad0c2011ce74ccc168736f | gar-kai/com404 | /TCA/Question7/functions.py | 1,381 | 4.15625 | 4 | def under(word):
print(word)
line = ""
for num in range(0,len(word)):
line = line + "//"
print(line)
def over(word):
line = ""
for num in range(0, len(word)):
line = line + "//"
print(line)
print(word)
def both(word):
line = ""
for num in range(0,len(word)):
line = line + "//"
print(line)
print(word)
print(line)
def grid(word, size):
WordLine = ""
Line = ""
LineLong = ""
for number1 in range(0,len,word):
Line = Line + "//"
for number2 in range(0,size):
LineLong = LineLong + Line +" "
if number2 == size -1:
WordLine =WordLine + words
else:
WordLine = WordLine + word + " | "
for number3 in range(0,size):
print(LineLong)
print(WordLine)
print(LineLong)
def run():
print("Type a word: ")
word=input()
print("Please choose one of the numbers as options shown below")
print("Option 1: under")
print("Option 2: over")
print("Option 3: both")
print("Option 4: grid")
option = int(input())
if option == 1 or "under":
under(word)
elif option== 2:
over(word)
elif option==3:
both(word)
elif option==4:
size = int(input("What size grid?"))
grid(word,size)
else:
print("Invalid option") | true |
fb28b2ccf807b4b13b4935037448ba38fa363c53 | gar-kai/com404 | /1-basics/3-decision/6-counter/bot.py | 606 | 4.21875 | 4 | #Beep is learning about mathematical operators
print("Please enter the first whole number")
number=(input())
print("Please enter the second whole number")
number2=(input())
print("Please enter the third whole number")
number3=(input())
evencount=0
oddcount=0
if int(number) % 2==0:
evencount = evencount +1
else:
oddcount = oddcount +1
if int(number2) % 2==0:
evencount = evencount +1
else:
oddcount = oddcount +1
if int(number3) % 2==0:
evencount = evencount +1
else:
oddcount = oddcount +1
print("There were " + str(evencount) + " even and " + str(oddcount) + " odd numbers.")
| true |
2ddf199dc632458fc0441c9a6d10cde9eda96784 | suprviserpy632157/zdy | /ZDY/Jan_all/pythonbase/January0111/text0111/day0111_test2.py | 814 | 4.1875 | 4 | # 2.已知有列表:
# L=[[3,5,8],10,[[13,14],15,18],20]
# 1)写一个函数print_list(lst)打印出所有的数字
# 如:print_list(L) #3 5 8 10 13 14
# 2)写一个函数sum_list(lst)返回这个列表中所有数字的和
# 如:print_sum(L) # 106
# 注:type(x)可以返回一个变量的类型,
# 如:
# >>>type(20) is int #True
# >>>type([1,2,3]) is list #True
L=[[3,5,8],10,[[13,14],15,18],20]
def print_list(lst,newline=False):
for x in lst:
if type(x) is list:
print_list(x)
else:
print(x,end=" ")
if newline:
print()
print_list(L,True)
def sum_list(lst):
s=0
for x in lst:
if type(x) is list:
s+=sum_list(x)
else:
s+=x
return s
print(sum_list(L))
| false |
132219cfee86f809f2633ddf3664f5cdf9d04e1a | alpineaddict/algorithm-scripts | /bubble_sort.py | 610 | 4.21875 | 4 | #!/usr/bin/env python
"""
Sort an array using the bubble sort algorithm.
"""
def bubble_Sort(arr):
swap_happened = True
while swap_happened:
# print('Bubble sort status: ' + str(arr))
swap_happened = False
for num in range(len(arr) - 1):
if arr[num] > arr[num+1]:
swap_happened = True
arr[num], arr[num+1] = arr[num+1], arr[num]
return(arr)
# xxxxxxxxxxxxxxxxxxxxxx Program execution xxxxxxxxxxxxxxxxxxxxxx
# l = [6,8,1,4,10,7,8,9,3,2,5]
# bubble_Sort(l)
# xxxxxxxxxxxxxxxxxxxxxx End execution xxxxxxxxxxxxxxxxxxxxxx | true |
d1ff44672173927456c3490cf05e5001f828e504 | h-kanazawa/introduction-to-algorithms | /src/insertion_sort.py | 661 | 4.15625 | 4 | # -*- coding: utf-8 -*-
from typing import List
def sort(arr: List[int]) -> List[int]:
"""insertion sort
"""
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i + 1] = arr[i]
i = i - 1
arr[i + 1] = key
return arr
def desc_sort(arr: List[int]) -> List[int]:
"""2.1-2
"""
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] < key:
arr[i + 1] = arr[i]
i = i - 1
arr[i + 1] = key
return arr
if __name__ == '__main__':
print(sort([5, 1, 4, 2, 3]))
| false |
7a879ed49db52faf980e5d9f8345fbca692aa6f0 | tajshaik24/interviews | /ReconstructItinerary.py | 1,280 | 4.1875 | 4 | '''
LeetCode 332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary.
'''
class Solution(object):
def findItinerary(self, tickets):
graph = collections.defaultdict(list)
for x,y in tickets:
graph[x].append(y)
L = len(tickets)
res = ["JFK"]
def dfs(port):
if len(res) == L + 1:
return True
for nex in sorted(graph[port]):
graph[port].remove(nex)
res.append(nex)
if dfs(nex):
return True
else:
graph[port].append(nex)
res.pop()
return False
dfs("JFK")
return res
| true |
7358e2f4c2f8ca5086809f7a629f52a1df22682f | ColibriKBO/ColibriTools | /TimeCompare.py | 1,786 | 4.125 | 4 | """
Filename: TimeCompare
Author(s): Peter Quigley
Contact: pquigle@uwo.ca
Updated: 2022-09-23
Used to measure the difference in timing between several functions
"""
from time import time
##############################
## Timing Single Functions
##############################
def singleFxn(fxn, *args):
"""
A function to measure how long it takes to execute a specific function
Parameters:
fxn (func): The function to be tested
*args (any): The arguments to be used in the test
Returns:
dt (float): Amount of time it took to run the function
with the given parameters
"""
t = time()
fxn(*args)
dt = time() - t
print("Time to run function: {}".format(dt))
return dt
##############################
## Time Compare Functions
##############################
def twoFxn(fxn1, fxn2, *args):
"""
A function to compare the execution time of two functions using the same parameters
Parameters:
fxn1 (func): The first function to be tested
fxn2 (func): The second function to be tested
*args (any): The arguments to be used in the test
Returns:
t1 (float): Amount of time it took to execute fxn1 with the given
parameters
t2 (float): Amount of time it took to execute fxn2 with the given
parameters
dt (float): The difference in execution time between fxn1 and fxn2
"""
## Timing the first function
t = time()
fxn1(*args)
t1 = time() - t
## Timing the second function
t = time()
fxn2(*args)
t2 = time() - t
print("Time to run the first function: {}".format(t1))
print("Time to run the second function: {}".format(t2))
print("Difference in execution time: {}".format(t2-t1))
return t1, t2, t2-t1
| true |
2849fdd1373b3328ed77ff91aceb837f7cf9b110 | rdm750/rdm750.github.io | /python/regex_data_files.py | 1,288 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
uses regex pattern to get data from text file using optional match and capture groups
example extract 'ABCD07' and '80' from the following line in file
.
.
.
ABCD0 0 1 4 833 0 0 0 5 0 41 -
ABCD1 0 1 5 860 0 0 0 5 0 43 -
ABCD2 0 1 8 858 0 0 0 5 0 43 -
ABCD3 0 1 9 858 0 0 0 5 0 43 -
.
.
.
extracts ABCD01 41, ABCD1 43 from above lines...
regexpattern:r'(ABCD\d{1,2})(:?\s+\d+){9}(\s+\d{1,2})'
tested at http://pythex.org/
www.regexpal.com
'''
import os
import re
test1= open("test12","w")
dr1=os.getenv("HOME")+'/Downloads/test'
for (dirname, dirs, files) in os.walk(dr1):
for fil in files:
print fil
fileop=open(dr1+"/"+fil,"r")
test1.write(fil+'\n')
for linerd in fileop:
regexpat=r'(VPPA\d{1,2})(:?\s+\d+){9}(\s+\d{1,2})'
#regexpat=r'(\w+)(:?\s+\d+)+(\s+\d{1,2})'
match = re.findall(regexpat,linerd)
for mat in match:
print mat
test1.write(' '.join(mat)+'\n')
test1.write('\n')
print len(match),'***********************'
fileop.close()
test1.close()
| true |
cd67d8e33b83501b5de8cf4083c96fcfe18b8e5d | fedcalderon/python1-Midterm | /src/randomizing_factors.py | 2,410 | 4.3125 | 4 | from random import seed
from random import randint
def get_random_total_num_voters():
"""
This function obtains a random number which represents
the population who voted.
:return: random sample of voters
"""
min_num_people_who_voted = 1_000
max_num_people_who_voted = 10_000
seed(randint(1, 17))
value = randint(min_num_people_who_voted, max_num_people_who_voted)
return value
def get_random_number(population):
"""
For the purpose of this exercise, only 4 types of parties are considered. However, this is theoretical and does
not correlate with actual historical data. This function must be modified in order to provide a historically
accurate type of vote.
This method generates a random number list which represents votes for a party.
0: democrat
1: republican
2: libertarian
3: independent
4: invalid
:return: a list of random numbers between 0 and 4
"""
percent_factor = 0.95
majority = int(population * percent_factor)
minority = population - majority
#print(majority)
#print(minority)
majority_vote_list = get_majority_votes(majority)
minority_vote_list = get_minority_votes(minority)
zeroes = 0
ones = 0
for m in majority_vote_list:
if m == 0:
zeroes += 1
elif m == 1:
ones += 1
#print(f"democrats={zeroes}")
#print(f"republicans={ones}")
twos = 0
threes = 0
fours = 0
for m in minority_vote_list:
if m == 2:
twos += 1
elif m == 3:
threes += 1
elif m == 4:
fours += 1
#print(f"independent={twos}")
#print(f"libertarians={threes}")
#print(f"invalid={fours}")
# print(majority_vote_list)
# print(minority_vote_list)
votes = []
votes = majority_vote_list + minority_vote_list
return votes
def get_majority_votes(population):
votes = []
seed()
min_value_possible = 0
max_value_possible = 1
for _ in range(population):
value = randint(min_value_possible, max_value_possible)
votes.append(value)
return votes
def get_minority_votes(population):
votes = []
seed()
min_value_possible = 2
max_value_possible = 4
for _ in range(population):
value = randint(min_value_possible, max_value_possible)
votes.append(value)
return votes | true |
0448dadf3266b1d45f449a49379e9e5dc289b921 | B-Rich/python3-excercises | /python3_recursive_functions/problem-6.py | 765 | 4.125 | 4 | """
Write a recursive function find_index(), which returns the index of a number in the Fibonacci sequence, if the number is an element of this sequence and returns -1 if the number is not contained in it, i.e.
# # # # # # # # # # # # # # # # # # #
# Not sure what that is asking for #
# # # # # # # # # # # # # # # # # # #
"""
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(x):
"""
(int) -> int
return fibonacci for int
"""
if(x <= 1):
return x
return fibonacci(x-1) + fibonacci(x-2)
def find_index(x, guess = 1):
"""
(int) -> int
return index of a fibonacci sequence
"""
while(x >= fibonacci(guess)):
guess += 1
return [fibonacci(i) for i in range(guess)]
print(fibonacci(10))
print(find_index(13))
| true |
cbd194d06baeed2d655f82b41169ae62077046ed | stolk/ZeroToSnake | /snake2.py | 1,476 | 4.125 | 4 | #!/usr/bin/python
#
# snake2.py adds a snake to the board.
import curses
# Our snake lives in a world of 15 rows of 25 characters.
world = [
"+-----------------------+",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"+-----------------------+",
]
# Our snake is defined as a list of coordinates (row,col) where its body is.
# We start as a snake of lenght 3, traveling to the right.
snake_body = [
( 7,7 ), # The head on the right.
( 7,6 ),
( 7,5 ), # The tail on the left.
]
def draw_board( screen, board ) :
for linenr, row in enumerate( board ):
line = "".join( row )
screen.addstr( linenr+1, 0, line )
def main( stdscr ):
while True:
stdscr.clear()
stdscr.addstr( 0, 0, "Snake game. Ctrl-C to quit." )
# Build up the board: start with a copy of the empty world.
board = [ list(row) for row in world ]
# Place the snake on our board.
for idx, ( row, col ) in enumerate( snake_body ) :
symbol = '#' if idx > 0 else 'O'
board[ row ][ col ] = symbol
# Now that we have set up the board, we should draw it on screen.
draw_board( stdscr, board )
stdscr.refresh()
curses.wrapper(main)
| false |
a3bb0b793ba57aaf3e488a005da42d04cf74aab1 | jamesrmuir/python-workbook | /commonFunctions.py | 521 | 4.15625 | 4 | def int_input(string):
while True:
try:
number = int(input(string))
break
except ValueError:
print("Enter numerical value.")
except:
print("I'm speechless...")
return number
def float_input(string):
while True:
try:
number = float(input(string))
break
except ValueError:
print("Enter numerical value.")
except:
print("I'm speechless...")
return number
| true |
46802d85b2d2b8d41ae1096896a678037faa5d75 | sarojbhatta/OCWIntroPython | /ps0.py | 451 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Write a program that does the following in order:
1. Asks the user to enter a number “x”
2. Asks the user to enter a number “y”
3. Prints out number “x”, raised to the power “y”.
4. Prints out the log (base 2) of “x”.
"""
import numpy
x = int(input("Enter number x:"))
y= int(input("Enter number y:"))
powval = x**y
print("X**Y = " + str(powval))
logval = numpy.log2(x)
print("log(x) = " + str(logval)) | true |
4a91163abd222c3c2b878135db70b071783371bb | sjsawyer/algorithms | /backtracking/sublists.py | 1,150 | 4.1875 | 4 | def get_sublists(l):
'''
Generate all possible sublists of the list `l`
>>> sublists([1, 2, 3])
[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
'''
# List to store all sublists
all_sublists = []
def _get_sublists(sublist, i):
'''
Generate all sublists of `l` that begin with a fixed sublist of
l[0,..,i-1] fixed in `sublist`.
'''
if i == len(l):
# No elements of `l` left to use
# Note we must make a copy of our sublist else each
# sublist in `all_sublists` will be the same object
sublist_copy = list(sublist)
all_sublists.append(sublist_copy)
else:
# We either use the item at `l[i]` or we don't
sublist.append(l[i])
_get_sublists(sublist, i+1)
sublist.pop()
_get_sublists(sublist, i+1)
# Populate all_sublists
_get_sublists([], 0)
return all_sublists
def main():
l = [1, 2, 3]
sublists = get_sublists(l)
for sublist in sublists:
print sublist
if __name__ == '__main__':
main()
| true |
da505004c48b8a33a6636db3ce2f0ae9ba3ef113 | sjsawyer/algorithms | /recursion/weave.py | 1,903 | 4.25 | 4 | '''
Q: "Weave" two lists together `a` and `b` together in all possible ways such that
in the produced list `l`, we always have that l.index(a[i]) < l.index(a[i+1]).
In other words, the ordering of the elements in a and b are maintained in the new
list.
For instance, weave([1, 2], [3, 4]) produces the following lists:
[1, 2, 3, 4]
[1, 3, 2, 4]
[1, 3, 4, 2]
[3, 4, 1, 2]
[3, 1, 2, 4]
[3, 1, 4, 2]
Note that this routine can come up as a subroutine in other algorithms. For
example, when considering all possible ordering of elements that can
produce a given binary tree.
'''
def weave(a, b):
'''
Return all possible "weaves" of the lists `a` and `b`, where a weave is
defined above
'''
all_weaves = []
def _weave(prefix, a_remaining, b_remaining):
'''
Produce all possible weave that begin with the elements in `prefix`,
with the remaining elements in `a` and `b` given in `a_remaining`
and `b_remaining`
'''
if not a_remaining or not b_remaining:
all_weaves.append(prefix + a_remaining + b_remaining)
return
# recurse by taking the first element from the remainder of a,
# and then the first element from the remainder of b
for l in (a_remaining, b_remaining):
# l is a reference
prefix.append(l.pop())
_weave(prefix, a_remaining, b_remaining)
# backtrack
l.append(prefix.pop())
# because we are treating a and b as stacks, we must call our recursive
# function with a and b reversed so we can pop from the "beginning"
_weave([], list(reversed(a)), list(reversed(b)))
return all_weaves
def main():
a = [1, 2]
b = [3, 4]
weaves = weave(a, b)
for w in weaves:
print w
if __name__ == '__main__':
main()
| true |
d3c38ffeecaddc4b4c961f63d1598e9fd64923a4 | sjsawyer/algorithms | /graphs/vertex_coloring.py | 2,202 | 4.1875 | 4 | def vertex_coloring(graph, m):
'''
Try to color the vertices of the graph `graph` using `m` colors so that no
two adjacent vertices are of the same color. If possible, returns a
coloring for the vertices. If not possible, returns None.
Note: `graph` is in adjacency list format, where the keys of `graph` are
the nodes in the graph, and the values are sets containing the adjacent
nodes in the graph.
'''
# available colors
colors = set(range(1, m+1))
# Store the colors of each vertex
# 0 will indicate no color, and 1, 2, ..., m will represent the colors
color_dict = {}
for node in graph:
color_dict[node] = 0
# attempt to color the vertices in an arbitrary order
vertices = graph.keys()
def _color_vertex(graph, color_dict, vertices, idx):
'''
Check if there is a way to color the `graph` using vertices that have
already been successfully colored in `color_dict`, considering the
vertex at `vertices[idx]`
Coloring is done in the order of `vertices`, so we are done when `idx`
is equal to the length of `vertices`.
'''
if idx == len(vertices):
# We have colored all vertices
return color_dict
# current vertex
vertex = vertices[idx]
# We try to color the next vertex
used_colors = set(color_dict[neighbour] for neighbour in graph[vertex]
if color_dict[neighbour])
available_colors = colors.difference(used_colors)
for color in available_colors:
color_dict[vertex] = color
coloring = _color_vertex(graph, color_dict, vertices, idx+1)
if coloring is not None:
return coloring
# a coloring was not possible with this choice, try next color
continue
# we were not able to color the vertex, backtrack
color_dict[vertex] = 0
return None
# Start the coloring from `vertices[0]`
return _color_vertex(graph, color_dict, vertices, 0)
def main():
from sample_graphs import g1
print vertex_coloring(g1, 3)
if __name__ == '__main__':
main()
| true |
66a28248645f0baba30eb1213cc230ae925c434f | Swathi-16-oss/python- | /celsius to fahrenheit.py | 464 | 4.15625 | 4 | celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
'''o/p:
37.5 degree Celsius is equal to 99.5 degree Fahrenheit'''
celsius=float(input("enter the temperature in celsius"))
# calculate fahrenheit
fahrenheit = float(celsius * 1.8) + 32
print("'%0.1f'fahrenheit" %(fahrenheit))
'''o/p:
enter the temperature in celsius37.5
'99.5'fahrenheit'''
| false |
8922ede05177fa70d59e5f3828167986f5ed8543 | idanrk/idanrk-ieeextreme-challenges | /CSAcademy/Blackgate Penitentiary/Blackgate.py | 966 | 4.15625 | 4 | #Challenge Link: https://csacademy.com/ieeextreme-practice/task/8761fb7efefcf1d890df1d8d91cae241/statement/
# a simple parser for python. use get_number() and get_word() to read
def parser():
while 1:
data = list(input().split(' '))
for number in data:
if len(number) > 0:
yield(number)
input_parser = parser()
def get_word():
global input_parser
return next(input_parser)
def get_number():
data = get_word()
try:
return int(data)
except ValueError:
return float(data)
n = get_number()
heights = {}
for _ in range(n):
name, height = get_word(), get_number()
if height not in heights.keys():
heights[height] = [name]
else:
heights[height].append(name)
heights = dict(sorted(heights.items()))
mini = 1
maxi=0
for val in heights.values():
for name in sorted(val):
print(name, end=' ')
maxi+=1
print(mini, maxi)
mini=maxi+1 | true |
3fe2171fe483fbbab7b37384ec0034559a90bf76 | morteza404/code_wars | /mid_char.py | 749 | 4.34375 | 4 | """
https://www.codewars.com/kata/56747fd5cb988479af000028/train/python
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
#Examples:
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
"""
a = "abc"
# def get_middle(a):
# ln = len(a)
# mid = ln // 2
# if ln % 2 == 0:
# return a[mid-1:mid+1]
# else:
# return a[mid]
def get_middle(s):
return s[(len(s)-1)//2:len(s)//2+1]
print(get_middle(a)) | true |
34a9201993106c7b0a276c611d0fd2ee95d6d68e | morteza404/code_wars | /UniqueOrder.py | 670 | 4.15625 | 4 | """
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3]) == [1,2,3]
"""
def unique_in_order(input_iterable):
out = [input_iterable[0]]
for i in range(1,len(input_iterable)):
if input_iterable[i] != input_iterable[i-1]:
out.append(input_iterable[i])
return out
| true |
8dc00f8f4122405c32ff58484299b45846af4273 | sibtainmasih/techguild | /learning_python3/workshop_june2020/format_time.py | 430 | 4.125 | 4 | """
Refactor Code Example
"""
total_seconds = int(input("Enter total seconds: "))
hours = str(int(total_seconds / 3600))
minutes = str(int(total_seconds / 60) % 60)
seconds = str(total_seconds % 60)
if len(minutes) < 2 and hours != "0":
minutes = "0" + minutes
if len(seconds) < 2:
seconds = "0" + seconds
time = minutes + ":" + seconds
if hours != "0":
time = hours + ":" + time
print(f"Formatted Time = {time}")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.