blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
582fe920cc4dd459ec3f9b102f3f91dc5fd3960f | xpansong/learn-python | /列表/列表元素的排序.py | 750 | 4.25 | 4 | print('--------使用列表对象sort()进行排序,不生成新的列表,原列表直接运算,不需要重新赋值----------')
lst=[10,90,398,34,21,77,68]
print(lst,id(lst))
#调用列表对象sort(),对列表进行升序排序
lst.sort()
print(lst,id(lst))
#通过指定关键字参数,对列表进行降序排序
lst.sort(reverse=True)
print(lst,id(lst))
print('-------使用内置函数sorted()进行排序,生成新的列表,因此新列表需要重新赋值----------')
lst=[10,90,398,34,21,77,68]
new_list=sorted(lst) #生成新的列表,new_list是新的列表,ID跟原列表不一样
print(new_list)
#通过指定关键字参数,对列表进行降序排序
list2=sorted(lst,reverse=True)
print(list2)
| false |
39768f5f5217adf08077dfc98865f9a298526804 | stayfu0705/python1 | /M5/method.py | 683 | 4.25 | 4 | str1='hello 123'
print(str1.isalnum()) #有空白就算兩個字串
print(str1.isalpha())
print(str1.isdigit())
print(str1.isidentifier())
str2='hello'
print(str1.isalnum())
print(str1.isalpha())
print(str1.isdigit())
print(str2.isidentifier())
print(str2.isspace())
str5='hello world'
print(str5.startswith('he'))
print(str5.endswith("d"))
print(str5.find('x'))
print(str5.rfind('o'))
print(str5.count('o'))
print(str5.capitalize())
print(str5.lower())
print(str5.upper())
print(str5.title())
print(str5.swapcase())
str4=' he y y eyye '
print(str4.lstrip())
print(str4.rstrip())
print(str4.strip())
'''print(str4.center())'''
str8 ='hello'
print("\\"+str8.center(15)+"/")
| false |
a29f06832bf4caa10f1c8d4141e96a7a50e55bb9 | YashMali597/Python-Programs | /binary_search.py | 1,180 | 4.125 | 4 | # Binary Search Implementation in Python (Iterative)
# If the given element is present in the array, it prints the index of the element.
# if the element is not found after traversing the whole array, it will give -1
# Prerequisite : the given array must be a sorted array
# Time Complexity : O(log n)
# Space complexity : O(1)
#defining the iterative function
def binary_search(array: list, n: int):
low = 0
high = len(array) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# checking if n is present at mid
if array[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif array[mid] > n:
high = mid - 1
# If n is smaller, compared to the left of mid
else:
return mid
# element was not present in the array, return -1 (standard procedure)
return -1
# example array
array = [2, 3, 4, 10, 12, 24, 32, 39, 40, 45, 50, 54]
n = 3
# calling the binary search function
result = binary_search(array, n)
if result != -1:
print("Element is present at index", result)
else:
print("Element is not present in given array")
| true |
de7cb8bb33a31a677b47d8c2915416145dcae572 | phillipemoreira/HackerRank | /Python/BasicDataTypes/Lists.py | 618 | 4.15625 | 4 | #Problem link: https://www.hackerrank.com/challenges/python-lists
list = list()
number_of_commands = int(input())
for i in range(0, number_of_commands):
s = input().split(' ')
command = s[0]
args = s[1:]
if command == "insert":
list.insert(int(args[0]), int(args[1]))
elif command == "print":
print(list)
elif command == "remove":
list.remove(int(args[0]))
elif command == "append":
list.append(int(args[0]))
elif command == "sort":
list.sort()
elif command == "pop":
list.pop()
elif command == "reverse":
list.reverse() | false |
d089562243b35b8be2df3c31888518a235858c43 | xiaoying1990/algorithm_stanford_part1 | /merge_sort.py | 2,293 | 4.53125 | 5 | #!/usr/bin/python3
import random
def merge_sort(ar):
"""
O(n*log(n)), dived & conquer algorithm for sorting array to increasing order.
:param ar: type(ar) = 'list', as a array of number.
:return: None, while sorting the parameter 'arr' itself. We can change it, because list is mutable.
"""
arr = ar[:]
def merge(begin, end, mid):
"""
The key function which merge two adjacent pieces of arr into a sorted one.
This function uses a copy list: arr[begin:end + 1].
first piece: arr[begin:mid + 1]
second piece: arr[mid + 1:end + 1]
:param begin: the beginning index of the first piece of list in arr
:param end: the last index of the second piece of list in arr
:param mid: the last index of the first piece of list in arr
:return: None, with the sorting change of arr[begin:end + 1]
"""
i, j, k = 0, mid + 1 - begin, begin # i and j means the index of the two pieces in arr_copy.
arr_copy = arr[begin:end + 1] # k is for resetting value from arr_copy to arr.
while i <= mid - begin and j <= end - begin:
if arr_copy[i] <= arr_copy[j]:
arr[k], k, i = arr_copy[i], k + 1, i + 1
else:
arr[k], k, j = arr_copy[j], k + 1, j + 1
while i <= mid - begin:
arr[k], k, i = arr_copy[i], k + 1, i + 1
while j <= end - begin:
arr[k], k, j = arr_copy[j], k + 1, j + 1
def merge_sort_for_arr(begin=0, end=len(arr) - 1):
if begin == end:
return
mid = (begin + end) // 2
merge_sort_for_arr(begin, mid)
merge_sort_for_arr(mid + 1, end)
merge(begin, end, mid)
merge_sort_for_arr()
return arr
def test():
l = list(random.randint(0 * i, 100) for i in range(50000))
random.shuffle(l)
print('the list l: {}'.format(l))
l_sorted = sorted(l)
l_sorted2 = merge_sort(l)
print('using built-in function sorted: {}'.format(l_sorted))
print('list l after applying merger_sort: {}'.format(l_sorted2))
print('Does these the same result? {}'.format(l_sorted2 == l_sorted))
print('Does these the same list object? {}'.format(l_sorted2 is l_sorted))
if __name__ == '__main__':
test()
| true |
0e48b82567ddcd2eabacdb0c1a4fb514f0e97eb7 | darwinini/practice | /python/avgArray.py | 655 | 4.21875 | 4 | # Program to find the average of all contiguous subarrays of size ‘5’ in the given array
def avg(k, array):
avg_array = []
for i in range(0, len(array) - k + 1):
sub = array[i:i+k]
sum, avg = 0, 0
# print(f"The subarray is {sub}")
for j in sub:
sum+= j
avg = sum / 5
avg_array.append(avg)
return avg_array
def main():
# test our avg function
k = 5
a = [1, 3, 2, 6, -1, 4, 1, 8, 2]
print(f"The input array is {a}, with k = {k}")
print(f"The averaged array is {avg(k,a)}")
print(f"the complexity for this algorithm is O(N*K) time | O(N) Space")
main()
| true |
0c0718a685533344d5fea9cfdf1ec9d925dbdcd9 | Surya0705/Number_Guessing_Game | /Main.py | 1,407 | 4.3125 | 4 | import random # Importing the Random Module for this Program
Random_Number = random.randint(1, 100) # Giving our program a Range.
User_Guess = None # Defining User Guess so that it doesn't throw up an error later.
Guesses = 0 # Defining Guesses so that it doesn't throw up an error later.
while(User_Guess != Random_Number): # Putting a while loop and telling Program to stop if Guess is Correct.
User_Guess = int(input("Enter the Guess: ")) # Taking the input from the User.
Guesses += 1 # Adding 1 per Guess.
if(User_Guess == Random_Number): # Telling the Program what to do if the Guess is Correct.
print("CORRECT! You Guessed it Right!") # Printing the Greetings if the guess is Correct.
else: # Putting an Else Condition so that the Program knows what to do in case the Guessed Number is not Correct.
if(User_Guess >= Random_Number): # In case if the User Guess is smaller than Random Number.
print("You guessed it Wrong! Enter a Smaller Number...") # Telling the user what to do.
else: # Putting an Else Condition so that the Program knows what to do in case the User guess is greater that Random Number.
print("You guessed it Wrong! Enter a Larger Number...") # Telling the User what to do.
print(f"You were able to guess the Number in {Guesses} Guesses!") # Printing the final output that you Guessed the Number in __ Number of Times. | true |
16d1c6a7eca1df4440a78ac2f657a56fa1b8300b | bnew59/sept_2018 | /find_largest_element.py | 275 | 4.21875 | 4 |
#Assignment: Write a program which finds the largest element in the array
# def largest_element(thing):
# for num in thing:
# if num + 1 in
# elements = [1, 2, 3, 4]
a=[1,2,3,4,6,7,99,88,999]
max = a[0]
for i in a:
if i > max:
max=i
print(max) | true |
c64b1e0c45ea4de9c2195c99bfd3b22ab2925347 | Samyak2607/CompetitiveProgramming | /Interview/postfix_evaluation.py | 1,133 | 4.15625 | 4 | print("For Example : abc+* should be entered as a b c + *")
for _ in range(int(input("Enter Number of Test you wanna Test: "))):
inp=input("Enter postfix expression with space: ")
lst=inp.split(" ")
operator=['+','-','/','*','^']
operands=[]
a=1
for i in lst:
if(i not in operator):
operands.insert(0,i)
else:
if(len(operands)>=2):
num1=operands.pop(0)
num2=operands.pop(0)
num1=int(num1)
num2=int(num2)
if(i=='*'):
operands.insert(0,num2*num1)
elif(i=='/'):
operands.insert(0,num2/num1)
elif(i=='+'):
operands.insert(0,num2+num1)
elif(i=='-'):
operands.insert(0,num2-num1)
elif(i=='^'):
operands.insert(0,num2**num1)
else:
print("Not Valid")
a=0
if(a==1):
if(len(operands)!=1):
print("Not valid")
else:
print(operands[0])
| true |
d5bcb62f24c54b161d518ac32c4a2434d01db76e | PaLaMuNDeR/algorithms | /Coding Interview Bootcamp/16_linked_list.py | 1,665 | 4.25 | 4 | """
Return the middle node of a Linked list.
If the list has an even number of elements, return the node
at the end of the first half of the list.
DO NOT use a counter variable, DO NOT retrieve the size of the list,
and only iterate through the list one time.
Example:
const l = LinkedL()
l.insertLast('a')
l.insertLast('b')
l.insertLast('c')
midpoint(l) -> { data: 'b' }
"""
class Node:
def __init__(self, data=None):
self.data = data
self.nextval = None
class LinkedList:
def __init__(self):
self.head = None
def insertLast(self, newdata):
NewNode = Node(newdata)
if self.head is None:
self.head = NewNode
return
last = self.head
while last.nextval:
last = last.nextval
last.nextval = NewNode
def listprint(self):
printval = self.head
while printval:
print(printval.data)
printval = printval.nextval
def midpoint(linkedL):
"""
We create two iterators.
One is jumping one step at a time
The other is jumping two steps at a time.
If in front of the second iterator the next 2 values are None,
then the first iterator has reached the midpoint
"""
head = linkedL.head
i = linkedL.head
j = linkedL.head
while j:
if j.nextval and j.nextval.nextval:
i = i.nextval
j = j.nextval.nextval
else:
return i.data
linkedL = LinkedList()
node1 = Node('a')
linkedL.head = node1
# print(linkedL.head.nextval.data)
linkedL.listprint()
print "Answer"
print midpoint(linkedL) | true |
edbbd4fe3fc4a8646c52d70636369ff1c1c23bd5 | PaLaMuNDeR/algorithms | /Coding Interview Bootcamp/10_capitalize.py | 2,096 | 4.28125 | 4 | import timeit
""" Write a function that accepts a string. The function should
capitalize the first letter of each word in the string then
return the capitalized string.
Examples:
capitalize('a short sentence') -> 'A Short Sentence'
capitalize('a lazy fox') -> 'A Lazy Fox'
capitalize('look, it is working!') -> 'Look, It Is Working!'
"""
def capitalize_move_index(str):
"""
Find a space, set index var to it and update the next char
Time: 16 sec.
"""
index = 0
str = str[index].upper() + str[index + 1:]
index = index + str[index + 1:].find(' ') + 1
while index < len(str):
str = str[0:index] + ' ' + str[index+1].upper() + str[index+2:]
next_space = str[index+1:].find(' ')
if not next_space == -1:
index = index + next_space + 1
else: break
return str
def capitalize_with_array(str):
"""
Split to array of words.
Convert the first letter of each to capital.
Join all the words
Time: 9 sec.
"""
index = 0
words = []
for word in str.split(' '):
words.append(word[0].upper() + word[1:])
return (' ').join(words)
def capitalize_after_space(str):
"""
Before you find a space, make the next character UpperCase
Time: 32 sec.
"""
result = str[0].upper()
for i in range(1, len(str)):
if str[i-1] == ' ':
result += str[i].upper()
else:
result += str[i]
return result
# print(capitalize_after_space('a short sentence') )
# print(capitalize_after_space('a lazy fox'))
# print(capitalize_after_space('look, it is working!'))
a_string = 'amanaplana canal panama' * 10
print "Method 1 - Find a space, set index var to it and capitalize after"
print min(timeit.repeat(lambda: capitalize_move_index(a_string)))
print "Method 2 - Split to array of words"
print min(timeit.repeat(lambda: capitalize_with_array(a_string)))
print "Method 3 - Capitalize everything after space"
print min(timeit.repeat(lambda: capitalize_after_space(a_string)))
| true |
52cf1f1b5914447294ae9eb29b40abaa5086f644 | PaLaMuNDeR/algorithms | /Algo Expert/113_group_anagrams.py | 894 | 4.34375 | 4 | """
Group Anagrams
Write a function that takes in an array of strings and returns a list of groups of anagrams.
Anagrams are strings made up of exactly the same letters, where order doesn't matter.
For example, "cinema" and "iceman" are anagrams; similarly, "foo" and "ofo" are anagrams.
Note that the groups of anagrams don't need to be ordered in any particular way.
Sample input: ["yo", "act", "flop", "tac", "cat", "oy", "olfp"] Sample output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"]]
"""
def groupAnagrams(words):
anagrams = {}
for word in words:
sortedWord = "".join(sorted(word))
if sortedWord not in anagrams.keys():
anagrams[sortedWord] = [word]
else:
anagrams[sortedWord] = anagrams[sortedWord]+[word]
return list(anagrams.values())
print groupAnagrams(["yo", "act", "flop", "tac", "cat", "oy", "olfp"] )
| true |
cdfa714d56aad96ba4cbcd6ff4dfd25865d8e085 | PaLaMuNDeR/algorithms | /Algo Expert/101_Two_number_sum.py | 819 | 4.125 | 4 | """
Two Number Sum
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
If any two numbers in the input array sum up to the target sum, the function should return them in an array,
in sorted order. If no two numbers sum up to the target sum, the function should return an empty array.
Assume that there will be at most one pair of numbers summing up to the target sum.
Sample input: [3, 5, -4, 8, 11, 1, -1, 6], 10 Sample output: [-1,11]
"""
# Time O(n) | Space O(n)
def twoNumberSum(array, targetSum):
dict = {}
for i in array:
dict[i] = i
for i in dict.keys():
j = targetSum - i
if j != i and j in dict.keys():
return [min(i,j),max(i,j)]
return []
print(twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)) | true |
995aaacefeb011ff0ef04a62d4c9fd4688b4450e | PaLaMuNDeR/algorithms | /Algo Expert/124_min_number_of_jumps.py | 1,006 | 4.125 | 4 | """
Min Number Of Jumps
You are given a non-empty array of integers. Each element represents the maximum number of steps you can take forward.
For example, if the element at index 1 is 3, you can go from index Ito index 2, 3, or 4. Write a function that returns
the minimum number of jumps needed to reach the final index. Note that jumping from index i to index i + x always
constitutes 1 jump, no matter how large x is.
Sample input: [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3] Sample output: 4 (3 --> 4 or 2 --> 2 or 3 --> 7 --> 3)
"""
def minNumberOfJumps(array):
if len(array)==1:
return 0
jump = 0
steps = array[0]
maxReach = array[0]
for i in range(1,len(array)-1):
maxReach = max(maxReach, array[i]+i)
steps -= 1
if steps == 0:
jump += 1
steps = maxReach-i
return jump +1
print(minNumberOfJumps([3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]))
print(minNumberOfJumps([1]))
print(minNumberOfJumps([2,1,1]))
print(minNumberOfJumps([1,1,1])) | true |
edca001ae4dd97c5081f1c6421a457eec39f4ff4 | yasab27/HelpOthers | /ps7twoD/ps7pr2.py | 1,179 | 4.25 | 4 | #
# ps7pr2.py (Problem Set 7, Problem 2)
#
# 2-D Lists
#
# Computer Science 111
#
# If you worked with a partner, put his or her contact info below:
# partner's name:
# partner's email:
#
# IMPORTANT: This file is for your solutions to Problem 2.
# Your solutions to problem 3 should go in ps7pr3.py instead.
import random
def create_grid(height, width):
""" creates and returns a 2-D list of 0s with the specified dimensions.
inputs: height and width are non-negative integers
"""
grid = []
for r in range(height):
row = [0] * width # a row containing width 0s
grid += [row]
return grid
def print_grid(grid):
""" prints the 2-D list specified by grid in 2-D form,
with each row on its own line, and nothing between values.
input: grid is a 2-D list. We assume that all of the cell
values are integers between 0 and 9.
"""
height = len(grid)
width = len(grid[0])
for r in range(height):
for c in range(width):
print(grid[r][c], end='') # print nothing between values
print() # at end of row, go to next line
| true |
8ed7f544dd1ba222cf0b96ee7f1e3a2b18b9e993 | krathee015/Python_assignment | /Assignment4-task7/task7_exc2.py | 722 | 4.375 | 4 | # Define a class named Shape and its subclass Square. The Square class has an init function which
# takes length as argument. Both classes have an area function which can print the area of the shape
# where Shape’s area is 0 by default.
class Shape:
def area(self):
self.area_var = 0
print("area of shape is: ",self.area_var)
class Square(Shape):
def __init__(self,length):
self.length = length
def area(self):
area = (self.length * self.length)
print("The area of square with length {} is:{}".format(self.length,area))
value_length = int(input("Enter the value of length: "))
s_shape = Shape()
s_shape.area()
s_square = Square(value_length)
s_square.area()
| true |
83e8f766412009bd71dea93ed83a1d1f17414290 | krathee015/Python_assignment | /Assignment3/task5/task5_exc2.py | 376 | 4.34375 | 4 | print("Exercise 2")
# Write a program in Python to allow the user to open a file by using the argv module. If the
# entered name is incorrect throw an exception and ask them to enter the name again. Make sure
# to use read only mode.
import sys
try:
with open(sys.argv[1],"r") as f:
print(f.read())
except:
print("Wrong file name entered. Please enter again") | true |
d282703436352013daf16052b74fd03110c645c8 | krathee015/Python_assignment | /Assignment1/Task2/tasktwo_exercise2.py | 984 | 4.125 | 4 | print ("Exercise 2")
result = 0
num1 = eval(input("Enter first number: "))
num2 = eval(input("Enter second number: "))
user_enter = eval(input("Enter 1 for Addition, 2 for Subtraction, 3 for Division, 4 for Multiplication, 5 for Average: "))
if (user_enter == 1):
result = num1 + num2
print ("Addition of two numbers is: ")
elif (user_enter == 2):
result = num1 - num2
print("Subtraction of two numbers is: ")
elif (user_enter == 3):
result = num1 / num2
print ("Division of two numbers is: ")
elif (user_enter == 4):
result = num1 * num2
print ("Multiplication of two number is: ")
elif (user_enter == 5):
first = eval(input("Enter third number: "))
second = eval(input("Enter fourth number: "))
result = (num1 + num2 + first +second)/ 4
print ("Average of four numbers is: ")
else:
print("Kindly enter correct number 1-5")
if (user_enter <= 5 and user_enter > 0):
print(result)
if (result < 0):
print("Negative") | true |
787ab85de849ddb79d1c471a1706677d9b4b74b9 | HuanbinWu/testgit | /pythonjike/function/fuct_test.py | 1,952 | 4.125 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
# Author:HuanBing
#函数基本操作
# print('abc',end='\n\n')
# print('abc')
# def func(a,b,c):
# print('a=%s'%a)
# print('b=%s' %b)
# print('c=%s' %c)
# func(1.c=3)
#取得参数个数
# def howlong(first,*other):
# print(1+len(other))
# howlong(123,234,456)
#函数作用域
# var1=123
#
# def func():
# #定义全局变量var1
# global var1
# var1=1233
# print(var1)
#
# func()
# print(var1)
#iter() next()
# list1=[1,3,4]
# # # it=iter(list1)
# # # print(next(it))
# # # print(next(it))
# # # print(next(it))
# # # print(next(it))
# for i in range(10,20,2):
# print(i)
#生成器,是迭代器的一种,自定义
# def frange(start,stop,step):
# x=start
# while x<stop:
# yield x
# x+=step
# for i in frange(10,20,0.5):
# print(i)
#lambda 表达式
# def true():return True
# lambda :True
#
# def add(x,y):return x+y
# lambda x,y:x+y
#
# print(add(3,5))
# lambda x:x<=(month,day)
# def func1(x):
# return x<(month,day)
# lambda item:item[1]
# def func2(item):
# return item[1]
# adict={'a':'aa','b':'bb','c':'cc'}
# for i in adict.items():
# print(func2(i))
# filter() map() reduce() zip()
# a=[1,2,3,4,5,6,7]
# b=list(filter(lambda x:x>2,a))
# print(b)
# a=[1,2,3,4,5]
# b=[2,3,4,5,6]
# c=list(map(lanbda x,y:x+y,a,b)
# print(c)
#
# >>> from functools import reduce
# >>> reduce(lambda x,y:x+y,[2,3,4],1)
# 10
# >>> 1+2+3+4
# 10
# for i in zip((1, 2, 3), (4, 5, 6)):
# print(i)
#对调
# dicta={'a':'aa','b':'bb'}
# dictb=dict(zip(dicta.values(),dicta.keys()))
# print(dictb)
#
# print((type(num2)))def func():
# # a=1
# # b=2
# # return a+b
# # #闭包
# # def sum(a):
# # def add(b):
# # return a+b
# # return add
# #
# # #add函数名称或函数的引用
# # #add()函数的调用
# # num1=func()
# # num2=sum(2)
# # print(num2(4))
# # # print(type(num1))
| false |
a09f3ab56f175cb0286000a3251ebf8feee07f68 | murphyk2021/Election_Analysis | /Python_practice.py | 2,712 | 4.5 | 4 | print("Hello World")
counties=["Arapahoe","Denver","Jefferson"]
if counties[1]=='Denver':
print(counties[1])
counties=["Arapahoe","Denver","Jefferson"]
if "El Paso" in counties:
print("El Paso is in the list of counties")
else:
print("El Paso is not in the list of counties")
if "Arapahoe" in counties and "El Paso" in counties:
print("Arapahoe and El Paso are in the list of counties")
else:
print("Arapahoe or El Paso is not in the list of counties")
if "Arapahoe" in counties or "El Paso" in counties:
print("Arapahoe or El Paso is in the list of counties")
else:
print("Arapahoe and El Paso are not in the list of counties")
if "Arapahoe" in counties and "El Paso" not in counties:
print("Only Arapahoe is in the list of counties")
else:
print("Arapahoe is in th list of counties and El Paso is not in the list of counties")
#Iterate through lists and tuples
for county in counties:
print(county)
numbers=[0, 1, 2, 3, 4]
for num in numbers:
print(num)
for num in range(5):
print(num)
for i in range(len(counties)):
print(counties[i])
#Get the keys of a dictionary
counties_dict={"Arapahoe":422829, "Denver": 463353, "Jefferson":432438}
for county in counties_dict:
print(county)
for county in counties_dict.keys():
print(county)
for voters in counties_dict.values():
print(voters)
for county in counties_dict:
print(counties_dict[county])
for county in counties_dict:
print(counties_dict.get(county))
#Get the Key-Value Pairs of a dictionary
for county, voters in counties_dict.items():
print(county + " county has " + str(voters) + " registered voters.")
#Iterate through a list of Dictionaries
voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters":463353},{"county":"Jefferson", "registered_voters": 432438}]
for county_dict in voting_data:
print(county_dict)
for i in range(len(voting_data)):
print(voting_data[0])
#Get the values from a list of dictionaries
for county_dict in voting_data:
for value in county_dict.values():
print(value)
for county_dict in voting_data:
print(county_dict['registered_voters'])
print(county_dict['county'])
for county_dict in voting_data:
print(county_dict['county'])
for county, voters in counties_dict.items():
print(f'{county} county has {voters:,} registered voters.')
for county_dict in voting_data:
print(f"{county_dict['county']} county has {county_dict['registered_voters']:,} registered voters.")
for i in range(len(voting_data)):
print(f"{voting_data[i]['county']} county has {voting_data[i]['registered_voters']:,} registered voters.") | false |
904d7bf1450e3838387f787eb0411593c739d5f0 | kunal5042/Python-for-Everybody | /Course 2: Python Data Structures/Week 3 (Files)/Assignment_7.2.py | 1,119 | 4.125 | 4 | """
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
Desired output:
Average spam confidence: 0.7507185185185187
"""
fileName = input("Please enter a file's name:\n")
try:
file = open(fileName)
except:
print("Coudn't open the file: " + fileName)
quit()
lineCount = 0
totalConfidence = 0.0
for line in file:
if not line.startswith("X-DSPAM-Confidence:"):
continue
lineCount += 1
index = line.find('0')
try:
totalConfidence += float((line[index:]).strip())
except:
print("Error while parsing the string.")
print("Average spam confidence: " + str(totalConfidence / lineCount))
| true |
b3be5eaf872a254f8cec7c7eb33740c9c4f30303 | kunal5042/Python-for-Everybody | /Course 1: Programming for Everbody (Getting Started with Python)/Week 6 (Functions)/Factorial.py | 603 | 4.28125 | 4 | # Here I am using recursion to solve this problem, don't worry about it if it's your first time at recursion.
def Factorial(variable):
if variable == 0:
return 1
return (variable * Factorial(variable-1))
variable = input("Enter a number to calculate it's factorial.\n")
try:
x = int(variable)
except:
print("Not a valid number.")
x = 0
if x == 0:
print("\nFactorial of", variable + " equals:")
print("Cannot compute factorial, because the number you entered is invalid.")
else:
print("\nFactorial of", variable + " equals:")
print(Factorial(x))
| true |
07f9f576b76b56b5f258d563de4b24cf8f5f2673 | kunal5042/Python-for-Everybody | /Course 2: Python Data Structures/Week 5 (Dictionaries)/Dictionaries.py | 1,291 | 4.3125 | 4 | """
Dictionaries:
Dic are python's most powerful data collection.
Dic allow us to do fast database-like operations in python.
Dic have different names in different languages.
For example:
Associative Arrays - Perl / PHP
Properties or Map or HashMap - Java
Property Bag - C# /.Net
"""
def dictionaryDemo():
#Initialization
myDictionary = dict()
#Dictionaries are like bags - no order
myDictionary["Kunal5042"] = 1
#So we index the things we put in the dictionary with a "lookup tag"
myDictionary["Tanya"] = 7
myDictionary["Macbook Pro"] = 2399.99
#To get something out we use the exact same label
print("Macbook Pro: $" + str(myDictionary["Macbook Pro"]))
#An object whose internal state can be changed is mutable. On the other hand, immutable doesn't allow any change in the object once it has been created
#Dictionary contents are mutable
myDictionary["Kunal5042"] = myDictionary["Kunal5042"] + 5041
print("kunal" + str(myDictionary["Kunal5042"]))
#Dictionaires are like lists except that they use keys instead of numbers to look up values.
#Changing values of the keys
myDictionary["Tanya"] = 9000
print("Power level over " + str(myDictionary["Tanya"]) + "!")
dictionaryDemo()
# Kunal Wadhwa
# Contact : kunalwadhwa.cs@gmail.com
# Alternate: kunalwadhwa900@gmail.com | true |
e52b318f5ef1e29c6f6ff08ef2fb68336c62ab4b | kunal5042/Python-for-Everybody | /Course 1: Programming for Everbody (Getting Started with Python)/Week 5 (Comparison Operators, Exception Handling basics)
/Assignment_3.1.py | 1,066 | 4.28125 | 4 | """
3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
"""
#print("This program computes gross pay.\n")
hours = input("Enter the number of hours:\n")
try:
H = float(hours)
except:
print("Not a valid number.")
print("Default hours value is 0 and will be used.")
H = 0
hourlyRate = input("Enter the hourly rate:\n")
try:
HR = float(hourlyRate)
except:
print("Not a valid number.")
print("Default hourly rate value is 0 and will be used.")
HR = 0
if H > 40:
extraHours = H - 40
print( 40*HR + (extraHours*1.5*HR))
else:
print(HR*H)
"""
Input:
Hours = 45
Rate = 10.05
Desired Output:
498.75
""" | true |
c2138c13915b9f7cde94d6989b462023e1b1becc | kunal5042/Python-for-Everybody | /Assignments-Only/Assignment_7.1.py | 1,002 | 4.46875 | 4 | """
7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.
You can download the sample data at http://www.py4e.com/code3/words.txt
"""
import urllib.request, urllib.parse, urllib.error
def getFileHandle():
try:
fileName = input("Please enter a file's name:\n")
file = open(fileName)
return file
except:
print("\nSample data file not found.")
print("I'll download it for you!\n\nProgram execution will continue once the sample data is available")
fileHandle = urllib.request.urlopen('http://data.pr4e.org/words.txt')
print("\nDESIRED OUTPUT:\n")
print((fileHandle.read()).decode().upper().strip())
quit()
file = getFileHandle()
print(((file.read()).upper()).rstrip())
# Answer by:
# kunal5042
# Email : kunalwadhwa.cs@gmail.com
# Alternate: kunalwadhwa900@gmail.com | true |
681e8e75e103cfb2227a50813a6a8789320a277a | kunal5042/Python-for-Everybody | /Course 1: Programming for Everbody (Getting Started with Python)/Week 4 (Syntax, Reserved Words, Type Conversions, Variables)
/AssignOperator.py | 597 | 4.46875 | 4 | print("Assignment operator example:")
#Example:
print("Hi!")
myName= "Kunal"
print("\nMy name is " + myName)
myLastName = "Wadhwa"
print("My last name is " + myLastName)
myFullName = myName + " " + myLastName
print("\nMy full name is " + myFullName)
age= 19
age= age + 1
print(("I am ") + str(age) + (" years old."))
print("\nAnd, I am really excited about learning python programming.")
#Output :
#Assignment operator example:
#Hi!
#
#My name is Kunal
#My last name is Wadhwa
#
#My full name is Kunal Wadhwa
#I am 20 years old.
#And, I am really excited about learning python programming.
| false |
97e1c7c3c00067602ca94705bb73f097d464a735 | ShrutiBhawsar/problem-solving-py | /Problem4.py | 1,547 | 4.5 | 4 | #Write a program that asks the user how many days are in a particular month, and what day of the
# week the month begins on (0 for Monday, 1 for Tuesday, etc), and then prints a calendar for that
# month. For example, here is the output for a 30-day month that begins on day 4 (Thursday):
# S M T W T F S
# 1 2 3
# 4 5 6 7 8 9 10
# 11 12 13 14 15 16 17
# 18 19 20 21 22 23 24
# 25 26 27 28 29 30
week = [ "Su", "Mo", 'Tu', "We", "Th", "Fr", "Sa"]
days30 = list(range(1, 30+1))
days31 = list(range(1 , 31 + 1))
# daystring = " ".join(week)
# print(daystring)
def calender():
input_No_of_days = input(" Enter the number of days in a particular month (30/31/28) : " )
print("select - 0 for Sunday ,1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday, 6 for Saturday,")
input_day_of_week = input(" Enter the day of the week the month begins on ( 0 to 6 ) : ")
start_pos = int(input_day_of_week)
daystring = " ".join(week) # converting week list to string
print(daystring)
spacing = list(range(0,start_pos)) #providing spacing till the first day of the week
for space in spacing:
print("{:>2}".format(""), end = " ")
if input_No_of_days == "30":
days = days30
else:
days = days31
for day in days:
print('{:>2}'.format(day), end=' ')
start_pos += 1
if start_pos ==7:
# If start_pos == 7 (Sunday) start new line
print()
start_pos = 0 # Reset counter
print('\n')
calender() | true |
4f03b84942530c09ff2932e497683e5f75ccbf9c | ShrutiBhawsar/problem-solving-py | /Problem2_USerInput.py | 1,237 | 4.3125 | 4 | #2. Print the given number in words.(eg.1234 => one two three four).
def NumberToWords(digit):
# dig = int(digit)
"""
It contains logic to convert the digit to word
it will return the word corresponding to the given digit
:param digit: It should be integer
:return: returns the string back
"""
digitToWord = {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven',
8: 'Eight', 9: 'Nine'}
return digitToWord.get(digit, " Not Valid")
def NumberInWords():
"""
This is the main function.We are getting the input(Number) in string
String is converted to list and each digit is passded to NumberToWords function
:param numInString: Number string
:return: it returns nothing
"""
numInString = input("Please input the number : ") #it takes input from the user
if numInString.isnumeric():
print("The Number to word convertion for {} is : ".format(numInString))
number = list(numInString)
for digit in number:
word = NumberToWords(int(digit))
print(word, end= " ")
print()
else:
print("Wrong input!!..Please enter the number only")
NumberInWords()
| true |
dcee80352c93df7f9dccfef14c15ea31dd7bfe88 | databooks/databook | /deepml/pytorch-examples02/nn/two_layer_net_module.py | 1,980 | 4.21875 | 4 | import torch
"""
A fully-connected ReLU network with one hidden layer, trained to predict y from x
by minimizing squared Euclidean distance.
This implementation defines the model as a custom Module subclass. Whenever you
want a model more complex than a simple sequence of existing Modules you will
need to define your model this way.
"""
class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we instantiate two nn.Linear modules and assign them as
member variables.
"""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, x):
"""
In the forward function we accept a Tensor of input data and we must return
a Tensor of output data. We can use Modules defined in the constructor as
well as arbitrary (differentiable) operations on Tensors.
"""
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
# Construct our model by instantiating the class defined above.
model = TwoLayerNet(D_in, H, D_out)
# Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model.
loss_fn = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
for t in range(500):
# Forward pass: Compute predicted y by passing x to the model
y_pred = model(x)
# Compute and print loss
loss = loss_fn(y_pred, y)
print(t, loss.item())
# Zero gradients, perform a backward pass, and update the weights.
optimizer.zero_grad()
loss.backward()
optimizer.step()
| true |
75e8edfa8f01a8605e6f8fb37fecfe5f23d1ce2f | lpython2006e/student-practices | /12_Nguyen_Lam_Manh_Tuyen/2.7.py | 610 | 4.1875 | 4 | #Write three functions that compute the sum of the numbers in a list: using a for-loop, a while-loop and recursion.
# (Subject to availability of these constructs in your language of choice.)
def sum_with_while(lists):
list_sum = 0
i = 0
while i < len(lists):
list_sum += lists[i]
i += 1
return list_sum
def sum_with_for(lists):
list_sum = 0
for i in range(0, len(lists)):
list_sum += lists[i]
return list_sum
def sum_with_recursion(lists, i):
if i == 0:
return lists[0]
else:
return lists[i] + sum_with_recursion(lists, i-1) | true |
b2c73a750653b98ec18668d59309bba5dc3f1a94 | lpython2006e/student-practices | /9_Phan_Van_Quan/bai2_9.py | 216 | 4.15625 | 4 | #Write a function that concatenates two lists. [a,b,c], [1,2,3] → [a,b,c,1,2,3]
def concatenates(list_1,list_2):
return list_2 + list_1
list_3 = ['a','b','c']
list_4 = [1,2,3]
print(concatenates(list_3,list_4)) | false |
820baad5f24cfc52195fbf11f5c74214812a1b76 | lpython2006e/student-practices | /12_Nguyen_Lam_Manh_Tuyen/1.3.py | 308 | 4.25 | 4 | #Modify the previous program such that only the users Alice and Bob are greeted with their names.
names=["Alice","Bob"]
name=()
while name not in names:
print("Please input your name")
name = input()
if name=="Alice":
print("Hello",name)
elif name=="Bob":
print("Hello",name)
| true |
56dbe18f5cd493157d153647e82cc9b94fcb8f6c | Bhaveshsadhwani/Test | /ASSESSMENT/Que14 .py | 281 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 16:25:08 2017
@author: User
"""
num = input("Enter a positive number:")
if (num > 0) and (num &(num-1))==0:
print num,"is a power of 2"
else:
print num,"is not a power of 2 "
| true |
4ff98dc017eda7df9a80c19e72fab899eac3b044 | YuhaoLu/leetcode | /1_Array/easy/python/rotate_array.py | 1,677 | 4.125 | 4 | """
0.Name:
Rotate Array
1.Description:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Could you do it in-place with O(1) extra space?
2.Example:
Input: [1, 2, 3, 4, 5, 6, 7] and k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
3.Solution:
array.unshift - add from the head
array.shift - delete from the head
array.push - add from the tail
array.pop - delete from the tail
l = 7, k = 3
----------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
-----------------------------
----------------------------
| 5 | 6 | 7 | 1 | 2 | 3 | 4 |
-----------------------------
l-k ... l 0 1 l-k-1
i -> (i + k)/l
4.Corner Case:
5.Complexity:
O(1)
"""
"""
0 -> 3 -> 6 -> 2 -> 5 -> 1 -> 4 -> 7
0 -> 2 -> 4 -> 6 -> 0
1 -> 3 -> 5 -> 7
"""
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
return nums[-k:] + nums[:len(nums)-k]
def rotate2(self, nums: List[int], k: int) -> None:
def gcd(a,b):
if b==0:
return a
else:
return gcd(b, a%b)
n = len(nums)
for i in range(gcd(n,k)):
pre = nums[i]
j = i
while (j+k)%n != i: # j+k/len !=i
nums[(j+k)%n], pre = pre, nums[(j+k)%n]
j = (j+k)%n
nums[(j+k)%n] = pre
nums = [1,2,3,4,5,6,7]
k = 3
sol = Solution()
result = sol.rotate(nums, k)
print(result) | true |
8244b2c89489b52681b49174ee7889ec473cf6d7 | YuhaoLu/leetcode | /4_Trees/easy/python/Symmetric_Tree.py | 2,166 | 4.53125 | 5 | """
0.Name:
Symmetric Tree
1.Description:
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center)
2.Example:
Given linked list:
1
/ \
2 2
/ \ / \
3 4 4 3
Input: root = [1,2,2,3,4,4,3]
Output: true
1
/ \
2 2
\ \
3 3
Constraints:
The number of nodes in the tree is in the range [1, 1000].
-100 <= Node.val <= 100
3.Solution:
Check whether the left tree and right tree are mirror
If both trees are empty, then they are mirror images
1 - Their root node's key must be same
2 - left subtree of left tree and right subtree
of the right tree have to be mirror images
3 - right subtree of left tree and left subtree
of right tree have to be mirror images
4.Corner Case:
node is head or tail
5.Complexity:
O(n)
"""
# Python program to check if a
# given Binary Tree is symmetric or not
# Node structure
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Returns True if trees
#with roots as root1 and root 2 are mirror
class Solution:
def isSymmetric(self, root):
# Check if tree is mirror of itself
return self.isMirror(root, root)
def isMirror(self, root1, root2):
#
if root1 is None and root2 is None:
return True
if (root1 is not None and root2 is not None):
if root1.key == root2.key:
return (self.isMirror(root1.left, root2.right)and
self.isMirror(root1.right, root2.left))
# If none of the above conditions is true then root1
# and root2 are not mirror images
return False
# Test
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
sol = Solution()
print ("Symmetric" if sol.isSymmetric(root) == True else "Not symmetric")
| true |
1df94c11e36c23bd17752519659f96de91f7ea97 | johnerick89/iCube_tasks | /task2.py | 735 | 4.375 | 4 |
def get_maximum_value_recursion(weight,values,capacity, n):
'''
Function to get maximum value
Function uses recursion to get maximum value
'''
if n==0 or capacity == 0:
return 0
if weight[n-1]>capacity:
return get_maximum_value_recursion(weight,values,capacity, n-1)
else:
return max(
values[n-1] + get_maximum_value_recursion(
weight, values,capacity-weight[n-1], n-1),
get_maximum_value_recursion(weight,values,capacity, n-1))
'''
Function driver code
'''
weight = [5,4,6,4]
values = [10,40,30,50]
capacity = 10
n = len(values)
maximum_value = get_maximum_value_recursion(weight,values,capacity,n)
print(maximum_value)
| true |
951e6870e1c504e5e17122f8cb7a8600d13115bc | jtpio/algo-toolbox | /python/mathematics/cycle_finding.py | 1,154 | 4.21875 | 4 | def floyd(f, start):
""" Floyd Cycle Finding implementation
Parameters
----------
f: function
The function to transform one value to its successor
start:
The start point from where the cycle detection starts.
Returns
-------
out: tuple:
- mu: int
Position at which the cycle starts
- length: int
The length of the cycle
"""
slow, fast = f(start), f(f(start))
while slow != fast:
slow, fast = f(slow), f(f(fast))
mu = 0
fast = start
while slow != fast:
slow, fast = f(slow), f(fast)
mu += 1
length = 1
fast = f(slow)
while slow != fast:
fast = f(fast)
length += 1
return (mu, length)
def brent(f, start):
p = length = 1
slow, fast = start, f(start)
while slow != fast:
if p == length:
slow = fast
p *= 2
length = 0
fast = f(fast)
length += 1
mu = 0
slow = fast = start
for i in range(length):
fast = f(fast)
while slow != fast:
slow, fast = f(slow), f(fast)
mu += 1
return mu, length
| true |
1947d4f1bdbcbc54ca8ffbbaaa984b8b91bb837f | BrenoAlv/Projeto-Programa-o- | /q15.py | 2,677 | 4.5 | 4 | #Jogo de Pedra, papel e tesoura: nesse jogo cada jogador faz sua escolha (1 –Tesoura, 2 – Pedra, 3 – Papel),
# e vence aquele que escolher um objeto que seja capaz de vencer o outro.Faça que leia a opção de objeto do primeiro jogador
# a opção de objeto do segundo jogador e informe qual jogador venceu(ou se houve empate).
print("VAMOS JOGAR PEDRA, PAPEL OU TESOURA!?")
print("\nOpções -->> 1-Tesoura 2-Pedra 3-Papel \nEscolham então!")
escolha1 = int(input("Usuário 1, escolha: "))
escolha2 =int(input("Usuário 2, escolha: "))
# usuário 1
if escolha1 == 1 and escolha2 == 3:
print("O usuário 1 escolheu Tesoura")
print("O usuário 2 escolheu Papel")
print("Tesoura corta papel!")
print("Usuário 1 ganhou!")
print("Obrigado por jogarem!")
elif escolha1 == 2 and escolha2 ==1:
print("O usuário 1 escolheu Pedra ")
print("O usuário 2 escolheu Tesoura")
print("Pedra quebra tesoura!")
print("Usuário 1 ganhou!")
print("Obrigado por jogarem!")
elif escolha1 == 3 and escolha2 == 2:
print("O usuário 1 escolheu Papel")
print("O usuário 2 escolheu Pedra ")
print("Papel embrulha a pedra!")
print("Usuário 1 ganhou!")
print("Obrigado por jogarem!")
# Aqui começa o usuário 2.
elif escolha2 == 1 and escolha1 == 3:
print("O usuário 1 escolheu Papel ")
print("O usuário 2 escolheu Tesoura ")
print("Tesoura corta papel!")
print("Usuário 2 ganhou!")
print("Obrigado por jogarem!")
elif escolha2 == 2 and escolha1 ==1:
print("O usuário 1 escolheu Tesoura")
print("O usuário 2 escolheu Pedra")
print("Pedra quebra tesoura!")
print("Usuário 2 ganhou")
print("Obrigado por jogarem!")
elif escolha2 == 3 and escolha1 == 2:
print("O usuário 1 escolheu Pedra")
print("O usuário 2 escolheu Papel ")
print("Papel embrulha a pedra!")
print("Usuário 2 ganhou")
print("Obrigado por jogarem!")
#Aqui trabalhei a possibilidade de empate
elif escolha1 == 1 and escolha2 == 1:
print("O usuário 1 escolheu Tesoura")
print("O usuário 2 escolheu Tesoura ")
print("EMPATE")
print("Obrigado por jogarem!")
elif escolha1 == 2 and escolha2 ==2:
print("O usuário 1 escolheu Pedra ")
print("O usuário 2 escolheu Pedra")
print("EMPATE")
print("Obrigado por jogarem!")
elif escolha1 == 3 and escolha2 == 3:
print("O usuário 1 escolheu Papel")
print("O usuário 2 escolheu papel")
print("EMPATE")
print("Obrigado por jogarem!")
else:
print("Por favor, usuários. Digitem somente 1-Tesoura 2-Pedra 3-Papel")
print("Tente de novo!") | false |
d73cc193848b102bd003c6328665289c6e4c6823 | mvered/ME106 | /Week3Assignment-VeredM-countdown.py | 552 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Week 3 Assignment - Wellstone ME 106 - Part II
Created on Sat Aug 11 12:46:54 2018
@author: mvered
"""
countdownMessage = ' more days until the election!'
lastDayMessage = ' more day until the election!'
electionDayMessage = 'Today is election day!'
daysLeft = input('How many days are left until election day? ')
daysLeft = int(daysLeft)
while daysLeft > 1:
print(str(daysLeft) + countdownMessage)
daysLeft = daysLeft - 1
print(str(daysLeft) + lastDayMessage)
print(electionDayMessage) | false |
104b6b05bd01b2b0cee8fdbfa5f58abfce1cba58 | geshem14/my_study | /Coursera_2019/Python/week4/week4task11.py | 1,109 | 4.15625 | 4 | # week 4 task 11
"""
текст задания тут 79 символ=>!
Дано действительное положительное число a и целое неотрицательное число n.
Вычислите aⁿ, не используя циклы и стандартную функцию pow,
но используя рекуррентное соотношение aⁿ=a⋅aⁿ⁻¹.
Решение оформите в виде функции power(a, n) (которая возвращает aⁿ).
Формат ввода
Вводятся действительное положительное число a и целое неотрицательное число n.
Формат вывода
Выведите ответ на задачу: print(power(a, n)).
"""
a, n = float(input()), int(input()) # переменные для ввода
def power(d_a, d_n):
"""
функция возвращает aⁿ
"""
if d_n >= 1:
return d_a * power(d_a, d_n - 1)
else:
return 1.0
print(power(a, n))
| false |
ff2c2f984035f5f3d4994da9e2c2654bab625a32 | geshem14/my_study | /Coursera_2019/Python/week3/week3task15.py | 1,259 | 4.125 | 4 | # week 3 task 15
"""
текст задания
Дана строка. Если в этой строке буква f встречается только один раз,
выведите её индекс. Если она встречается два и более раз,
выведите индекс её первого и последнего появления.
Если буква f в данной строке не встречается, ничего не выводите.
При решении этой задачи нельзя использовать метод count и циклы.
"""
string = input() # строковая переменная для ввода
search_string = "f" # искомая строка
temp_position = string.find(search_string) # врем. строка для позиции входа
position1 = temp_position # переменная для первой позиции входа
position_last = -2 # переменная для последней позиции входа
while temp_position != -1:
position_last = temp_position
temp_position = string.find(search_string, temp_position + 1)
if position_last > position1:
print(position1, position_last)
elif position1 >= 0:
print(position1)
| false |
0bf6ccbcf81fde22edc6fb0ed7af72317050ca53 | geshem14/my_study | /Coursera_2019/Python/week3/week3task16.py | 832 | 4.125 | 4 | # week 3 task 16
"""
текст задания тут 79 символ=>!
Дана строка, в которой буква h встречается минимум два раза.Удалите из этой
строки первое и последнее вхождение буквы h,
а также все символы, находящиеся между ними.
"""
string = input() # строковая переменная для ввода
search_string = "h" # искомая строка
position1 = string.find(search_string) # переменная для первой позиции входа
position_last = string.rfind(search_string)
# переменная для последней позиции входа
print(string[:position1]+string[position_last+1:])
| false |
4803471f9a118dc56d4996bf5c850706e6258d17 | geshem14/my_study | /Coursera_2019/Python_Advance/week2/week1learning.py | 1,547 | 4.75 | 5 | # week 2 learning
# video 1. Lists and Tuples
"""
поиск медианы случайного списка. Медиана - это значение в отсортированном
списке, которое лежит ровно посередине, таким образом, половина значений -
слева от него, и половина значений --- справа
"""
import random
import statistics
numbers = []
numbers_size = random.randint(10, 15)
print("Size of list:", numbers_size) # напечатаем размер списка
# мы не будем использовать переменную, которую используем
# для итерации, поэтому назовём её _
for _ in range(numbers_size):
numbers.append(random.randint(10, 20))
# randint возвращает случайное целое
# число в переданном ей интервале
print(numbers) # напечатаем список
numbers.sort() # отсортируем список изменяя его
print("Отсортированный список:")
print(numbers) # напечатаем отсортированный список
half_size = len(numbers) // 2
median = None
if numbers_size % 2 == 1:
median = numbers[half_size]
else:
median = sum(numbers[half_size - 1:half_size + 1]) / 2
numbers.sort()
print("Медиана:", median)
print("Проверка ответа с помощью метода медиана:", statistics.median(numbers))
| false |
ed32eff5d2a297f299deacf1e22d68193494fcce | Starluxe/MIT-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Problem Set 1/Problem 3 - Longest Alphabetcal Substring.py | 1,187 | 4.28125 | 4 | # Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl',
# then your program should print
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print
# Longest substring in alphabetical order is: abc
# Note: This problem may be challenging. We encourage you to work smart.
# If you'\ve spent more than a few hours on this problem, we suggest
# that you move on to a different part of the course. If you have time,
# come back to this problem after you've had a break and cleared your head.
# Paste your code into this box
maxLen=0
current=s[0]
longest=s[0]
# step through s indices
for i in range(len(s) - 1):
if s[i + 1] >= s[i]:
current += s[i + 1]
# if current length is bigger update
if len(current) > maxLen:
maxLen = len(current)
longest = current
else:
current=s[i + 1]
i += 1
print ('Longest substring in alphabetical order is: ' + longest)
| true |
b2da8890a183783c996070701b900c866f235d61 | Starluxe/MIT-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Final Exam/Problem 3.py | 631 | 4.1875 | 4 | # Implement a function that meets the specifications below.
# def sum_digits(s):
# """ assumes s a string
# Returns an int that is the sum of all of the digits in s.
# If there are no digits in s it raises a ValueError exception. """
# # Your code here
# For example, sum_digits("a;35d4") returns 12.
# Paste your entire function, including the definition, in the box below.
# Do not leave any debugging print statements.
def sum_digits(string):
if any(i.isdigit() for i in string):
return sum(int(x) for x in string if x.isdigit())
else:
raise ValueError('No digits in input') | true |
0d9cee17b396341ca249c90414f66e2d9602757f | willianyoliveira/Mundo-Python-1---curso-em-v-deo | /DEsafio017.py | 430 | 4.125 | 4 | '''Catetos e hipotenusa'''
import math
'''x = float(input('Qual o comprimento do cateto oposto: '))
y = float(input('Qual o comprimento do cateto adjascente: '))
h = (x*x + y*y)**0.5
print('O valor da hipotenusa é {.2f}.'.format(h))'''
x = float(input('Qual o comprimento do cateto oposto: '))
y = float(input('Qual o comprimento do cateto adjascente: '))
h = math.hypot(x,y)
print('O valor da hipotenusa é {:.2f}.'.format(h)) | false |
94846af53f588d81cf57e822044d204cb5fef2d1 | lukelafountaine/euler | /23.py | 1,887 | 4.25 | 4 | #! /usr/bin/env python
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
# For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
# which means that 28 is a perfect number.
#
# A number n is called deficient if the sum of its proper divisors is less than n
# and it is called abundant if this sum exceeds n.
#
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
# the smallest number that can be written as the sum of two abundant numbers is 24.
# By mathematical analysis, it can be shown that all integers greater than 28123
# can be written as the sum of two abundant numbers.
#
# However, this upper limit cannot be reduced any further by analysis even though it is known
# that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
#
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
def get_divisors(n):
divisors = []
for x in range(n + 1):
divisors.append([])
for num in range(1, (n / 2) + 1):
multiple = num + num
while multiple < len(divisors):
divisors[multiple].append(num)
multiple += num
return divisors
def get_abundants(n, divisors):
abundants = []
for x in range(n):
if sum(divisors[x]) > x:
abundants.append(x)
return abundants
def non_abundant():
upper_limit = 28123
divisors = get_divisors(upper_limit)
abundants = get_abundants(upper_limit, divisors)
can_sum = set()
for i in range(len(abundants)):
for j in range(i, len(abundants)):
can_sum.add(abundants[i] + abundants[j])
total = 0
for x in range(upper_limit):
if x not in can_sum:
total += x
return total
print non_abundant()
| true |
f3d520e3294cb123db91beab99d28c34c939b1d0 | lukelafountaine/euler | /1.py | 426 | 4.34375 | 4 | #! /usr/bin/env python
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def sum_of_multiples(n, bound):
multiples = (bound - 1) / n
return n * ((multiples * (multiples + 1)) / 2)
print sum_of_multiples(3, 1000) + sum_of_multiples(5, 1000) - sum_of_multiples(15, 1000)
| true |
e847163243fab51dede630b814f58e804aca5569 | cristiancmello/python-learning | /10-brief-tour-stdlib/10.5-str-pattern-match/script-1.py | 314 | 4.28125 | 4 | # String Pattern Matching
# Um módulo chamado 're' fornece ferramentas para processamento avançado de strings
# através de expressões regulares.
import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')) # ['foot', 'fell', 'fastest']
print('tea for too'.replace('too', 'two')) # tea for two | false |
73cf62270898593c9931bb8d1cc1c477f326bea8 | cristiancmello/python-learning | /3-informal-intro-python/3.2-strings/script-1.py | 2,068 | 4.25 | 4 | # Strings
# Pode usar tanto '' quanto "" para expressar strings. Os caracteres de escape
# são POSIX (\n, \t, ...)
print('spam eggs')
print('\"Hello, Double Quotes\"')
print('Fist Line\n\tSecond Line.')
# String com caractere de formatação ignorado
print('Primeira linha\nova linha') # Observa-se que 'nova linha' ficará 'ova linha'
print(r'Primeira linha\nova linha') # \n será ignorado
# Múltiplas linhas
print("""
Usage: stringify [OPTIONS]
-json
-JSON json
""")
# Concatenação (+) e Repetição (*)
print('ba' + 2 * 'na') # 'banana'
# Concatenação entre string literals
# IMPORTANTE! NÃO FUNCIONA ENTRE VARIÁVEIS OU EXPRESSÕES
print('Py' 'thon') # 'Python'
# Concatenação entre string e variável
prefixo = 'Py'
print(prefixo + 'thon') # 'Python'
texto = ('Titulo'
'\n\tTexto texto texto texto texto texto texto')
print(texto)
# Indexação de Strings
# Semelhante à linguagem C
word = 'Python'
print(word[0] + word[1] + word[2]) # Pyt
# Podemos obter caracteres da string de trás para frente
print(word[-3] + word[-2] + word[-1]) # hon
# IMPORTANTE! Índice 0 <=> -0
print(word[-0] + word[0]) # PP
# Slicing
# Com o Slicing, podemos subdividir a string em substrings
print(word[0:3]) # Pyt ( intervalo: [0, 3) -> não inclui o índice 3 )
print(word[3:6]) # thon ( intervalo: [3, 6) -> não inclui o índice 6 )
# Equivalência
# String s = s[:i] + s[i:] (sempre tem início e exclui-se o fim)
print(word[:2]) # Py
print(word[2:]) # thon
print(word[:2] + word[2:]) # Python
# IMPORTANTE!
# - Valores fora de limite da string são tratados como região vazia da string
# - Trechos de strings em Python não podem ser alterados - IMUTÁVEIS
# (qualquer tentativa de atribuição dará erro)
# Função len(s) (nativa, ou 'built-in')
# Equivalente ao strlen()
string = 'Lorem Ipsum'
print('Comprimento da string: ' + str(len(string)) + ' caracteres')
# printf-style
print("Name: %s\nAge: %d" % ('John Doe', 32))
# Alternativa
print('%(language)s' % {'language': 'Python'}) # Python | false |
9f1ceda961e34223e3f49243c7bb0718bcb00d18 | cristiancmello/python-learning | /5-data-structures/5.1-more-on-lists/script-1.py | 2,717 | 4.71875 | 5 | # Data Structures
# Funções de listas
# Append
# Colocar um elemento ao final de uma lista.
lista = [1, 2]
lista.append(3)
print(lista) # [1, 2, 3]
# Extend
# Colocar uma lista ao final de outra.
lista = [1, 2]
lista.extend([3, 4])
print(lista) # [1, 2, 3, 4]
# Insert
# Inserir um elemento em determinada posição.
lista.insert(0, 5)
print(lista) # [5, 1, 2, 3, 4]
# Remove
# Remover o primeiro item da lista.
lista.remove(5)
print(lista) # [1, 2, 3, 4]
# Pop
# Remove elemento da lista e o retorna.
print(lista.pop()) # 4
print(lista) # [1, 2, 3]
# Podemos especificar o índice.
print(lista.pop(1))
print(lista) # [1, 3]
# Clear
# Remove todos os itens de uma lista. Equivale a 'del a[:]'.
lista.clear()
print(lista)
# Index
# Retorna o índice do primeiro elemento encontrada na lista.
lista = [1, 2, 3]
print(lista.index(2)) # 1
# Sort
# Ordena uma lista.
lista = [-1, 5, 4, 2, 1, 0]
lista.sort()
print(lista) # [-1, 0, 1, 2, 4, 5]
# Reverse
# Reverte os elementos da lista
lista.reverse()
print(lista) # [5, 4, 2, 1, 0, -1]
# Copy
# Retorna uma cópia da lista.
lista_copia = lista.copy()
print(lista_copia)
# IMPORTANTE!
# Podemos utilizar as listas como pilhas também.
# Usando Listas como Filas
# Importar 'deque', que possui funcionalidades de fila
from collections import deque
fila = deque(['John', 'Eric', 'Michael'])
# Colocar 'Terry' ao final da fila
fila.append('Terry')
# O primeiro da fila será "atendido". Ou seja, 'John' será atendido
fila.popleft()
print(fila) # deque(['Eric', 'Michael', 'Terry'])
# List Comprehensions
# Provê uma forma concisa de criar listas.
squares = []
for x in range(10):
squares.append(x**2)
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Podemos escrever de forma concisa...
# {x pertence a [0, 1, 2, ..., 9] | x**2}
# ou {x**2 | x pertence a [0, 1, 2, ...., 9]}
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Alternativa usando Expressão Lambda
squares = list(map(lambda x: x**2, range(10))) # funcao => lambda x x**2 (entrada de x)
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Podemos fazer estruturas mais elaboradas
# { par (x, y) na lista | Para todo x e y pertencente a [1, 2, 3] e [3, 1, 4] ^ x != y }
lista = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(lista)
# Operação de flatten numa matriz
matriz = [[1, 2, 3], [4, 5, 6]]
flatten_matriz = [num for elem in matriz for num in elem]
print(flatten_matriz) # [1, 2, 3, 4, 5, 6]
# Nested function in List Comprehension
from math import pi
lista_pi_prec = [str(round(pi, i)) for i in range(1, 4)]
print(lista_pi_prec) # ['3.1', '3.14', '3.142']
| false |
e3f3b2e210c39bcbfab71de8ab5e725d2f763586 | cristiancmello/python-learning | /9-classes/9.9-iterators/script-1.py | 392 | 4.53125 | 5 | # Iterators
# Muitos objetos podem ser percorridos por loops 'for'.
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one': 1, 'two': 2}:
print(key)
# Por trás da cortina, o Python chama o método 'iter()' do objeto.
obj = {'name': 'John Doe', 'email': 'john@doe.com'}
it = iter(obj)
print(next(it)) # name
print(next(it)) # email
| false |
e0d9b4ea2c9cd5128237e4c28a9eec2d275bcf42 | yangninghua/code_library | /book-code/图解LeetCode初级算法-源码/5/reverseInteger.py | 1,316 | 4.15625 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
# File: /Users/king/Python初级算法/code/5/reverse.py
# Project: /Users/king/Python初级算法/code/5
# Created Date: 2019/02/10
# Author: hstking hst_king@hotmail.com
def reverse(x):
# tList = list(str(x))
# if tList[0] == '-':
# rNum = int(''.join(tList[1:][::-1])) * (-1) #列表反转
# else:
# rNum = int(''.join(tList[::-1])) #列表反转
#
# if rNum in range(pow(2, 31)* (-1), pow(2, 31) -1):
# return rNum
# else:
# return 0
rList = []
minus = False #负数标识,为False时表明是正数,True时为负数
if x < 0:
minus = True
x = x * (-1) #将输入的数变成正数
while x // 10 != 0: #将参数x的绝对值倒序放入列表
rList.append(str(x % 10))
x = x // 10
rList.append(x)
length = len(rList)
rNum = 0
for i in range(length): #列表还原成数字
rNum += int(rList[i]) * pow(10, length - i - 1)
if minus: #还原参数的符号
rNum = rNum * (-1)
if rNum in range(pow(2, 31)* (-1), pow(2, 31) -1): #判断值区间
return rNum
else:
return 0
if __name__ == "__main__":
x = 120
print("numbers = %d" %x)
rNum = reverse(x)
print("reverse number = %d" %rNum) | false |
4315e3e8c1185f64dc1dd7ad6fcf63e723fc6e0c | marii-20/GeekBrains-Homework | /lesson-1-1.py | 896 | 4.21875 | 4 | #Поработайте с переменными, создайте несколько,
# выведите на экран, запросите у пользователя несколько
# чисел и строк и сохраните в переменные, выведите на экран
greeting = ('Привет! Меня зовут Мария. \n')
age = 28
info = (f'Мне {age} лет и я учусь на python-разработчика. \n')
question = ('Теперь ваша очередь рассказать о себе.')
print(greeting + info)
print(question)
user_name = input('Как вас зовут? ')
user_age = int(input('А сколько вам лет? '))
user_occupation = input('Расскажите, кто вы по профессии? ')
print(f'Приятно познакомиться, {user_name} . \nТеперь я знаю, что вы {user_occupation} и вам {user_age} лет.')
| false |
87351efb827796bdde84fa15df577ad52b615ff5 | jfulghum/practice_thy_algos | /LinkedList/LLStack.py | 1,496 | 4.1875 | 4 | # Prompt
# Implement a basic stack class using an linked list as the underlying storage. Stacks have two critical methods, push() and pop() to add and remove an item from the stack, respectively. You'll also need a constructor for your class, and for convenience, add a size() method that returns the current size of the stack. All of these methods should run in O(1) time!
# Remember, a stack is a first in, first out data structure!
# A singly linked list is a simple way to create a stack. The head of the list is the top of the stack.
# Function Signature
class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
class LLStack:
def __init__(self):
self.stack = []
def size(self):
return len(self.stack)
def pop(self):
return self.stack.pop()
def push(self, item):
return self.stack.append(item)
# Expected Runtime
# O(1) for all methods!
# Examples
stack = LLStack();
print(stack.size()) # 0
stack.push(2);
stack.push(3);
print(stack.size()) # 2
print(stack.pop()) # 3
print(stack.size()) # 1
print(stack.pop()) # 2
# Test various sequences of push/pop and be sure to test edge cases around an empty stack.
# Expected Questions
# If you were presented this question in an interview, these are some questions(s) you might want to ask:
# Q: Computing the size of a linked list is O(n). How can I make this constant?
# A: Keep track of the size as you push and pop in a separate field.
| true |
be1d46e5b24abc08a5ea94810dc69cc3297bbc29 | jfulghum/practice_thy_algos | /LinkedList/queue_with_linked _list.py | 1,352 | 4.5625 | 5 | # Your class will need a head and tail pointer, as well as a field to track the current size.
# Enqueue adds a new value at one side.
# Dequeue removes and returns the value at the opposite side.
# A doubly linked list is one of the simplest ways to implement a queue. You'll need both a head and tail pointer to keep track of where to add and where to remove data. Using a doubly linked list means you can do both operations without walking the whole list and all modifications of the list are at the ends.
class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
class LLQueue:
def __init__(self):
self.front = self.rear = None
self.length = 0
def enqueue(self, item):
temp = ListNode(item)
self.length += 1
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
def dequeue(self, item = None):
if self.front == None:
return
self.length -= 1
temp = self.front
self.front = temp.next
return temp.value
def size(self):
return self.length
# Expected Runtime
# O(1) for all methods!
# Examples
q = LLQueue()
print(q.size()) # 0
q.enqueue(2)
q.enqueue(3)
print(q.size()) # 2
print(q.dequeue()) # 2
print(q.size()) # 1
print(q.dequeue()) # 3
| true |
20059f23388b82201b8a8210f90fe3cc04a16e5a | 31337root/Python_crash_course | /Exercises/Chapter5/0.Conditionial_tests.py | 500 | 4.15625 | 4 | best_car = "Mercedes"
cars = ["Mercedes", "Nissan", "McLaren"]
print("Is " + cars[0] + " the best car?\nMy prediction is yes!")
print(cars[0] == best_car)
print("Is " + cars[1] + " the best car?\nMy prediction is nop :/")
print(cars[1] == best_car)
print("Is " + cars[2] + " the best car?\nMy prediction is nop :/")
print(cars[2] == best_car)
print(cars[0].lower() == best_car.lower())
if 1 > 0 and 0 < 1 and 3 == 3 or 3 != 3:
print("LOLA")
print(best_car in cars)
print(best_car not in cars)
| true |
c7663e6804cc478e517727f7996c6f5df936d364 | jerrywardlow/Euler | /6sumsquare.py | 592 | 4.1875 | 4 | def sum_square(x):
'''1 squared plus 2 squared plus 3 squared...'''
total = 0
for i in range(1, x+1):
total += i**2
return total
def square_sum(x):
'''(1+2+3+4+5...) squared'''
return sum(range(1, x+1))**2
def print_result(num):
print "The range is 1 through %s" % num
print "The sum of the squares is: %s" % sum_square(num)
print "The square of the sum is: %s" % square_sum(num)
print ("The difference between the sum of the squares and the square of "
"the sum is: %s" % (square_sum(num) - sum_square(num)))
print_result(100)
| true |
8428faf468f3c47d0e789bc73037d4da2380b206 | MikhailChernetsov/python_basics_task_1 | /Hometask3/ex1/main.py | 1,562 | 4.34375 | 4 | '''
1. Реализовать функцию, принимающую два числа (позиционные аргументы)
и выполняющую их деление. Числа запрашивать у пользователя,
предусмотреть обработку ситуации деления на ноль.
'''
# Вариант 1 - через исключения
def division(dividend, divisor):
try:
result = dividend / divisor
except ZeroDivisionError:
return 'На ноль делить нельзя'
except ValueError:
return 'Некорректный ввод данных'
else:
return result
# Вариант 2
def division2(dividend, divisor):
if divisor == 0:
return 'На ноль делить нельзя'
else:
return dividend / divisor
my_dividend = input('Введите делимое: ')
my_divisor = input('Введите делитель: ')
while not my_dividend.isdigit() or not my_divisor.isdigit():
print('Данные необходимо вводить числами! Повторите ввод!')
my_dividend = input('Введите делимое: ')
my_divisor = input('Введите делитель: ')
my_dividend = int(my_dividend)
my_divisor = int(my_divisor)
print('Результат работы первой функции:', end=' ')
print(division(my_dividend, my_divisor))
print('Результат работы второй функции:', end=' ')
print(division2(my_dividend, my_divisor))
| false |
de7890db84895c8c8b9e5131bbf7528dc9e3a74f | Annarien/Lectures | /L6.2_25_04_2018.py | 356 | 4.3125 | 4 | import numpy
#make a dictionary containing cube from 1-10
numbers= numpy.arange(0,11,1)
cubes = {}
for x in numbers:
y = x**3
cubes[x]=y
print ("The cube of "+ str(x) +" is "+ str(y))
# making a z dictionary
# print (cubes)
print (cubes)
#for x in cubes.keys(): #want to list it nicely
#print (x, cubes())
| true |
d50712514658b8684da51f1e1d6dae88a5d1fb9f | FangShinDeng/pythonlearning | /datatype.py | 1,612 | 4.3125 | 4 | """
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
"""
x = 'John'
print(type(x))
# Numeric Types
x = 5
print(type(x))
x = 5.4
print(type(x))
x = 5j #虛數
print(type(x))
# Sequence Types
x = ['a','b','c'] # 小筆記好寄用法List, 第一個字L為直的, 因此為[]
print(type(x))
x = ('a','b','c')
print(type(x))
# List vs Tuple
# List 為串列, 可以被修改, 但tuple不行
numbers = range(1,10,2) #range(起始,終點,間距)
for number in numbers:
print(number)
pass
print(type(x))
x = {"name": 'John', "age":"20", "Male":"Man"} # Mapping Type
print(x["name"])
print(type(x))
# Set Types
# set() 函式是python內建函式的其中一個,屬於比較基礎的函式。建立一個無序不重複元素集,可進行關係測試,刪除重複資料,還可以計算交集、差集、並集等。
# set无序排序且不重复,是可变的,有add(),remove()等方法。
# frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
x = {"apple", "banana", "cherry"} # Set
print(type(x))
a = set(('apple','banana'))
print(a)
a.add('z')
print(a)
b = frozenset('apple')
print(b)
# b.add('z') forzenest會凍結, 不能再被添加或刪除
# print(b)
# Boolean Type
x = bool(5)
print(x)
x = True
print(type(x))
# Binary Types
x = bytes(5)
print(x)
x = b"Hello"
print(x)
print(type(x))
x = bytearray(5)
print(x)
print(type(x))
x = memoryview(bytes(5))
print(x)
| false |
e1336bc4c6810f7cd908f333502a3b6c83ca394c | bossenti/python-advanced-course | /sets.py | 1,137 | 4.21875 | 4 | # Set: collection data-type, unordered, mutable, no duplicates
# creation
my_set = {1, 2, 3}
my_set_2 = set([1, 2, 3])
my_set_3 = set("Hello") # good trick to count number of different characters in one word
# empty set
empty_set = set # {} creates a dictionary
# add elements
my_set.add(4)
# remove elements
my_set.remove(3)
my_set.discard(2) # does not throw an error if element does not exist
# remove all elements
my_set_3.clear()
# iterate over set
for i in my_set:
print(i)
# check element is in set
if 1 in my_set:
print("Yes")
# combine elements from both sets
union = my_set.union(my_set_2)
# only elements that are in both sets
intersec = my_set.intersection(my_set_2)
# determine the difference of two sets
diff = my_set.difference(my_set_2)
# all elements that are in one of set but not in both
sym_diff = my_set.symmetric_difference(my_set_2)
# check set is a subset of the other other
print(my_set.issubset(my_set_2))
# check set is a superset of the other
print(my_set.issuperset(my_set_2))
# check for same elements
print(my_set.isdisjoint(my_set_2))
# immutable set
a = frozenset([1, 2, 3, 4])
| true |
0473436545a37999dd4788a5438e8db3116d506e | chengaojie0011/offer-comein | /py-project/tree/tree_build 2.py | 1,308 | 4.28125 | 4 | # -*- coding:utf-8 -*-
class Node(object):
"""节点类"""
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
class Tree(object):
"""二叉树类"""
def __init__(self):
"""初始化树类的根节点和遍历队列"""
self.root = Node()
self.tree_queue = [] # 叶子结点的数据
def add(self, value):
"""添加数据构造函数"""
node = Node(value)
if self.root.value is None: # 树为空则进行节点的添加
self.root = node
self.tree_queue.append(node)
else:
cur_node = self.tree_queue[0] # 获取当前的根节点
if cur_node.left is None: # 左子树为空则进行添加
cur_node.left = node
self.tree_queue.append(node)
else: # 有字数为空则加入
cur_node.right = node
self.tree_queue.append(node)
self.tree_queue.pop(0) # 当前节点分配完成,退出队列
def main():
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(None)
tree.add(3)
return tree
if __name__ == '__main__':
tree = main()
l = tree.tree_queue
| false |
6ba34b1bcd307cbac829ad8fbaba27571cd2c807 | punkyjoy/LearningPython | /03.py | 514 | 4.125 | 4 | print("I will now count my chickens")
print("hens", 25.00+30.00/6.0)
print("roosters", 100.0-25.0*3.0%4.0)
print("Now I will count the eggs:")
print(3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6.0)
print("Is is true that 3.0+2.0<5.0-7.0?")
print(3.0+2.0<5.0-7.0)
print("What is 3+2?", 3.0+2.0)
print("What is 5-7?", 5-7)
#this is a comment
print("Oh, that's why it's false.")
print("how about some more.")
print("Is it greater?", 5 > -2)
print("is it greater or equal?", 5>= -2)
print("Is it less or equal?, 5 <= -2") | true |
9d92d23a4cd275da2cbcefa822c0c5fb0228853f | ananunes07/Lista6python | /Lista de exercício 2/Exe01.py | 879 | 4.34375 | 4 | '''
Autor: Ana Clara Nunes
Data: 14/05/2018
Enunciado:
Faça um programa que peça os três lados de um triângulo. O programa deverá informar se os valores poem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
'''
A = float(input('Digite o lado A: '))
B = float(input('Digite o lado B: '))
C = float(input('Digite o lado C: '))
if (B - C) < A < B + C or (A - C) < B < A + C or (A - B) < C < A + B:
if A == B == C:
print('É um triângulo equilátero')
if (B - C) < A < B + C or (A - C) < B < A + C or (A - B) < C < A + B:
if A == C or A == B or B == C:
print('É um triângulo isósceles')
if (B - C) < A < B + C or (A - C) < B < A + C or (A - B) < C < A + B:
if A != B != C:
print('É um triângulo escaleno')
else:
print ('Não é um triângulo')
| false |
d4bad854227ad91b7ad5a305906060837f0a11fa | Prince9ish/Rubik-Solver | /colors.py | 1,592 | 4.1875 | 4 | '''For representing color of the rubik's cube.'''
from pygame.locals import Color
from vpython import *
class ColorItem(object):
'''WHITE,RED,BLUE,etc are all instances of this class.'''
def __init__(self,name="red"):
self.name=name
self.color=color.red
self.opposite=None
def setColor(self,color):
self.color=color
def getColor(self):
return self.color
def getOpposite(self):
return self.opposite
def __str__(self):
return self.name
def __repr__(self):
return str(self)
def setOpposite(self,opposite):
self.opposite=opposite
opposite.opposite=self
RED=ColorItem("red");
BLUE=ColorItem("blue");
GREEN=ColorItem("green");
ORANGE=ColorItem("orange");
WHITE=ColorItem("white");
YELLOW=ColorItem("yellow");
RED.setColor(color.red)
GREEN.setColor(color.green)
YELLOW.setColor(color.yellow)
BLUE.setColor(color.blue)
WHITE.setColor(color.white)
ORANGE.setColor((color.orange))
RED.setOpposite(ORANGE)
BLUE.setOpposite(GREEN)
WHITE.setOpposite(YELLOW)
def decodeColorFromText(color):
'''Converts text and returns its instance.'''
color=color.lower()
if color.startswith(str(RED)): return RED
elif color.startswith(str(GREEN)): return GREEN
elif color.startswith(str(YELLOW)): return YELLOW
elif color.startswith(str(WHITE)): return WHITE
elif color.startswith(str(BLUE)): return BLUE
elif color.startswith(str(ORANGE)): return ORANGE
return None
print(RED.color)
if __name__=="__main__":
pass
| true |
521654cd787e15308b36e274745edf1cc1a0dae7 | joaopauloramos/pythonbirds_I | /calculadora/oo/framework.py | 1,460 | 4.21875 | 4 | # Classes Abstratas
class Operacao:
"""Classe responsável por definir como calculo é feito"""
def calcular(self, p1, p2):
raise NotImplementedError('Precisa ser implementado')
class Calculadora:
"""Classe responsável por obter inputs e efetuar operação de acordo"""
def __init__(self):
self._operacoes = {}
adicao = Adicao()
self.adicionar_operacao('+', adicao)
def obter_inputs(self):
"""Deve obter sinal, p1, e p2 retornando os valores nessa ordem"""
raise NotImplementedError('Precisa ser implementado')
def efetuar_operacao(self):
sinal, p1, p2 = self.obter_inputs()
try:
operacao_escolhida = self._operacoes[sinal]
except KeyError:
raise Exception('Operação não suportada')
else:
return operacao_escolhida.calcular(p1, p2)
def adicionar_operacao(self, sinal, operacao):
self._operacoes[sinal] = operacao
# Classes concretas
class CalculadoraInfixa(Calculadora):
def obter_inputs(self):
p1 = input('Digite o primeiro número: ')
p1 = float(p1)
sinal = input(
'Digite o sinal da operação {}: '.format(
', '.join(self._operacoes.keys()))
)
p2 = input('Digite o segundo número: ')
p2 = float(p2)
return sinal, p1, p2
class Adicao(Operacao):
def calcular(self, p1, p2):
return p1 + p2
| false |
70b5dfe3c86a6f59f0e656834df5b5dc52e2e151 | joaopauloramos/pythonbirds_I | /calculadora/procedural/biblioteca.py | 763 | 4.15625 | 4 | def calcular_iterativamente_forma_infixa():
p1 = input('Digite o primeiro número: ')
p1 = float(p1)
sinal = input('Digite o sinal da operação (+ ou -): ')
p2 = input('Digite o segundo número: ')
p2 = float(p2)
return _calcular(sinal, p1, p2)
def calcular_iterativamente_forma_prefixa():
sinal = input('Digite o sinal da operação (*, + ou -): ')
p1 = input('Digite o primeiro número: ')
p1 = float(p1)
p2 = input('Digite o segundo número: ')
p2 = float(p2)
return _calcular(sinal, p1, p2)
def _calcular(sinal, p1, p2):
if sinal == '+':
return p1 + p2
elif sinal == '-':
return p1 - p2
elif sinal == '*':
return p1 * p2
raise Exception('Operação não suportada')
| false |
ae471d6db283d8d28d6fe43934656f47a5192cec | claudiordgz/GoodrichTamassiaGoldwasser | /ch01/c113.py | 357 | 4.125 | 4 | __author__ = 'Claudio'
"""Write a pseudo-code description of a function that reverses a list of n
integers, so that the numbers are listed in the opposite order than they
were before, and compare this method to an equivalent Python function
for doing the same thing.
"""
def custom_reverse(data):
return [data[len(data)-x-1] for x in range(len(data))] | true |
364107a1b807d346b5dc38846598dd402063aa3a | gauthamkrishna1312/python_xp | /fn1.py | 233 | 4.125 | 4 | def check(num):
if num == 0:
print("Zero")
elif num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Invalid input")
value = input("Enter a number = ")
check(value) | false |
47ade36bd4fc754b29fd7a3cd898ddef5b87ca7e | smholloway/miscellaneous | /python/indentation_checker/indentation_checker.py | 2,876 | 4.375 | 4 | def indentation_checker(input):
# ensure the first line is left-aligned at 0
if (spaces(input[0]) != 0):
return False
# emulate a stack with a list
indent_level = []
indent_level.append(0)
# flag to determine if previous line encountered was a control flow statement
previous_line_was_control = False
# iterate over all input lines
for line in input:
previous_indentation_level = indent_level[-1]
current_indentation_level = spaces(line)
if previous_line_was_control:
# ensure we have added spaces after a control flow statement
if current_indentation_level <= indent_level[-1]:
return False
previous_line_was_control = False
indent_level.append(current_indentation_level)
# are we at a valid indent level?
if not current_indentation_level in indent_level:
return False
# is this line a control flow statement
if line.endswith(":"):
previous_line_was_control = True
previous_indentation_level = current_indentation_level
# check to see that we did not exit without an indentation after a control flow statement
if previous_line_was_control:
return False
# if we made it this far, the indentation was clean
return True
# generic function to return the number of spaces at the beginning of a string
def spaces(input):
if input.startswith(' '):
return 1 + spaces(input[1:])
else:
return 0
# main will check the indentation in this file
def main():
# read this program into a variable so we can check indentation on a working file
filename = "indentation_checker.py"
source = open(filename, 'r').readlines()
# if this program compiles and runs via python indentation_checker.py
# we should see that the indentation check is True
print "Indentation check on %s is %s" %(filename, indentation_checker(source))
# some tests
def test():
print "### TESTS RUNNING ###"
print spaces(" test") , "should be 1"
print spaces(" test") , "should be 2"
print spaces(" test") , "should be 3"
print indentation_checker([" def main():"]) , "should be False"
print indentation_checker(["def main():"]) , "should be False"
print indentation_checker(["print foo"]) , "should be True"
print indentation_checker(["def main():", " print foo"]) , "should be True"
print indentation_checker(["def main():", " print foo", "print bar"]) , "should be True"
print indentation_checker(["def main():", "print foo", "print bar"]) , "should be False"
print indentation_checker(["print begin", "def main():", " print foo", " print bar"]) , "should be True"
print indentation_checker(["def main():", " if True:", " print 'True'", "print 'end'"]) , "should be True"
print indentation_checker(["print begin", " def main():"]) , "should be False"
print indentation_checker(["print begin", "def main():", " print 'begin'", " print 'end'"]) , "should be False"
print "### TESTS COMPLETED ###\n"
test()
main()
| true |
d1f00fa6f224748010687c63f08e01a3142d62cf | pawlmurray/CodeExamples | /ProjectEuler/1/MultiplesOf3sAnd5s.py | 688 | 4.3125 | 4 | #get all of the multiples of threes and add them up
def sumOfMultiplesOfThrees(max):
currentSum = 0
threeCounter = 3
while(threeCounter < max):
currentSum+= threeCounter
threeCounter += 3
return currentSum
#Get all of the multiples of fives and add them up, if they are
#evenly divisible by three just leave them out
def sumOfMultiplesOfFivesWithoutThrees(max):
currentSum = 0
fiveCounter = 5
while(fiveCounter < max):
if not fiveCounter % 3 == 0:
currentSum += fiveCounter
fiveCounter += 5
return currentSum
totalSum = sumOfMultiplesOfThrees(1000) + sumOfMultiplesOfFivesWithoutThrees(1000)
print totalSum | true |
d7468de2be523b14bb8cddf5e10bf67e64663fe9 | Kartikkh/OpenCv-Starter | /Chapter-2/8-Blurring.py | 2,789 | 4.15625 | 4 |
## Blurring is a operation where we average the pixel with that region
#In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening,
#embossing, edge detection, and more.
#This is accomplished by doing a convolution between a kernel and an image.
# https://www.youtube.com/watch?v=C_zFhWdM4ic&t=301s
# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_filtering/py_filtering.html
import cv2
import numpy as np
image = cv2.imread('image.jpg')
cv2.imshow('Original Image' , image)
cv2.waitKey(0)
kernel_3 = np.ones((3,3),np.float32)/9
blurImage = cv2.filter2D(image,-1,kernel_3)
cv2.imshow("blurredImage",blurImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
# checking with kernel of different size
kernel_9 = np.ones((20,20),np.float32)/400
blurImage = cv2.filter2D(image,-1,kernel_3)
cv2.imshow("blurredImage",blurImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
## Other Blur Techniques
# Averaging
#This is done by convolving the image with a normalized box filter. It simply takes the average of all the pixels under kernel area
# and replaces the central element with this average. This is done by the function cv2.blur() or cv2.boxFilter().
img = cv2.imread('image.jpg')
blur = cv2.blur(img,(5,5))
cv2.imshow("blur",blur)
cv2.waitKey(0)
#Gaussian Filtering
#In this approach, instead of a box filter consisting of equal filter coefficients, a Gaussian kernel is used.
# It is done with the function, cv2.GaussianBlur().
# We should specify the width and height of the kernel which should be positive and odd.
img = cv2.imread('image.jpg')
blur = cv2.GaussianBlur(img,(5,5),0)
cv2.imshow("blur",blur)
cv2.waitKey(0)
# Median Filtering
# Here, the function cv2.medianBlur() computes the median of all the pixels under the kernel window and the central pixel
# is replaced with this median value. This is highly effective in removing salt-and-pepper noise.
# One interesting thing to note is that, in the Gaussian and box filters, the filtered value for the central element
# can be a value which may not exist in the original image. However this is not the case in median filtering,
# since the central element is always replaced by some pixel value in the image. This reduces the noise effectively.
# The kernel size must be a positive odd integer.
img = cv2.imread('image.jpg')
median = cv2.medianBlur(img,5)
cv2.imshow("median",median)
cv2.waitKey(0)
#Bilateral Filtering
#bilateral filter, cv2.bilateralFilter(), which was defined for, and is highly effective at noise removal while preserving edges.
img = cv2.imread('image.jpg')
bilateralFilter = cv2.bilateralFilter(img,9,75,75)
cv2.imshow("bilateralFilter",bilateralFilter)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
514fbfa2e340addc29c2a928a6ace99c042fcb7b | jmtaysom/Python | /Euler/004ep.py | 643 | 4.25 | 4 | from math import sqrt
def palindrome():
"""
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.
"""
for x in range(999,100,-1):
pal = int(str(x) + str(x)[::-1])
for i in range(999,int(sqrt(pal)), -1):
if pal % i == 0 and len(str(i)) > 2 and len(str(pal/i)) > 2:
return pal, i , pal / i
if __name__ == '__main__':
from time import time
start = time()
print(palindrome())
print(time()-start)
| true |
25785c99718e4f26dbb5b63a583b522d46697ebd | Agent1000/pythoner-ML2AI | /หาเลข มากสุด น้อยสุด.py | 682 | 4.25 | 4 | x=int(input("กรอกเลขครั้งที่ 1 > "))
y=int(input("กรอกเลขครั้งที่ 2 > "))
z=int(input("กรอกเลขครั้งที่ 3 > "))
if z>y and z>x :print(z,"มากที่สุด")
elif x>y and x>z:print(x,"มากที่สุด")
elif y>x and y>z :print(y,"มากที่สุด")
if z<y and z<x : print(z,"น้อยที่สุด") #if เช็คใหม่ หาเลขน้อยสุด
elif x<y and x<z:print(x,"น้อยที่สุด")
elif y<x and y<z :print(y,"น้อยที่สุด")
# อันนี้ไม่ได้ใช้ loop ช่วย | false |
5904acd697e84a4063452b706ab129537e53ab5b | Aryamanz29/DSA-CP | /gfg/Recursion/binary_search.py | 627 | 4.15625 | 4 | #binary search using recursion
def binary_search(arr, target):
arr = sorted(arr) #if array is not sorted
return binary_search_func(arr, 0, len(arr)-1, target)
def binary_search_func(arr, start_index, end_index, target):
if start_index > end_index:
return -1 # element not found
mid = (start_index+end_index) //2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search_func(arr, start_index, mid-1, target)
else:
return binary_search_func(arr, mid+1, end_index, target)
arr = [1,2,3,4,5,6,7,8,9]
target = 5
res = binary_search(arr,target)
print(res)
# time complexity : T(n) = log(n) | true |
d346746005b6b2a5c0b25a92e63f92c0bbadfa89 | Aryamanz29/DSA-CP | /random/word_count.py | 1,116 | 4.125 | 4 | # You are given some words. Some of them may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
# Note:
# All the words are composed of lowercase English letters only.
# Input Format
# It should contain all the words separated by space.
# Output Format
# Output the number of distinct words from the input
# Output the number of occurrences for each distinct word according to their appearance in the input.
# Both the outputs should be separated by space.
# Sample Input
# bcdef abcdefg bcde bcdef
# Sample Output
# 3 211
# Explanation
# There are distinct words. Here, "bcdef" appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds to the output.
words = input().split()
d = {}
for i in words:
d[i] = d.get(i, 0) + 1
# print(d)
print(len(d), end=" ")
for i in words:
if d[i] is not None:
print(d[i], end="")
d[i] = None
| true |
eba979bd967c81ba4ad6d2435ffb09b3e4f5059f | n1e2h4a/AllBasicProgram | /BasicPython/leadingzero.py | 264 | 4.21875 | 4 | mystring="python"
#print original string
print("the original string :--- "+ str(mystring))
#no of zeros want
zero=5
#using rjust()for for adding leading zero
final=mystring.rjust(zero + len(mystring), '0')
print("string after adding leading zeros : " + str(final)) | true |
435fd488d1a513ebebcfc35354be57debca54442 | n1e2h4a/AllBasicProgram | /ListPrograms.py/MinimumInList.py | 213 | 4.125 | 4 | table = []
number = int(input("Enter number of digit you want to print:---"))
for x in range(number):
Element = int((input(' > ')))
table.append(Element)
table.sort()
print("Smallest in List:", *table[:1]) | true |
18b9d6e60429bcfc31d56ece3f3d1c1c79bb30d6 | abdul1380/UC6 | /learn/decorater_timer.py | 1,792 | 4.4375 | 4 | """
The following @debug decorator will print the arguments a function is
called with as well as its return value every time the function is called:
"""
import functools
import math
def debug(func):
"""Print the function signature and return value"""
@functools.wraps(func)
def wrapper_debug(*args, **kwargs):
args_repr = [repr(a) for a in args] # 1
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] # 2
signature = ", ".join(args_repr + kwargs_repr) # 3
print(f"Calling {func.__name__}({signature})")
value = func(*args, **kwargs)
print(f"{func.__name__!r} returned {value!r}") # 4
return value
return wrapper_debug
'''
The signature is created by joining the string representations of all the arguments.
The numbers in the following list correspond to the numbered comments in the code:
1 Create a list of the positional arguments. Use repr() to get a nice string representing each argument.
2: Create a list of the keyword arguments. The f-string formats each argument as key=value where the !r specifier means that repr() is used to represent the value.
3: The lists of positional and keyword arguments is joined together to one signature string with each argument separated by a comma.
4: The return value is printed after the function is executed.
Lets see how the decorator works in practice by applying it to a simple function with one position and one keyword argument:
'''
@debug
def make_greeting(name, age=None):
if age is None:
return f"Howdy {name}!"
else:
return f"Whoa {name}! {age} already, you are growing up!"
if __name__ == '__main__':
make_greeting("Benjamin")
print()
make_greeting("Benjamin", age = 21) | true |
d4cbd946ea754ed8bddb1f487f6a4250c4e3a96b | dengxinjuan/springboard | /python-syntax/words.py | 319 | 4.15625 | 4 | def print_upper_words(words,must_start_with):
for word in words:
for any in must_start_with:
if word.startswith(any):
result = word.upper()
print(result)
print_upper_words(["hello", "hey", "goodbye", "yo", "yes"],
must_start_with={"h", "y"}) | true |
5e26fa7180ec61b226b2824f4c3d4120df770254 | ptsiampas/Exercises_Learning_Python3 | /18_Recursion/Exercise_18.7.2a.py | 1,089 | 4.375 | 4 | import turtle
from math import cos, sin
def cesaro_fractal(turtle, order, size):
"""
(a) Draw a Casaro torn line fractal, of the order given by the user.
We show four different lines of order 0, 1, 2, 3. In this example, the angle of the
tear is 10 degrees.
:return:
"""
if order == 0: # The base case is just a straight line
turtle.forward(size)
else:
for angle in [-85, 170, -85, 0]:
cesaro_fractal(turtle, order - 1, size / 3)
turtle.left(angle)
wn = turtle.Screen()
wn.title("Exercise 18.7.2a Cesaro Fractal!")
wn.bgcolor("white")
fract_turtle = turtle.Turtle()
fract_turtle.pencolor("#0000FF")
fract_turtle.hideturtle()
fract_turtle.pensize(1)
# setup initial location
fract_turtle.penup()
fract_turtle.back(450)
fract_turtle.right(90)
fract_turtle.back(400)
fract_turtle.left(90)
fract_turtle.pendown()
size = 150
for order in [0, 1, 2, 3]:
cesaro_fractal(fract_turtle, order, size + (50 * (order + 1)))
fract_turtle.penup()
fract_turtle.forward(50)
fract_turtle.pendown()
wn.mainloop()
| true |
712a129202333470151c53d20af112057b41d9f6 | ptsiampas/Exercises_Learning_Python3 | /15._Classes and Objects_Basics/Exercise_15.12.4.py | 1,970 | 4.375 | 4 | # 4. The equation of a straight line is “y = ax + b”, (or perhaps “y = mx + c”). The coefficients
# a and b completely describe the line. Write a method in the Point class so that if a point
# instance is given another point, it will compute the equation of the straight line joining
# the two points. It must return the two coefficients as a tuple of two values.
#
# For example,
# >>> print(Point(4, 11).get_line_to(Point(6, 15)))
# >>> (2, 3)
#
# This tells us that the equation of the line joining the two points is “y = 2x + 3”. When
# will your method fail?
from unit_tester import test
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x
self.y = y
def distance_from_origin(self):
""" Compute my distance from the origin """
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def __str__(self): # All we have done is renamed the method
return "({0}, {1})".format(self.x, self.y)
def halfway(self, target):
""" Return the halfway point between myself and the target """
mx = (self.x + target.x) / 2
my = (self.y + target.y) / 2
return Point(mx, my)
def distance(self, target):
dx = target.x - self.x
dy = target.y - self.y
dsquared = dx * dx + dy * dy
result = dsquared ** 0.5
return result
def reflect_x(self):
ry = self.y * -1
return Point(self.x, ry)
def slope_from_origin(self):
if self.y == 0 or self.x == 0:
return 0
slope = float(self.y) / self.x
return slope
def get_line_to(self, target):
# y = mx + b
# m is the slope, and b is the y-intercept
m = (self.y - target.y) / (self.x - target.x)
b = self.y - (m * self.x)
return (m, b)
test(Point(4, 11).get_line_to(Point(6, 15)), (2, 3))
| true |
b10e4275bac85b19fbd094a6e205386b6f73f169 | ptsiampas/Exercises_Learning_Python3 | /07_Iteration/Exercise_7.26.16.py | 1,062 | 4.125 | 4 | # Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs.
# For example, sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29:
#
# test(sum_of_squares([2, 3, 4]), 29)
# test(sum_of_squares([ ]), 0)
# test(sum_of_squares([2, -3, 4]), 29)
import sys
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
.format(linenum, expected, actual))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(sum_of_squares([2, 3, 4]), 29)
test(sum_of_squares([ ]), 0)
test(sum_of_squares([2, -3, 4]), 29)
def sum_of_squares(xn):
result=0
for nu in xn:
result += (nu**2)
return result
test_suite() | true |
ad104e36e782364406c66006947e838a5ec2ab4d | ptsiampas/Exercises_Learning_Python3 | /05_Conditionals/Exercise_5.14.11.py | 710 | 4.25 | 4 | #
# Write a function is_rightangled which, given the length of three sides of a triangle, will determine whether the
# triangle is right-angled. Assume that the third argument to the function is always the longest side. It will return
# True if the triangle is right-angled, or False otherwise.
#
__author__ = 'petert'
def find_hypot(c1,c2):
hpot=((c1**2)+(c2**2))**0.5
return hpot
def is_rightangled(side1, side2, side3):
hypot_test=find_hypot(side1,side2)
if abs(hypot_test - side3) < 0.000001:
print("Triangle is at right angle",abs(hypot_test - side3))
else:
print("truangle is NOT a right angle",abs(hypot_test - side3))
is_rightangled(3,4,5)
is_rightangled(18,8,20) | true |
087cad1c17766f45940c7e98e789862465ba2934 | ptsiampas/Exercises_Learning_Python3 | /18_Recursion/Exercise_18.7.3.py | 1,236 | 4.4375 | 4 | from turtle import *
def Triangle(t, length):
for angle in [120, 120, 120]:
t.forward(length)
t.left(angle)
def sierpinski_triangle(turtle, order, length):
"""
3. A Sierpinski triangle of order 0 is an equilateral triangle. An order 1 triangle can be drawn by drawing 3
smaller triangles (shown slightly disconnected here, just to help our understanding).
Higher order 2 and 3 triangles are also shown.
Draw Sierpinski triangles of any order input by the user..
:return:
"""
if order == 0: # The base case is just a straight line
Triangle(turtle, length)
else:
for i in range(3):
turtle.forward(length)
turtle.left(120)
sierpinski_triangle(turtle, order - 1, length / 2)
wn = Screen()
wn.title("Exercise 18.7.3 Sierpinski triangle Fractal!")
wn.bgcolor("white")
fract_turtle = Turtle()
fract_turtle.pencolor("#0000FF")
fract_turtle.fillcolor("black")
fract_turtle.pensize(1)
# setup initial location
# delay(0)
fract_turtle.speed(0)
fract_turtle.up()
fract_turtle.goto(-450, -200)
fract_turtle.down()
fract_turtle.pendown()
fract_turtle.hideturtle()
size = 200
sierpinski_triangle(fract_turtle, 4, size)
exitonclick()
| true |
fa87af0a96105b9589fad9a32955db349089d5cd | ptsiampas/Exercises_Learning_Python3 | /18_Recursion/Exercise_18.7.10.py | 1,506 | 4.21875 | 4 | # Write a program that walks a directory structure (as in the last section of this chapter), but instead of printing
# filenames, it returns a list of all the full paths of files in the directory or the subdirectories.
# (Don’t include directories in this list — just files.) For example, the output list might have elements like this:
#
# ['C:\Python31\Lib\site-packages\pygame\docs\ref\mask.html',
# 'C:\Python31\Lib\site-packages\pygame\docs\ref\midi.html',
# ...
# 'C:\Python31\Lib\site-packages\pygame\examples\aliens.py',
# ...
# 'C:\Python31\Lib\site-packages\pygame\examples\data\boom.wav',
# ... ]
import os
def get_dirlist(path):
"""
Return a sorted list of all entries in path.
This returns just the names, not the full path to the names.
"""
dirlist = os.listdir(path)
dirlist.sort()
return dirlist
def list_files(path, prefix=""):
fileList = []
if prefix == "":
print('Folder listing for', path)
prefix = path + '/'
dirlist = get_dirlist(path)
for f in dirlist:
if not os.path.isdir(os.path.join(path, f)): # FIXME: this is ugly as, but just want to fix it now..
fileList.append(prefix + f)
fullname = os.path.join(path, f)
if os.path.isdir(fullname):
fileList.extend(list_files(fullname, prefix + f + '/'))
return fileList
def main():
print(list_files("/usr/local/lib/python3.4/dist-packages/pygame"))
return
if __name__ == '__main__':
main()
| true |
3de631c83b785cac3822aaaf26d06e85a32ce736 | ptsiampas/Exercises_Learning_Python3 | /21_Even_more_OOP/Examples_Point21.py | 2,367 | 4.5625 | 5 | class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x
self.y = y
def __str__(self): # All we have done is renamed the method
return "({0}, {1})".format(self.x, self.y)
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __mul__(self, other):
return self.x * other.x + self.y * other.y
def __rmul__(self, other):
""" If the left operand of * is a primitive type and the right operand is a Point, Python
invokes __rmul__, which performs scalar multiplication:
"""
return Point(other * self.x, other * self.y)
def reverse(self):
(self.x, self.y) = (self.y, self.x)
def distance_from_origin(self):
""" Compute my distance from the origin """
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def halfway(self, target):
""" Return the halfway point between myself and the target """
mx = (self.x + target.x) / 2
my = (self.y + target.y) / 2
return Point(mx, my)
def heading(s):
"""Draws a line under the heading - yes because I am bored"""
line = ""
for x in range(len(s)):
line += "="
return "{}\n{}".format(s, line)
def multadd(x, y, z):
return x * y + z
def front_and_back(front):
import copy
back = copy.copy(front)
back.reverse()
print(str(front) + str(back))
def main():
# examples of operator overloading - check the add, mul and rmul definitions
print(heading("21.8. Operator overloading Examples"))
p1 = Point(3, 4)
p2 = Point(5, 7)
print("Point{} * Point{} = {}".format(p1, p2, p1 * p2)) # Execute mul because the left of the * is a Point.
print("2 * Point{} = {}".format(p2, 2 * p2)) # Executes rmul because the left operand of * is a primitive.
print()
print(heading("21.9. Polymorphism Examples"))
print("multiadd function = {}".format(multadd(3, 2, 1)))
print("multiadd function also works with points = {}".format(multadd(2, p1, p2)))
print("multiadd function also works with points = {}".format(multadd(p1, p2, 1)))
my_list = [1, 2, 3, 4]
front_and_back(my_list)
p = Point(3, 4)
front_and_back(p)
if __name__ == '__main__':
main()
| true |
dbdf7c1059cffe23b0d8c47348e25e0c9347ed7e | ptsiampas/Exercises_Learning_Python3 | /01_03_Introduction/play_scr.py | 615 | 4.15625 | 4 | import turtle # Allows us to use turtles
wn = turtle.Screen() # Creates a playground for turtles
wn.bgcolor("lightgreen") # Sets window background colour
wn.title("Hey its me") # Sets title
alex = turtle.Turtle() # Create a turtle, assign to alex
alex.color("blue") # pen colour blue
alex.pensize(3) # Set pen size
alex.forward(50) # Tell alex to move forward by 50 units
alex.left(120) # Tell alex to turn by 90 degrees
alex.forward(50) # Complete the second side of a rectangle
turtle.mainloop() # Wait for user to close window | true |
6c151bbd8c7b00728fc6288bce8cec511d839050 | ptsiampas/Exercises_Learning_Python3 | /06_Fruitful_functions/Exercises_6.9.14-15.py | 1,449 | 4.53125 | 5 | # 14. Write a function called is_even(n) that takes an integer as an argument and returns True if the argument is
# an even number and False if it is odd.
import sys
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
.format(linenum, expected, actual))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(is_even(0),True)
test(is_even(1),False)
test(is_even(2),True)
test(is_even(3),False)
test(is_odd(0),False)
test(is_odd(1),True)
test(is_odd(2),False)
test(is_odd(3),True)
def is_even(n):
if (n % 2) == 0:
return True
return False
# 15. Now write the function is_odd(n) that returns True when n is odd and False otherwise.
# Include unit tests for this function too.
def is_odd(n):
#if (n % 2) != 0:
# return True
# Finally, modify it so that it uses a call to is_even to determine if its argument is an
# odd integer, and ensure that its test still pass.
if is_even(n) == True:
return False
return True
test_suite() # Here is the call to run the tests | true |
2217a5fe8973d2d5a8d900f1c5ddc9b2b07f5689 | sobinrajan1999/258213_dailyCommit | /print.py | 518 | 4.28125 | 4 | print("hello world")
print(1+2+3)
print(1+3-4)
# Python also carries out multiplication and division,
# using an asterisk * to indicate multiplication and
# a forward slash / to indicate division.
print(2+(3*4))
# This will give you float value
print(10/4)
print(2*0.75)
print(3.4*5)
# if you do not want float value then
print(10//4)
# Exponential or power
# base 2 power 4
print(2**4)
# Chain exponential
print(2**3**2)
# Square root (result will be in float)
print(9**(1/2))
# Remainder
print(20%6)
print(1.25%0.5)
| true |
c0ced71bc1ef01689981bdc9f5c0f227ac76226a | rosexw/Practice_Python | /1-character_input.py | 842 | 4.125 | 4 | # https://www.practicepython.org/
# 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.
# name = raw_input("What is your name: ")
# age = int(input("How old are you: "))
# year = str((2018 - age)+100)
# print(name + " will be 100 years old in the year " + year)
# print("Were" + "wolf")
# print("Door" + "man")
# print("4" + "chan")
# print(str(4) + "chan")
# Extras:
# Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
print(3 * "test")
# Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)
print(3 * "test\n")
| true |
b96824853b54624a33730716da977019b9958c3d | BubbaHotepp/code_guild | /python/palindrome.py | 505 | 4.1875 | 4 | def reverse_string(x):
return x[::-1]
def compare(x,y):
if x == y:
return True
else:
return False
def main():
user_input = input('Please enter a word you think is an anagram: ')
print(user_input)
input_reversed = reverse_string(user_input)
print(input_reversed)
x = compare(user_input, input_reversed)
print(x)
if x is True:
print(f'{user_input} is a palindrome.')
else:
print(f'{user_input} is not a palindrome.')
main() | true |
e9bac2547bac4dc0637c3abee43a3194802cbddc | tab0r/Week0 | /day2/src/dict_exercise.py | 1,762 | 4.15625 | 4 | def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pythonic code, use iteritems!
Note: it's possible to do this in 1 line using list comprehensions and the
join method.
'''
S = ''
for key in d.keys():
S += str(key) + ": " + str(d[key]) + "\n"
return S.rstrip()
def dict_to_str_sorted(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is sorted in ascending order by key.
This is sorted version of dict_to_str().
Note: This one is also doable in one line!
'''
S = []
for key in d.keys():
S.append(str(key) + ": " + str(d[key]))
S.sort()
return '\n'.join(S)
def dict_difference(d1, d2):
'''
INPUT: dict, dict
OUTPUT: dict
Combine the two dictionaries, d1 and d2 as follows. The keys are the union of the keys
from each dictionary. If the keys are in both dictionaries then the values should be the
absolute value of the difference between the two values. If a value is only in one dictionary, the
value should be the absolute value of that value.
'''
newDict = {}
s1 = set(d1.keys())
s2 = set(d2.keys())
newKeys = s1.union(s2)
for key in newKeys:
if key in d1 and key in d2:
newDict[key] = abs(d1[key]-d2[key])
elif key in d1:
newDict[key] = abs(d1[key])
elif key in d2:
newDict[key] = abs(d2[key])
return newDict
| true |
b350d4fc0a75b1e745d7d4dfd0d3eb29a8c121df | MykolaPavlenkov/Pavlenkov | /HomeWork/HomeWork1/task#6.py | 779 | 4.375 | 4 | x = int(input ('Введите с клавиатуры целое число x: '))
y = int(input ('Введите с клавиатуры целое число y: '))
print("1) Вывести на экран консоли оба числа используя только один вызов print ")
print (x,y)
print("2) вывод суммы чисел x + y =")
c = x + y
print (c)
print("3) Выполнить целочисленное деление с помощью оператора '//' Проведем деление x//y")
print (x//y)
print( 'Найти остаток от деления с помощью оператора ''%'' Произведем действие x % y ')
print(x%y)
print('Вычислить степень числа: x^y')
print(x**y) | false |
360f00f7d38fa89588606cf429e0c1e9321f8680 | mounika123chowdary/Coding | /cutting_paper_squares.py | 809 | 4.1875 | 4 | '''Mary has an n x m piece of paper that she wants to cut into 1 x 1 pieces according to the following rules:
She can only cut one piece of paper at a time, meaning she cannot fold the paper or layer already-cut pieces on top of one another.
Each cut is a straight line from one side of the paper to the other side of the paper. For example, the diagram below depicts the three possible ways to cut a 3 x 2 piece of paper:
Given n and m, find and print the minimum number of cuts Mary must make to cut the paper into n.m squares that are 1 x 1 unit in size.
Note : you have to write the complete code for taking input and print the result.
Input Format
A single line of two space-separated integers denoting the respective values of n and m.
'''
n,m=map(int,input().split())
print((n-1)+n*(m-1))
| true |
12b9d7a90eb7d3e8fbec3e17144564f49698e507 | BenjaminNicholson/cp1404practicals | /cp1404practicals/Prac_05/word_occurrences.py | 401 | 4.25 | 4 | words_for_counting = {}
number_of_words = input("Text: ")
words = number_of_words.split()
for word in words:
frequency = words_for_counting.get(word, 0)
words_for_counting[word] = frequency + 1
words = list(words_for_counting.keys())
words.sort()
max_length = max((len(word) for word in words))
for word in words:
print("{:{}} : {}".format(word, max_length, words_for_counting[word]))
| true |
f130de72784cf53cf392a96a8cf09c111474bf5c | BenjaminNicholson/cp1404practicals | /cp1404practicals/Prac_05/hex_colours.py | 528 | 4.28125 | 4 | COLOURS = {'AliceBlue': '#f0f8ff', 'Aquamarine1': '#7fffd4', 'AntiqueWhite': '#faebd7', 'azure1': '#f0ffff',
'aquamarine4': '#458b74', 'azure4': '#838b8b', 'blue1': '#0000ff', 'BlueViolet': '#8a2be2',
'brown3': '#cd3333'}
print(COLOURS)
choice = input("Which colour do you want to pick? ")
while choice != "":
if choice in COLOURS:
print("{} is {}".format(choice, COLOURS[choice]))
else:
print("Invalid option, try again")
choice = input("Which colour do you want to pick? ")
| false |
a44221832be1eece6cbcbd78df99a8dcc4aea9ab | mcampo2/python-exercises | /chapter_03/exercise_04.py | 539 | 4.59375 | 5 | #!/usr/bin/env python3
# (Geometry: area of a pentagon) The area of a pentagon can be computed using the
# following formula (s is the length of a side):
# Area = (5 X s²) / (4 X tan(π/5))
# Write a program that prompts the user to enter the side of a pentagon and displays
# the area. Here is a sample run:
# Enter the side: 5.5 [Enter]
# The area of the pentagon is 53.04444136781625
import math
s = eval(input("Enter the side: "))
area = (5 * s ** 2) / (4 * math.tan(math.pi/5))
print("The area of the pentagon is", area)
| true |
66106c9065c8dcabaa8a094326a2b601cdf07524 | mcampo2/python-exercises | /chapter_03/exercise_11.py | 523 | 4.34375 | 4 | #!/usr/bin/env python3
# (Reverse numbers) Write a program that prompts the user to enter a four-digit int-
# ger and displays the number in reverse order. Here is a sample run:
# Enter an integer: 3125 [Enter]
# The reversed number is 5213
reverse = ""
integer = eval(input("Enter an integer: "))
reverse += str(integer % 10)
integer //= 10
reverse += str(integer % 10)
integer //= 10
reverse += str(integer % 10)
integer //= 10
reverse += str(integer % 10)
integer //= 10
print("The reversed number is", reverse)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.