blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c324c4139710069983df6b836199bab22999d92c | NataliaDiaz/BrainGym | /diagonals-difference.py | 719 | 4.46875 | 4 | """
Given a square matrix of size , calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, . The next lines denote the matrix's rows, with each line
containing space-separated integers describing the columns.
Output Format
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
"""
def diagonals_difference(n, m):
d1 = 0
d2 = 0
i = 0
while i<n:
d1 += m[i][i]
d2 += m[i][n-1-i]
i +=1
result = abs(d1 - d2)
print result
return result
diagonals_difference(3,[[11, 2, 4],[4, 5, 6],[10, 8, -12]] )
| true |
6db2741fa74a3669be653874175e8d7e4c720478 | NataliaDiaz/BrainGym | /gemstones.py | 1,555 | 4.1875 | 4 | import sys
"""
Gemstones
Each rock is composed of various elements, and each element is represented by a lower-case Latin letter from
'a' to 'z'. An element can be present multiple times in a rock. An element is called a gem-element if it
occurs at least once in each of the rocks.
Given the list of rocks with their compositions, display the number of gem-elements that exist in those rocks.
Input Format: The first line consists of an integer, the number of rocks.
Each of the next lines contains a rock's composition. Each composition consists of lower-case letters of English
alphabet. Each composition consists of only lower-case Latin letters ('a'-'z').
Print the number of gem-elements that are common in these rocks. If there are none, print 0.
Sample Input
3
abcdde
baccd
eeabg
Sample Output
2
Only "a" and "b" are the two kinds of gem-elements, since these are the only characters that occur in
every rock's composition.
"""
import sys
def gemstones(stones=[]):
if len(stones)== 0:
i = 0
#n = int(sys.stdin.readline())
n = int(raw_input("N of stones:\n"))
while i< n:
#stones.append(str(sys.stdin.readline()))
stones.append(raw_input(" Stone:\n"))
i +=1
intersection = set(list(stones[0])) # otherwise the intersection is always the empty list!
for s in stones[1:]:
intersection = intersection & set(list(s))
gems = len(intersection)
print gems #, " Gemstones (", intersection,")"
gemstones(['abcdde','baccd','eeabg'])
gemstones()
| true |
38eeb0ad4d991a3d4e6e1e864045f6b9c492a029 | NataliaDiaz/BrainGym | /python-tasty-recipes.py | 1,109 | 4.21875 | 4 | import itertools
def select_best_possible_score(possible_values, n_elements):
"""
Returns all possible combinations, cartesian product, of subsets of values
in possible_values, where repeat= n_elements is the length of each combination tuple.
It does not produce same item repetitions
E.g.: list(itertools.product([1,2], repeat=3))
"""
possibilities = set(list(itertools.product(possible_values, repeat=n_elements)))
for combination_tuple in possibilities:
print "Combination possible: ", combination_tuple
return possibilities
select_best_possible_score([1,11], 2)
select_best_possible_score([1,11,111], 3)
import random
def sampling_without_replacement(list_of_values, n):
"""
Samples n samples without replacement
"""
#random.sample(xrange(len(list_of_values)), n)
samples = random.sample(list_of_values, n) # n = samples to take
print "Sampled elements: ", samples
# remove if this method is called more than once in our program!
for s in samples:
list_of_values.remove(s)
return samples
sampling_without_replacement([4,5,2,40], 2)
| true |
f4642731f7e807a5ca66e74ef116a24b86ec11c8 | hungry4therock/my-python | /exam2/exam2_7.py | 776 | 4.3125 | 4 | """
날짜:2021-05-13
이름:최현진
내용:파이썬 클래스 상속 연습문제
"""
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def hello(self):
print('--------')
print('이름:',self._name)
print('skdl:',self._age)
class :
def __init__(self, name, age, school, major):
super(). __init__(name, age)
self. _school = school
self. _major = major
def hello(self):
print('학교:',self._school)
print('이름:',self._major)
class :
def __init__(self, name, age, school, major, company):
super(). __init__(name, age,school, major)
self. _company = company
def hello(self):
print('회사:',self._company)
| false |
fc624f3b2c7bb3458e81e67d3d5a838cb566b256 | LalityaSawant/Python | /Somesmall problems/HelloWorld.py | 404 | 4.1875 | 4 | print('Hello, World!')
print(1 + 2)
print(7 * 6)
print()
print("The End")
print("Pytho's strings are easy to use")
print('We can even include "quotes" in strings')
print('hello' + ' world')
greetings = "Hello"
name = "Bruce"
print(greetings + name)
#if we want a space , we can add that too --> this is comment
print(greetings + ' ' + name)
name = input('Enter your name: ')
print(greetings + ' ' + name) | true |
c2ed8b0f456196309ce58b9a78251f346e62697d | LalityaSawant/Python | /python-masterclass/ProgramFlow/ifChallange.py | 257 | 4.125 | 4 | name = input("Enter your name: ")
age = input("Enter your age: ")
if name != '' and age != '' and 18 <= int(age) < 31:
print("Welcome to club 18-30 holidays, {}".format(name))
else:
print("Sorry you are not in our age limit to enjoy the holiday")
| true |
062f9e4dca95f644f30fd2a8c936ca42cf81f25b | latika18/learning | /Q002_check_if_prime.py | 328 | 4.1875 | 4 | # Question : Create a simple function that checks if a given number is prime number or not.
#check prime
def checkPrime(x):
status = True
for i in range (2, int(x**0.5),2):
if x % i == 0:
status = False
return status
x = int(raw_input("enter a number : "))
print checkPrime(x)
| true |
211f27fb2be98ee743b3457a60b5b86d8ba1b709 | latika18/learning | /Q018_merge_sort_on_list_s_c.py | 1,208 | 4.28125 | 4 |
def merge_sort(list_sort):
"""splits the list in two parts until each part is left with one member"""
if len(list_sort) == 1:
return list_sort
if len(list_sort)>= 2:
x= len(list_sort) / 2
part_a = list_sort[:x]
part_b = list_sort[x:]
sorted_part_a = merge_sort(part_a)
sorted_part_b = merge_sort(part_b)
return merge(sorted_part_a, sorted_part_b)
def merge(left , right):
"""merges the two parts of list after sorting them"""
sorted_list = []
i = 0
while left[:] and right[:] :
if left [i] > right [i]:
sorted_list.append(right[i])
right.remove(right[i])
else :
sorted_list.append(left[i])
left.remove(left[i])
if left[:]:
sorted_list.extend(left[:])
elif right[:] :
sorted_list.extend(right[:])
return sorted_list
details = [1,127,56,2,1,5,7,9,11,65,12,24,76,87,123,65,8,32,86,123,67,1,67,92,72,39,49,12 ,98,52,45,19,37,22,1,66,943,415,21,785,12,698,26,36,18,97,0,63,25,85,24,94,150]
print "List to be sorted = ", details
print "Sorted List = ", merge_sort(details)
| true |
9ebb5aeb2892bbb8399c2ced700740a85bccbbf8 | latika18/learning | /remove_duplicate_from_string.py | 1,231 | 4.34375 | 4 | # Python program to remove duplicates, the order of
# characters is not maintained in this program
# Utility function to convert string to list
def toMutable(string):
temp = []
for x in string:
temp.append(x)
return temp
# Utility function to convert string to list
def toString(List):
return ''.join(List)
# Function to remove duplicates in a sorted array
def removeDupsSorted(List):
res_ind = 1
ip_ind = 1
# In place removal of duplicate characters
while ip_ind != len(List):
if List[ip_ind] != List[ip_ind-1]:
List[res_ind] = List[ip_ind]
res_ind += 1
ip_ind+=1
# After above step string is efgkorskkorss.
# Removing extra kkorss after string
string = toString(List[0:res_ind])
return string
# Function removes duplicate characters from the string
# This function work in-place and fills null characters in the extra space left
def removeDups(string):
# Convert string to list
List = toMutable(string)
# Sort the character list
List.sort()
# Remove duplicates from sorted
return removeDupsSorted(List)
# Driver program to test the above functions
string = "geeksforgeeks"
print removeDups(string)
| true |
fa6efe8e93a28b118ded56e819eb27d7291ed532 | latika18/learning | /Q024_implement_queue_class_in_python.py | 1,395 | 4.46875 | 4 | #Question 24
#Implement a queue class in Python: It should support 3 APIs:
#queue.top(): prints current element at front of queue
#queue.pop(): takes out an element from front of queue
#queue.add(): adds a new element at end of stack
class Queue:
def __init__(self):
"""initialise a Queue class"""
self.items = []
def top(self):
"""returns the current element at front of queue"""
if self.items:
return self.items[0]
else:
raise Exception("Empty Queue")
def pop(self):
"""takes out an element from front of queue"""
if self.items:
self.items.pop(0)
else :
raise Exception("Empty Queue")
def add(self , item):
"""adds a new element at the end of queue"""
self.items.append(item)
queue_1 = Queue()
queue_1.add(12)
queue_1.add(11)
queue_1.add(55)
queue_1.add(66)
queue_1.add(56)
queue_1.add(43)
queue_1.add(33)
queue_1.add(88)
queue_1.add(56)
queue_1.add(34)
print queue_1
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
print queue_1.top()
queue_1.pop()
| true |
9862d8c162a46ae424d5e36d624a458088d136fc | dychen1/euler_project | /euler5.py | 319 | 4.21875 | 4 | #function 1: check if divisible by numbers between 1 to 20
def divisible(num):
for denum in range (2,21):
if num%denum != 0:
return False
return True
#increment numbers until divisible by all numbers between 1 to 20
num = 20
while True:
if divisible(num) == True:
break
num += 20
print (num) | true |
b917f048e245a5b6737f05a2622c932d71095a1a | burnjoe/fibonacci-sequence | /Fibonacci Sequence.py | 534 | 4.21875 | 4 | #ask user how many terms
term = int(input("Enter How Many Fibonacci Terms: "))
#declare variable
n1 = 0 #or n1, n2 = 0, 1
n2 = 1
ctr = 0
#conditioning (if user's input is a negative number then restart. elseif usinput is 1 then print 0)
#(else compute terms and print)
if term <= 0:
print("Please Enter Positive Integer Only, Please Restart.")
elif term == 1:
print(n1)
else:
while ctr < term:
print(n1)
nth = n1 + n2
#update variable
n1 = n2
n2 = nth
ctr += 1
| true |
f74843ea317d41e51e1c5fc767a096a978f1d39d | kumarsandeep2166/arpita-python-class | /functions/demo3.py | 671 | 4.3125 | 4 | # how to check a number is prime or not.
# A number must have two dividends i.e. 1 and the number itself only.
# algorithm for finding out 5 is prime or not
# take the number and check from 2 to 5 if there is any dividends available or not
# divide each number from 2 to 5 by 5
# take a counter value and assign it 1 if it is prime else if it is 0 then it is not prime.
def prime_check(n):
x=1
for i in range(2,n):
if n%i==0:
x=0
break
else:
x=1
return x
x = int(input("ENter a number: "))
result = prime_check(x)
if result==1:
print(x," is a prime number")
else:
print(x," is not a prime number")
| true |
9aac5ee44bf24699aeb581c61cfb3eafbc533406 | kumarsandeep2166/arpita-python-class | /array/demo7.py | 971 | 4.15625 | 4 | from numpy import *
arr = array([12,34,54,65,67])
print(arr)
# creating array using array()
arr = array([12,34,54,65,67])
print(arr)
a = array(arr)
# assigning an array on a variable by calling array()
print(a)
b=a
print(b)
# creating arrays using linspace()
# linspace(start, stop, n)
# start is a point from where iteration will start
# stop is where iteration stops
# n is the number that parts the element should be divided equally
x = linspace(0,10,5)
print(x)
x = linspace(0,15,5)
print(x)
x= linspace(0,100, 5)
print(x)
# creating array using logspace()
# logspace(start, stop, n)
# start is the starting point where iteration will start to the power to 10
# stop is the ending point where iteration will stop to the power to 10
# n is the divider
y = logspace(1, 5, 4)
n = len(y)
for i in range(n):
print('%.1f'%y[i])
# creating arrays using arrange()
# arange() in numpy is same as range()
a = arange(5,12)
print(a)
b = arange(1,21,2)
print(b) | true |
d0a4528955a43d5edbc230d8e635f8bd4057474d | kumarsandeep2166/arpita-python-class | /List/demo2.py | 858 | 4.3125 | 4 | num = [1,2,3,4,5]
n = len(num)
print('length of list is: ', n)
num.append(6)
print('after appending the list is: ', num)
num.insert(3,7)
print('after inserting the list is: ', num)
num1= num.copy()
print('after copying the new list is: ', num1)
i = num.count(1)
print('no of times: ', i)
num.extend(num1)
print('after extending the list is: ', num)
num.remove(7)
print('after removing the list is: ', num)
num.pop()
print('after poping the list is: ', num)
num.reverse()
print('after reversing the list is: ', num)
num.sort()
print('after sorting the list is: ', num)
num.sort(reverse=True)
print('after sorting the list is: ', num)
# num.clear()
# print('after clearing the list is: ', num)
# finding biggest and smallest element from list
n1 = max(num)
print('the biggest element is: ', n1)
n2 = min(num)
print('the smallest element is:', n2) | true |
a634f5f7e77776f7a29af094f8cc0df9404f8851 | kumarsandeep2166/arpita-python-class | /tuple/demo3.py | 456 | 4.34375 | 4 | # find out first occurance of an element in a tuple
# tup = (12,23,43,23,12,34,45,67)
# take inputs in the form of string separated by commas
str = input('enter elements:').split(',')
# store all the elements in the form of list
lst = [int(num) for num in str]
# list is converted to tuple
tup = tuple(lst)
x = int(input('enter the element to search:'))
try:
pos = tup.index(x)
print('index of 12 is:', pos+1)
except:
print('item not present') | true |
8ca540861e5f07ffceef984b6d61ab3643d46b46 | kumarsandeep2166/arpita-python-class | /List/demo4.py | 334 | 4.21875 | 4 | # howmany times an element is occured in the list
x = []
n = int(input("enter how many elements: "))
for i in range(n):
x.append(int(input('enter the element: ')))
print('the original list is: ', x)
y = int(input('enter the element to count: '))
c=0
for i in x:
if y==i:
c+=1
print(y, ' is repeated ',c, ' times' )
| true |
4fc347492926aa1faecef72dd99ef45592cc5095 | kumarsandeep2166/arpita-python-class | /functions/demo5.py | 781 | 4.28125 | 4 | # functions are first class objects
# it is possible to assign a function to a variable.
def fun():
i = int(input("enter a number: "))
return i
x=fun()
print(x)
# it is possible to define a function inside another function
def message(str):
def fun():
return "Hello "
res = fun()+str
return res
print(message("Python!!!!!"))
# it is possible to pass a functions as parameter to another function
def display(fun):
return "Hello "+fun
def call():
return "python!!!!"
print(display(call()))
# it is possible that a fucntion can return another function
def myfun():
def anotherfun():
return "Hello Moto!!!!!"
return anotherfun
x=myfun()
# when myfun is assigned over "x" then x also becomes a new function
print(x()) | true |
1b1cbc6c3ef4bf7d6d602a71bd0b05e312224fdd | kumarsandeep2166/arpita-python-class | /operators/demo3.py | 235 | 4.125 | 4 | # relational operator
a,b=1,2
print(a>b)
print(a>=b)
print(a<b)
print(a<=b)
print(a==b)
print(a!=b)
n=int(input("enter a number: "))
m=int(input("enter a number: "))
print(m>n)
print(m>=n)
print(m<n)
print(m<=n)
print(m==n)
print(m!=n) | false |
8c975d5c5b6d05aae226de9a604cb9c2d50593bb | ancuongnguyen07/TUNI_Prog1 | /Week9/tvsarjat.py | 2,177 | 4.40625 | 4 | """
COMP.CS.100 Programming 1
Read genres and tv-series from a file into a dict.
Print a list of the genres in alphabetical order
and list tv-series by given genre on user's command.
"""
def read_file(filename):
"""
Reads and saves the series and their genres from the file.
TODO: comment the parameter and the return value.
:para :filename-string
:return : a dict with key is genre and values are names of movies
"""
# TODO initialize a new data structure
movieDict = {}
try:
file = open(filename, mode="r")
for row in file:
# If the input row was correct, it contained two parts:
# · the show name before semicolon (;) and
# · comma separated list of genres after the semicolon.
# If we know that a function (method split in this case)
# returns a list containing two elements, we can assign
# names for those elements as follows:
name, genres = row.rstrip().split(";")
genres = genres.split(",")
# TODO add the name and genres data to the data structure
for g in genres:
if g not in movieDict:
movieDict[g] = [name]
continue
movieDict[g].append(name)
file.close()
return movieDict
# TODO return the data structure
except ValueError:
print("Error: rows were not in the format name;genres.")
return None
except IOError:
print("Error: the file could not be read.")
return None
def main():
filename = input("Enter the name of the file: ")
genre_data = read_file(filename)
# TODO print the genres
print(f"Available genres are: {(', '.join(sorted(genre_data.keys())).rstrip())}")
while True:
genre = input("> ")
if genre == "exit":
return
# TODO print the series belonging to a genre.
if genre not in genre_data or len(genre_data[genre]) == 0:
continue
else:
print(('\n'.join(sorted(genre_data[genre]))).rstrip())
if __name__ == "__main__":
main()
| true |
8ef21400c010f1b7546b24e1371254e25651d852 | ancuongnguyen07/TUNI_Prog1 | /Week10/product_template.py | 2,916 | 4.3125 | 4 | """
COMP.CS.100 Ohjelmointi 1 / Programming 1
Template for the product assignment.
"""
class Product:
"""
This class defines a simplified product for sale in a store.
"""
# TODO: Define all the methods here. You can see what they are,
# what parameters they take, and what their return value is
# by examining the main-function carefully.
#
# You also need to consider which attributes the class needs.
#
# You are allowed to modify the main function, but your
# methods have to stay compatible with the original
# since the automatic tests assume that.
def __init__(self, name, price, salePercentage = 0):
"""
A product objected is initialized with the name, price, sale attributes
:param : nam (string), price, salePercentage (float)
"""
self.__name = name
self.__price = price
self.__sale = salePercentage
def get_price(self):
"""
Calculate the price of the product object
formula: price - price * salePer
"""
return self.__price - self.__price * self.__sale / 100
def printout(self):
"""
Print all attributes of the object
"""
print(self.__name)
print(" "*2,end='')
print(f"price: {self.__price:.2f}")
print(" "*2,end='')
print(f"sale%: {self.__sale:.2f}")
def set_sale_percentage(self, salePer):
"""
Set a new value for the sale attribute
"""
self.__sale = salePer
def main():
################################################################
# #
# You can use the main-function to test your Product class. #
# The automatic tests will not use the main you submitted. #
# #
# Voit käyttää main-funktiota Product-luokkasi testaamiseen. #
# Automaattiset testit eivät käytä palauttamaasi mainia. #
# #
################################################################
test_products = {
"milk": 1.00,
"sushi": 12.95,
}
for product_name in test_products:
print("=" * 20)
print(f"TESTING: {product_name}")
print("=" * 20)
prod = Product(product_name, test_products[product_name])
prod.printout()
print(f"Normal price: {prod.get_price():.2f}")
print("-" * 20)
prod.set_sale_percentage(10.0)
prod.printout()
print(f"Sale price: {prod.get_price():.2f}")
print("-" * 20)
prod.set_sale_percentage(25.0)
prod.printout()
print(f"Sale price: {prod.get_price():.2f}")
print("-" * 20)
if __name__ == "__main__":
main()
| true |
a0d91f17aa049c237628b05dfb05e316e4027da7 | ancuongnguyen07/TUNI_Prog1 | /Week4/rubikCompetition.py | 1,090 | 4.3125 | 4 | """
COMP.CS.100 Programming 1 code template
Fill in all TODOs in this file
"""
def inputList(numOfPoints):
"""
Ask user type the point and package these points into
a ascending-order list
:param numOfPoints: a number of points a list can contains
:return :list of points
"""
pointList = []
for i in range(numOfPoints):
pointList.append(float(input(f"Enter the time for performance {i + 1}: ")))
return pointList
def removeMinMax(pointList):
"""
Remove the best and the worst point of the list
:param list of points
:return removed-best-worst list of points
"""
pointList.sort()
pointList.pop(0)
pointList.pop(len(pointList) - 1)
return pointList
def avgPoint(pointList):
"""
Calculate the average point of the list
:param list of points
:return avg_point
"""
return sum(pointList)/len(pointList)
def main():
myList = inputList(5)
removeMinMax(myList)
print(f"The official competition score is {avgPoint(myList):.2f} seconds.")
if __name__ == "__main__":
main() | true |
d400322c1abd5d6391ed21731059b00fa58347e1 | ancuongnguyen07/TUNI_Prog1 | /Week5/viesti.py | 683 | 4.1875 | 4 | """
COMP.CS.100 Programming 1
Code Template
"""
def main():
print("Enter text rows to the message. Quit by entering an empty row.")
msg = read_message()
print("The same, shouting:")
print('\n'.join(msg).upper().strip())
def read_message():
"""
Encrypts its parameter using ROT13 encryption technology.
:param text: str, string to be encrypted
:return: str, <text> parameter encrypted using ROT13
"""
rowList = []
#print("Enter the text rows of the message. End by entering an empty row.")
while True:
mess = input()
if mess == '': return rowList
rowList.append(mess)
if __name__ == "__main__":
main()
| true |
8a75e9745fd530c419cd390583fb0c5c672362bc | shahbaazsheikh7/pythoncode | /wordfreq.py | 1,291 | 4.125 | 4 | # Program to compute most used words in a text file
import string
import matplotlib.pyplot as plt
fname = input("Enter the filname: ")
try:
fhand = open(fname)
except:
print("Invalid filename")
exit()
wordcount = {}
cnt = 0
for line in fhand:
line = line.translate(str.maketrans('','',string.punctuation))
line = line.strip()
line = line.lower()
words = line.split()
if len(words)==0:
continue
for word in words:
wordcount[word] = wordcount.get(word,0) + 1
cnt = cnt + 1
#print(count)
wordlist = []
#print(type(wordcount.items()))
for word,count in wordcount.items():
wordlist.append((count,word)) #wordlist is list of tuples-- (count,word)
#print(type(wordlist[0]))
wordlist.sort(reverse=True)
print(fname,"contains",cnt,"words")
print("The 10 most used words in %s are: "%fname)
count_list = []
word_list = []
for count,word in wordlist[:10]:
print(word,count)
word_list.append(word)
count_list.append(count)
plt.xlabel("Words",color="Green")
plt.ylabel("Number of Occurences",color="Green")
plt.title("Top 10 most used words in '%s'"%fname,color="Green")
#plt.legend("'%s' has %d words"%(fname,cnt))
plt.bar(word_list,count_list)
plt.show()
| true |
6083eb6608f61567b90e966063d26a943f7b6bd4 | MrOrioleCashback/snippets | /Checkio.Common.Words.py | 858 | 4.375 | 4 | def checkio(first, second):
result = []
for word in first.split(','):
if word in second.split(','):
result.append(word)
return ','.join(sorted(result))
"""
Let's continue examining words. You are given two string with words separated
by commas. Try to find what is common between these strings. The words are not
repeated in the same string.
Your function should find all of the words that appear in both strings. The
result must be represented as a string of words separated by commas in
alphabetic order.
Input: Two arguments as strings.
Output: The common words as a string.
Example:
print(checkio("hello,world", "hello,earth")) == "hello"
print(checkio("one,two,three", "four,five,six")) == ""
print(checkio("one,two,three", "four,five,one,two,six,three")) == "one,three,two"
"""
| true |
4d154394affc20376b15f8d39882dc85405db708 | MrOrioleCashback/snippets | /Checkio.The.end.of.other.py | 971 | 4.5 | 4 | def checkio(words_set):
for word1 in words_set:
for word2 in words_set:
if is_at_end(word1, word2):
return True
return False
def is_at_end(word1, word2):
"""checks if word1 is at the end of word2"""
return word1 != word2 and word1 == word2[-len(word1):]
"""
Checkio: The end of other
http://www.checkio.org/mission/end-of-other/
In this task, you are given a set of words in lower case. Check
whether there is a pair of words, such that one word is the end
of another (a suffix of another).
For example: {"hi", "hello", "lo"} -- "lo" is the end of "hello",
so the result is True.
Input: Words as a set of strings.
Output: True or False, as a boolean.
Example:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
checkio({"walk", "duckwalk"}) == True
checkio({"one"}) == False
checkio({"helicopter", "li", "he"}) == False
"""
| true |
eaa8b096844f2e40158f71d5fe183cf31f7f13b4 | MrOrioleCashback/snippets | /CodeWars kyu7 2016-3-14.py | 2,467 | 4.40625 | 4 | """
Write a function that generate the sequence of numbers which starts from the
"From" number, then adds to each next term the "Step" number until the "To"
number. For example:
generator(10, 20, 10) = [10, 20] # "From" = 10, "Step" = 10, "To" = 20
generator(10, 20, 1) = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
generator(10, 20, 5) = [10, 15, 20]
If next term is greater than "To", it can't be included into the output array:
generator(10, 20, 7) = [10, 17]
If "From" bigger than "To", the output array should be written in reverse order:
generator(20, 10, 2) = [20, 18, 16, 14, 12, 10]
Don't forget about input data correctness:
generator(20, 10, 0) = []
generator(10, 20, -5) = []
"From" and "To" numbers are always integer, which can be negative or positive
independently. "Step" can always be positive.
"""
def generator (From, To, Step):
s = Step if From < To else -Step
t = 1 if From < To else -1
return [] if Step == 0 else [x for x in range(From, To+t, s)]
#print(generator(10, 20, 1))# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
#print(generator(20, 10, 1))# [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]
#print(generator(10, 20, 0))# []
#print(generator(10, 20, 5))# [10, 15, 20]
#print(generator(0, 1, 1)) # [0, 1]
#print(generator(10, 20, 7))# [10, 17]
"""
While developing a website, you detect that some of the members have troubles
logging in. Searching through the code you find that all logins ending with
a "_" make problems. So you want to write a function that takes an array of
pairs of login-names and e-mails, and outputs an array of all login-name,
e-mails-pairs from the login-names that end with "_".
If you have the input-array:
[ [ "foo", "foo@foo.com" ], [ "bar_", "bar@bar.com" ] ]
it should output
[ [ "bar_", "bar@bar.com" ] ]
You have to use the filter-method of Python, which returns each element of
the array for which the filter-method returns true.
"""
def search_names_list_comp(logins):
return ([x for x in logins if x[0][-1] == '_'])
def search_names(logins):
return list(filter(lambda x: x[0][-1] == '_', logins))
#print(search_names([[ "foo", "foo@foo.com" ], [ "bar_", "bar@bar.com" ]]))
#[[ "bar_", "bar@bar.com"]]
#print(search_names([[ "foobar_", "foo@foo.com" ], [ "bar_", "bar@bar.com" ]]))
#[["foobar_", "foo@foo.com"], ["bar_", "bar@bar.com"]]
#print(search_names([[ "foo", "foo@foo.com" ], [ "bar", "bar@bar.com" ]]))
# []
| true |
6240b1ba8cbf3dfc857b0838849a69dbf67ec128 | willidv/pie | /stars/stars.py | 498 | 4.1875 | 4 | def draw_Stars(list):
for i in list:
if type(i) == int:
print i * "*"
elif type(i) == str:
print i[0].lower() * len(i)
draw_Stars([4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"])
#This is a function that will iterate through an array(list). If the element in the array is an integer, it will print out the length of the integer in stars. If the element in the array is a string, it will print out the first letter of the string times the length of the string
| true |
71d57b6f8c8679e10502ce0860ead74dd72ed006 | sarmour/GitHub_Python_Scripts | /Coderbyte/swap_ii.py | 1,688 | 4.15625 | 4 | ##"""Using the Python language, have the function SwapII(str)
##take the str parameter and swap the case of each character.
##Then, if a letter is between two numbers (without separation),
##switch the places of the two numbers. \
##For example: if str is "6Hello4 -8World, 7 yes3"
##the output should be 4hELLO6 -8wORLD, 7 YES3"
##
def SwapII(str):
new = str.swapcase()
newword = ''
newsentence = []
count = 0
for word in new.split():
count = 0
for l in word:
if l.isdigit():
count +=1
if count >= 2:
nums = []
ind = []
i = 0
for l in word:
if l.isdigit():
nums.append(l)
ind.append(i)
i +=1
zipped = zip(nums,ind)
print v, i
print SwapII("6Hello4 -8World, 7 yes3")
## ct = 0
## nums = []
## for l in word:
## if l.isdigit():
## ct += 1
## nums.append(l)
##
## if ct>=2():
## i = 0
## for l in word:
## tmp.append(l)
##
## startpos = l.index(nums[o])
## endpos = l.index(nums[1])
##
#### for l in word:
#### if l in nums:
####
####
#### newword = "".join(lst)
####
## if newword <> "": newsentence.append(newword)
## else: newsentence.append(word)
## newword = ''
## return " ".join(newsentence)
# keep this function call here
# to see how to enter arguments in Python scroll down
| true |
935dfe7ebd5dea171c97d630e85ea6008544cacd | larj3852/Curso_Python | /03 - List Comprehension/ListComprehensions.py | 1,457 | 4.65625 | 5 | """
@description List comprehensions are used for creating new lists from other iterables
As list comprehensions return lists, they consist of brackets containing the expression,
which is executed for each element along with the for loop to iterate over each element.
@sintax new_list = [expression for_loop_one_or_more conditions]
"""
#Ejemplo1 --> Finding squares using list comprehensions
print("Ejemplo1 --> Finding squares using list comprehensions")
numbers = range(10)
squares = [n**2 for n in numbers]
print(squares)
#Ejmplo 2 --> Find common numbers from two lists using list comprehension
print("Ejmplo 2 --> Find common numbers from two lists using list comprehension")
list_a = [1, 2, 3, 4];list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num) # Output: [2, 3, 4]
#Ejemplo 3 --> Filtros
print("Ejemplo 3 --> Filtros")
list_a = ["Hello", "World", "In", "Python"]
small_list_a = [str.lower() for str in list_a]
print(small_list_a) # Output: ['hello', 'world', 'in', 'python']
#Ejemplo 4 --> Lista de listas
print("Ejemplo 4 --> Lista de listas")
list_a = [1, 2, 3]
square_cube_list = [ [a**2, a**3] for a in list_a]
print(square_cube_list) # Output: [[1, 1], [4, 8], [9, 27]]
#Ejemplo 5 --> Iterating through a string Using for Loop
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters) #['h', 'u', 'm', 'a', 'n']
| true |
31019f92c8d61347ecefe25817fc4274ca613fcd | troywill1/NanoSupport | /mindstorms.py | 1,239 | 4.84375 | 5 | # Lesson 3.3: Use Classes
# Mini-Project: Draw Turtles
# turtle is a library we can use to make simple computer graphics. Kunal
# wants you to try drawing circles using squares. You can also use this
# space to create other kinds of shapes. Experiment and share your results
# on the Discussion Forum!
import turtle
# Your code here.
def draw_square(some_turtle):
"""
docstring here
"""
for i in range(0,4):
some_turtle.forward(100)
some_turtle.right(90)
def draw_circle():
# Draw a circle
angie = turtle.Turtle()
angie.shape("circle")
angie.color("blue")
angie.circle(100)
def draw_triangle():
# Draw a triangle
bart = turtle.Turtle()
bart.shape("triangle")
bart.color("red")
for i in range(0,3):
bart.forward(200)
bart.left(120)
# Create a screen and set its background color
window = turtle.Screen()
window.bgcolor("white")
# Create a turtle to draw a square
troy = turtle.Turtle()
troy.shape("arrow")
troy.color("black", "blue")
troy.speed(2)
# Draw a circle out of squares
for i in range(0,36):
draw_square(troy)
troy.right(10)
# draw_circle()
# draw_triangle()
# Ability to exit the window by clicking
window.exitonclick()
| true |
eea13cc42e02a60d4ec81f8d7a45fc5b45bb1d4e | vaibhavsingh97/PythonPrograms | /week 1/6.py | 230 | 4.46875 | 4 | # 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):
return string[::-1]
print(reverse("i am testing"))
| true |
0e070d53ce691eb68db270efd6d3c290a23307c3 | XiaoliSong/Aim-at-offer-python | /11-20/12.数值的整数次方.py | 1,089 | 4.40625 | 4 | '''
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
解题思路
一、直接返回 base**exponen
二、一维数组分别保存base的1,2,4,8,....2^31 次方,然后exponent对应二进制位为1则乘上,注意exponent为负的情况
'''
'''
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return base**exponent
'''
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 0:
return 1
arr = [base]
i = 1
while i < 32:
arr.append(arr[-1] * base)
i += 1
if exponent < 0:
positive = False
exponent = -exponent
else:
positive = True
res = 1
i = 0
while i < 32:
if exponent & 1:
res *= arr[i]
exponent = exponent >> 1
i += 1
if not positive:
res = 1 / res
return res | false |
df654be4951e3c74c41f24093b635b5ad168bead | ariellewaller/Python-Crash-Course | /Chapter 6/favorite_places.py | 723 | 4.625 | 5 | # 6-9. Favorite Places: Make a dictionary called favorite_places. Think of
# three names to use as keys in the dictionary, and store one to three
# favorite places for each person. To make this exercise a bit more
# interesting, ask some friends to name a few of their favorite places.
# Loop through the dictionary, and print each person’s name and their favorite
# places.
favorite_places = {
'david': ['Miami', 'Los Angeles', 'Chicago'],
'alexis': ['Dubai', 'Greece', 'Galapagos Islands'],
'moira': ['Paris', 'Milan', 'Barcelona']
}
for person, places in favorite_places.items():
print(f"\n{person.title()}'s favorite places are:")
for place in places:
print(f"{place}")
| true |
19888c998e8787533e84413272da1183f16fcdb1 | ariellewaller/Python-Crash-Course | /Chapter 8/album.py | 1,801 | 4.625 | 5 | # 8-7. Album: Write a function called make_album() that builds a dictionary
# describing a music album. The function should take in an artist name and an
# album title, and it should return a dictionary containing these two pieces
# of information. Use the function to make three dictionaries representing
# different albums. Print each return value to show that the dictionaries are
# storing the album information correctly. Use None to add an optional
# parameter to make_album() that allows you to store the number of songs on an
# album. If the calling line includes a value for the number of songs, add
# that value to the album’s dictionary. Make at least one new function call
# that includes the number of songs on an album.
# PART ONE
def make_album(artist_name, album_title):
"""Build a dictionary describing a music album"""
music_album = {
'Artist': artist_name.title(),
'Album': album_title.title()
}
return music_album
print("Here's Part One:")
cardi = make_album('cardi b', 'invasion of privacy')
print(cardi)
jhene = make_album('jhene aiko', 'souled out')
print(jhene)
lennon = make_album('lennon stella', 'three. two. one.')
print(lennon)
# PART TWO
def make_album_two(artist_name, album_title, number_of_songs= None):
"""Build a dictionary describing a music album"""
music_album = {'Artist': artist_name.title(),
'Album': album_title.title()}
if number_of_songs:
music_album['Number of Songs'] = number_of_songs
return music_album
print("\nHere's Part Two:")
cardi = make_album_two('cardi b', 'invasion of privacy')
print(cardi)
jhene = make_album_two('jhene aiko', 'souled out')
print(jhene)
lennon = make_album_two('lennon stella', 'three. two. one.', 13)
print(lennon)
| true |
56c1c95fda930d741b4d781002aeab0004a643e3 | ariellewaller/Python-Crash-Course | /Chapter 8/sandwiches.py | 684 | 4.375 | 4 | # 8-12. Sandwiches: Write a function that accepts a list of items a person
# wants on a sandwich. The function should have one parameter that collects as
# many items as the function call provides, and it should print a summary of
# the sandwich that’s being ordered. Call the function three times, using a
# different number of arguments each time.
def build_a_sandwich(*toppings):
"""Print a summary of the sandwich being ordered."""
print("\nHere's what I have for your order:")
for topping in toppings:
print(f"-{topping}")
build_a_sandwich('tomato', 'cheese', 'lettuce')
build_a_sandwich('zucchini')
build_a_sandwich('mayo', 'cheese', 'pickes')
| true |
81c9ae277f6a3fe013cd9969eef94c35cd31c04f | ariellewaller/Python-Crash-Course | /Chapter_9/number_served.py | 2,291 | 4.46875 | 4 | # 9-4. Number Served: Start with your program from Exercise 9-1 (page 162).
# Add an attribute called number_served with a default value of 0. Create an
# instance called restaurant from this class. Print the number of customers
# the restaurant has served, and then change this value and print it again.
# Add a method called set_number_served() that lets you set the number of
# customers that have been served. Call this method with a new number and
# print the value again.
# Add a method called increment_number_served() that lets you increment the
# number of customers who’ve been served. Call this method with any number you
# like that could represent how many customers were served in, say, a day of
# business.
class Restaurant:
"""Represent a restaurant."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize the restaurant."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""Print the restaurant name and cuisine type."""
print(f"Restaurant name: {self.restaurant_name}")
print(f"Cusine type: {self.cuisine_type}")
def open_restaurant(self):
"""Prints a message saying the restaurant is open."""
print(f"{self.restaurant_name} is open for business.")
def set_number_served(self, number_served):
"""Set the number of customers that have been served."""
self.number_served = number_served
def increment_number_served(self, add_number_served):
"""Add the given number to the number of customers served."""
self.number_served += add_number_served
restaurant = Restaurant("Terry's", "soul food")
print(f"{restaurant.restaurant_name} has served {restaurant.number_served} "
"customers.")
restaurant.number_served = 1_000_000
print(f"\n{restaurant.restaurant_name} has served {restaurant.number_served} "
"customers.")
restaurant.set_number_served(5_000_000)
print(f"\n{restaurant.restaurant_name} has served {restaurant.number_served} "
"customers.")
restaurant.increment_number_served(10_000)
print(f"\n{restaurant.restaurant_name} has served {restaurant.number_served} "
"customers.")
| true |
87899c8daab82a1187003637621a307095340822 | Collumbus/Python-Stuffs | /calculating-with-functions.py | 1,736 | 4.40625 | 4 | '''
This time we want to write calculations using functions and get the results. Let's have a look at some examples:
seven(times(five())) # must return 35
four(plus(nine())) # must return 13
eight(minus(three())) # must return 5
six(divided_by(two())) # must return 3
Requirements:
There must be a function for each number from 0 ("zero") to 9 ("nine")
There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy (divided_by in Ruby and Python)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner function represents the right operand
Divison should be integer division. For example, this should return 2, not 2.666666...:
eight(divided_by(three()))
'''
def zero(operation=None): return 0 if not operation else operation(0)
def one(operation=None): return 1 if not operation else operation(1)
def two(operation=None): return 2 if not operation else operation(2)
def three(operation=None): return 3 if not operation else operation(3)
def four(operation=None): return 4 if not operation else operation(4)
def five(operation=None): return 5 if not operation else operation(5)
def six(operation=None): return 6 if not operation else operation(6)
def seven(operation=None): return 7 if not operation else operation(7)
def eight(operation=None): return 8 if not operation else operation(8)
def nine(operation=None): return 9 if not operation else operation(9)
def plus(b): return lambda a: a + b
def minus(b): return lambda a: a - b
def times(b): return lambda a: a * b
def divided_by(b): return lambda a: int(a / b) if b != 0 else 'Imposible divide by zero!'
print(two(plus(three()))) | true |
bf70f9f40654d99bad3e0b311d0297b29cab154c | shahdharm/PythonBasics | /lab exercise 2/q 4.py | 315 | 4.375 | 4 | # if temperature is grater than 30,it's a hot day other wise if it's less than 10;
# it's a cold day ; other wise,it's neither hot and cold.
int = int(input("enter the temperature:"))
if int >30:
print("hot")
if int <10:
print("cold")
elif int<30>10:
print("neither hot and cold")
else:
print()
| true |
d6d91a8b23098e982d50d55076e390cb56096c79 | shahdharm/PythonBasics | /lab exercise 2/qn.9.py | 413 | 4.1875 | 4 | # Check whether the given year is leap year or not. If year is leap print ‘LEAP YEAR’ else print ‘COMMON YEAR’.
# Hint: •a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100•
# a year is always a leap year if its number is exactly divisible by 400
year = int(input("enter the days:"))
if (year%400)==0:
print("leap year")
else:
print("common year") | true |
9084cf8b0e421f605120643c9f16f70a6867f74a | beadoer1/sparta | /etc/hello.py | 2,383 | 4.21875 | 4 | # print ('Hello, sparta')
# a = 3 # 3을 a에 넣는다
# b = a # a를 b에 넣는다
# a = a + 1 # a+1을 다시 a에 넣는다
# num1 = a*b # a*b의 값을 num1이라는 변수에 넣는다
# num2 = 99 # 99의 값을 num2이라는 변수에 넣는다
# print (num1)
# print (num2)
# # 변수의 이름은 마음대로 지을 수 있음!
# # 진짜 "마음대로" 짓는 게 좋을까? var1, var2 이렇게?
# name = 'bob' # 변수에는 문자열이 들어갈 수도 있고,
# num = 12 # 숫자가 들어갈 수도 있고,
# is_number = True # True 또는 False -> "Boolean"형이 들어갈 수도 있습니다.
# print (name)
# print (num)
# print (is_number)
# #########
# # 그리고 List, Dictionary 도 들어갈 수도 있죠. 그게 뭔지는 아래에서!
# a_list = []
# a_list.append(1) # 리스트에 값을 넣는다
# a_list.append([2,3]) # 리스트에 [2,3]이라는 리스트를 다시 넣는다
# # print 를 사용해서 아래 값을 확인해봅시다
# # a_list의 값은? [1,[2,3]]
# # a_list[0]의 값은? 1
# # a_list[1]의 값은? [2,3]
# # a_list[1][0]의 값은? 2
# print (a_list)
# print (a_list[0])
# print (a_list[1])
# print (a_list[1][0])
# a_dict = {}
# a_dict = {'name':'bob','age':21}
# a_dict['height'] = 178
# # print 를 사용해서 아래 값을 확인해봅시다
# # a_dict의 값은? {'name':'bob','age':21, 'height':178}
# # a_dict['name']의 값은? 'bob'
# # a_dict['age']의 값은? 21
# # a_dict['height']의 값은? 178
# print(a_dict)
# print(a_dict['name'])
# print(a_dict['age'])
# print(a_dict['height'])
# people = [{'name':'bob','age':20},{'name':'carry','age':38}]
# # print 를 사용해서 아래 값을 확인해봅시다
# # people[0]['name']의 값은? 'bob'
# # people[1]['name']의 값은? 'carry'
# print (people[0]['name'])
# print (people[1]['name'])
# person = {'name':'john','age':7}
# people.append(person)
# # print 를 사용해서 아래 값을 확인해봅시다
# # people의 값은? [{'name':'bob','age':20},{'name':'carry','age':38},{'name':'john','age':7}]
# # people[2]['name']의 값은? 'john'
# print (people) # --> 지정해놓은 List 는 ''를 붙이지 않고 출력
# print (people[2]['name'])
# def sum_all(a,b,c):
# return a+b+c
# def mul(a,b):
# return a*b
# result = sum_all(1,2,3) + mul(10,10)
# # result라는 변수의 값은?
# print (result)
| false |
ce0c6846be80f87b85828b31232f0644bf5809b3 | sbrohl3/projects | /IT410_SBrohl2/Lecture Notes/user_input.py | 493 | 4.34375 | 4 | ## Lecture: Gathering User Input Demonstration
## IT 410 - Walsh College
## 05/25/2019
## BROHL, STEVEN
area_code = input("Please enter your area code: ")
if area_code:
try:
int(area_code)
if len(area_code) == 3:
print("Your area code is: " + area_code)
else:
print("Your inputted area code is not long enough")
except:
print("You did not provide a valid area code")
else:
print("You did not enter an area code.") | true |
1667b705238268a9db9b4db0558daf1d4efb3135 | sbrohl3/projects | /IT410_SBrohl2/Lecture Notes/function_test.py | 1,044 | 4.25 | 4 | ## Lecture: Working with Functions
## IT 410 - Walsh College
## 06/02/2019
## BROHL, STEVEN
def divideTwoNumbers(passed_list):
divide_results = []
numbers_ok = True
passed_number1 = 1
passed_number2 = 1
for divide_vals in passed_list:
numbers_ok = True
try:
passed_number1 = int(divide_vals["top_number"])
except:
print("The first parameter is not an integer")
numbers_ok = False
try:
passed_number2 = int(divide_vals["bottom_number"])
except:
print("The second parameter is not an integer")
numbers_ok = False
if numbers_ok:
divide_result = passed_number1 / passed_number2
divide_results.append(divide_result)
return divide_results
division_list = [{"top_number": "square", "bottom_number": 2,}, {"top_number": 5, "bottom_number": 8,}]
the_result = divideTwoNumbers(division_list)
print("The result of division is:")
print(the_result) | true |
a1e03abb28991983009713887bee0f98380b979b | dwaghray/python-basics | /02.numberEvaluator.py | 342 | 4.46875 | 4 | # Number evauluation program
# get input from the user
number = eval(input("Please enter a number: "))
# determine if the number is odd, even, or not a whole number
if number % 2 == 0:
print("Even number detected.")
elif number % 2 == 1:
print("Odd number detected.")
else:
print("Brace yourself - that's not a whole number!")
| true |
601c5a1c887a578d173126ca28407084acb194ed | dwaghray/python-basics | /26.movieObject.py | 1,230 | 4.125 | 4 | class Movie(object):
def __init__(self, title, rating):
self.title = title
self.rating = rating
def __str__(self):
return self.title + " is rated " + \
str(self.rating) + "/10."
def __gt__(self, other): # overloads >, comparison is based on rating
return self.rating > other.rating
def __eq__(self, other): # overloads ==, comparison is based on rating
return self.rating == other.rating
movies = [Movie("The Extremely Disreputable Budapest Hotel", 2), Movie("Inside Out 2: Total Rage", 4),
Movie("Star Wars: episode VIII - Luke Sulks For Two Hours", 1), Movie("The Martian 2 - Revenge of the Potato", 6),
Movie("Zootopia Vs The Jungle Book", 5), Movie("Losing Dory", 3),
Movie("Guardians of the Galaxy 2: Endless Dance-off", 7), Movie("Captain America: Tony Stark Takes His Medication", 8),
Movie("The Lego my Eggo Movie", 5), Movie("Three Days, Two Nights, Business Economy Class", 2),
Movie("Mad Max: Really Peaceful Road", 6), Movie("Dawn of the Revenge of the Sequel of the Movie About Apes", 3)]
print("The movies, sorted by rating:")
print("-" * 70)
for movie in sorted(movies):
print(movie)
| true |
28cd6de577fcd935768a775c26d84a3d85ed51af | dwaghray/python-basics | /08.wordTriangle.py | 220 | 4.34375 | 4 | # takes a message as user input and prints it out in a "triangle"
# shape with one character added on to a new line
message = input("Please enter a message: ")
for i in range(len(message) + 1):
print(message[:i])
| true |
cb50583fe82fda156267b972224067fd87a0429e | marcusshepp/intro_ai | /tictacfinger/play.py | 1,581 | 4.25 | 4 | import random as rand
from tictacfinger.tictactoe import Game
from tictacfinger.cpu_player import CPUPlayer
if __name__ == "__main__":
start_text = """
Tic Tac Toe
Human vs CPU
How to play:
Enter: 0, 1 or 2
First value is the row.
Second value is the column.
You are "X".
The CPU is "O".
Example:
[in]:
1
1
[out]:
[" ", " ", " "]
[" ", "X", " "]
[" ", " ", " "]
"""
print start_text
g = Game()
init_cpu = {"piece":-1, "game":g}
cpu = CPUPlayer(**init_cpu)
rand_num = rand.randint(0, 1)
if rand_num == 1:
print "Human goes first"
while not g.there_is_a_winner():
# u = user
u_x = raw_input()
u_x = int(u_x)
u_y = raw_input()
u_y = int(u_y)
g.move(u_x, u_y, 1)
g.display_board()
if g.draw():
break
if g.there_is_a_winner():
break
g.move(**cpu.level_three())
g.display_board()
g.display_winner()
else:
print "CPU goes first"
while not g.there_is_a_winner():
g.move(**cpu.level_three())
g.display_board()
if g.draw():
break
if g.there_is_a_winner():
break
# u = user
u_x = raw_input()
u_x = int(u_x)
u_y = raw_input()
u_y = int(u_y)
g.move(u_x, u_y, 1)
g.display_board()
g.display_winner()
| false |
9c010ce836b15aede6d95eca0f6959453a1ba2eb | sarthaksr19/Chapter-5 | /05_pr_01.py | 353 | 4.25 | 4 | myDict = {
"kitaab": "books",
"darwaaza": "door",
"bartaan": "utensils"
}
print("your hindi words are ", myDict.keys())
a = input("enter your hindi word: ")
# print("the meaning of your word is ", myDict[a)]
# below line will return none value if keys doesn't match with a user input.
print("the meaning of your word is ", myDict.get(a))
| false |
9758ab1367478ee19f7123681da649f0bd3b1ea0 | cprezes/phyton_tests | /phyton_test0/u3-2.py | 2,217 | 4.375 | 4 | python_versions = [1.0, 1.5, 1.6, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6]
def p(args):
print(args)
p( python_versions[0])
p(python_versions[1])
p(python_versions[7])
p(python_versions[-1])
def how_many_days(month_number):
"""Returns the number of days in a month.
WARNING: This function doesn't account for leap years!
"""
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
#todo: return the correct value
return days_in_month[month_number]
# This test case should print 31, the number of days in the eighth month, August
print(how_many_days(8)+1)
eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
'March 9, 2016']
# TODO: Modify this line so it prints the last three elements of the list
print(eclipse_dates[-3:])
nautical_directions = "\n".join(["fore", "aft", "starboard", "port"])
print(nautical_directions)
names = ["García", "O'Kelly", "Davis"]
print("-".join(names))
names = ["García" "O'Kelly", "Davis"]
print("-".join(names))
def top_three(input_list):
"""Returns a list of the three largest elements input_list in order from largest to smallest.
If input_list has fewer than three elements, return input_list element sorted largest to smallest/
"""
lista= sorted(input_list,reverse=True)
return lista[0:3]
print( top_three([2,3,5,6,8,4,2,1]))
def median(numbers):
numbers.sort() #The sort method sorts a list directly, rather than returning a new sorted list
if len(numbers)%2==1:
middle_index = int(len(numbers)/2)
return numbers[middle_index]
else:
middle_index = int(len(numbers)/2)
return (numbers[middle_index]+numbers[middle_index-1])/2
test1 = median([1,2,3])
print("expected result: 2, actual result: {}".format(test1))
test2 = median([1,2,3,4])
print("expected result: 2.5, actual result: {}".format(test2))
test3 = median([53, 12, 65, 7, 420, 317, 88])
print("expected result: 65, actual result: {}".format(test3))
| true |
572e674ad948c40dee59d3af5f20c3a7513c64ee | xlanor/bored | /reverse_32_bit.py | 1,093 | 4.21875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
is_neg = True if x < 0 else False
int_str = list(str(abs(x)))
left = 0
right = len(int_str)-1
while left < right:
int_str[left], int_str[right] = int_str[right], int_str[left]
left, right = left+1, right-1
int_val = int("".join(int_str))
# upper bound of a signed integer is not 232 - 1, but 231 - 1, since the first bit is the sign bit.
if int_val>>31:
return 0
return -1 * int_val if is_neg else int_val
| true |
909b0e2d3ba56eb42b9a0e916536ad22e675584f | aharring/GMITPyProg2021 | /week03/lab3.2.3.floor.py | 249 | 4.21875 | 4 | # floors a number.
#
# Author: Adele Harrington,based on tutorial by lecturer Andrew Beatty
#
import math
numberTofloor = float(input("Enter a float number:"))
flooredNumber = math.floor(numberTofloor)
print('{} floored is {}'.format(numberTofloor,flooredNumber))
| true |
e56b92f0d103bbe8b126f994b429db4ae1087f08 | aharring/GMITPyProg2021 | /week04/lab4.2.2.guess1.py | 428 | 4.21875 | 4 | # Lab week 4. Based on Lecture 2.
# Write a program (guess1.py) that prompts the user to guess a number, the
# program should keep prompting the user to guess the number until the user
# gets the right on
#
numberToGuess = 30
guess = int(input("Please guess the number:"))
while guess != numberToGuess:
print ("Wrong")
guess = int(input("Please guess again:"))
print ("Well done! Yes the number was ", numberToGuess)
| true |
c8b3906d36673a2c25932b185b299954dc33b24b | aharring/GMITPyProg2021 | /week01/Lab1/firstprogram.py | 1,765 | 4.46875 | 4 | # 20/01/2021 My first Python Program
# It imports the date module
# Then it create a variable 'today' and assigns todays date to it
# It then prints out a statement including todays date
# It then opens the ReadMe file and prints the contents to screen
# The ReadMe file explains what commands will run next - either listdir or ls -alrt, one uses os, one uses subprocees run
# The user is asked if they want to proceed
# If the user answers y or Y the code executes otherwise the program ends
# I am using W3schools to learn python syntax. I learned about the subprocess module from pymotw.com
# I tested this program by typing python3 firstprogram.py on my command line
# I am not sure yet how Anaconda is used with Python
from datetime import date
today = date.today()
print("Today is :", today)
ReadMe = open("ReadMe.txt", "r")
# Open the file ReadMe.txt for reading
ReadMeContents = ReadMe.read()
# Assign the contents of the file to the variable ReadMeContents
print (ReadMeContents)
#Print the contents of the file now stored in variable ReadMeContents
ReadMe.close()
# Close the file handle
UserInput = input("Continue y or n: ")
# Debug statement print("You entered: " + UserInput)
# Using module OS to get a directory listing
# I used listdir as opposed to walk because walk required a path but listdir lists the contents of the current directoy
if UserInput.upper() == "Y":
import os
CurrentDirListing = os.listdir()
print("Printing the results of os.listdir command")
print(CurrentDirListing)
import subprocess
print("Executing subprocess command run with parameters ls -alrt")
commandreturncode = subprocess.run(['ls', '-alrt'])
print('returncode:', commandreturncode.returncode)
else:
print("You chose not to execute the commands")
| true |
239fe5a4aba83bba7f262ee720c399feee91d9bf | ijayoa/drama_trailer_website | /media.py | 1,412 | 4.3125 | 4 | class Drama(): # Create drama class
"""This class stores information about tv dramas."""
# Set constructor to initialize new drama instances
def __init__(self, drama_title, drama_description, drama_poster,
trailer_url, year_released, number_of_episodes):
""" Constructor, the class initializer method.
Args:
drama_title (str): Stores the title of the drama
drama_description (str): Synopsis of the drama
drama_poster (str): Official poster imagery
trailer_url (str): Drama trailer url on youtube
year_released (int): This is year the drama was released
number_of_episodes (int): Number of drama episodes
Attributes:
title (str): Stores the title of the drama
drama_description (str): Synopsis of the drama
poster_image_url (str): Official poster imagery
trailer_youtube_url (str): Drama trailer on youtube
year_released (int): This stores the release year of the drama
episodes (int): Number of drama episodes
"""
self.title = drama_title
self.drama_description = drama_description
self.poster_image_url = drama_poster
self.trailer_youtube_url = trailer_url # define instance variables
self.year_released = year_released
self.episodes = number_of_episodes
| true |
8eda03743be548df443e06262636d543270d79c8 | Irinkaaa/Practice_Python_archived | /01_Character_input.py | 921 | 4.34375 | 4 | '''Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will turn 100 years old.
Extras:
Add on to the previous program by asking the user for another number
and printing out that many copies of the previous message.
Print out that many copies of the previous message on separate lines.'''
print("Hello there! Let me tell you a secret.")
name = str(input("Give me your name: "))
print("Hey, " + name)
age = int(input("Tell me how old are you: "))
current_year = 2018
number = int(input("Pick a number between 1 and 10: "))
def calculate_year(year):
born_year = current_year - year
future_year = born_year + 100
return future_year
hundred_year = str(calculate_year(age))
print(("Hey, %s you will be 100 years old in " % name + hundred_year + "! HAHAHA" + '\n') * number)
| true |
db9ae9dd86c86df1bd8b0ac1ef37c544390b456e | Irinkaaa/Practice_Python_archived | /06_String_Lists.py | 383 | 4.375 | 4 | '''Ask the user for a string and print out whether this string is a palindrome or not.
A palindrome is a string that reads the same forwards and backwards.)'''
print("Lets play another game.")
word = (input("Type in any word you like: "))
if str(word) == str(word[::-1]):
print("Hey, your word is palindrome!")
else:
print("Hey, your word is not palindrome!")
| true |
2afbbfddd21234891542db7d15c645b43ad08685 | 1024Person/LearnPy | /Day11/code/闭包的简单应用.py | 508 | 4.21875 | 4 | # 闭包的简单应用
# 打破壁垒,(打破作用域的权限)
# 记录状态
def func(a, b):
c = 100
def inner_func():
s = a + b + c
print('相加之后的结果为', s)
return inner_func
# add 就是内部函数,相当于函数指针
a = 120
b = 123
add = func(a, b)
add1 = func(1, 2)
add() # a , b 状态下的相加
add1() # 1,2 状态下的相加
# 闭包不会因为参数的改变而受影响
f = func
print(f(1, 2))
print(add1)
print(add)
f(1, 2)()
| false |
d9fc87b00cd12a77de072ed36b030cad7fb29b67 | soaresderik/IFLCC | /01semestre/introducao-algoritmo/python/qst03.py | 296 | 4.28125 | 4 | num = int(input("Digite um número: "))
if num > 0:
pos_or_neg = "e é positivo."
elif num < 0:
pos_or_neg = "e é nagativo."
else:
pos_or_neg = "e o número é zero"
if num % 2 == 0:
print(num, "É um número par", pos_or_neg)
else:
print(num, "É um número impar", pos_or_neg)
| false |
9f17669ad0850110bef641d7583901dee1e81cb8 | TejshreeLavatre/GeeksForGeeks | /String/Save Ironman.py | 1,164 | 4.125 | 4 | """
Jarvis is weak in computing palindromes for Alphanumeric characters.
While Ironman is busy fighting Thanos, he needs to activate sonic punch but Jarvis is stuck in computing palindromes.
You are given a string S containing alphanumeric characters. Find out whether the string is a palindrome or not.
If you are unable to solve it then it may result in the death of Iron Man.
Input:
The first line of the input contains T, the number of test cases. T testcases follow.
Each line of the test case contains string 'S'.
Output:
Each new line of the output contains "YES" if the string is palindrome and "NO" if the string is not a palindrome.
Constraints:
1<=T<=100
1<=|S|<=100000
Note: Consider alphabets and numbers only for palindrome check. Ignore symbols and whitespaces.
Example:
Input:
2
I am :IronnorI Ma, i
Ab?/Ba
Output:
YES
YES
"""
def is_palindrome(S):
i = 0
while len(S) > i:
if not S[i].isalnum():
S = S.replace(S[i], "")
continue
i += 1
if S.lower() == S[::-1].lower():
print("YES")
else:
print("NO")
for _ in range(int(input())):
S = input()
is_palindrome(S) | true |
e80db37fb0ac97fc52d2a031c6f6c70f8a085219 | fufuzzz/note | /Python基础/第02周_预习/第02周/day08/code/02_函数入门.py | 1,163 | 4.375 | 4 | # 函数
# 作用:封装一个具有特定功能的代码
# 数学的函数:
# f(x) = 3x + 2
# Python的函数:
# def f(x):
# return 3*x + 2
# 1.函数定义
def f():
print('f')
# 2.函数调用
f()
f()
# 3.参数
# 求x和y的和
def my_sum(x, y):
s = x + y
print(s)
my_sum(1, 3)
my_sum(100, 200)
# 参数: 形参,实参
# 形参: x,y; 形式参数,函数定义时括号()中的参数(变量)
# 实参: 3,5; 实际参数,函数调用时括号()中的参数(值)
print('-' * 50)
# 4. 返回值
# return:
# 1.存在于函数中
# 2.可以返回结果(可以是1一个值,或多个值:会返回元组)
# 3.会立刻终止函数(立刻退出函数)
# 4.如果不写return或return后不写值,则默认返回None
def sum2(x, y):
s = x + y
return s
# return 100, 200
print('我永远不会执行')
r = sum2(3, 5)
print(r)
print(sum2(100, 200) * 10)
# 判断一个函数is_leap(year)判断闰年,并返回True或False
def is_leap(year1):
if year1 % 4 == 0 and year1 % 100 != 0 or year1 % 400 == 0:
return True
else:
return False
a = is_leap(2000)
print(a)
| false |
d8157323c90a9e536da0915f70db9a04cc27862f | rongyafeng/python-practice | /Intro2ProgrammingUsingPython/Chapter2-Exercise2.py | 1,596 | 4.28125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @date : 2019/5/9
# @author : Rong Ya-feng
# @desc : Chapter 1 : Programming Exercise2
import turtle
'''
# Case Study : ComputeDistanceGraphics
# Prompt the user for inputting two points
x1, y1 = eval(input("Enter x1 and y1 for point 1: "))
x2, y2 = eval(input("Enter x2 and y2 for point 2: "))
distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
turtle.pu()
turtle.goto(x1, y1)
turtle.write("Point 1")
turtle.pd()
turtle.goto(x2, y2)
turtle.write("Point 2")
turtle.pu()
turtle.goto((x1 + x2) / 2, (y1 + y2) / 2)
turtle.write(distance)
turtle.done()
'''
# Draw a rectangle
'''
width, height = eval(input("Enter the width and height of a rectangle:"))
for i in range(2):
turtle.fd(width)
turtle.lt(90)
turtle.fd(height)
turtle.lt(90)
turtle.done()
'''
# Draw four hexagons
'''
def drawHexagon():
turtle.seth(30)
for i in range(6):
turtle.fd(40)
turtle.lt(60)
def drawFourHexagons():
drawHexagon()
turtle.pu()
turtle.goto(0, -80)
turtle.pd()
drawHexagon()
turtle.pu()
turtle.goto(80, 0)
turtle.pd()
drawHexagon()
turtle.pu()
turtle.goto(80, -80)
turtle.pd()
drawHexagon()
if __name__ == '__main__':
drawFourHexagons()
turtle.done()
'''
# Draw a circle
'''
radius = eval(input("Enter the radius of a circle:"))
PI = 3.1415926
area = radius * radius * PI
turtle.circle(radius)
turtle.pu()
turtle.goto(0, radius)
turtle.pd()
turtle.write(area)
turtle.ht()
turtle.done()
'''
| false |
a0c059bf1639c17586ee9023bbf7926ec550ccdc | kateybatey/calculator-2 | /calculator.py | 1,402 | 4.5 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
#def calculator():
while True:
user_input = raw_input("> ")
tokens = user_input.split(" ")
if len(tokens) > 3:
print "Please enter one operator followed by two numbers."
continue
elif len(tokens) < 3:
print """Please enter an operator followd by two numbers.
Format example: + 10 5 ."""
continue
operator = tokens[0]
num1 = tokens[1]
num2 = tokens[2]
if not num1.isdigit() or not num2.isdigit():
print """Those aren't numbers! You broke me.
Start over and enter an operator followed by two numbers."""
continue
elif operator == "+":
result = add(int(num1), int(num2))
elif operator == "-":
result = subtract(int(num1), int(num2))
elif operator == "*":
result = multiply(int(num1), int(num2))
elif operator == "/":
result = float(divide(int(num1), int(num2)))
elif operator == "square":
result = square(int(num1))
elif operator == "cube":
result = cube(int(num1))
elif operator == "pow":
result = power(int(num1), int(num2))
elif operator == "mod":
result = mod(int(num1), int(num2))
print result
# return result
#calculator()
| true |
a289c0005da1552fa4c1a84496dc044a93598f79 | SandhyaTanwar24/Test19 | /SetExam.py | 1,586 | 4.25 | 4 | #Addition and Deletion in set
'''setexam = {"Jan", "Feb", "Mar", "Apr", "May"}
setexam.update(["June", "July", "Aug", "Sep"])
print("Set after adding multiple elements", setexam)
setexam.pop()
print("Set after using pop function", setexam)'''
#Dictionary
'''
EmployeeDetail = {
"Name": "Sandhya",
"Profile": "QA",
"EmplyeeID": "123",
"CompanyName": "S&PGlobal"
}
print("Fetching key value using get method", EmployeeDetail.get("Name"))
print("Fetching key value simply via", EmployeeDetail["Profile"])
#Different functions to get the key and values using loops
for x in EmployeeDetail:
print("Print all keys in the EmployeeDetails Dic", x)
for x in EmployeeDetail:
print("Print all values in the EmployeeDetails Dic", EmployeeDetail[x])
for x in EmployeeDetail.values():
print("Print all values using values function of the dictionary", x)
#Print all keys and Values all together used in a dictionary using items function
for x,y in EmployeeDetail.items():
print(x, y)'''
#ShortHandIf
a = 10
b = 100
#print("A") if a > b else print("B")
i = 1
while i < 6:
print("Print values of until it met the condition", i)
if i == 3:
break
print("Statement Break")
i += 1
#use of Continue Condition within Loop
i = 0
while i < 6:
i += 1
if i == 3:
continue
print("Use of continue statment", i)
#Use of break and continue statement in a for loop condition
#EmpName = {"Sandhya", "Neha", "Akanksha"}
#for x in E
| true |
d6a7d35bb1684cc5b7b7a8c0dd26694c63010b59 | ZeroStack/algorithms | /bubble_sort/bubble_sort.py | 802 | 4.34375 | 4 |
if __name__ == "__main__":
main()
def main():
toSort = [6, 5, 3, 1, 8, 7, 2, 4]
bubbleSort(toSort)
def bubbleSort(a):
# number of numbers of times to iterate over main array
n = len(a)
# for every element in the array
for i in range(n):
# create a range n times with a diminishing n by i-1
for j in range(n-i-1):
# if the right element is larger than the left element
if a[j] > a[j+1]:
# display the array
print("[",a[j],"]",">","[",a[j+1],"]")
# swap the elements
a[j], a[j+1] = a[j+1],a[j]
# print array a at the end of swap
print([i for i in a])
# print array a at end
print([i for i in a])
| false |
ea0c210a2b5b4cc69103c7dcd8abfbb862fc9ad2 | bxtom/python-old | /Basics1/basics/Conditionals.py | 254 | 4.125 | 4 | # 15:45
age = 19
if age > 20:
print("yes")
elif age == 20:
print("just right")
else:
print("no")
if (17 > 15) and (13 < 100):
print("yes")
if (17 > 15) or (13 < 100):
print("yes")
if not((17 > 15) or (13 < 100)):
print("no")
| true |
15f796a9f5ea316d2fea7ede6cd99203d1d9cb4f | J-Chaudhary/dataStructureAndAlgo | /BinerySearch_vs_interpolationSearch.py | 1,853 | 4.1875 | 4 | # Assignment 6
# Author: Jignesh Chaudhary, Student Id: 197320
# c) CompareSearch: Implement Interpolation Search algorithm from textbook (Algorithm 8.1) and the Binary Search algorithm from textbook
# (Algorithm 1.5). Try different problem instances against both algorithms to analyze best-case, average-case, and worstcase. Compare the
# performances of both of the algorithms based on your results and how they compare to each other.
def interpolationSearch(input, x):
n = len(input)
low = 0
high = int(n - 1)
i = 0
if input[low] <= x <= input[high]:
while low <= high and i == 0:
denominator = input[high] - input[low]
if denominator == 0:
mid = low
else:
mid = low + (x - input[low]) * (high - low) / denominator
if input[int(mid)] == x:
i = int(mid)
elif x < input[int(mid)]:
high = int(mid) - 1
else:
low = int(mid) + 1
return int(mid)
def binarySearch(input, x):
low = 0
high = len(input) - 1
while low <= high:
mid = (low + high) / 2
if input[int(mid)] == x:
return int(mid)
if input[int(mid)] > x:
high = int(mid) - 1
else:
low = int(mid) + 1
return mid
if __name__ == '__main__':
input1 = (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)
x1 = 11
input2 = (21, 22, 23, 24, 25, 26, 27, 28, 29, 30)
x2 = 27
print("InterpolationSearch usinginput1: ", interpolationSearch(input1, x1))
print("BinarySearch using input1:", binarySearch(input1, x1))
print("InterpolationSearch usinginput2:", interpolationSearch(input2, x2))
print("BinarySearch using input2:", binarySearch(input2, x2))
| true |
cc8930c86cd3eeb9d534781bcbb2c90ebb586e86 | J-Chaudhary/dataStructureAndAlgo | /Queue.py | 1,664 | 4.1875 | 4 | # Student : Jignesh Chaudhary, Student id : 197320
# Assignment - 1 (b)
class Node:
'''Node for storing data in to queue'''
def __init__(self, data):
self.data = data
self.next = None
class Queue:
'''Queue structure implement using link list'''
def __init__(self): # create empty list
self.front = None
self.rear = None
def isEmpty(self):# to check queue is empty or not and return result
if self.front == None:
return True
return False
def EnQueue(self, data):# Method to add data to the queue
new_node = Node(data)
if self.front == None and self.rear == None:
self.front = new_node
self.rear = self.front
else:
self.rear.next = new_node
self.rear = new_node
def DeQueue(self):# Method to remove data from front of the queue
if self.isEmpty():
return
temp = self.front.data
if (self.front == self.rear):
self.rear = None
self.front = None
else:
self.front = self.front.next
return temp
def size(self): # methhod to check size of Queue
current = self.front
total = 0
while current.next != None:
total += 1
current = current.next
return total
def display(self): # Method to display Queue elements
list = []
current_node = self.front
while current_node != None:
list.append(current_node.data)
current_node = current_node.next
print(list)
| true |
0dc70f8b72203c1390c005fcd1a93b49f4ba5934 | CiroLV/Data_Analysis_UHelsinki | /hy-data-analysis-with-python-2020/part01-e13_reverse_dictionary/src/reverse_dictionary.py | 454 | 4.34375 | 4 | #!/usr/bin/env python3
def reverse_dictionary(d):
dict_FtE= {}
for key in d.keys():
for x in d[key]:
if x in dict_FtE.keys():
dict_FtE[x].append(key)
else:
dict_FtE[x] = [key]
return dict_FtE
def main():
d={'move': ['liikuttaa'], 'hide': ['piilottaa','salata'], 'six': ['kuusi'], 'fir': ['kuusi']}
reverse_dictionary(d)
pass
if __name__ == "__main__":
main()
| false |
5f4007b91671c7b40aea12aa53f44a8a774c2c0e | hihumi/renote | /split.py | 636 | 4.21875 | 4 | #!/usr/bin/env python3
"""renote: re split module
"""
import re
def my_split(word):
"""renote: re split function
"""
pattern = re.compile(r' +')
res = pattern.split(word)
if res:
print('OK')
print('{}'.format(res))
else:
print('NG')
if __name__ == '__main__':
print('文字列を入力 終了するにはq, Qキー')
print('>>> ', end='')
while True:
enter_word = input()
if enter_word == 'q' or enter_word == 'Q':
print('終了')
break
elif enter_word:
my_split(enter_word)
print('>>> ', end='')
| false |
9272d57f9071395b711e18787836f088c3fa9802 | gordonwatts/functional_adl | /adl_func_backend/cpplib/cpp_types.py | 2,641 | 4.34375 | 4 | # Simple type system to help reason about types as they go through the system.
class terminal:
'Represents something we cannot see inside, like float, or int, or bool'
def __init__ (self, t, is_pointer = False):
'''
Initialize a terminal type
t: The type as a string (valid in C++)
'''
self._type = t
self._is_pointer = is_pointer
def __str__(self):
return self._type
def is_pointer(self):
return self._is_pointer
def default_value(self):
if self._type == "double":
return "0.0"
elif self._type == "float":
return "0.0"
elif self._type == "int":
return "0"
else:
raise BaseException("Do not know a default value for the type '{0}'.".format(self._type))
class collection:
'Represents a collection/list/vector of the same type'
def __init__ (self, t, is_pointer = False):
'''
Initialize a collection type.
t: The type of each element in the collection
'''
self._element_type = t
self._is_pointer = is_pointer
def __str__(self):
return "std::vector<" + str(self._element_type) + ">"
def element_type(self):
return self._element_type
def is_pointer(self):
return self._is_pointer
class tuple:
'Represents a value which is a collection of other types'
def __init__ (self, type_list):
'''
Initialize a type list. The value consists of `len(type_list)` items, each
of the type held inside type_lits.
type_list: tuple,etc., that we can iterate over to get the types.
'''
self._type_list = type_list
def __str__(self):
return "(" + ','.join(self._type_list) + ")"
###########################
# Manage types
g_method_type_dict = {}
def add_method_type_info (type_string, method_name, t):
'''
Define a return type for a method
type_string String of the object the method is calling against
method_name Name of the object
t The type (terminal, collection, etc.) of return type
'''
if type_string not in g_method_type_dict:
g_method_type_dict[type_string] = {}
g_method_type_dict[type_string][method_name] = t
def method_type_info(type_string, method_name):
'''
Return the type of the method's return value
'''
if type_string not in g_method_type_dict:
return None
if method_name not in g_method_type_dict[type_string]:
return None
return g_method_type_dict[type_string][method_name] | true |
0503a875112e2c98fe6df2b5ca634d6338c69b3b | gabriel-torres3077/curso-em-video-exercicios | /exercicios/desafio026.py | 479 | 4.125 | 4 | """
Faça um programa
que leia uma frase pelo
teclado e mostre:
-Quantas vezes aparece a letra'A'
-Em que posição ela aparece a primeira vez
-Em que posiçlão ela aparece a ultimavez
"""
phrase = str(input('Ensira uma frase qualquer: ')).strip()
print('-Quantas vezes aparece a letra A: {}\n'
'-Em que posição ela aparece a primeira vez: {}\n'
'-Em que posiçlão ela aparece a ultimavez: {}\n'.format(phrase.count('a'), phrase.find('a')+1, phrase.rfind('a')+1)) | false |
d2865e11698d1bf62c6caf465409bff59a8c794a | gabriel-torres3077/curso-em-video-exercicios | /exercicios/desafio049.py | 282 | 4.15625 | 4 | """
Refaça o desafio 009, mostrando a tabuada
de um numero que o usuário escolher só que
agora ultilizando um laço for.
"""
num = int(input('Ensira o numero desejado para a visualização da tabuada: '))
for x in range (1, 11):
print('{} X {} = {}' .format(num, x, num * x)) | false |
24cc3445566e4cd81baba2f5da37c138a6f5b94a | gabriel-torres3077/curso-em-video-exercicios | /exercicios/desafio035.py | 435 | 4.125 | 4 | """
Desenvolva um programa
que leia o comprimento
de três retas e diga se elas podem ou não formar um triangulo
"""
a = int(input('ensira o comprimento da primeira reta: '))
b = int(input('ensira o comprimento da segunda reta: '))
c = int(input('ensira o comprimento da terceura reta: '))
if(a < b + c and b < a + c and c < a + b):
print('É possivel formar um triangulo')
else:
print('Não é possivel formar um triangulo') | false |
dd12cf90172712554e0ad866818baf883189edf7 | gabriel-torres3077/curso-em-video-exercicios | /exercicios/desafio072.py | 688 | 4.15625 | 4 | """
Crie um programa
que tenha uma tupla
totalmente preenchida
com uma contagem por
extenso de zero até vinte.
Seu programa deverá
ler um número pelo
teclado (entre 0 e 20)
e mostra-lo por extenso
"""
numbers = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco',
'Seis', 'Sete', 'Oito','Nove', 'Dez', 'Onze',
'Doze', 'Treze','Quatorze', 'Quinze', 'Dezeseis',
'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
print(numbers)
num = int(input('Ensira o valor a ser analizado por extenso: '))
while True:
if num < 20 and num > -1:
print(numbers[num])
break
else:
num = int(input('Valor incorreto. Ensira o valor a ser analizado por extenso: ')) | false |
5c92c9b8798075823f5178d79f48c37a59b77e19 | gabriel-torres3077/curso-em-video-exercicios | /exercicios/desafio036.py | 580 | 4.1875 | 4 | """
Escreva um
programa para aprovar
o empéstimo bancário
para a compra de uma
casa. O programa vai
perguntar o valor da casa,
o salário do comprador e em
quantos anos ele vai pagar.
calcule o valor da prestação mensal
sabendo que ela não pode exceder 30%
do salário ou então o emprestimo será negado
"""
houseValue = float(input('Qual o valor da casa? '))
wage = float(input('Qual o salário? '))
years = int(input('Em quantos anos será pago? '))
if ((houseValue / (years * 12))< (wage*0.3)):
print('empréstimo permitido')
else:
print('Empréstimo negado!')
| false |
d9204ff0ffe91a2e7c3a39307a79c8b646b87708 | pavdmyt/recursion_examples | /math/factorial.py | 508 | 4.125 | 4 | """
Recursive way to calculate the factorial of the given number.
"""
def fact(num):
"""
Returns factorial of a non-negative integer `num`.
"""
if num == 0:
return 1
return num * fact(num - 1)
if __name__ == '__main__':
import math
import unittest
class Test(unittest.TestCase):
def test_fact(self):
test_seq = range(15)
for num in test_seq:
self.assertEqual(fact(num), math.factorial(num))
unittest.main()
| true |
025f51f655d4901d06b237f5cd738298ac53b0d1 | Meeshbhoombah/makeschool | /CS3/source/search.py | 2,600 | 4.28125 | 4 | #!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
#return linear_search_iterative(array, item)
return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None # not found
def linear_search_recursive(array, item, index=0):
# implement linear search recursively here
# once implemented, change linear_search to call linear_search_recursive
# to verify that your recursive implementation passes all tests
if index == len(array):
return None
if item == array[index]:
return index
linear_search_recursive(array, item, index + 1)
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
# implement binary_search_iterative and binary_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return binary_search_iterative(array, item)
# return binary_search_recursive(array, item)
def binary_search_iterative(array, item):
# implement binary search iteratively here
# once implemented, change binary_search to call binary_search_iterative
# to verify that your iterative implementation passes all tests
start_index = 0
stop_index = len(array) - 1
while start_index <= stop_index:
split_index = int((start_index + stop_index) / 2)
if array[split_index] == item:
return split_index
else:
if item < array[split_index]:
stop_index = split_index - 1
else:
start_index = split_index + 1
def binary_search_recursive(array, item):
# implement binary search recursively here
# once implemented, change binary_search to call binary_search_recursive
# to verify that your recursive implementation passes all tests
if len(array) == 0:
return
else:
split = len(array) // 2
if array[midpoint] == item:
return True
else:
if item < array[split]:
return binary_search_recursive(array[:midpoint], item)
else:
return binary_search_recursive(array[midpoint + 1:], item)
| true |
650e8479345397c85e269c2d603295539da4a504 | aneestahirnbs/Python-Practice | /Problem - Reverse iterator.py | 645 | 4.28125 | 4 | #Problem 1: Write an iterator class reverse_iter, that takes a list and iterates it from the reverse direction. ::
class ReverseIter:
def __init__(self,list_):
self.list=list_
self.index=len(self.list)
def __iter__(self):
return self;
def next(self):
if self.index>0:
self.index-=1;
return self.list[self.index]
else:
print("nothing to print")
list=[1,2,3,4,5]
rev_iter=ReverseIter(list)
print(rev_iter.next())
print(rev_iter.next())
print(rev_iter.next())
print(rev_iter.next())
print(rev_iter.next())
print(rev_iter.next())
print(rev_iter.next())
| true |
be9efff5764d13730864b220d0713a53bf3760ec | khkpoo/External | /string.py | 1,470 | 4.1875 | 4 | # 문자열 함수
str1="Hello Python!"
## 문자열 포메팅
print("{0}과 {1}".format('left','right')) # 인자 사용하기
print("{0:>100}".format("right")) # 오른쪽 정렬
print("{0:<100}".format("left")) # 왼쪽 정렬
print("{0:^100}".format("Center")) # 가운데 정렬
print("{0:=^100}".format(" Center ")) # 빈칸 채우기
print(f'{"hi":-^100}') # 동일 표현 (f 이용)
print(f"{'hi':-^100}") # 동일 표현 (f 이용)
print(f'{str1}') # 3.6~ 가능 변수참조용
print("{0}".format('*') * 100 )
## 슬라이싱
print(str1[0:4]) # Substring.. 마지막 인덱스 번호값은 포함안됨 주의
## 패턴 검색
print(str1.count('o')) # 패턴 개수 리턴
print(str1.find('o')) # 패턴 위치 리턴(최초), 없을경우 -1
print(str1.index('o')) # 패턴 위치 리턴(최초), 없을경우 에러
print("*"*100)
## 삽입
print(str1.join('abc')) # 후행 값 중간중간에 문자열 삽입.
print(".".join(str1)) # 이따위로 더 쓰는듯
print("*"*100)
## 대소문자
print(str1.upper()) # 대문자 어규먼트없음
print(str1.lower()) # 소문자 어규먼트없음
print("*"*100)
## 변형
str2= " BLINK "
print(str2.lstrip()) # 공백 제거 (왼쪽 오른쪽 모두)
print(str2.rstrip())
print(str2.strip())
print("*"*100)
## 치환
print(str1.replace("!","?")) # 문자열 replace
print(str1.split("P")) # 문자열 Split 하여 List로 반환
print(str2.split())
print("*"*100)
| false |
be89da060c37f32c64b7215d67af01d780a6c896 | roderick-bishop11/codingSamples | /codingMadLibProgram/codingMadLib.py | 1,308 | 4.375 | 4 | # Author: Roderick Bishop
# Date: 2/1/2019
# Program: codingMadLibProgram.py; the python version of the coding mad lib program that takes a users input and makes
# a story out of it
print("Welcome to the python coding madLib!\n")
print("First, read the story, then insert your own words to make the story as cool as you like! \n")
print("This morning I got up and decided to go to the {place} to {verb1} and get my {noun} {verb2}.")
print("Then I went to {verb3} with my {person} because I have't {verb3} with {pronoun} in a little while.")
print("After a long day of {adjective} fun, I decided to go home and {verb4} until I fell asleep. \n")
place = input("Input place ")
verb1 = input("Input verb 1 ")
noun = input("Input noun ")
verb2 = input("Input verb 2 ")
verb3 = input("Input verb 3 ")
person = input("Input person ")
pronoun = input("Input pronoun ")
adjective = input("Input adjective ")
verb4 = input("Input verb 4 ")
print("Here is your finished madLib! \n \n")
print("This morning I got up and decided to go to the", place, "to", verb1, "and get my", noun, verb2, "\b. ")
print("Then I went to", verb3, "with my", person, "because I have't", verb3, "\bed with", pronoun, "in a little while.")
print("After a long day of", adjective, "fun, I decided to go home and", verb4, "until I fell asleep.")
| true |
82db1a722911fda03ee6431442db4e453d854d90 | pravinarajkas/Guvi_python_program_set_1 | /vowel_consonant.py | 294 | 4.15625 | 4 | ch=input("Enter the character:")
if ch in ('a','e','i','o','u','A','E','I','O','U'):
'''if ch=='a' or ch=='e' or ch=='i' or ch=="o" or ch=="u" or ch=='A' or ch=='E' or ch=='I' or ch=='O' or ch=='U':'''
print("The character is a vowel")
else:
print("The character is a consonant")
| false |
4282c3d9fe44f4580687fe16ad6607a12672c1b9 | dvlupr/fdn_course | /Week2/Module2Lab2.py | 969 | 4.25 | 4 | """
Author: Jim Jenkins (dvlupr)
Date: 06/27/2018
Get a random number:
DO EITHER
- create a variable called test_number with a number between 50 and 100 in it
- Assign a random number between 50 and 100 to a variable called test_num (read page 50-52 in your text)
If test_num is divisible by three, print "fizz"
If test_num is divisible by five, print "buzz"
if test_num is divisible by both three and five, print "fizzbuzz!"
if test_num does not meet any of the above criteria, print test_num
"""
import random
# random number
rn = random.randint(1,51)
# assign test_num to random number
test_num = rn
# run variable
test_num3 = test_num % 3
test_num5 = test_num % 5
# print to see output
print('random number: ', rn)
print('test_num3: ', test_num3)
print('test_num5: ', test_num5)
#FizzBuzz logic
if test_num3 == 0 and test_num5 == 0:
print('fizzbuzz')
elif test_num3 == 0:
print('fizz')
elif test_num5 == 0:
print('buzz')
else:
print(test_num)
| true |
421131c9da60cf5accf032c1b167f74c3137b53e | drgarc/Homeworks-ZyLab-Codes | /2.19zylab.py | 1,931 | 4.46875 | 4 | #Daniel Garcia ; PSID 1601483
#Prompt the user for the number of cups of lemon juice, water, and agave nectar needed to make lemonade. Prompt the user to specify the number of servings the recipe yields. Output the ingredients and serving size.
print('Enter amount of lemon juice (in cups):')
lemon_juice = int(input())
print('Enter amount of water (in cups):')
water = int(input())
print('Enter amount of agave nectar (in cups):')
agave_nectar = float(input())
print('How many servings does this make?')
servings = float(input())
print()
print('Lemonade ingredients - yields', '{:.2f}'.format(servings), 'servings')
print('{:.2f}'.format(lemon_juice), 'cup(s) lemon juice')
print('{:.2f}'.format(water), 'cup(s) water')
print('{:.2f}'.format(agave_nectar), 'cup(s) agave nectar')
print()
#Prompt the user to specify the desired number of servings. Adjust the amounts of each ingredient accordingly, and then output the ingredients and serving size.
print('How many servings would you like to make?')
print()
servings_quantity = int(input())
print('Lemonade ingredients - yields', '{:.2f}'.format(servings_quantity), 'servings')
print('{:.2f}'.format(lemon_juice * servings_quantity / servings), 'cup(s) lemon juice')
print('{:.2f}'.format(water * servings_quantity / servings), 'cup(s) water')
print('{:.2f}'.format(agave_nectar * servings_quantity / servings), 'cup(s) agave nectar')
print()
#Convert the ingredient measurements from (2) to gallons. Output the ingredients and serving size. Note: There are 16 cups in a gallon.
print('Lemonade ingredients - yields', '{:.2f}'.format(servings_quantity), 'servings')
print('{:.2f}'.format(lemon_juice * servings_quantity / servings / 16), 'gallon(s) lemon juice')
print('{:.2f}'.format(water * servings_quantity / servings / 16), 'gallon(s) water')
print('{:.2f}'.format(agave_nectar * servings_quantity / servings / 16), 'gallon(s) agave nectar')
| true |
b5ac5ee13fbaa70c20701f7ae2d44c6c1227249e | vsoch/algorithms | /full-binary-tree/full-tree.py | 1,151 | 4.21875 | 4 | # Check if is full binary tree
# 1. If root node is None, return False
# 2. If root node left and right are None, return True
# 3. if both left and right are not None, check the rest
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_full_tree(root):
# No tree!
if root == None:
return False
# This is a stump
if root.left is None and root.right is None:
return True
# Otherwise, both child trees need to be full
if root.left is not None or root.right is not None:
return is_full_tree(root.left) and is_full_tree(root.right)
return False
# Driver Program
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.right = Node(40)
root.left.left = Node(50)
root.right.left = Node(60)
root.right.right = Node(70)
root.left.left.left = Node(80)
root.left.left.right = Node(90)
root.left.right.left = Node(80)
root.left.right.right = Node(90)
root.right.left.left = Node(80)
root.right.left.right = Node(90)
root.right.right.left = Node(80)
root.right.right.right = Node(90)
print(is_full_tree(root))
| true |
7e76cf913e3d31470bcb2c443e4256d7f899e6ba | vsoch/algorithms | /largest-palindrome/largest-palindrome-3-digits.py | 974 | 4.21875 | 4 | # A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def largest_palindrome():
largest = -1
# First try brute force
for i in range(100, 999):
for j in range(100, 999):
product = str(i * j)
# Come at from both sides
start = 0
end = len(product) - 1
is_palindrome = True
while start <= end:
if start == end:
break
# If they aren't equal, get our early
if product[start] != product[end]:
is_palindrome = False
break
start += 1
end -= 1
if is_palindrome and (i * j > largest):
largest = i * j
print("The largest palindrome is %s" % largest)
| true |
aa174f0924cbefe850b2bfff4ef076451b87fd2d | FelixAlvarado/notes | /january 2021/intervals.py | 1,327 | 4.15625 | 4 | # merge intervals
# Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
# Example 1:
# Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: intervals = [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] and [4,5] are considered overlapping.
# my answer
from operator import itemgetter
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# go through array
# for each element, check to see if the start point is less than the previous result elements end point. if so, modify endpoint to be end point of current element.
# if not, add current element to result
result = []
intervals = sorted(intervals,key=itemgetter(0))
for interval in intervals:
if len(result) == 0:
result.append(interval)
elif interval[0] <= result[-1][1] and interval[1] > result[-1][1]:
result[-1][1] = interval[1]
elif interval[0] > result[-1][1]:
result.append(interval)
return result | true |
3489c8f7844d9803d4cfbe7c57a841e7aa5ae0fb | Vineeth1652/python_practice | /list.py | 981 | 4.5625 | 5 | # Create an empty list 'emplist1' using list operation.
# Print 'emplist1'.
# Append to empty list 'emplist1' created above with element 9.
# Append another element 10 to 'emplist1'.
# Print 'emplist1'.
# Create an empty list 'emplist2' using [].
# Print 'emplist2'.
# Extend the empty list 'emplist2' created above with elements 'a', 'b', 'c'.
# Print 'emplist2'.
# Remove the last element of 'emplist2', and assign it to variable 'e'.
# Print 'emplist2'.
# Print the variable 'e'.
# emplist1=list()
# print(emplist1)
# emplist1.append('element 9')
# emplist1.append('element 10')
# print(emplist1)
# emplist2=[]
# print(emplist2)
# emplist2.extend('a')
# emplist2.extend('b')
# emplist2.extend('c')
# print(emplist2)
# e=emplist2.pop()
# # print(emplist2)
# print(e)
emplist1 = list()
print(emplist1)
emplist1.append(9)
emplist1.append(10)
print(emplist1)
emplist2 = []
print(emplist2)
emplist2.extend(('a','b','c'))
print(emplist2)
e = emplist2.pop()
print(emplist2)
print(e)
| true |
c75558598773c2470a94449fa5569b6886e141f6 | astikanand/Interview-Preparation | /Data Structures/4. Queues/6_max_of_all_subarrays_size_k_sliding_window.py | 1,074 | 4.15625 | 4 | def max_of_all_subarrays_of_k_size(arr, k):
n = len(arr)
max_subarray = []
# Initially current window
current_window = arr[:k]
# First get the initial current_window of of first k elements,
# the first element of max_subarray is max of initial window.
max_subarray.append(max(current_window))
# Now start from k+1th element, and in current_window
# dequeue the first element from current_window and enqueue the k+1th element
# get max of current_window and put in max_subarray and continue till the last element.
for i in range(k, n):
# Dequeue the first element and enqueue the next element
current_window.pop(0)
current_window.append(arr[i])
max_subarray.append(max(current_window))
return max_subarray
print("Example-1: max_of_all_subarrays_of_k_size")
arr = [1, 2, 3, 1, 4, 5, 2, 3, 6]
print(max_of_all_subarrays_of_k_size(arr, 3))
print("\nExample-2: max_of_all_subarrays_of_k_size")
arr = [8, 5, 10, 7, 9, 4, 15, 12, 90, 13]
print(max_of_all_subarrays_of_k_size(arr, 4)) | true |
e6d255849aa59101c50c01272cb83e7df466f808 | astikanand/Interview-Preparation | /Data Structures/3. Stacks/3_balanced_parantheses_in_an_expression.py | 903 | 4.5 | 4 | def check_balanced_bracket(expression):
stack = []
balanced = True
for bracket in expression:
# If current is opening bracket push closing bracket to stack
if bracket=='(':
stack.append(')')
elif bracket=='{':
stack.append('}')
elif bracket=='[':
stack.append(']')
# If current is not opening bracket or the bracket doesnt match the top of stack -> Unbalanced
elif not stack or stack.pop() != bracket:
balanced = False
break
# If Stack is empty it is balanced else not balanced
if stack or not balanced:
print("Not Balanced")
else:
print("Balanced")
print("Example-1: check_balanced_bracket('[()]{}{[()()]()}')")
check_balanced_bracket('[()]{}{[()()]()}')
print("\nExample-2: check_balanced_bracket('[(])')")
check_balanced_bracket('[(])')
| true |
a48ac27955cce67be17af2fbe8e79a16e2e9a6d5 | astikanand/Interview-Preparation | /Algorithms/3. Backtracking/3_n_queen.py | 1,931 | 4.375 | 4 | # To check if a queen can be placed on board[row][col].
# Note that this function is called when "col" number of queens are already placed in columns from 0 to col -1.
# So we need to check only left side for attacking queens.
def is_safe(board, row, col):
safe = True
# Check this row on left side.
for j in range(col):
if(board[row][j] == 1):
safe = False
break
# Check upper diagonal on left side
i = row; j=col
while(i>=0 and j>=0):
if(board[i][j]==1):
safe = False
break
i-=1; j-=1
# Check lower diagonal on left side
i = row; j = col
while(i<N and j>=0 and safe):
if(board[i][j]==1):
safe = False
break
i+=1; j-=1
return safe
def n_queen_util(board, col):
# Base case: If all queens are placed then return true
if(col == N):
return True
# Consider this column and try placing this queen in all rows one by one
for i in range(N):
if(is_safe(board, i, col)):
# Place this queen in board[i][col]
board[i][col] = 1
# Recur to place rest of the queens
if(n_queen_util(board, col+1) == True):
return True
else:
board[i][col] = 0 # Backtrack
# If the queen can not be placed in any row in this colum col then return false
return False
def n_queen():
board = [[0]*N for i in range(N)]
if(n_queen_util(board, 0) == True):
for i in range(N):
print(board[i])
else:
print("No solution exists")
print("N-Queen Example-1: 3*3 Matrix")
N = 3
n_queen()
print("\nN-Queen Example-2: 4*4 Matrix")
N = 4
n_queen()
print("\nN-Queen Example-3: 5*5 Matrix")
N = 5
n_queen()
print("\nN-Queen Example-4: 8*8 Matrix")
N = 8
n_queen()
# Complexity:
# • Time:
# • Space:
| true |
3b08945db7b12e29876525c29e713505210a7e3c | astikanand/Interview-Preparation | /Python/2_dict.py | 1,833 | 4.4375 | 4 | # initialize
dict1 = {1: "abcd", "apples": 3, "fruits": ["apples", "mangoes"], }
print("Initial Dict = {}".format(dict1))
# Insert
dict1[2] = 7
print("Modified Dict after insertion = {}".format(dict1))
# len(): size of the dict
print("Size of the dict = {}\n".format(len(dict1)))
# get(): access
print("Key = {} and Val = {}".format("apples", dict1["apples"]))
print("Key = {} and Val = {}".format("fruits", dict1.get("fruits", False)))
print("Key = {} and Val = {}\n".format("mangoes", dict1.get("mangoes", False)))
# key in dict: Membership check
print("mangoes present in dict1 ? : {}".format("mangoes" in dict1))
print("apples present in dict1 ? : {}\n".format("apples" in dict1))
# items(): set of key, val
print("Items = {}".format(dict1.items()))
# keys(): all the keys of dict
print("Keys = {}".format(dict1.keys()))
# values(): all the values of dict
print("Values = {}\n".format(dict1.values()))
# setdefault(): get the value if key present else sets the default value to key
print("Key = {} and Val = {}".format("apples", dict1.setdefault("apples", 0)))
print("Key = {} and Val = {}\n".format("mangoes", dict1.setdefault("mangoes", 0)))
print("Dict Now = {}".format(dict1))
# update(): update from other dictionary
dict2 = {"mangoes": 5, "oranges": 3}
dict1.update(dict2)
print("Dict after Updated from Dict2 = {}".format(dict1))
# del: delete the key
del dict1["fruits"]
print("Dict after deleting 'fruits' = {}\n".format(dict1))
# copy(): copy the dict
dict2 = dict1.copy()
print("Copied Dict = {}".format(dict2))
# clear(): clear the dict
dict1.clear()
print("Dict after clearing = {}\n".format(dict1))
# fromkeys(): dict from keys
seq = ('name', 'age', 'sex')
print ("New Dictionary from sequence: {}".format(dict.fromkeys(seq)))
print ("New Dictionary from sequence: {}".format(dict.fromkeys(seq, 10))) | true |
baa4b288af08a2ea4906d8ef7654d02af9df841a | astikanand/Interview-Preparation | /Data Structures/3. Stacks/0_stack_array_implementation.py | 770 | 4.21875 | 4 | class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def push(self, data):
self.stack.append(data)
def pop(self):
if(self.is_empty()):
return "Underflow"
return self.stack.pop()
def top(self):
if(self.is_empty()):
return "Underflow"
return self.stack[-1]
print("Example:- Array Implementation of Stack.")
my_stack = Stack()
print("Push: 4, 1, 7, 8 to stack.")
my_stack.push(4)
my_stack.push(1)
my_stack.push(7)
my_stack.push(8)
print("Pop the first element: {}".format(my_stack.pop()))
print("Top element in stack: {}".format(my_stack.top()))
print("Is stack empty? {}".format(my_stack.is_empty()))
| true |
ff0ad57259f9d86055d7bf0b65580cca8f8b169b | astikanand/Interview-Preparation | /Data Structures/2. Linked List/4_merge_2_sorted_linked_lists.py | 2,170 | 4.28125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
while(temp):
print("{}-->".format(temp.data), end="")
temp = temp.next
print("Null")
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def merge_2_sorted_linked_lists(self, sorted_list_2):
# Take 2 pointers temp_1 and temp_2 to track both lists and a stack to put the data.
temp_1 = self.head
temp_2 = sorted_list_2.head
stack = []
# While both temp_1 and temp_2 are exists keep on going:
while(temp_1 and temp_2):
# If data of temp_1 is lesser temp_1 is selected and incremented else temp_2 is selected and incrmented.
if(temp_1.data <= temp_2.data):
stack.append(temp_1.data)
temp_1 = temp_1.next
else:
stack.append(temp_2.data)
temp_2 = temp_2.next
# If elements are left in temp_1, push all of them to stack.
while(temp_1):
stack.append(temp_1.data)
temp_1 = temp_1.next
# If elements are left in temp_2, push all of them to stack.
while(temp_2):
stack.append(temp_2.data)
temp_2 = temp_2.next
# Now, finally make head point to None and create the linked_list from popping from stack and pushing all nodes to it.
self.head = None
while(stack):
self.push(stack.pop())
print("First Sorted Linked List:")
linked_list_1 = LinkedList()
linked_list_1.push(5)
linked_list_1.push(4)
linked_list_1.push(1)
linked_list_1.print_list()
print("\nSecond Sorted Linked List:")
linked_list_2 = LinkedList()
linked_list_2.push(9)
linked_list_2.push(8)
linked_list_2.push(6)
linked_list_2.push(3)
linked_list_2.push(2)
linked_list_2.print_list()
print("\nMerged List:")
linked_list_1.merge_2_sorted_linked_lists(linked_list_2)
linked_list_1.print_list() | true |
3286078dae01a1db50f37e717170828492ffb85b | astikanand/Interview-Preparation | /Data Structures/6. Binary Tree/6_left_view_of_tree.py | 1,666 | 4.1875 | 4 | class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def left_view_binary_tree(root):
# (1) If root is None, then return.
if root is None:
return
# (2) Create an empty queue.
queue = []
# (3) Enqueue root to queue.
queue.append(root)
# (4) While queue is not empty.
while(queue):
# Get the current_count.
current_count = len(queue)
# Flag to know if first element in this level is printed.
printed = False
# Dequeue all the nodes instead of one. So, while current_count > 0.
while(current_count > 0):
# Dequeue the temp_node from queue.
temp_node = queue.pop(0)
# Print the first element in this level if it is not printed.
if(not printed):
print(temp_node.val, end=" ")
printed = True
# If temp_node's left exists: enqueue left to queue.
if (temp_node.left):
queue.append(temp_node.left)
# And if right exists: enqueue right also to queue.
if (temp_node.right):
queue.append(temp_node.right)
current_count -= 1
# Root
root = Node(7)
# 1st Level
root.left = Node(14)
root.right = Node(3)
# 2nd Level
root.right.left = Node(12)
root.right.right = Node(5)
# 3rd Level
root.right.left.left = Node(8)
root.right.left.right = Node(17)
root.right.right.right = Node(4)
# 4th Level
root.right.right.right.left = Node(9)
print("Left View of Binary Tree: ")
left_view_binary_tree(root)
print() | true |
4e81eae8fc2c7e4bf23ca08f2ef0d96f8dfc443a | AngieYi/Leetcode_python | /amazon/Left View of a Binary Tree.py | 1,815 | 4.375 | 4 | '''
Print Left View of a Binary Tree
Left view of a Binary Tree is set of nodes visible when tree is visited from left side.
Left view of following tree is 12, 10, 25.
12
/ \
10 20
/ \
25 40
The left view contains all nodes that are first nodes in their levels.
A simple solution is to do level order traversal and print the first node in every level.
The problem can also be solved using simple recursive traversal.
We can keep track of level of a node by passing a parameter to all recursive calls.
The idea is to keep track of maximum level also.
Whenever we see a node whose level is more than maximum level so far,
we print the node because this is the first node in its level
(Note that we traverse the left subtree before right subtree).
'''
# A binary tree node
class Node:
def __init__(self, data): # Constructor to create a new node
self.data = data
self.left = None
self.right = None
# Recursive function print left view of a binary tree
def leftViewUtil(root, level, max_level):
if root is None: # Base Case
return
if (max_level[0] < level): # If this is the first node of its level
print root.data,
max_level[0] = level
leftViewUtil(root.left, level+1, max_level) # traverse the left subtree before right subtree
leftViewUtil(root.right, level+1, max_level)
def leftView(root):
max_level = [0]
leftViewUtil(root, 1, max_level) # A wrapper over leftViewUtil()
# Driver program to test above function
root = Node(12)
root.left = Node(10)
root.right = Node(20)
root.right.left = Node(25)
root.right.right = Node(40)
leftView(root) | true |
3fd96e10bcf1ce4c9c87e68f9f990510d91eccea | zmeizy/rps-game | /rps_game.py | 1,097 | 4.25 | 4 | import random
turns = ["rock", "paper", "scissors"]
computer_score = 0
human_score = 0
games_played = 0
while True:
games_played +=1
computer_turn = random.choice(turns)
while True:
human_turn = input("Enter human turn: ").lower()
if human_turn == "rock" or human_turn == "paper" or human_turn == "scissors":
break
elif human_turn == "stop":
exit()
else:
print("Select only from rock, paper or scissors")
print(f"Computer: {computer_turn} VS. Human: {human_turn}")
if computer_turn == human_turn:
print(f"Draw! Score: {computer_score}:{human_score}")
elif ((computer_turn == "paper" and human_turn == "rock") or
(computer_turn == "scissors" and human_turn == "paper") or
(computer_turn == "rock" and human_turn == "scissors")):
computer_score += 1
print(f"Computer wins! Score: {computer_score}:{human_score}")
else:
human_score += 1
print(f"Human wins! Score: {computer_score}:{human_score}")
| true |
3ff6adf5275389d45e3416b9f25ef4498f48c298 | TARIQ882/STRING-FUNCTION | /String Function.py | 1,499 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
print("hello world")
# In[9]:
txt="my name is Muhammad Tariq"
txt
# # CAPITALIZE()
# In[10]:
txt.capitalize()
# # UPPER()
# In[11]:
txt.upper()
# # LOWER()
# In[12]:
txt.lower()
# # IS UPPER()
#
# In[13]:
z=txt.upper()
z.isupper()
# # IS LOWER()
# In[14]:
r=txt.lower()
r.islower()
# # LENGHT()
# In[15]:
len(txt)
# # CHECK STRING()
#
# In[16]:
st="i live in mardan"
print("live" in st)
# # STRIP()
# In[17]:
q=" pakistan zindabad "
print(q.strip())
# # R-STRIP()
# In[18]:
print(q.rstrip())
# # L-STRIP()
# In[19]:
print(q.lstrip())
# # find()
# In[20]:
print(q.find("a"))
# # R-FIND()
# In[21]:
print(q.rfind("a"))
# # COUNT()
# In[22]:
print(q.count("a"))
# # REPLACE()
# In[23]:
print(q.replace("pakistan","python"))
# # SPLIT()
# In[24]:
x="Sir Adil Mughal"
print(x.split())
# # ISALPHA()
# In[26]:
c="ASSIGNMENT"
print(c.isalpha())
# In[27]:
print(x.isalpha())
# # CENTER()
# In[28]:
v="I am doing BSCS"
print(v.center(60))
# # endswith()
# In[29]:
print(v.endswith("s"))
# In[30]:
print(v.endswith("S"))
# # STARTSWITH()
# In[31]:
print(v.startswith("i"))
# In[32]:
print(v.startswith("I"))
# # CASEFOLD()
# In[33]:
u="My favourite Hobby is cricket"
print(u.casefold())
# # SWAPCASE()
# In[34]:
y="my favourite colour is green"
print(y.swapcase())
# # ISALNUM()
# In[35]:
w="abcde12345"
print(w.isalnum())
# In[ ]:
pr
| false |
5c77f8d4d8416ef28d18b487a7bbd828a8cd6669 | LesterYHZ/Python-100-Day-Practice | /08-09_OOP/Person-Class.py | 1,657 | 4.125 | 4 | class Person(object):
# Apparently, we can add as many properties as we want in main()
# to the class variables. Or we can use __slots__ to limit the properties
__slots__ = ('_name','_age','_gender')
def __init__(self,name,age):
# _variable name indicates that the author doesn't want this property
# to be 100% public yet doesn't want to make it completely private
# either
self._name = name
self._age = age
# Since the author doesn't recommend a direct access from the outside of
# the class, to get access to the properties, we may use getter and setter
@property
def name(self):
# getter
return self._name
@property
def age(self):
# getter
return self._age
@age.setter
def age(self, age):
# setter helps to alter the properties in the class
self._age = age
def play(self):
if self._age <= 18:
print('%s is playing chess.' % self._name)
else:
print('%s is playing galgames.' % self._name)
def main():
person = Person('Hana Song', 19)
person.play()
person.age = 15
person.play()
# person.name = 'Meiling Zhou'
# that's not gonna work since there is no setter for name property
person._gender = 'F'
# person._ismywaifu = True
# Even though that Hana Song is my waifu is the truth, because of
# __slots__, we are not able to define another property called
# _ismywaifu
# 我不管我不管宋哈娜就是我老婆!!!o((>ω< ))o
if __name__ == '__main__':
main() | true |
6d3c3366cca7740c50f4a5cca75eca352a7f0ec6 | LesterYHZ/Python-100-Day-Practice | /12_Regular-Expression/PhoneNumber.py | 1,896 | 4.34375 | 4 | """
Given: A sentence in which there can be regular numbers or specific
phone numbers
Find: Use RE to find the phone numbers
电信: 133/153/180/181/189/177
联通: 130/131/132/155/156/185/186/145/176
移动: 134/135/136/137/138/139/150/151/152/157/158/159/182/183
184/187/188/147/178
"""
import re
def main():
# compile(pattern)
# 编译正则表达式返回正则表达式对象
pattern = re.compile(r'(?<=\D)1[345780]\d{9}(?=\D)')
"""
(?<=exp) 匹配exp后面的位置
\D 匹配非数字
(?=exp) 匹配exp前面的位置
"""
sentence = '''Dva\'s MEKA number is 8462512326548456;
her phone number is 13802451956; remember,
it\'s not 15640255832; phone numbers include
110, 911, 120, etc. My phone number is 13080861622. '''
# findall(pattern, string)
# 查找字符串所有与正则表达式匹配的模式 返回字符串的列表
mylist = re.findall(pattern,sentence)
print(mylist)
print('---------ˋ( ° ▽、° ) ---------')
# finditer(pattern, string)
# 查找字符串所有与正则表达式匹配的模式 返回一个迭代器
for temp in pattern.finditer(sentence):
print(temp.group())
print('---------ˋ( ° ▽、° ) ---------')
# search(pattern, string)
# 搜索字符串中第一次出现正则表达式的模式 成功返回匹配对象 否则返回None
m = pattern.search(sentence)
while m:
print(m.group())
m = pattern.search(sentence,m.end())
print('---------ˋ( ° ▽、° ) ---------')
"""Better Pattern"""
pattern = re.compile(r'(?<=\D)(13[0-24-9]\d{8}|1[38]\d{9}|14[57]\d{8}|15[0-35-9]\d{8}|17[678]\d{8})(?=\D)')
mylist = re.findall(pattern,sentence)
print(mylist)
if __name__ == "__main__":
main() | false |
ce5b535df019d57c9a836824c03de1b6bc621110 | vipul-sharma20/python-code-examples | /iterator_example.py | 425 | 4.15625 | 4 | '''
Iterating over iterable objects:
list, string, dictionary, text file
'''
# iterating over a list
test_list = [1, 2, 3, 4]
for i in test_list:
print i
# iterating over characters of string
test_string = 'python'
for c in test_string:
print c
# iterating over dictionary keys
test_dict = {'x': 1, 'y': 2}
for k in test_dict:
print k
# iterating over a text file
for line in open('test.txt'):
print line
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.