blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8651baed10580c8ca5dc1e4345cd019aa599c413 | ItsSamarth/ds-python | /basics.py | 2,114 | 4.125 | 4 | print('hello world')
print('Enter your name')
x=input()
print('Hello '+x)
# IDENTITY OPERATORS
x=["apple", "banana"]
y=["apple", "banana"]
z=x;
print(z is x) #returns true cause both object are same
print(x is y) #returns false cause objects are not same even if the contents are same
# MEMEBERSHIP OPERATORS
# it is used to check the sequence is present in the list or not
print('banana' in x)
# COLLECTIONS
#list simple
theList=["item1", "item2"]
print(theList[1])
#The list constructors
list2 =list(("samarth", "pearl", "slayer"))
print(list2)
list2.append("swapnil") #appending data to the list2
print(list2)
list2.remove("pearl") #removing data from the list
print(list2)
print(len(list2)) #length of list2
print(len(theList))
theList.append("we can append data to the normal list as well")
print(theList)
#other list methods are - clear() , copy(), count(), extend(), index(),insert(), pop(), remove(), reverse(), sort()
print(list2.index("swapnil"))
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
print(cars)
#LOOPS
#The for iterator LOOPS (strings , lists , tuples)
fruits=['apple', 'banana', 'cherry']
for x in fruits:
print(x)
#for numbers
for x in range(6):
print(x)
for x in range(20,30):
print(x)
for num in range(50,100,5): #for loop with 3 increment
print(num)
#RECURSION
def tir_recursion(num):
if(num>0):
result = num + tir_recursion(num-1)
print(result)
else:
result=0
return result
print("Recursion example results")
tir_recursion(50)
#LAMBDA FUNCTIONS
#lambda is used to create anonymous funtions it is the functions with no predefined names
#Good for- constructing adaptable functions, event handling
myfunc = lambda i: i**i
print(myfunc(2))
#power of lambda is better shown when you generate anonymous function at run-time
def myfunc(n):
return lambda i: i*n
double= myfunc(2)
triple= myfunc(3)
value=11
print("Doubled: " + str(double(value)) + " Tripled " + str(triple(value)))
| true |
c4fac4f8bf3de9ec76d99ba13b80753c8b1fda89 | ItsSamarth/ds-python | /itertoolsProduct.py | 493 | 4.28125 | 4 | # itertools.product()
# This tool compute the cartesian product of input tables
#Ex- product(a,b) is same as ((x,y) for x in A for y in B)
from itertools import product
print (list(product([1,2,3],repeat = 2)))
print( list(product([1,2,3],[3,4])))
A=[[1,2,3] , [3,4,5]]
print(list(product(*A)))
B = [[1,2,3],[3,4,5],[7,8]]
print(list(product(*B)))
# Taking Input from list
a = list(map(int, input().split()))
# multiple ways to print
print(*product(a,b))
print(*itertools.product(A,B))
| true |
726d2f475d3788241d2c92d7a3d8e89ebad366e2 | suryandpl/UberPreparationPrograms | /alok-tripathi-workplace/set3/p9.py | 782 | 4.25 | 4 | '''
Problem : Find all the palindromic string in the given Input
Suppose we have a string; we have to count how many palindromic substrings present in this string.
The substrings with different start indices or end indices are counted as different substrings even
they consist of same characters. So if the input is like “aaa”, then the
output will be 6 as there are six palindromic substrings like “a”, “a”, “a”, “aa”, “aa”, “aaa”
Malyalam --
'''
class Solution:
def countSubstrings(self, s):
counter = 0
for i in range(len(s)):
for j in range(i+1,len(s)+1):
temp = s[i:j]
if temp == temp[::-1]:
counter+=1
return counter
ob1 = Solution()
print(ob1.countSubstrings("malyalam")) | true |
e1f39be794c4980b926365cc6cb6ace4b5a5f189 | jivakalan/LeetCoding | /judgeCircle.py | 1,657 | 4.1875 | 4 |
# =============================================================================
# 657. Robot Return to Origin
# There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.
#
# The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.
#
# Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
#
# Example 1:
#
# Input: moves = "UD"
# Output: true
#
#Example 2:
#Input: moves = "LL"
#Output: false
# =============================================================================
#10:20
#10:26-accepted/submitted
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
x_axis = 0
y_axis = 0
for letter in moves:
if letter =='U':
x_axis += 1
if letter =='D':
x_axis = x_axis - 1
if letter =='R':
y_axis += 1
if letter =='L':
y_axis = y_axis - 1
if x_axis == 0 and y_axis ==0:
return True
else:
return False
a=Solution()
a.judgeCircle(moves ="LL")
| true |
d2c6e1f3c915fa8e6a61ea20567c7a8e45b19101 | nainireddy/python | /excercises/apple_circles_program.py | 2,790 | 4.4375 | 4 | import math
'''
Method to identify overlapping circles from the two input circles provided as input
'''
def overlap(circle1, circle2):
x1,y1,r1 = circle1
x2,y2,r2 = circle2
width = abs(x1-x2)
height = abs(y1-y2)
tuplex = tuple((0,0,0))
distance = math.sqrt(width**2 + height**2)
if distance <= (r1 + r2):
return circle1, circle2
return 0
'''
Method to calculate area of circle to determine biggest circle in overlapping circles
'''
def area_circle(circle):
x1,y1,r1 = circle1
area = math.pi*r1**2
return area
'''
Method to create a key lambda function to sort of largest radius circle
'''
def getkey(tuple1):
return tuple1[2]
'''
Method to take list of arguments as circles and remove overlapping circles.
'''
def cricle_cluster(*args):
circles = []
overlap_circles = []
nonoverlap_circles = []
output_circles = []
# Since the input arguments can be any number, *args let us provide dynamic input. Function populates circles list
for circle in args:
circles.append(circle)
#going over the loop and checking each circle with over to find the overlapping circles
for i in range(len(circles)):
for j in range(i+1, len(circles)):
overlap_circle = overlap(circles[i],circles[j])
if overlap_circle:
for element in overlap_circle:
overlap_circles.append(element)
# remove overlapping circles from the circles list, gives non-overlap circle list
for element in circles:
if element not in overlap_circles:
nonoverlap_circles.append(element)
#Following code will give the list of overlapping circles with the biggest circle as first element
overlap_circles = list(set(overlap_circles))
overlap_circles = sorted(overlap_circles, key = getkey, reverse=True)
if overlap_circles and nonoverlap_circles:
output_circles = [(element) for element in nonoverlap_circles]
output_circles.append(overlap_circles[0])
output_circles.sort()
return output_circles
elif nonoverlap_circles:
output_circles = [(element) for element in nonoverlap_circles]
return output_circles
else:
output_circles.append(overlap_circles[0])
return output_circles
c1 = (0.5,0.5,0.5)
c2 = (1.5,1.5,1.1)
c3 = (0.7,0.7,0.4)
c4 = (4,4,0.7)
c5 = (1.5,1.5,1.3)
c6 = (1,3,0.7)
c7 = (2,3,0.4)
c8 = (3,3,0.9)
#First condition
print cricle_cluster(c1,c2,c3,c4)
#second condition
print cricle_cluster(c5,c4)
#Third condition
print cricle_cluster(c6,c7,c8)
#Final condition where all the circles put together
#print cricle_cluster(c1,c2,c3,c4,c5,c6,c7,c8)
| true |
e0de6d81484ad10793d857ea91bacf5c05e130af | Felipev98/Ejercicios | /Ejercicios__Complementarios/Ejercicio15.py | 302 | 4.125 | 4 | #Ingresar un número y mostrar si es positivo,negativo o 0
numero = float(input('Ingrese un número: '))
if numero > 0:
print(f'{numero} es un número positivo')
elif numero < 0:
print(f'{numero} es un número negativo')
else:
print('Usted a ingresado un 0')
| false |
fff54c1b5aa575e3ecab67a8e86926ef91aa1ab9 | Timelomo/leetcode | /88 Merge Sorted Array.py | 611 | 4.125 | 4 | """
直接字符串拼接 然后sort
"""
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
# nums1 = nums1[0:m] + nums2[0:n]
nums1[m:len(nums1)] = nums2[0:n]
nums1.sort()
# return nums1
def main():
result = Solution().merge(nums1 = [1,2,3,0,0,0], m = 3,nums2 = [2,5,6],n = 3)
print(result)
return result
if __name__ == '__main__':
main()
| false |
2b4056aeff6d2f752f4fe454c2fe179ce4ee0bb5 | Pyk017/Python | /InfyTQ(Infosys_Platform)/Fundamentals_of_Python_Practise_Problems/Level1/Problem-3.py | 728 | 4.125 | 4 | """
Write a Python function to create and return a new dictionary from the given dictionary(item:price).
Given the following input, create a new dictionary with elements having price more than 200.
Sample Input :
{'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}
{'Mango': 150.45, 'Pomegranate': 250.67, 'Banana': 20.55, 'Cherry': 500.10, 'Orange': 200.75}
Sample Output :
{'AAPL': 612.78, 'IBM': 205.55}
{'Orange': 200.75, 'Cherry': 500.10, 'Pomegranate': 250.67}
"""
def new_dictionary(prices):
new_dict = {i: j for i, j in prices.items() if j > 200}
return new_dict
dictionary = {'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}
print(new_dictionary(dictionary))
| false |
6a325e7c25526dd5508b468da6bbe012439b3096 | Pyk017/Python | /DataStructure/QueueLinkedListImplementation.py | 2,899 | 4.25 | 4 | <<<<<<< HEAD
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def insert(self,data):
newNode = Node(data)
if self.front is None:
self.front = self.rear = newNode
else:
self.rear.next = newNode
self.rear = newNode
def delete(self):
if self.front is None:
print("Stack UnderFlow!")
else:
pNode = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
del pNode
def display(self):
pNode = self.front
while(pNode is not None):
print (pNode.data, end=" ")
pNode = pNode.next
queue = Queue()
while(True):
choice = int(input(
"Enter choice : \n Press 1 to Insert element in the Queue.\n Press 2 to delete element from the Queue.\n Press 3 to display the Queue.\n Press 0 to exit Immediately."))
if choice == 1:
queue.insert(int(input("\nEnter element to be Inserted in the Queue.")))
print("Operation Completed!\n")
elif choice == 2:
queue.delete()
print("\nOperation Completed!")
elif choice == 3:
print(queue.display())
elif choice == 0:
break
else:
=======
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def insert(self,data):
newNode = Node(data)
if self.front is None:
self.front = self.rear = newNode
else:
self.rear.next = newNode
self.rear = newNode
def delete(self):
if self.front is None:
print("Stack UnderFlow!")
else:
pNode = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
del pNode
def display(self):
pNode = self.front
while(pNode is not None):
print (pNode.data, end=" ")
pNode = pNode.next
queue = Queue()
while(True):
choice = int(input(
"Enter choice : \n Press 1 to Insert element in the Queue.\n Press 2 to delete element from the Queue.\n Press 3 to display the Queue.\n Press 0 to exit Immediately."))
if choice == 1:
queue.insert(int(input("\nEnter element to be Inserted in the Queue.")))
print("Operation Completed!\n")
elif choice == 2:
queue.delete()
print("\nOperation Completed!")
elif choice == 3:
print(queue.display())
elif choice == 0:
break
else:
>>>>>>> Python repo committed
print("Invalid Inputs.") | true |
180840d5b26e04e90effae58101662307363beb4 | Pyk017/Python | /InfyTQ(Infosys_Platform)/InfyTQ_Fundamental_Python_Assignment30.py | 874 | 4.28125 | 4 | # Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run.
# Write a python function which performs the run length encoding for a given String and returns the run length encoded String.
'''
Sample Input :- AAAABBBBCCCCCCCCA
Output :- 4A4B8C1A
'''
def encode (message):
if len(message) == 1:
return str(1) + message
count = 0
digit = []
for i in range(len(message)-1):
if message[i] != message[i+1]:
digit.append(count+1)
digit.append(message[i])
count = 0
else:
count += 1
digit.append(count+1)
digit.append(message[i+1])
return ''.join(list(map(str, digit)))
string = input("Enter String :- ")
print(encode(string))
| true |
aaa035836e558680f94ac57a54af7841b36e2d19 | Pyk017/Python | /OOPs/Question01.py | 1,252 | 4.53125 | 5 | # 1. Write a program to implement a class to store details related to a Student. The Student class contains the following information of a student.
# rollno
# name
# address
# father name
# age
# contact number
# nationality
# branch
# section
# Then after create an instance of the class and print all the details of a student after assigning the values.
class Student:
def __init__(self,name,rn,add,fname,age,contact,nation,branch,sec):
self.name = name
self.rn = rn
self.add = add
self.fname = fname
self.age = age
self.contact = contact
self.nation = nation
self.branch = branch
self.sec = sec
student = Student("Prakhar Kumar",22771,"Latouche Road","Suresh Kumar",21,8874109902,"Indian","CSE","E")
print("Name is :- {}".format(student.name))
print("Address is :- {}".format(student.add))
print("Roll No. is :- {}".format(student.rn))
print("Father's Name is :- {}".format(student.fname))
print("Age :- {}".format(student.age))
print("Contact Number :- {}".format(student.contact))
print("Nationality :- {}".format(student.nation))
print("Branch :- {}".format(student.branch))
print("Section :- {}".format(student.sec))
| true |
daf01186742902332f4e2edb6f6cb11b25e7967c | Pyk017/Python | /InfyTQ(Infosys_Platform)/Fundamentals_of_Python_Practise_Problems/Level2/Problem-21.py | 832 | 4.375 | 4 | """
Tom is working in a shop where he labels item. Each item is labelled with a number between num1 and num2(both inclusive)
Since Tom is also a natural mathematician, he likes to observe pattern in numbers. Tom could observe that some of these
label numbers are divisible by other label numbers.
Write a Python function to find out those label numbers that are divisible by another number and display how many such
label numbers are there totally.
Note :- Consider only distinct label Numbers. The list of those label Numbers should be considered as a set.
"""
def check_numbers(num1, num2):
num_list = set()
for i in range(num1, num2+1):
for j in range(num1, num2+1):
if i != j and i % j == 0:
num_list.add(i)
return [list(num_list), len(num_list)]
print(check_numbers(2, 20))
| true |
269ad772067d3bf12d70dd4d6ee4dfec88424de0 | Pyk017/Python | /InfyTQ(Infosys_Platform)/Fundamentals_of_Python_Practise_Problems/Level1/Problem-38.py | 898 | 4.4375 | 4 | """
University of Washington CSE140 Mid term 2015
Write a function build_index_grid(rows, columns) that, given a number of rows and columns, creates a list of lists of that shape that includes the 'row,column' of that location.
For example, after the following code is executed: new_index_grid = build_index_grid(4,3)
new_index_grid would contain:
[['0,0', '0,1', '0,2'],
['1,0', '1,1', '1,2'],
['2,0', '2,1', '2,2'],
['3,0', '3,1', '3,2']]
Note that these are strings.
After the following code is executed : small_index_grid = build_new_grid(1, 1)
small_index_grid would contain: [['0, 0']].
"""
def build_index_grid(rows, columns):
result = [[str(i)+','+str(j) for j in range(columns)] for i in range(rows)]
return result
row = 4
col = 3
results = build_index_grid(row, col)
print('Rows: ', row, 'Columns: ', col)
print('The Matrix is :- ', results)
for k in results:
print(k)
| true |
497ba5434719d974c6537d95f6c338d4dbf1d64a | Pyk017/Python | /InfyTQ(Infosys_Platform)/Fundamentals_of_Python_Practise_Problems/Level1/Problem-12.py | 793 | 4.125 | 4 | """
Write a python function to generate and return the list of all possible sentences created from the given lists of
Subject, Verb and Object.
Note: The sentence should contain only one subject, verb and object each.
Sample Input :
subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
Expected Output :
I Play Hockey
I Play Football
I Love Hockey
I Love Football
You Play Hockey
You Play Football
You Love Hockey
You Love Football
"""
def generate_sentences(subjects, verbs, objects):
result = []
for i in subjects:
for j in verbs:
for k in objects:
result.append(i + " " + j + " " + k)
return result
sub = ["I", "You"]
verb = ["love", "play"]
obj = ["Hockey", "Football"]
print(generate_sentences(sub, verb, obj))
| true |
d126de7f8e9d70b0f8a6510b51687929fb3a38ed | billforthewynn/PythonProjects | /46exercises/reverse.py | 396 | 4.5625 | 5 | # Define a function reverse() that computes the reversal of a string.
# For example, reverse("I am testing") should return the string "gnitset ma I".
def reverse(string):
target_string = ''
location = len(string) - 1
while location >= 0:
target_string = target_string + string[location]
location = location - 1
return target_string
print reverse("go hang a salami I'm a lasagna hog")
| true |
830fa80bb3d68de93f71cc9016da934b2a60bfe2 | carloscobian96/CSI-Python-2021 | /Modules/Module2/HelloWorld.py | 307 | 4.15625 | 4 | from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
name = input("Hello there! What is your name? ")
studentId = input("What is your student id? ")
print(f"Hello {name}! ")
print(f"Your Student id is: {studentId} ")
print(f"Currently, the time is: {current_time} ") | true |
c0398831a218118c65e2c35157531fdd1c38f1e1 | hjh0915/study-python | /demo22.py | 1,582 | 4.1875 | 4 | def find_two_smallest_01(L):
"""(list of float) -> tuple of (int, int)
Return a tuple of the indices of the two smallest values in list L.
>>> find_two_smallest([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
(6, 7)
"""
x = min(L)
min1 = L.index(x)
L.remove(x)
y = min(L)
min2 = L.index(y)
L.insert(min1,x)
if min1 <= min2:
min2 += 1
return (min1, min2)
def find_two_smallest_02(L):
"""(list of float) -> tuple of (int, int)
Return a tuple of the indices of the two smallest values in list L.
>>> find_two_smallest([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
(6, 7)
"""
list1 = sorted(L)
a = list1[0]
b = list1[1]
min1 = L.index(a)
min2 = L.index(b)
return (min1, min2)
def find_two_smallest_03(L):
"""(list of float) -> tuple of (int, int)
Return a tuple of the indices of the two smallest values in list L.
>>> find_two_smallest([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
(6, 7)
"""
if L[0] < L[1]:
min1, min2 = 0, 1
else:
min1, min2 = 1, 0
for i in range(2, len(L)):
if L[i] < L[min1]:
min2 = min1
min1 = i
elif L[i] < L[min2]:
min2 = i
return (min1, min2)
if __name__ == '__main__':
print find_two_smallest_01([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
print find_two_smallest_02([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
print find_two_smallest_03([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
| true |
92496627913e9762b025c605f6dcb0905b5804c5 | hjh0915/study-python | /demo42.py | 1,049 | 4.1875 | 4 | def build_username_to_mention_count(tweet_list):
""" (list of str) -> dict of {str: int}
Return a dictionary where each key is a username mentioned in tweet_list
and each value is the total number of times this username was mentioned in
all of the tweets in tweet_list.
>>> tweets = ['hi @me and @you', '@me yesterday', 'i saw @you', '@yo @you there']
>>> d = build_username_to_mention_count(tweets)
>>> d == {'yo': 1, 'me': 2, 'you': 3}
True
"""
d = {}
for sentence in tweet_list:
words = sentence.split()
# y = ['hi', '@me', 'and', '@you']
for word in words:
if word.startswith('@'):
username = word[1:]
if username in d:
d[username] = d[username] + 1
else:
d[username] = 1
return d
if __name__ == '__main__':
tweets = ['hi @me and @you', '@me yesterday', 'i saw @you', '@yo @you there']
print build_username_to_mention_count(tweets)
| true |
d0ad87b564661e1408e61dcab49977b853460126 | zarayork/hort503 | /Assignment03/ex18.py | 1,087 | 4.34375 | 4 | # this one is like your scripts with argv
#Set a definition to print two arguments.
def print_two(*args):
#Assign arguments.
arg1, arg2 = args
#Print a string that states what the arguments are.
print(f"arg1: {arg1}, arg2: {arg2}")
# ok, that *args is actually pointless, we can just do this
#Define a function to assign and print two arguments.
def print_two_again(arg1, arg2):
#Print a string that states what the arguments are.
print(f"arg1: {arg1}, arg2: {arg2}")
# this just takes one argument
#Define a function to assign and print one argument.
def print_one(arg1):
#Print a string that states what the argument is.
print(f"arg1: {arg1}")
# this one takes no arguments
#Define what to print when there are no arguments.
def print_none():
#Print a string.
print("I got nothin'.")
#Run the two-argument, two-assigning-steps function.
print_two("Zed","Shaw")
#Run the two-argument function.
print_two_again("Zed","Shaw")
#Run the single argument function.
print_one("First!")
#Run the function that does not have an argument.
print_none()
| true |
0c74b501b60b05d183a6413a42f78c5138f21dd3 | Andrea227/dailyexercise | /HW7/HW7-Richardson-rounding.py | 1,055 | 4.4375 | 4 | import math
import numpy as np
# Since it is a continuation of the book example, as they are using
# forward difference formula, we will continue using forward formula
n1 = 3
xp = float(eval(input("What's your approximation point: ")))
hp = float(eval(input("What's your step size: ")))
f1 = lambda x: (2 ** x) * (math.sin(x))
f2 = lambda x: (x ** 3) * (math.cos(x))
def richard3(x, f, h, n):
Dh = np.zeros((n, n))
for i in range(0, n):
h1 = h / (2 ** i)
Dh[i][0] = round((1 / h1) * (round(f(x + h1), ndigits=4) - round(f(x), ndigits=4)), ndigits=4)
for j in range(1, n):
Dh[j][1] = round(Dh[j][0] + round((1 / 3) * (round(Dh[j][0] - Dh[j - 1][0], ndigits=4)), ndigits=4), ndigits=4)
Dh[2][2] = round(Dh[2][1] + round((1 / 15) * round((Dh[2][1] - Dh[1][1]), ndigits=4), ndigits=4), ndigits=4)
return print(Dh)
np.set_printoptions(precision=4, suppress=True, floatmode='fixed')
print("As the book example doing, we will use forward difference")
print("The extrapolation table is")
richard3(xp, f2, hp, n1)
| true |
194761283baa8f30459d933f68703990a03f21ae | Angin-96/Python | /src/first _month/task 1.2.1.py | 451 | 4.21875 | 4 | #Write a Python program to get the largest number from a list.
s=[1,56,8,96,5,86,23,74,6,8]
s.sort()
f=s[-1]
print(f)
#Write a Python program to get the frequency of the given element in a list to.
s=[1,2,3,5,5,6,7,8,5]
d=s.count(5)
print(d)
#Write a Python program to remove the second element from a given list, if we know that the first elements index with that value is n.
s=[1,2,3,4,1,5,6,1]
a=s.index(1,2)
print(a)
d=s.pop(a)
print(d)
| true |
2e5fb6ca31c7ce681f8f59eea6b4ce92ba731cd8 | lukeaparker/data-struct-algos | /sorting_algos/sorting_recursive.py | 2,820 | 4.375 | 4 |
#!python
from sorting_iterative import bubble_sort
from sorting_iterative import is_sorted
def merge(items1, items2, new_list):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order."""
if len(items1) == 0:
return new_list + items2
elif len(items2) == 0:
return new_list + items1
elif items1[0] <= items2[0]:
new_list.append(items1[0])
items1.pop(0)
return merge(items1, items2, new_list)
elif items1[0] >= items2[0]:
new_list.append(items2[0])
items2.pop(0)
return merge(items1, items2, new_list)
# items1 = [1, 2, 3, 4]
# items2 = [1, 2, 3, 4]
# sorted = merge(items1, items2, [])
# print(sorted)
def split_sort_merge(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each with an iterative sorting algorithm, and merging results into
a list in sorted order."""
mid = int(len(items) / 2)
items1 = items[:mid]
items2 = items[mid:]
new_list = merge(bubble_sort(items1), bubble_sort(items2), [])
return new_list
# items = [1, 8, 3, 7, 28, 100, 1032, 234, 839, 425]
# result = split_sort_merge(items)
# print(result)
def merge_sort(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each recursively, and merging results into a list in sorted order."""
if len(items) == 1:
return items
elif items != 1:
mid = int(len(items) / 2)
items1 = merge_sort(items[:mid])
items2 = merge_sort(items[mid:])
return merge(items1, items2, [])
# items = [20, 3, 34, 326, 345, 765, 35, 1]
# result = merge_sort(items)
# print(result)
def partition(items, low, hi):
pivot = items[low]
li = low + 1
hi = hi
while True:
while li <= hi and items[hi] >= pivot:
hi = hi - 1
while li <= hi and items[li] <= pivot:
li = li + 1
if li <= hi:
items[li], items[hi] = items[hi], items[li]
else:
break
items[low], items[hi] = items[hi], items[low]
return hi
def quick_sort(items, low=None, high=None):
"""Sort given items in place by partitioning items in range `[low...high]`
around a pivot item and recursively sorting each remaining sublist range."""
if len(items) <= 1:
return items
elif low == None and high == None:
low = 0
high = len(items) - 1
if low < high:
pivot = partition(items, low, high)
quick_sort(items, low, pivot-1)
quick_sort(items, pivot+1, high)
return items
items = [90, 87, 32, 22, 53, 3, 2, 8, 89, 42, 1000, 142, 98, 32, 64, 33, 800, 720, 630, 37, 88, 87, 83, 74, 76]
result = quick_sort(items)
print(result) | true |
85a9d62073afff8dac4fcf9278e79150e04bcc48 | calmwalter/python_homework | /lab1/3.15.py | 633 | 4.125 | 4 | import turtle
turtle.penup()
turtle.goto((0, -100))
turtle.pendown()
turtle.circle(100)
turtle.penup()
turtle.goto((25, -20))
turtle.pendown()
x=0
while x is not 3:
x=x+1
turtle.left(120)
turtle.forward(50)
def eye(pos):
turtle.penup()
turtle.goto(pos)
turtle.begin_fill()
turtle.color("black")
turtle.pendown()
turtle.circle(15)
turtle.end_fill()
eye((-50,40))
eye((50,40))
turtle.penup()
turtle.goto((-85,-20))
turtle.right(30)
turtle.pendown()
turtle.forward(100)
turtle.left(60)
turtle.pendown()
turtle.forward(100)
turtle.hideturtle()
turtle.done() | false |
6c5d472e249cb6b8d071ec0302ab421e7f913938 | Gr33nMax/Python-CodeWars | /replace_aplh_pos.py | 721 | 4.4375 | 4 | """
Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)
"""
def alphabet_position(text: str) -> str:
return ' '.join(
map(
lambda x: str(ord(x) - 96),
list(
filter(str.isalpha, list(text.lower()))
)
)
)
test_text = "The sunset sets at twelve o' clock."
print(alphabet_position(test_text))
| true |
73254a74dc9cf0f8768993b29d48febfe2b3653b | lazycoder1/learn_NN | /first_NN.py | 2,544 | 4.4375 | 4 | import numpy as np
#This is the neural net class, which has the methods to train and predict the outputs for the input
class neural_net:
#This method gets called when the class is initialized
def __init__(self):
#You seed the random. This will make sure that the random number generated every time you run the program is the same
#This makes it easier to debug
np.random.seed(1)
#We initialize the neural network weights with the random weights to start at
neural_net.weights = 2 * np.random.random((6,1)) -1
#All the outputs after being multiplied with the weights are pass to the sigmoid function
#which converts the outputs to be in the range 0 - 1
def sigmoid(self,x):
return 1/(1+np.exp(-x))
#The derivative of the sigmoid
#This function is used to adjust the weights
def sigmoid_derivative(self,x):
return x*(1-x)
#Train the neural net using the training data and the outputs for the same
def train(self,training_data,training_outputs,iterations):
for i in range(iterations):
output = self.predict(training_data)
error = training_outputs - output
adjustment = np.dot(training_data.T, error * self.sigmoid_derivative(output))
self.weights += adjustment
def predict(self,input):
return self.sigmoid(np.dot(input,self.weights))
if __name__ == '__main__':
#The output for the following input should be same as the 4th column or ( 1st OR 4th column )
input = np.array([[1,0,0,1,1,0],
[0,1,1,1,0,1],
[1,0,1,1,0,1],
[0,1,1,0,1,1],
[0,0,0,1,0,1]])
print("Input\n",input)
output = np.array([[1,1,1,0,1]]).T
print("Output\n",output)
neural_net = neural_net()
neural_net.train(input,output,1000)
#Display the weights of the neural net after it gets trained
print("Neural net weights ")
print(neural_net.weights)
np.set_printoptions(precision=2)
print('\n\nprediction\n',neural_net.predict(np.array([[0,1,1,0,1,0],
[0,0,1,1,1,0],
[1,0,1,0,0,1],
[0,1,0,0,0,1],
[0,0,0,0,0,1]])))
| true |
c1eb2c9b59be336780c7b1c823591781b3a7f6c5 | Sabonta/Pet | /Date.py | 502 | 4.3125 | 4 | def main():
print('Enter a date (mm/dd/yyyy): ', end='')
date = str(input())
print('The new date is: ', end='')
print(date_converter(date))
def date_converter(date):
date_list = date.split('/')
list2 = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December']
index = int(date_list[0]) - 1
month = list2[index]
new = month + " " + date_list[1] + "," + date_list[2]
return new
main()
| false |
16eafdd96f5adf51f4c43bf2edbabc7734083850 | SACHSTech/livehack-3-FloorCheese | /problem1.py | 395 | 4.1875 | 4 | number = 1
wins = 0
print("Enter w or l for win or loss game" + number)
input("Enter W or L")
if number = 6:
print("Enter w or l for win or loss game" + number)
input("Enter W or L")
for w in word:
wins = wins +1
number = number +1
elif wins < 2:
print ("Your team is in group 3")
elif wins = >3 and <4:
print("Your team is in group 2")\
else:
print("Your team is in group 1") | false |
c27f9e4a961d37c1eb102eb8d5efdf88a8d18b79 | viditjha/python-projects | /calc.py | 1,013 | 4.1875 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x/y
print("enter operation: ")
print("1) add")
print("2) subtract")
print("3) multiply")
print("4) divide")
choice = input("enter choice (1/2/3/4): ")
if choice == '1':
num_1 = int(input("enter 1st number: "))
num_2 = int(input("enter 2nd number: "))
print("num_1", "+", "num_2", "=", add(num_1, num_2))
elif choice == '2':
num_1 = int(input("enter 1st number: "))
num_2 = int(input("enter 2nd number: "))
print("num_1", "-", "num_2", "=", subtract(num_1, num_2))
elif choice == '3':
num_1 = int(input("enter 1st number: "))
num_2 = int(input("enter 2nd number: "))
print("num_1", "*", "num_2", "=", multiply(num_1, num_2))
elif choice == '4':
num_1 = int(input("enter 1st number: "))
num_2 = int(input("enter 2nd number: "))
print("num_1", "/", "num_2", "=", divide(num_1,num_2))
else:
print("invalid") | false |
25bb2b398721e8f6b976e0f3c582ed0cb7d37888 | Sorens121/Goodrich | /Chapter 1/R-1.2.py | 339 | 4.25 | 4 | def is_even(k):
n = '{:0b}'.format(k)
if n[-1] == '1':
return False
else:
return True
#-----Driver Function-----
k = int(input())
print(is_even(k))
"""
Explaination: Convert the no into the binary format and check the last
element of the output if it's 1 then its an odd no but if it's 0 then
it's even
"""
| true |
49d5b1a75cf6b46c359fe57d79b9224114ff9602 | tsuiwwwayne/learn-python-the-hard-way | /projects/ex48_advanced_user_input/ex48_advanced_user_input/lexicon.py | 1,391 | 4.40625 | 4 | # Learn Python the Hard Way
# Exercise 48 - Advanced User Input, Lexicon
direction = ["north", "south", "east", "west",
"down", "up", "left", "right", "back"]
verb = ["go", "stop", "kill", "eat"]
stop = ["the", "in", "of", "from", "at", "it"]
noun = ["door", "bear", "princess", "cabinet"]
lexicons = [direction, verb, stop, noun]
lexicons_names = ["direction", "verb", "stop", "noun"]
def scan(sentence):
words = sentence.split()
result = []
index_position = 0
for word in words:
found_word = False
# check if it is a valid number
if not found_word:
try:
number = int(word)
result.append(("number", number))
found_word = True
except ValueError:
pass
# check amongst list of list of approved words
if not found_word:
for lexicon in lexicons:
name = lexicons_names[index_position]
if word in lexicon:
found_word = True
result.append((name, word))
else:
pass
index_position += 1
index_position = 0
# if word is not an approved word and not an valid number, the word is not valid
if not found_word:
result.append(("error", word))
return result
| true |
fc792bf344802fa4ae1f679c14e4cda662ed5e7e | drazyn-dev/python-library | /quick_sort.py | 1,293 | 4.5 | 4 | # Quick sort works by taking a list and sorting smaller sections of it around a pivot.
def quick_sort(sequence: list) -> list:
"""This will take a list and return the sorted version"""
if len(sequence) < 2:
return sequence
# Base case. If the list looks like either of these:
# []
# [3]
# It is sorted.
else:
# Otherwise, we need to sort the two sides around the pivot.
pivot = sequence.pop()
# Just taking the last value and using it as the pivot. Not
# particularly important.
lower_values, higher_values = [], []
# Creating two lists to store the left and right sides of
# the pivot.
for value in sequence:
if value > pivot:
higher_values.append(value)
else:
lower_values.append(value)
# Here, we go through every value in the sequence.
# For example, let's say that the sequence was:
# [1, -4, 3, 3, -5]
# We decided our pivot will be -5 as that is the last value.
# Now we check each value and see if it is greater.
# If it is, it goes into the right side. Otherwise, it goes into
# the left.
# [-5] [1, -4, 3, 3]
return quick_sort(lower_values) + [pivot] + quick_sort(higher_values)
# Lastly, we need to sort the newly created lists.
if __name__ == '__main__':
test = [1, -4, 3, 3, -5]
print(test)
test = quick_sort(test)
print(test)
| true |
50d4558e67f8f808fc5c4d660c5730f83d278569 | GauravAmarnani/Python-Basics | /com/college/lecture2.py | 2,073 | 4.34375 | 4 | """ Data Types in Python :
1. Number : int, long, float, complex.
2. String.
3. List.
4. Tuple.
5. List.
6. Dictionary.
"""
# Number Data Type :
# If we want to find out the Data Type of a variable then :
a = 10
print(type(a))
a = 10.5
print(type(a))
a = "Gaurav"
print(type(a))
# If we want to delete a variable (Like null in Java) :
del a
# If we delete a variable using 'del' and then try to print it, it will give an error
# saying that 'Variable Not Defined'.
# print(a)
# String Data Type:
string1 = "Hello"
string2 = "World "
# '+' for concatenation :
string3 = string1 + string2
print(string3)
# '*' for repetitive printing :
string4 = string3 * 4
print(string4)
print(string1 * 2 + string2 * 3)
# List Data Type : [obj1, obj2, obj3] (It is mutable).
list1 = [1, "Gaurav", True, 10.5]
print(type(list1))
list2 = [2, "Amarnani", False, 20.5]
# '+' for concatenation :
print(list1 + list2)
# '*' for repetitive printing :
print(list1 * 3)
# : for slicing :
# The following code will print the list from 1st index till the end.
print(list1[2:])
# The following code will print the list from start till 3rd index.
print("", list1[:3])
# Tuple Data Type : Almost same to List but is Immutable and has round brackets.
tuple1 = (1, 2, 3, "String", True, 10.5)
print("Type of tuple1 is : ", type(tuple1))
# TypeError: 'tuple' object does not support item assignment
# tuple1[1] = "Gaurav"
# Dictionary Data Type : Just like (java.util.Map).
map1 = {1: "Gaurav"}
map2 = {2: "Archita"}
map3 = {3: "Neha"}
map4 = {4: "Komal"}
print(map1)
list5 = [{1: "Gaurav"}, {2: "Archita"}, {3: "Neha"}, {4: "Komal"}]
print(list5)
# Type Conversion:
a = "123"
print(int(a))
# input() to take user input:
name = input("Enter Your Name : ")
age = int(input("Enter Your Age : "))
print("Welcome to our Python tutorial Mr. ", name, " your age after 10 years will be : ", age+10)
# Square Root:
number = int(input("Enter the Number to get it's square root : "))
print("The Square root is : ", number**(1/2))
| true |
ca2a251cb755680ca9b8e4426468b04239209e93 | GauravAmarnani/Python-Basics | /com/college/practicals/practical08/program1.py | 347 | 4.40625 | 4 | # Q. Create a Set, add members in a Set and remove one item from Set.
# Creating Set:
set1 = {1, 2, 3, 4, 5}
# Adding an Element in Set:
set1.add(6)
# Adding multiple Elements in Set:
set1.update([7, 8, 9])
# Removing an Element in Set using remove():
set1.remove(9)
# Removing an Element in Set using discard():
set1.discard(8)
print(set1)
| true |
42a4188d88c3e02cd4743e624d064d9f930f4307 | GauravAmarnani/Python-Basics | /com/college/viva/exp15.py | 558 | 4.1875 | 4 | # WAP to Create a List, Add Elements into List and reverse the List.
listName = [] # Creating List.
temp = [] # Creating Another List.
listName.extend("ABC") # Adding Element using extend().
listName.insert(1, "A1") # Adding Element using insert().
listName.insert(2, "A2")
listName.append("D") # Adding Element using append().
temp.extend(listName)
listName.reverse() # Reversing List using reverse().
print("The reversed of list", temp, " is ", listName)
# Performed by Gaurav Amarnani, Roll No. 21, CO6IA.
| true |
cc9f955d47cb0d18db71622b9c036b5e4e4c01e0 | GauravAmarnani/Python-Basics | /com/college/practicals/practical15/program1.py | 608 | 4.3125 | 4 | """
Q. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.
"""
class Employee:
def setValue(self):
self.name = input("Enter Name: ")
self.department = input("Enter Department: ")
self.salary = int(input("Enter Salary: "))
def printValue(self):
print("----------------------------\nEmployee Information: ")
print("Name: ", self.name, "\nDepartment: ", self.department, "\nSalary: ", self.salary)
employee = Employee()
employee.setValue()
employee.printValue()
| true |
44fc568bf44cde73b8767e59e4820af94aa2cc56 | Zahidsqldba07/Advanced-Trees-Sorting-Algorithms | /sorting/raise_power_recursive.py | 426 | 4.34375 | 4 | #!python
def raise_power(base, power):
"""
a recursive function called raise_power() that takes in two integer parameters,
the first parameter being the base number and the second parameter being the power
you want to raise it to
"""
if power == 0:
return 1
# multiply base by itself until power reaches 0
if power >= 1:
return base * raise_power(base, power - 1)
| true |
be33ca14bf93746ed64854ad99788b41138db107 | barreto-jpedro/Python-course-exercises | /Mundo 02/Ex041.py | 487 | 4.15625 | 4 | print('Descubra em qual categoria você se encaixa!')
idade = int(input('Digite a sua idade: '))
if idade < 9:
print('Você será alocado na categoria MIRIM')
elif 9 <= idade and idade < 14:
print('Você será alocado na categoria INFANTIL')
elif 14 <= idade and idade < 19:
print('Você será alocado na categoria JUNIOR')
elif 19 <= idade and idade < 20:
print('Você será alocado na categoria SENIOR')
else:
print('Você será alocado na categoria MASTER')
| false |
a56fbb55a07fd4105e0abb0a09464daff1ba9171 | barreto-jpedro/Python-course-exercises | /Mundo 01/Ex004.py | 558 | 4.21875 | 4 | #Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis sobre ela
var1 = input('Digite algo: ')
print('O tipo primitivo desse valor é: {}'.format(type(var1)))
print('Só tem espaços? {}'.format(var1.isspace()))
print('É alfabético? {}'.format(var1.isalpha()))
print('É alfanumérico? {}'.format(var1.isalnum()))
print('Está em maiúsculas? {}'.format(var1.isupper()))
print('Está em minúsculas? {}'.format(var1.islower()))
print('Está capitalizada? {}'.format(var1.istitle()))
| false |
243e8a6170a1cafae0995bec4738023e1ffae04e | kevein/pyex | /func_param.py | 580 | 4.15625 | 4 | #!/usr/bin/env python
# Filename: func_param.py
import sys
def printMax(a,b):
'''Hello, this function prints the maximum number of two input.
The two values must be integers.'''
if a>b:
print a,'is maximum'
else:
print b,'is maximum'
x1 = raw_input('Please input the first number: ')
if not x1.isdigit():
print "Please input a integer!!"
sys.exit(1)
y1 = raw_input('Please input the second number: ')
if not y1.isdigit():
print "Please input a integer!!"
sys.exit(1)
x = int(x1)
y = int(y1)
printMax(x,y) # give variables as arguments
print printMax.__doc__
| true |
53aa77c66a37bae945911ecb37b3a0e448de0798 | squatmasters/meth | /meth.py | 1,401 | 4.3125 | 4 | import pythagore
problem_type = input("Type 1 for right triangle checker. Type 2 for hypotenuse calc. for right triangle. Type 3 for missing arm value calc. for right triangle. Type 4 for volume of a cylinder calc. Type 5 for cone volume calc. Type 6 for volume of a sphere calc.")
if problem_type == "1":
pythagore.check()
elif problem_type == "2":
a = input("a=")
b = input("b=")
a = float(a)
b = float(b)
a = a ** 2
b = b ** 2
print("the hypotenuse is" , (a + b) ** 0.5 , "and a and b squared equal" , a , "and" , b)
elif problem_type == "3":
a = input("a=")
c = input("c=")
a = float(a)
c = float(c)
a = a ** 2
c = c ** 2
b = c - a
b = b ** 0.5
print("the missing arm value is" , b , "and a and c squared are" , a , "and" , c)
elif problem_type == "4":
a = input("radius=")
b = input("height=")
a = float(a)
b = float(b)
circle_area = a ** 2 * 3.14
print("the volume is" , circle_area * b)
elif problem_type == "5":
a = input("radius=")
b = input("height=")
a = float(a)
b = float(b)
circle_area = a ** 2 * 3.14
volume = circle_area * b / 3
print("the volume is" , volume , "and the base area is" , circle_area)
elif problem_type == "6":
a = input("radius=")
a = float(a)
a = a ** 3
a = a * 3.14
a = a * 4
a = a / 3
print("The volume is about" , a)
else:
yes = True
while yes:
print("That is not a valid function")
| false |
f2769f9a3939091fde19e15cda66d611ecc979f6 | singlestore-labs/wasm-eval | /src/tvm/demo.py | 699 | 4.125 | 4 | # This example demonstrates Gradient Boosting to produce a predictive model from an ensemble
# of weak predictive models. Gradient boosting can be used for regression and classification problems.
# Here, we will train a model to tackle a diabetes regression task. We will obtain the results from
# GradientBoostingRegressor with least squares loss and 500 regression trees of depth 4.
from sklearn import datasets
import xgboost as xgb
# First we need to load the data.
diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target
xgb_model = xgb.XGBClassifier(objective="binary:logistic", random_state=42, booster='gbtree')
xgb_model.fit(X, y)
xgb_model.save_model("xgb_model.bst")
| true |
d7a4d6409d9257cdff32cc32099da70265d54c81 | JLowe-N/Algorithms | /AlgoExpert/longeststringchain.py | 2,749 | 4.21875 | 4 | '''
Function that given a list of strings, returns the longest string chain that can
be built from those strings.
A string chain is defined as a string "A" in the initial array - if removing any
single character from string "A" yields a new string "B" that is in the initial
array of strings, then "A" and "B" form a string chain. Similarly, if removing
any single character in string "B", yields string "C" contained in the list
of strings, it can also be part of the string chain.
Only one longest string chain can be possible in the input.
'''
# Complexity O(n * m^2 + n log(n)) time | O(nm) space
# Where n is the number of strings in the list input
# and m is the number of characters in the longest of the strings
# Time complexity can be improved by n log(n) if we drop the strings sorting step
# but this will require much more complexity, adding checks to see
# if the shorter strings than the current iteration element have had their hash tables built
def longestStringChain(strings):
stringChains = {}
for string in strings:
stringChains[string] = {"nextString": "", "maxChainLength": 1}
sortedStrings = sorted(strings, key=len)
for string in sortedStrings:
findLongestStringChain(string, stringChains)
return buildLongestStringChain(strings, stringChains)
def findLongestStringChain(string, stringChains):
for i in range(len(string)):
smallerString = getSmallerString(string, i)
if smallerString not in stringChains:
continue
tryUpdateLongestStringChainLength(string, smallerString, stringChains)
def getSmallerString(string, index):
return string[0:index] + string[index + 1 :]
def tryUpdateLongestStringChainLength(currentString, smallerString, stringChains):
smallerStringChainLength = stringChains[smallerString]["maxChainLength"]
currentStringChainLength = stringChains[currentString]["maxChainLength"]
if smallerStringChainLength + 1 > currentStringChainLength:
stringChains[currentString]["maxChainLength"] = smallerStringChainLength + 1
stringChains[currentString]["nextString"] = smallerString
def buildLongestStringChain(strings, stringChains):
maxChainLength = 0
chainStartingString = ""
for string in strings:
if stringChains[string]["maxChainLength"] > maxChainLength:
maxChainLength = stringChains[string]["maxChainLength"]
chainStartingString = string
ourLongestStringChain = []
currentString = chainStartingString
while currentString != "":
ourLongestStringChain.append(currentString)
currentString = stringChains[currentString]["nextString"]
return [] if len(ourLongestStringChain) == 1 else ourLongestStringChain
| true |
151be63793304d9a1b804a0d3c24801a35927c0a | JLowe-N/Algorithms | /AlgoExpert/rightsiblingtree.py | 1,289 | 4.125 | 4 | '''
This function takes in a Binary tree, and transforms it into a Right Sibling Tree,
returning the root of the mutated tree.
A right sibling tree is obtained by making every node in a Binary Tree have its
right property point to its right sibling instead of its right child. The sibling
is the node immediately to its right on the same level or None/null if there is
no node immediately to its right.
'''
# Complexity O(N) time | O(d) space
# where N is # of nodes and d is the deepest branch of tree
# average case / balanced tree O(log N) space on call stack
# worst case / unbalanced tree (effectively linked list) O(N) space on call stack
def rightSiblingTree(root):
mutate(root, None, None)
return root
def mutate(node, parent, isLeftChild):
if node is None:
return
left, right = node.left, node.right
mutate(left, node, True)
#
if parent is None:
node.right = None
elif isLeftChild:
node.right = parent.right
else:
if parent.right is None:
node.right = None
else:
node.right = parent.right.left
mutate(right, node, False)
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right | true |
01ed0b1159a4ec7b7523267bd17bc33bfa78c8fe | sergiosacj/DELPHOS | /problema2.py | 1,012 | 4.375 | 4 | from pandas import read_csv
def sort_list(fileName):
dataframe = read_csv(fileName+'.csv', delimiter=';')
rowsList = [list(row) for row in dataframe.values]
rowsList.sort(key=lambda column:column[2])
# rowsList.insert(0, dataframe.columns.to_list())
return rowsList
fileName = input("Nome do arquivo csv: ")
print(sort_list(fileName))
"""
Utilizando a biblioteca de dados pandas, li o arquivo csv e armazenei em um
dataframe, que é uma estrutura de dados fornecida pela biblioteca pandas.
Em seguida, criei uma lista de listas a partir desse dataframe. É importante ressaltar que
essa lista de listas não possui a primeira linha do arquivo csv, já que é apenas o header.
Caso fosse necessário adicionar o header, bastaria descomentar a linha 7 que adiciona todas
as colunas 0, ou seja, todo o header.
Por fim, na ordenação, é utilizada uma função lambda para definir os critérios de ordenação.
Foi definido apenas o critério exigido, mas poderiam ser definidos vários critérios.
"""
| false |
591afc2071655638e97c9a045535a9bb89e20ad1 | candace-farris/Python-HW | /Farris_Candace_Project_03.py | 594 | 4.21875 | 4 | # Name: Farris, Candace
# Project #: 03
# Project Description:
# Write a program that lets the user enter six (6) values into a list. The program should calculate and display
# the sum, the average, the highest and the lowest values of all the numbers entered.
# Project Filename: Farris_Candace_Project_03
print("\nPlease input 6 numbers:\n")
nums = [int(x) for x in input().split()[:6]] # Input 6 digits only
print("")
print(nums)
print("\nSum:", sum(nums))
print("\nAverage:", sum(nums)/len(nums))
print("\nHighest number:", max(nums))
print("\nLowest number:", min(nums))
# End of program
| true |
72b0ede4c5faca64bd76e0a532b605c0de362fbd | hovikgas/Python-Coding-Challenges | /dictionaries/int_freq/int_freq_solution.py | 1,313 | 4.53125 | 5 | '''
Solution by GitHub user @allardbrain in July 2017.
Write a function called int_frequency() that takes a list of positive integers as
an argument and returns the integer that appears the most frequently in the list.
If there are multiple integers that share the same high frequency, return any one
of the integers. If the list is empty, return None.
>>> int_frequency([])
>>> int_frequency([3, 3, 4, 4, 5, 5]) == 3 or 4 or 5
True
>>> int_frequency([1, 1, 3, 2, 1, 4, 3, 5])
1
'''
def int_frequency(intlist):
int_freq_dict = {}
# If inlist is not empty (ie: if it is True)
if intlist:
for i in range(len(intlist)):
if intlist[i] not in int_freq_dict:
int_freq_dict[intlist[i]] = 1
else:
int_freq_dict[intlist[i]] += 1
# .items() returns a list of tuples containg all (key, value) pairs
freq_data = int_freq_dict.items()
temp_freq = 0
temp_num = 0
for pair in freq_data:
if pair[1] > temp_freq:
temp_freq = pair[1]
temp_num = pair[0]
return temp_num
# If intlist is empty
else:
return None
int_frequency([3, 3, 4, 4, 5, 5])
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
f286b3da2dc53b7972147e01f2a6ed1321e997aa | hovikgas/Python-Coding-Challenges | /numbers/no_multiply/no_multiply_solution.py | 559 | 4.25 | 4 | '''
Solution by GitHub user @allardbrain in July 2017.
Write a function called no_multiply() that takes in 2 integers as arguments.
Return the product of these two numbers without using multiplication (the * operator).
>>> no_multiply(3, 5)
15
>>> no_multiply(1, 4)
4
>>> no_multiply(5, 1)
5
>>> no_multiply(0, 9)
0
>>> no_multiply(9,0)
0
'''
def no_multiply(int1, int2):
result = 0
for each in range(int2):
result += int1
return result
no_multiply(2, 7)
if __name__ == '__main__':
import doctest
doctest.testmod() | true |
c5d96e0a87e96a8e6480d9475ca76075d87c91e2 | hovikgas/Python-Coding-Challenges | /lists/sum_odds/sum_odds.py | 433 | 4.15625 | 4 | '''
Write a function called oddball_sum() that takes in a list of integers
and returns the sum of the odd elements.
>>> oddball_sum([1,2,3,4,5])
9
>>> oddball_sum([0,6,4,4])
0
>>> oddball_sum([1,2,1])
2
'''
def oddball_sum(nums):
# Replace the line below with all your code. Remember to return the requested data.
pass
oddball_sum([17, 15, 0])
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
b3900273fdb5e699723d477cf3ffbcdea82c6a63 | hovikgas/Python-Coding-Challenges | /lists/sum_to_ten/sum_to_ten.py | 566 | 4.21875 | 4 | '''
Write a function called pairs_of_ten() that takes a list of integers as an argument.
Return a list of unique integer pairs that sum to 10, represented as tuples, from the input list.
Assume that pairs following this example are unique: (7, 3) and (3, 7).
>>> pairs_of_ten([5, 6, 6, 5, 7, 4, 3, 4]) == {(6, 4), (5, 5), (7, 3)}
True
'''
def pairs_of_ten(intlist):
# Replace the line below with all your code. Remember to return the requested data.
pass
pairs_of_ten([10, 1, 0, 9])
if __name__ == '__main__':
import doctest
doctest.testmod() | true |
8308a7a2f296744c170b10e6c3515ce94c1fd775 | hovikgas/Python-Coding-Challenges | /dictionaries/scrabble_score/scrabble_score.py | 1,379 | 4.375 | 4 | '''
From the Codecademy Python track.
Scrabble is a game where players get points by spelling words.
Words are scored by adding together the point values of each individual letter.
Leave out the double and triple letter and word scores for now.
A dictionary containing all of the letters in the alphabet
with their corresponding Scrabble point values is provided.
For example: the word "Helix" would score 15 points
due to the sum of the letters: 4 + 1 + 1 + 1 + 8.
Write a function called scrabble_score() that takes a word (as a string) as input
and returns the equivalent scrabble score for that word.
Assume your input is only one word containing only letters.
Your function should work even if the letters you get are uppercase, lowercase, or a mix.
Assume that you're only given non-empty strings.
>>> scrabble_score("orange")
7
>>> scrabble_score("NINJA")
12
>>> scrabble_score("Write")
8
'''
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def scrabble_score(word):
# Replace the line below with all your code. Remember to return the requested data.
pass
if __name__ == '__main__':
import doctest
doctest.testmod() | true |
c5cf8e6ba039f9b2a500938d5ad3e872ece838cf | hovikgas/Python-Coding-Challenges | /strings/is_anagram/is_anagram_solution.py | 637 | 4.40625 | 4 | '''
Solution by GitHub user @allardbrain in July 2017.
Write a function called is_anagram() that takes in 2 strings as arguments.
Return True if the strings are anagrams of each other (ie: they contain the same
letters and no extra letters). Otherwise, return false.
>>> is_anagram("cat", "dog")
False
>>> is_anagram("care", "race")
True
'''
def is_anagram(text1, text2):
sorted_text1 = sorted(text1)
sorted_text2 = sorted(text2)
if sorted_text1 == sorted_text2:
return True
else:
return False
is_anagram("blue", "black")
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
5cb9c38c9cf855efd7acb633f00452f9953bd9fb | saicharan-gouru/python | /PangramorNot.py | 414 | 4.28125 | 4 | '''
We can say the given string is a 'Pangram' when the string consists all the alphabets from a to z, if anyone letter is missing we can say that it is not a pangram
'''
def pangram(s):
alphabet="abcdefghijklmnopqrstuvwxyz"
for i in alphabet:
if i not in s:
return False
return True
string = input()
if(pangram(string)):
print(string+" is a pangram")
else:
print("sorry")
| true |
366dbb547d2cfd9dfff901688ea5fbe9eb2124a8 | saarhaber/CSCI-127 | /saarHourslefttInToTheWeekend.py | 202 | 4.125 | 4 | #name Saar Haber
#date 22 February 2018
#Hours
Hours = int(input("Enter hours left to the weekend: "))
print("Days left: " , Hours/24)
print("Leftover hours: " , Hours%24)
| true |
835cd7d42c7ca773301ea48f9e858df155696bb2 | MysticalGuest/Advanced-Python | /CourseReview/calculate_areas.py | 794 | 4.3125 | 4 | """***************************************************************************
calculate_areas.py
Calculate areas of geometric shapes
***************************************************************************"""
# To run this program, start python and then type:
# calculate_areas
import math
rect_length = 10
rect_height = 20
circle_radius = 10
a = 30
b = 24
c = 18
p = (a + b + c) / 2
print('The area of a rectangle of length ', rect_length,' and height', rect_height, ' is ', rect_length*rect_height)
print('The area of a circle of radius', circle_radius, ' is ', math.pi*circle_radius*circle_radius)
print("The area of a triangle of dimensions a=", a, ",b=", b, ",c=", c,
" using Heron's Formula is", math.sqrt(p*(p-a)*(p-b)*(p-c)))
| true |
91d427e3569982b4782831a9ad2485c488bd367d | yushi5344/python1 | /lists.py | 889 | 4.21875 | 4 | # Author guomin
name=["张三","李四","王五","马六","小七"]
# print(name)#列表
# print(name[0],name[2])
# print(name[0:3])#切片
# print(name[1:3])#从第二个开始去完第三个
# print(name[::3])
# print(name[-1])#取倒数第一个值
# print(name[-2:])#从倒数第二个开始取到末尾
#追加到列表最后
name.append("大哥")
print(name)
#添加到列表某个位置
name.insert(2,"小迪")#把小迪插到第三个值上
print(name)
#直接更改
name[0]="张三三";
print(name)
#删除某个值
name.remove("李四")
print(name)
del name[2]#删除第三个值
print(name)
name.pop(1)#删除第二个值
print(name)
print(name.index("马六"))#通过值找到位置
name.reverse()#列表反转
print(name)
print(name.count("马六"))#统计某个值出现的次数
names=name.copy()#复制一个列表
print(names)
name2=name[::2]
for i in name2 :
print(i) | false |
e4a4629e7572d4416c73431b0670c6a6b5088dd2 | PoulaAdel/python-crash-course-solutions | /ch3/3.4-7.py | 637 | 4.3125 | 4 | names=['eric','mona','mary']
for target_list in names:
print("Hello my dear friend: {}, Let's have dinner tonight!".format(target_list.title()))
print("\n{} can't make it, she won't come!".format(names[1]))
names.remove('mona')
# or names.pop(1)
names.append('samy')
# or names.insert(1,'hany')
for target_list in names:
print("Hello my dear friend: {}, Let's have dinner tonight!".format(target_list.title()))
print("\nSorry Fellas, I can only invite 2 people to dinner!")
for target_list in names:
print("Hello my dear friend: {}, sorry I don't have place for you!".format(target_list.title()))
names.pop(target_list)
| true |
4f099c7c4812d4898ce5be9f263101635050cd07 | Reza-Salim/Training | /2.py | 282 | 4.125 | 4 | pi = 22 / 7
height = float (input('Height of cylinder: '))
radian = float (input ('radius of cylinder: '))
volume = pi * radian * height
sur_area = ((2* pi * radian)* height ) + ((pi * radian ** 2 ) * 2 )
print ("Volume is : ", volume)
print ("Surface Area is :" , sur_area)
| false |
778d2bf133fa0ba3c827278ada81d54b156bc9b9 | mash716/Python | /base/array/array0017.py | 859 | 4.125 | 4 | #セットはディクショナリと同じように「 {} 」(中カッコ)を使用します。
test_set_1 = {'python','-','izm','.','com'}
print(test_set_1)
print('------------------------')
for i in test_set_1:
print(i)
#要素がない空のセットを作成する時はsetを用います。
#これはディクショナリ
test_dict = {}
#これはセット
test_set = {'python'}
#空のセット「set」を使う
empty_set = set()
# 前述の通り、重複した値を持つことはできません。
# たとえば次の例では‘python’と‘izm’が重複していますが、
# そのセットの出力結果には1つだけしか存在していません。
test_set_1 = {'python','-','izm','.','com','python','izm'}
print(test_set_1)
print('-----------------------')
for i in test_set_1:
print(i) | false |
8a5503873709e825c3dfacdc5d1565f6f25476ea | AdEDavis/search-replace-txt | /replace.py | 431 | 4.15625 | 4 | from sys import argv
script, filename = argv
prompt = ('> ')
print("What word would you like to be replace?")
word = input(prompt)
# Read in the file
with open(filename, 'r+') as file :
filedata = file.read()
print("What word would you like to input?")
new = input(prompt)
# Replace the target string
filedata = filedata.replace(word, new)
# Write the file out again
with open(filename, 'w') as file:
file.write(filedata)
| true |
b9b24d90530ac589b732b677bb4372424acee10c | marththex/Python | /MarcusChong_0/Helloworld.py | 383 | 4.21875 | 4 | import sys
x = input("What is the Radius of the Circle: ")
try:
floatX = float(x)
except ValueError:
print("That's not a valid number")
sys.exit()
while(floatX < 0.0):
print("Error: Please type in a valid number")
x = input()
floatX = float(x)
cirX = float(2*3.14*floatX)
areaX = float(3.14*floatX*floatX)
print("Circumference: ")
print(cirX)
print("Area: ")
print(areaX)
| true |
c9176d4540480fc75b3ccbfb2075cc6c2114151e | Marcus-Mosley/ICS3U-Unit3-04-Python | /negative_positive_zero.py | 552 | 4.25 | 4 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on September 2020
# This program checks if an integer is negative, positive, or zero
def main():
# This function checks if an integer is negative, positive, or zero
# Input
integer = int(input("Enter an Integer: "))
print("")
# Process & Output
if integer > 0:
print("This integer is + (positive)!")
elif integer < 0:
print("This integer is - (negative)!")
else:
print("This integer is 0 (zero)!")
if __name__ == "__main__":
main()
| true |
43fcae410e846d961455680340f60830c5c728c4 | ravinaNG/python | /If_statement/Big_number.py | 496 | 4.125 | 4 | First = int(raw_input("Enter your first number:- "))
Second = int(raw_input("Enter your Second number:- "))
Third = int(raw_input("Enter your Third number:- "))
if(First > Second and First > Third):
print "First number is your bigest number:- ", First
elif(Second > First and Second > Third):
print "Second number is your bigest number:- ", Second
elif(Third > First and Third > Second):
print "Third number is your bigest number:- ", Third
else:
print "Here no any number is bigest number."
| true |
724d6efa5fc34c66202229d7f65d9ea2687d73a9 | Alainfou/python_training | /battleship.py | 2,460 | 4.28125 | 4 | from random import randint
# Variables (board, board size, number of turns):
sea = []
sea_size = 0
turns = 0
# Function to print the current board game:
def print_game(sea):
print "_"+"__"*(sea_size+1)
for row in sea:
print "| "+" ".join(row)+" |"
print "="+"=="*(sea_size+1)
# Functions to choose a random column or row index:
def random_row(sea):
return randint(0, len(sea) - 1)
def random_col(sea):
return randint(0, len(sea[0]) - 1)
# Welcome message :
print "/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ "
print "| Hello, and welcome to my Battleship game! |"
print "\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/ "
# Get input (size of the square sea):
while sea_size not in range(5,11):
sea_size = int(raw_input("Size of your board game (from 5 to 10): "))
# Create a square sea:
for x in range(sea_size):
sea.append(["~"] * sea_size)
# Create a ship (single cell), hidden in the sea:
ship_row = random_row(sea)
ship_col = random_col(sea)
# Get input (number of turns):
while turns not in range(1,21):
turns = int(raw_input("Number of turns (from 1 to 20): "))
# Repeat for each turn:
for turn in range(0,turns):
# Print the number of turns left (but counts from 0):
print "Turns left: ",turns-turn
# Print the game at every turn:
print_game(sea)
# Get the input (row and column):
guess_row = int(raw_input('Guess row (from 0 to '+str(sea_size-1)+'): '))
guess_col = int(raw_input('Guess column (from 0 to '+str(sea_size-1)+'): '))
# Check the input:
if guess_row not in range(0,sea_size) or \
guess_col not in range(0,sea_size) :
print "Wow dude, you're so high, that's not even in the sea..."
# If the selected index matches, you won!
elif guess_row == ship_row and guess_col == ship_col:
print "URRR!! Damn'! You sunk my battleship, matey!"
break
# If the index is in the board game but not the ship,
# check if it has been tried already or mark it as tried:
else:
if(sea[guess_row][guess_col] == "O"):
print "You tried here already, too bad!"
else:
print "Missed! Eh eh!"
sea[guess_row][guess_col] = "O"
# Will print in every cases:
sea[ship_row][ship_col] = "X"
print_game(sea)
print "GAME OVER"
print "/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ "
print "| ~ ~ ~ Thanks for playing Battleship ~ ~ ~ |"
print "\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/ "
| true |
1f79f889bb2f0bd2027c7ebc9b9f06c3c92b777e | nogand/py0220 | /Calculadora/code.py | 958 | 4.15625 | 4 | #!/usr/bin/python3
from calculadora import *
operaciones={"+":suma, "-":resta, "*":multiplicacion, "/": division}
def esnumero(candidato):
valido=True
for caracter in candidato :
if caracter == "1" or caracter == "2" or caracter == "3" or caracter == "4" or caracter == "5" or caracter == "6" or caracter == "7" or caracter == "8" or caracter == "9" or caracter == "0" :
continue
else :
valido=False
break
return valido
print("Bienvenido a la calculadora")
operacion = ""
while len(operacion) != 1 or operacion not in '+-*/' :
operacion=input("Indique la operación (+, -, *, /): ")
oper1=input("Indique el primer número: ")
oper2=input("Indique el segundo número: ")
if oper1.isnumeric() and oper2.isnumeric() :
oper1 = int(oper1)
oper2 = int(oper2)
print(operaciones[operacion](oper1, oper2))
else :
print("Error! Ambos números deben tener formato numérico.")
| false |
56d8db50fe0e8c2b517e0f23cf10ac7426d32882 | anselb/coding-challenges | /get_pair.py | 950 | 4.25 | 4 | """
Email from subscription of Daily Coding Problems
https://galaiko.rocks/posts/2018-07-06/
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr.
"""
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
def get_left(left, right):
return left
return pair(get_left)
def cdr(pair):
def get_right(left, right):
return right
return pair(get_right)
if __name__ == '__main__':
left = 332
right = 1234
after_cons = cons(left, right)
left_result = car(after_cons)
right_result = cdr(after_cons)
print('Left should be {}: {}'.format(left, left_result))
print('Right should be {}: {}'.format(right, right_result))
| true |
bed769b4fcea2297a3b71817c65e5517c171b8e7 | sbojnak/IDEA-IDMEF-Converter | /src/Converter/IdeaAndIdmefConverter/InnerConverterStructure/MessageConverter.py | 830 | 4.125 | 4 | from abc import ABC, abstractmethod
class MessageConverter(ABC):
"""
Abstract class, which declares methods for converting just single message for specific format.
All important operations of data conversion should be done in this class.
"""
@abstractmethod
def modify_data(self, input_message):
"""
Takes data from input_message structure and converts it into data structure of output format
:param input_message: Parsed message of specific format, for example in JSON it will be probably dictionary,
in XML ElementTree root, but it depends on parsers.
If input_message is None, method takes input_message from class attribute
:return: data in output data structure for exporting
"""
pass
| true |
cd36bdedca5043e9496e883d4b6f3692b62bc6b9 | dcampore98/dcampore | /dcampore_HW5.py | 371 | 4.1875 | 4 | #5.39
# Define exclamation, also takes input
def exclamation(word):
new_word = ""
# For loop uses value from input
for char in word:
if char in "AaEeIiOoUu":
new_word += char * 4
else:
new_word += char
new_word += "!"
return new_word
print(exclamation("argh"))
print(exclamation("hello"))
| true |
712e2ca108fe5070f2f8308552cdda1988146a6b | joosequezada/LearningPython | /cofacilito/ExGradeAverageEnhance.py | 658 | 4.40625 | 4 | #!/usr/bin/python3
subjects = {}
print("<<#>>Python3 Script to PRINT Average's Grades<<#>>\n\
<<Type retire subjects grade as number 0>>\n")
""" Adding values to variasbles
"""
ca = input("Calculus grade: ")
ar = input("Art grade: ")
ac = input("Accouting grade: ")
hi = input("History grade: ")
""" Adding values to dictionary
"""
subjects["calculus"] = float(ca)
subjects["art"] = float(ar)
subjects["accounting"] = float(ac)
subjects["history"] = float(hi)
grades = subjects.values()
def Average(values):
return sum(values) / len(values)
average = Average(grades)
print("\nAverage's Grades: [{}]".format(round(average, 2)))
#print(mean(values)) | false |
3a4827ce4e865941929918183ce85a06a684fbb0 | alvarule/calculator_gui | /calculator.py | 2,658 | 4.375 | 4 | # Creating a Calculator using Tkinter
from tkinter import *
# --------------Actual logic of calculator goes here--------------
def click(event):
global scvalue
# Will automatically clear the display if Error is generated in previous calculations
if display.get() == "Error":
scvalue.set("")
display.update()
# Will extract the value of the clicked button
text = event.widget.cget("text")
# if "=" button is clicked, it will evaluate the expression on the display
if text == "=":
if scvalue.get().isdigit():
value = int(scvalue.get())
else:
# when the evaluating expression is not valid
try:
value = eval(display.get())
except Exception as e:
value = "Error"
print(e)
# updating the display with the result
scvalue.set(value)
display.update()
# if "C" button is clicked, it will clear the display
elif text == "C":
scvalue.set("")
display.update()
# if "<-" button is clicked, it will erase the last char of expression on the display
elif text == "<-":
scvalue.set(scvalue.get()[:-1])
display.update()
# except all above, if any other button is clicked, it will be appended to the expression on the display
else:
scvalue.set(scvalue.get() + text)
display.update()
# --------------Defining the GUI structure--------------
root = Tk()
root.geometry("345x640")
root.minsize(345, 640)
root.maxsize(345, 640)
root.title("Calculator by Atharva")
root.configure(background="black")
scvalue = StringVar()
scvalue.set("")
# Creating main display where i/o will be displayed
display = Entry(root, textvariable=scvalue, font=("times new roman", 35, "bold"),
justify=RIGHT, bg="black", fg="white", relief=FLAT)
display.pack(side=TOP, fill=X, pady=10, padx=10, ipady=20)
# List of buttons to be placed in the calculator
buttons = [["C", "%", "<-", "/"],
["7", "8", "9", "*"],
["4", "5", "6", "-"],
["1", "2", "3", "+"],
["00", "0", ".", "="]]
# creating buttons using for loops and iterating the items in above list
for row in buttons:
f = Frame(root, bg="black", borderwidth=0)
f.pack(side=TOP, fill=X, padx=20)
for btn in row:
b = Button(f, text=btn, font=("times new roman", 28, "bold"), relief=FLAT,
width=3, height=1, pady=15, bg="black", fg="white",
activebackground="black", activeforeground="white")
b.pack(side=LEFT)
b.bind("<Button-1>", click)
root.mainloop()
| true |
e82db25d62f1cae3956821de560a644938d9c556 | hareshgundlapalli/DataScience | /Sampletest.py | 1,728 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 17:52:37 2019
Python program to validate the user input is numeric and if its odd / even
@author: Haresh
"""
import math
#Sample 1 - Accepts only integers:
value = input("Please enter a number to validate ODD/EVEN : ")
print("You have entered", value, "is in", str(type(value)), "and we are converting it to int.")
try:
value = int(value)
except ValueError:
print("Invalid input. Please enter a valid integer.")
if isinstance(value, (int, float, complex)) and not isinstance(value, bool):
value = int(value)
if value % 2 == 0:
print(value, "is even number.")
elif value % 2 != 0:
print(value, "is odd number.")
else:
print(value, "is not a number.")
# Sample 2 - Accepts float / integer and converts to an integer
value = input("Please enter a number to validate ODD/EVEN : ")
print("You have entered", value, "is in", str(type(value)), "and we are converting it to int.")
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
print("Invalid input. Please enter a valid Number.")
if isinstance(value, int):
value = int(value)
if value % 2 == 0:
print(value, "is even number.")
elif value % 2 != 0:
print(value, "is odd number.")
else:
if isinstance(value, float):
value = math.floor(value)
value = int(value)
if value % 2 == 0:
print("Floor value", value, "is even number.")
elif value % 2 != 0:
print("Floor value", value, "is odd number.")
else:
print(value, "is not a number.")
| true |
0edd40f6dc018dded0b14c27d4fdbb57f40c31c8 | indrajeet-droid/PythonPractice | /29_exception_handling.py | 830 | 4.21875 | 4 | # exception = events detected during execution that interrupt the flow of a program
try:
numerator = int(input("Enter a number to divide: "))
denominator = int(input("Enter a number to divide by: "))
result = numerator / denominator
except ZeroDivisionError as e:#we can write without e as well
#it's not consider good practice to have single except block that will handle all Exception. it is much batter to first handle specific Exception when the occured. we can do so by creating addional except block
print(e)
print("You can't divide by zero! idiot")
except ValueError as e:#5/pizza give you error as value error
print(e)
print("Enter only number plz")
except Exception as e:
print(e)
print("something went worng :( ")
else:
print(result)
finally:
print("this will always execute")
| true |
e3c5e94c6a115a9592a344cd95925a3f3a3cc282 | indrajeet-droid/PythonPractice | /4_type_casting.py | 707 | 4.59375 | 5 | #type casting = convert the data type of a value to another data type
x = 1 #int
y = 2.0 #float
z = "3" # string
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
#convert y & z to int
print(x)
print(int(y))#this is not permanent change. if you want, you need to reassign as below
print(int(z))#this is not permanent change. if you want, you need to reassign as below
#permanent change
y = int(y)
z = int(z)
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
x= float(x)
print(x)
#why we need to convert
# for example suppose you want to display x value is + str(x)----we can't display string and int together
print("x value is "+ str(x))
print(z*3) | true |
f59ef895fa9536cbdb784e49575d3427c2593fba | indrajeet-droid/PythonPractice | /13_loop_control_statements.py | 471 | 4.125 | 4 | #loop control statements = change a loop execution from its normal sequence
#break = used to terminate the loop entirely
#continue = skips to the next iteration of the loop
#pass = does nothing, acts as a placeholder
while True:
name = input("Enter your name: ")
if name != "":
break
phone_number = "123-456-7890"
for i in phone_number:
if i == "-":
continue
print(i, end= "")
for i in range(1,21):
if i == 13:
pass
else:
print(i)
| true |
376378a12ed8246cec475a046de741656dfc0b4d | indrajeet-droid/PythonPractice | /3_useful_method_for_strings.py | 394 | 4.25 | 4 | #useful methods in string
name = "indrajeet"
print(len(name))
print(name.find("B"))#return index of B
print(name.capitalize())
print(name.lower())
print(name.isdigit())#return false as name is not digit
print(name.isalpha())# return false as it contain space. it will check only alphabet letters
print(name.count("o"))#return how many o are there
print(name.replace("o","a"))
print(name * 3)
| true |
edf6ac1c39b4e8d66fee3e9824f999435d588da0 | naa45/advance_python | /even_numbers.py | 547 | 4.15625 | 4 |
def is_even():
number= int (input("please enter a number : "))
if number%2 !=0:
print("true")
else:
print("false")
is_even()
'''def is_even1(number):return number%2 ==0
numbers = [1,56,234,87,4,76,24,69,90,135]
print(list(filter(is_even1,numbers)))'''
'''numbers=[1,56,234,87,4,76,24,69,90,135]
filtered_list = list(filter(lambda num:(num%2==0),numbers))
print(filtered_list)'''
'''numbers=[1,56,234,87,4,76,24,69,90,135]
filtered_list = list(filter(lambda num:(num%2==1),numbers))
print(filtered_list)'''
| false |
85bd4ff4849e965ae602da2a1b980dc025eb106a | Severa1326/Severa | /weight converter.py | 417 | 4.1875 | 4 | weight = int(input("Weight: "))
unit = input("(L)bs or (K)gs?: ")
if unit.upper() == "L":
transformed_weight = weight * 0.45
print(f"You're {transformed_weight} {unit.upper()}")
elif unit.upper() == "K":
transformed_weight = weight / 0.45
print(f"You're {transformed_weight} {unit.upper()}")
else:
print("Please select your weight in pounds (L) or kilograms (K)")
"done 03/03/2020"
| false |
686416b577e6ff993fa0d91b185058e203731553 | CodingDojoDallas/python_september_2017 | /Shivi_khanuja/bike.py | 1,068 | 4.15625 | 4 | class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print 'Price is: $ ' + str(self.price)
print 'Max Speed is: ' + str(self.max_speed) + 'mph'
print 'Total Miles is: ' + str(self.miles) + 'miles'
return self
def drive(self):
print 'Driving'
self.miles += 10
return self
def reverse(self):
print 'Reversing'
if self.miles >= 5:
miles -= 5
return self
else:
self.miles -= 0
print "Can't reverse anymore"
return self
CRX = Bike(220, 9)
Suzuki = Bike(120, 15)
Fuji = Bike(180, 12)
print CRX.price
print Suzuki.max_speed
print Fuji.price
CRX.reverse()
Suzuki.drive().drive().reverse()
CRX.drive().drive().reverse().displayInfo()
Fuji.ride().ride().reverse().reverse().displayInfo()
Road.reverse().reverse().reverse().displayInfo() | true |
5b99850fed41def371139ca1792e44cc62ff00f2 | CodingDojoDallas/python_september_2017 | /KatherineK/animal.py | 1,504 | 4.1875 | 4 |
# Create parent class Animal, with methods run, walk, and display_health
class Animal(object) :
def __init__(self, name, health=150):
self.health = health
self.name = name
print self.name + " created"
def walk(self, repeat):
self.health -= 1 * repeat
return self
def run(self, repeat):
self.health -= 5 * repeat
return self
def display_health(self):
print self.health
return self
#Creating three instances of Animal class
GwendolyntheGiraffe = Animal("Gwen")
LarrytheLion = Animal("Larry")
BobtheBear = Animal("Bob")
#Walking and Running an instance of Animal class
BobtheBear.walk(3).run(2).display_health()
# create class Dog, inheriting traits from Animal, with method .pet()
class Dog(Animal) :
def __init__(self, name, health):
super(Dog, self).__init__(name, health)
def pet(self, repeat):
self.health += 5 * repeat
return self
# Create instance of Dog, call methods .run(), .walk(), and .pet()
Rowdy = Dog("Rowdy", 150)
Rowdy.walk(3).run(2).pet(1).display_health()
# Create class Dragon, inheriting from Animal, with method .fly()
class Dragon(Animal) :
def __init__(self, name, health):
super(Dragon, self).__init__(name, health)
def fly(self):
self.health -= 10
def display(self):
self.display_health()
print "I am a dragon"
# Create instance of Dragon, call method .fly()
Puff = Dragon("Puff", 170)
Puff.display()
| true |
53de29c5db76a70dcc91e581126b8b7157722e22 | ryanpepe2000/cmpt120pepe | /pi.py | 278 | 4.25 | 4 | # pi.py
# Calculates the value of pi.
def main():
n = int(input("Enter the number of terms to use to estimate pi: "))
sign = 1
pi = 0
for i in range(1,n*2+1,2):
pi = pi + sign * (4/i)
sign = sign * -1
print(pi)
main()
| true |
beb2b2e82ff39c0f3046095b56842e6e2458adbf | agarwalrahul-22/iiec | /linear_search.py | 656 | 4.21875 | 4 | #code for linear_search complexity O(n)
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
#added a few lines
#added few other lines
list1 = [1 ,3, 5, 4, 7, 9]
//initialising an array
=======
#creating the input data for verifing the code
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
//initialising an key
n = len(list1)
res = linear_Search(list1, n, key)
#checking the base case
if(res == -1):
print("Element not found")
//for cases in which no ans is posible
else:
print("Element found at index: ", res)
| true |
87ce5ef9b4d49c0d0a41271984a270bacdd9f95c | nikiel0405/Campus-Practicals | /comp 100 pracs/prac#3/question6.py | 255 | 4.15625 | 4 | for i in range (4):
for j in range (i):
print("*", end="")
print()
for k in range (4,0,-1):# starts at 4 ends at 0 and takes -1 steps so reverse of the first nestes for loops
for l in range (k):
print("*", end="")
print() | true |
20e70654e62038b51e53a2a79b793c0d006d2772 | GuoyiLi1991/python-refresher | /05_lists_tuples_sets/code.py | 940 | 4.40625 | 4 | '''
we can change list but can not do it on tuple
list and tuple have order but set does not have
- so we can do list[1] or tuple[1]; but can not do set[2]
list and tuple can have multiple same element but set could not
'''
l = ["Bob", "Rolf", "Anne"]
t = ("Bob", "Rolf", "Anne")
s = {"Bob", "Rolf", "Anne"}
# Access individual items in lists and tuples using the index.
print(l[0])
print(t[0])
# print(s[0]) # This gives an error because sets are unordered, so accessing element 0 of something without order doesn't make sense.
# Modify individual items in lists using the index.
l[0] = "Smith"
# t[0] = "Smith" # This gives an error because tuples are "immutable".
print(l)
print(t)
# Add to a list by using `.append`
l.append("Jen")
print(l)
# Tuples cannot be appended to because they are immutable.
# Add to sets by using `.add`
s.add("Jen")
print(s)
# Sets can't have the same element twice.
s.add("Bob")
print(s)
| true |
8578cdae55b83b5c1cf8a4ee4121b6a86c103f61 | sarcox/CTF-Tools | /partial_hash_finder.py | 1,559 | 4.25 | 4 | import string
import hashlib
# This program is written in Python 3
# This program generates MD5 hashes from a wordlist and compares to a partial
# hash you provide.
words_to_hash = []
# Describe program and prompt for input.
print('*******************')
print('This program looks for hash collisions.')
print('Make sure there is wordlist.txt is in the same folder where you run this.\n')
print('*******************')
partial_hash = input('What is the partial hash you want to match? ')
# Save the partial hash input by user; note there is no error checking on this.
partial_hash_len = len(partial_hash)
with open('wordlist.txt') as f:
words_to_hash = f.read().splitlines()
i =0 #counter
num_words=len(words_to_hash) # store number of words in wordlist to loop through
# Provide information on wordlist
print ("Number of Words in wordlist.txt to check: " + str(num_words))
print('*******************')
# Set flag if you only want find one match.
found_hash = 0
while i < num_words:
current_hash = hashlib.md5(words_to_hash[i].encode()).hexdigest()
j = 0 # reset counter to check each character of partial hash
while j < partial_hash_len:
if(current_hash[j]== partial_hash[j]):
if j == partial_hash_len - 1:
# print headers for output
print ("Word: MD5")
print (words_to_hash[i] + ": " + current_hash)
found_hash = 1
j = j+ 1
else:
break
if found_hash:
break
else:
i = i+1
if found_hash == 0:
print('No hashes found. Try a larger wordlist.') | true |
41689ffe35aae66e08b5a11f5c8ee4d35fed039c | A4th/Recursive-Functions | /Recursive-Functions.py | 778 | 4.375 | 4 | # Recursive functions
def factorial(n):
if n == 1:
return 1
elif n > 1:
return n * factorial(n -1)
'''The reason this works is ... well let's first break down the code and see what is essentially happening
so what is happening we take in an argument n which represents the number that the user wants to take the factorial of
then from there what we essentially do is that we say if the user passes in 1 which we know that the factorial of 1 is 1 therefore we can
return 1 but if that is not the case then we want to take the number the user passes in and we want to multiply
that number to every number decremented by one and we know this would be save due to the simple fact that we have a base case saying
that if it reaches 1 we can return out '''
| true |
9d65cc445656978df78d0c4552b3b16b3f1de8ee | UpendraDange/JALATechnologiesAssignment | /pythonString/program_1.py | 491 | 4.125 | 4 | """
Different ways creating a string.
"""
#creating empty string
pystr = str()
print(pystr)
print(type(pystr))
#creating string with single quote
pystr2 = 'I am single quote string'
print(pystr2)
#creating string with double quote
pystr3 = "I am double quote string"
print(pystr3)
#creating string with triple single quote
pystr4 = '''I am triple single quote string'''
print(pystr4)
#creating string with triple double quote
pystr5 = """I am triple double quote string"""
print(pystr5)
| true |
da360e908a60f2e5d55ffacc98fbf866b6f25387 | UpendraDange/JALATechnologiesAssignment | /pythonBasics/program_4.py | 601 | 4.15625 | 4 | """
Define variables for different Data Types int, Boolean, char,
float, double and print on the console.
Ans: Python is a dynamically typed language.
We don't have to declare the type of variable while assigning a value to a variable in Python
"""
pyInt=10 #integer variable
print(pyInt)
pyBoolean=True #Boolean variable
print(pyBoolean)
#There is no such datatype called 'char' in python
#Python has 'String' datatype
pyStr="Python" #String variable
print(pyStr)
pyFloat=20.44 #float variable
print(pyFloat)
#There is no such datatype called 'double' in python
| true |
ce0de94a1d3e959cc02749e8b27ab02fa1a7700c | UpendraDange/JALATechnologiesAssignment | /pythonAbstractClass/program_4.py | 470 | 4.40625 | 4 | """
Create an instance for the child class in child class and call non-abstract methods.
"""
from abc import ABC, abstractmethod
class pyParent(ABC):
def parentMethod(self):
print("I am in parent method")
class pyChild(pyParent):
def childMethod(self):
print("I am in child method")
def show(self):
obj = pyChild()
obj.parentMethod()
obj.childMethod()
if __name__ == "__main__":
pyC = pyChild()
pyC.show() | true |
2948bcf060c8f83a431e44699ba760cfebaa2a2f | cwilkins-8/7 | /7.2.py | 481 | 4.25 | 4 | #7.2 Restaurant Seating
#seating = input("How many people are in your dinner group? ")
#seating = int(seating)
#if seating <= 8:
#print("\n We have a table avaible for you")
#else:
# print("Sorry, you will have to wait for a table.")
#7.3 Multiples of Ten
number = input("Please enter a number : ")
number =int(number)
if number % 10 == 0 :
print("\n This number is a multiple of 10!")
else:
print("This number is not a multiple of 10")
| true |
364d97970a6dba9d1291571b08f3a67f03056e55 | itsdennon/Dennon-91883-884-Quiz-Project- | /videogamequiz_userdetails.py | 746 | 4.1875 | 4 | while True:
name = input("May I please know your name? : ") #Here is where I ask the user for their name
print("------------------------------")
if name.isalpha():
break
print("Please enter letters only.")
while True:
age = input("Please tell me your age? : ") #Here is where I ask the user for their age
print("------------------------------")
if age.isnumeric():
break
print("Please enter numbers only.")
while True:
yearlvl = input("And lastly, what is your year level? : ") #Here is where I ask the user for their year level
print("------------------------------")
if yearlvl.isnumeric():
break
print("Please enter numbers only.")
| true |
e98c0da6f6eeadf6532da28c52c52fabb4f66357 | suryanjain14/prat | /linked list/linkedlist.py | 837 | 4.1875 | 4 | class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
# Linked List Class
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
# creates a new node with given value and appends it at the end of the linked list
def append(self, new_value):
new_node = Node(new_value)
if self.head is None:
self.head = new_node
self.tail = new_node
return
self.tail.next = new_node
self.tail = new_node
# prints the elements of linked list starting with head
def printList(head):
if head is None:
print(' ')
return
curr_node = head
while curr_node:
print(curr_node.data, end=" ")
curr_node = curr_node.next
print(' ')
| true |
215a7c17588c49ff792cbb940017d851a12647b1 | suryanjain14/prat | /stack/nGreater.py | 2,081 | 4.375 | 4 | # Next Greater Element
# Last Updated: 24-07-2019
# Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1.
#
# Examples:
#
# For any array, rightmost element always has next greater element as -1.
# For an array which is sorted in decreasing order, all elements have next greater element as -1.
# For the input array [4, 5, 2, 25}, the next greater elements for each element are as follows.
# Element NGE
# 4 --> 5
# 5 --> 25
# 2 --> 25
# 25 --> -1
# d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows.
#
# Element NGE
# 13 --> -1
# 7 --> 12
# 6 --> 12
# 12 --> -1
def nGreaterRight(array):
stack = [] #memo for right array
greater_array = []
for i in array[::-1]:
if len(stack) == 0:
greater_array.append(-1)
elif i <= stack[-1]:
greater_array.append(stack[-1])
elif i > stack[-1]:
while len(stack) > 0 and stack[-1] < i:
stack.pop()
if len(stack) == 0:
greater_array.append(-1)
else:
greater_array.append(stack[-1])
stack.append(i)
return greater_array[::-1]
def nGreaterLeft(array):
stack=[]
greater_left=[]
for i in array:
if len(stack)==0:
greater_left.append(-1)
elif stack[-1]>=i:
greater_left.append(stack[-1])
elif stack[-1]<i:
while len(stack)>0 and stack[-1]<i:
stack.pop()
if len(stack)==0:
greater_left.append(-1)
else:
greater_left.append(stack[-1])
stack.append(i)
return greater_left
array=[1, 2, 0, 0, 4, 3, 2]
# ans = nGreaterRight(array)
ans = nGreaterLeft(array)
print(array)
print(ans) | true |
14e51e0317a84c97ca0dd6da2282e9cf531856b3 | aravindanath/TeslaEV | /PycharmProjects/PythonSeleniumAutoAugSep/day5/findMethod.py | 367 | 4.28125 | 4 | word = 'geeks for geeks'
# returns first occurrence of Substring
result = word.find('geeks')
print("Substring 'geeks' found at index:", result)
result = word.find('for')
print("Substring 'for ' found at index:", result)
# # How to use find()
if (word.find('pawan') != -1):
print("Contains given substring ")
else:
print("Doesn't contains given substring")
| true |
6cae05d3adf52c391c9e87d9b02ce23944cd8eb7 | radadiyamohit81/Code-for-FAANG | /Graph/theMaze.py | 2,013 | 4.125 | 4 | # There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
# Given the maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return true if the ball can stop at the destination, otherwise return false.
# You may assume that the borders of the maze are all walls (see examples).
# Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
# Output: true
# Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.
class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
a, b = start
visited = set()
# DFS approach to explore all directions
visited.add((a, b))
q = [ [a, b] ]
while q != []:
a, b = q.pop(0)
# choose a direction
for dir in dirs:
r = a + dir[0]
c = b + dir[1]
# Move in that direction until stopping point
while 0 <= r <= len(maze)-1 and 0 <= c <= len(maze[0])-1 and maze[r][c] != 1:
r += dir[0]
c += dir[1]
r -= dir[0]
c -= dir[1]
# check if the stopped point is the destination, else mark the stopped point visited and add the ending position to stack to process on all possible directions
if [r, c] == destination:
return True
if (r, c) not in visited:
visited.add((r, c))
q.append([r, c])
return False
| true |
6491463571a713ba87c0dda8afc92d8b61a8c404 | radadiyamohit81/Code-for-FAANG | /DESIGN/PreCourse_1/Exercise_3.py | 2,279 | 4.28125 | 4 |
# PreCourse_1: Exercise_3 : Implement Singly Linked List.
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self, item):
if self.head == None:
self.head = Node(item)
else:
current = self.head
while current.next != None:
current = current.next #identifying the last node
current.next = Node(item) #adding the new node as the last node in the linkedlist
def iterate(self):
if self.head == None:
print ("It's an Empty List.")
else:
current = self.head
while current.next != None:
print (current.data)
current = current.next
print (current.data)
def length(self):
count = 0
current = self.head
if current == None:
return count
else:
while current != None:
count += 1
current = current.next
return count
def search(self, item):
current = self.head
found = False
while current != None and not found:
if current.data == item:
found = True
else:
current = current.next
return found
def remove(self, item):
current = self.head
found = False
previous = None
while not found: #finding the node to be deleted
if current.data == item:
found = True
else:
if current.next != None:
previous = current
current = current.next
else:
break
if previous == None: #deleting the node
self.head = current.next
else:
previous.next = current.next
mylist = UnorderedList()
mylist.add(12)
mylist.add(23)
mylist.add(45)
mylist.iterate()
print (mylist.length())
print (mylist.search(23))
# Deleting the node with value 12
mylist.remove(12)
mylist.iterate()
| true |
140d044640b7a648fb5f8a610c5ba81adf1e4020 | stasi009/FDSA | /hanoi_tower.py | 1,698 | 4.21875 | 4 |
def __move(N,frompole,topole,withpole):
"""
plate 1~N are on from pole
we are going to move plate 1~N from 'frompole' to 'topole' via 'withpole'
"""
if N == 1:
print "%d: %s ==> %s"%(N,frompole,topole)# move directly
else:
__move(N-1,frompole,withpole,topole)
print "%d: %s ==> %s"%(N,frompole,topole)
__move(N-1,withpole,topole,frompole)
def move(N):
__move(N,"L","R","M")
move(3)
############################## print out pole status at each time
class Pole(object):
def __init__(self,name,N=0):
self.name = name
self.items = range(N,0,-1)
def push(self,e):
self.items.append(e)
def pop(self):
return self.items.pop() # pop from tail only O(1)
def display(self):
print "%s: %s"%(self.name," ".join((str(e) for e in self.items)))
class HanoiTower(object):
def __init__(self,N):
self.N = N
self.poles = [Pole("L",N),Pole("M"),Pole("R")]
self.counter = 0
def display(self):
for p in self.poles:
p.display()
def __move(self,n,frompole,topole,withpole):
if n>=1:
self.__move(n-1,frompole,withpole,topole)
self.counter +=1
top = frompole.pop()
assert top == n # the last one
topole.push(top)
print "\n[%-3dth] disk#%-3d: %s ===> %s"%(self.counter,top,frompole.name,topole.name)
self.display()
self.__move(n-1,withpole,topole,frompole)
def move(self):
self.display()
self.__move(self.N,self.poles[0],self.poles[2],self.poles[1])
ht = HanoiTower(10)
ht.move()
| false |
05ea28bd4339f9c61efaceae3b9c31599c1bbe72 | n0execution/Cracking-the-code-interview | /Linked_Lists/python/palindrome.py | 1,437 | 4.1875 | 4 | from LinkedList import LinkedList
from Stack import Stack
def compare_lists(node1, node2):
while node1.next is not None:
if node1.data != node2.data:
return False
node1 = node1.next
node2 = node2.next
return True
def reverse_linked_list(node):
if node.next is None:
result_list = LinkedList()
result_list.append(node.data)
return result_list
result_list = reverse_linked_list(node.next)
result_list.append(node.data)
return result_list
def is_palindrome(linked_list):
reversed_list = reverse_linked_list(linked_list.head)
return compare_lists(linked_list.head, reversed_list.head)
def is_palindrome2(linked_list):
slow = linked_list.head
fast = linked_list.head
s = Stack()
while fast is not None and fast.next is not None:
s.push(slow.data)
slow = slow.next
fast = fast.next.next
if fast is not None:
slow = slow.next
while slow is not None:
top = s.pop()
if slow.data != top:
return False
slow = slow.next
return True
def main():
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(2)
linked_list.append(1)
linked_list.append(2)
print(is_palindrome2(linked_list))
if __name__ == '__main__':
main()
| true |
dcacfb0efc3c154e0e147cbb2f42d60f7c038232 | anamicusoftwire/calculator | /calculator.py | 1,126 | 4.21875 | 4 |
MULTIPLY_SIGN = 'x'
ADD_SIGN = '+'
SUBTRACT_SIGN = '-'
DIVIDE_SIGN = '/'
MOD_SIGN = '%'
POWER_SIGN = '^'
QUIT = 'q'
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def divide(a, b):
return float(a) / b
def multiply(a, b):
return a * b
def modulo(a, b):
return a % b
def power(a, b):
return a ** b
def calculate(operation, a, b):
if operation == MULTIPLY_SIGN:
return multiply(a, b)
if operation == ADD_SIGN:
return add(a, b)
if operation == DIVIDE_SIGN:
return divide(a, b)
if operation == SUBTRACT_SIGN:
return subtract(a, b)
if operation == MOD_SIGN:
return modulo(a, b)
if operation == POWER_SIGN:
return power(a, b)
print('Error: Undefined operation\n')
return None
def main():
while True:
operation = input('Enter operation:\n')
if (operation == QUIT):
break
a = int(input('First number:\n'))
b = int(input('Second number:\n'))
result = calculate(operation, a, b)
if result:
print('Result: ' + str(result))
main()
| false |
30f365b43aa536644108a92bbc8a4deec915cefc | afilcheff/Softuni-s-Programming-Basics-with-Python | /lecture 16/lecture 16 ex. 7.py | 498 | 4.125 | 4 | n = int(input())
sum_grades = 0
presentation = input()
final_grade = 0
counter = 0
while not presentation == 'Finish':
for i in range(n):
grade = float(input())
sum_grades += grade
average_grade = sum_grades / n
final_grade += average_grade
print(f'{presentation} - {average_grade:.2f}.')
counter += 1
sum_grades = 0
presentation = input()
final_grade = final_grade / counter
print(f"Student's final assessment is {final_grade:.2f}.") | true |
0d70c0fcb91850a5a560084ad1efd033f9039063 | Bariss77/Lesson_PYTHON | /Lesson_11_manager_context_pattern/lesson_11.2_example_Pattern.py | 2,192 | 4.59375 | 5 | # Пример повторяющего кода и устранение через паттерное проэктированиеЖ
# First example:
class Person(object): # Сщздаем два класса с одинаковой логикой
def say(self):
print('I am a person!')
class Teacher(object):
def tell_about_yourself(self):
print('I am a teacher!')
c = Person() # Сщздаем объекты классов
print(c.say()) # result: I am a person!
b = Teacher()
print(b.tell_about_yourself()) # result: I am a teacher!
# Убираем дублирование кода, тот же результат:
class Person2(object): # Сщздаем два класса, второй наследует первый.
role = 'person' # Объявляем атрибут класса
def say2(self): # Объявляем метод класса, через подстановку атрибута.
print('I am a {}!'.format(self.role))
class Teacher2(Person2):
role = 'teacher'
a = Person2()
print(a.say2()) # result: I am a person!
d = Teacher2()
print(d.say2()) # result: I am a teacher!
# Second example:
class Square(object):
def __init__(self, size):
self.height = size
self.width = size
print('Area is %d' % (self.height * self.width))
def __str__(self):
return 'Square with area: %d' % (self.width * self.height)
s = Square(size=10)
print(s.__str__()) # Считаем площадь квадрата
# Убираем дублирование кода, тот же результат:
class Square2(object):
def __init__(self, size):
self.height = size
self.width = size
print('Area is %d' % (self.get_area()))
def get_area(self):
return self.height * self.width
def __str__(self):
return 'Square with area: %d' % (self.get_area())
s = Square2(size=15)
print(s.__str__()) # Считаем площадь квадрата
| false |
91eed87cbf95564736bbcafbb6f3fcd700e821b6 | jspigner/online-item | /online-item.py | 590 | 4.125 | 4 | # Create a class called Grocery_Item
# Define parameters in the class with the following: self, name, price, and discount
# Define display_info to show information about grocery items in the class
class Grocery_Item:
def __init__(self, name, price, discount):
self.name = name
self.price = price
self.has_discount = discount
def display_info(self):
print(self.name, "is $", self.price)
apple = Grocery_Item("apple", 1, False)
cheerios = Grocery_Item("cheerios", 4, True)
apple.display_info()
print("does", cheerios.name, "have a discount?", cheerios.has_discount)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.