blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
3a6d4b45c0dc2a0e77274788d52aac17fc3c987e
|
deepakrkris/py-algorithms
|
/dcp/dcp-8.py
| 2,014
| 4.28125
| 4
|
# A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
#
# Given the root to a binary tree, count the number of unival subtrees.
#
# For example, the following tree has 5 unival subtrees:
#
# 0
# / \
# 1 0
# / \
# 1 0
# / \
# 1 1
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def deserialize(strNode, start = 1):
index = start
begin = start
rootNode = None
left = None
right = None
while index < len(strNode) and strNode[index] != ',':
index += 1
rootNode = Node(strNode[begin:index])
index += 1
if strNode[index] == '{':
index, left = deserialize(strNode, index + 1)
# print(left.val)
elif strNode[index] == '#':
index += 1
index += 1
if strNode[index] == '{':
index, right = deserialize(strNode, index + 1)
# print(right.val)
elif strNode[index] == '#':
index += 1
index += 1
rootNode.left = left
rootNode.right = right
if start == 1:
return rootNode
else:
return index, rootNode
def isUnival(node, value):
if node is None:
return True
if node.left is not None and node.left.val != value:
return False
if node.right is not None and node.right.val != value:
return False
return isUnival(node.left, value) and isUnival(node.right, value)
def countTrees(node):
if node is None:
return 0
count = 0
if node.left is not None:
count += countTrees(node.left)
if node.right is not None:
count += countTrees(node.right)
return 1 + count
def numOfUnival(node):
if node is None:
return 0
if isUnival(node, node.val):
return countTrees(node)
return numOfUnival(node.left) + numOfUnival(node.right)
print(numOfUnival(deserialize('{0,{1,#,#},{0,{1,{1,#,#},{1,#,#}},{0,#,#}}}')))
| true
|
b026172df9da07b51d08f93cb970c1053f1f7901
|
VSVR19/DAA_Python
|
/StacksQueuesDeques/QueueUsingTwoStacks.py
| 1,489
| 4.15625
| 4
|
# Inspiration- https://stackoverflow.com/questions/69192/how-to-implement-a-queue-using-two-stacks
class Queue2Stacks(object):
def __init__(self):
# Two Stacks
self.stack1 = []
self.stack2 = []
def enqueue(self, element):
# Add elements to Stack 1 having element as the range.
for i in range(element):
self.stack1.append(i)
print("Stack 1: {0}".format(self.stack1))
# Check length of stack 2.
if len(self.stack2) == 0:
# While we have elements in Stack 1,
while self.stack1:
# Pop- append those elements to stack 2.
# So Stack 2 has the element in reverse order when compared to Stack 1.
# Eg- Stack 1- 0 1 2 3 4
# Stack 2 (after popped)- 4 3 2 1 0
self.stack2.append(self.stack1.pop())
print("Stack 2: {0}".format(self.stack2))
# A method to pop- print elements from Stack 2.
def dequeue(self):
# While we have elements in Stack 2.
while self.stack2:
# Pop- print the elements from Stack 2.
# Eg- 4 3 2 1 0- pop- printed becomes 0 1 2 3 4.
# Thus when we pop, we get the original order when we inserted elements
# In Stack 1.
print(self.stack2.pop())
print("Stack 2.0: {0}".format(self.stack2))
ObjectQueue2Stacks = Queue2Stacks()
ObjectQueue2Stacks.enqueue(5)
ObjectQueue2Stacks.dequeue()
| true
|
5dfc5b0e7de1e49ecd4155d698ca05c5cd2692ef
|
VSVR19/DAA_Python
|
/LinkedLists/DoublyLinkedListImplementation.py
| 915
| 4.375
| 4
|
# This class implements a Singly Doubly List.
class Node:
# This constructor assigns values to nodes and
# temporarily makes the nextnode and previousnode as 'None'.
def __init__(self, value):
self.value = value
self.nextnode = None
self.previousnode = None
# Setting up nodes and their values.
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
# Linking nodes to set up a doubly linked list.
a.nextnode = b
b.nextnode = c
b.previousnode = a
c.nextnode = d
c.previousnode = b
d.nextnode = e
d.previousnode = c
e.previousnode = d
# Printing the nextnode and previousnode of each node in the singly linked list.
print(a.nextnode.value) # 2
print(b.nextnode.value) # 3
print(b.previousnode.value) # 1
print(c.nextnode.value) # 4
print(c.previousnode.value) # 2
print(d.nextnode.value) # 5
print(d.previousnode.value) # 3
print(e.previousnode.value) # 4
| true
|
719e956d0b6b79da3f485580157c0cf8cc51c05b
|
remsanjiv/Machine_Learning
|
/Machine Learning A-Z New/Part 2 - Regression/Section 9 - Random Forest Regression/random_forest_regression.py
| 2,239
| 4.21875
| 4
|
# Random Forest Regression
# Lecture 77 https://www.udemy.com/machinelearning/learn/lecture/5855120
# basic idea of random forest is you use multiple Decisions Trees make up
# a forest. This is also called Ensemble. Each decision tree provides a prediction
# of the dependent variables.The prediction is the average of all the trees.
# check working directory
import os
os.getcwd()
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Splitting the dataset into the Training set and Test set
"""from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""
# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train.reshape(-1,1))"""
# Fitting Random Forest Regression to the dataset
# step 1 import the class we want
from sklearn.ensemble import RandomForestRegressor
# step 2 make a regressor across our data
# n_estimators is the number of trees; we started with 10
# random_state is just set to 0
regressor1 = RandomForestRegressor(n_estimators = 10, random_state = 0)
# step 3 fit regressor to our model
regressor1.fit(X, y)
regressor2 = RandomForestRegressor(n_estimators = 100, random_state = 0)
# step 3 fit regressor to our model
regressor2.fit(X, y)
regressor3 = RandomForestRegressor(n_estimators = 300, random_state = 0)
# step 3 fit regressor to our model
regressor3.fit(X, y)
# Predicting a new result
y_pred1 = regressor1.predict([[6.5]])
y_pred2 = regressor2.predict([[6.5]])
y_pred3 = regressor3.predict([[6.5]])
# Visualising the Random Forest Regression results (higher resolution)
X_grid = np.arange(min(X), max(X), 0.01)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color = 'red')
plt.plot(X_grid, regressor3.predict(X_grid), color = 'blue')
plt.title('Truth or Bluff (Random Forest Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
| true
|
5268874f85dcf7dbcc8dacda9de2813ad88f9e69
|
sadika22/py4e
|
/ch11/ch11ex01.py
| 759
| 4.15625
| 4
|
# Exercise 1: Write a simple program to simulate the operation of the grep com-
# mand on Unix. Ask the user to enter a regular expression and count the number
# of lines that matched the regular expression:
# $ python grep.py
# Enter a regular expression: ^Author
# mbox.txt had 1798 lines that matched ^Author
# $ python grep.py
# Enter a regular expression: ^X-
# mbox.txt had 14368 lines that matched ^X-
# $ python grep.py
# Enter a regular expression: java$
# mbox.txt had 4218 lines that matched java$
import re
filename = input("Enter the filename: ")
regex = input("Enter a regular expression: ")
counter = 0
fhand = open(filename, 'r')
for line in fhand:
line = line.rstrip()
if re.search(regex, line):
counter += 1
print(counter)
| true
|
1c911d0c01de5812365e98378108071a47d7c44e
|
PruthviP7/Programming-Hands-on
|
/pp/Problems on numbers/11DisplayPower.py
| 557
| 4.1875
| 4
|
'''Accept number from user and calculate its power.
Input : 2 4
Output : 2*2*2*2 = 16
Input : 4 3
Output : 4*4*4 = 64
iNo1 5 iNo2 4
5 * 5 * 5 * 5
1 * 5 = 5
5 * 5 = 25
'''
def CalculatePower(ino1,ino2):
iMul = 1
for i in range(ino2):
iMul = iMul * ino1
return iMul
def main():
print("Enter first number")
iNo1 = int(input())
print("Enter second number")
iNo2 = int(input())
iRet = CalculatePower(iNo1,iNo2)
print(f"{iNo2} times power of {iNo1} is {iRet}")
if __name__ == "__main__":
main()
| false
|
0d466471f22138a6b079a50f06bc76c3b4e400a5
|
srikarporeddy/project
|
/udemy/lcm.py
| 337
| 4.125
| 4
|
def lcm(x,y):
""" this functions takes two integers and return L>C>M"""
if x>y:
greater = x
else:
greater = y
while(True):
if((greater %x==0) and (greater %y==0)):
lcm = greater
break
greater += 1
return lcm
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print (lcm(num1,num2))
| true
|
709eb2afb2fe89532b6f95c35a4d3b416ff088f6
|
KartikShrikantHegde/Core-Algorithms-Implementation
|
/Selection_Sort.py
| 1,126
| 4.125
| 4
|
'''
Selection_Sort Implementation
Let the first element in the array be the least. Scan through rest of the array and if
a value less than least is found, make it the new least And swap with old least
Selection_Sort running time needs N-1 + N-2 + ..... Comparisons and N exchanges which is a quadratic time.
Thus the running time is n**2 in all conditions , no matter if array is sorted or partially sorted.
Fails stability by not preserving the sorting of key pairs.
Time Complexity :
Best case : O(n**2)
Worst Case : O(n**2) ------ No matter however the way array is arranged initially
Space Complexity: O(1)
'''
def Selectionsort(array):
for i in range(0, len(array)):
least_value = i
for k in range(i + 1, len(array)):
if array[k] < array[least_value]:
least_value = k
swap(array, least_value, i)
def swap(array, least_value, i):
temp = array[least_value]
array[least_value] = array[i]
array[i] = temp
list = [54, 26, 93, 17, 77, 31, 44, 55, 20, 4]
print "Array before sorting", list
Selectionsort(list)
print "Array after sorting", list
| true
|
98f4d8b4a54003c0f0591c6b68cb8bd3c769f3c8
|
jtrieudang/Python-Udemy
|
/Day1.0.py
| 1,142
| 4.46875
| 4
|
# Write your code below this line 👇
print("hello world!")
print('Day 1 - Python Print Function')
print('The function is declared like this:')
print("print('what to print')")
# Return to the front
print("Hello world!\nHello World!\n Hello Dude!")
# concatenate, taking seperate strings
print("Hello" + "Jimmy")
print("Hello" + " Jimmy")
# space sensitive, don't space in the front of the code
print("Hello" + " " + "Jimmy")
# __debug__
#Fix the code below 👇
# #Fix the code below 👇
# print(Day 1 - String Manipulation")
# print("String Concatenation is done with the "+" sign.")
# print('e.g. print("Hello " + "world")')
# print(("New lines can be created with a backslash and n.")
print("Day 1 - String Manipulation")
print("String Concatenation is done with the "'+'" sign.")
print('e.g. print("Hello " + "world")')
print("New lines can be created with a backslash and n.")
# input function to put in data and return back.
input("What is your name?")
print("Hello " + input("What is your name?"))
print(len(input("What is your name?")))
# assigning to a variable
name = "Jimmy"
print(name)
| true
|
faa46dec270c2a7b3cf438fa338ad65027f8ee64
|
Aunik97/variables
|
/practice exercise 3.py
| 352
| 4.21875
| 4
|
#Aunik Hussain
#15-09-2014
#Practice Exercise 3
print("this programme will divide two numbers and show the remainder")
number1 = int(input("please enter the first number"))
number2 = int(input("please enter the second number"))
answer = number1 / number2
print("The answer of this calculation is {0} / {1} is {2}.".format(number1,number2,answer))
| true
|
8a739a09405d195143c7b92c8a611abd6a6b073c
|
AnantPatkal/Python_Handson
|
/AA_BTA_course/Cinema_stimulator.py
| 1,465
| 4.125
| 4
|
Films = {
"Malang":[15,5], #Here 1 element is age ,second is seats available
"Bhoot":[16,4],
"Street Dancer":[12,6],
"Love Aaj Kal":[14,5]
}
print("Please select movie from the list of movies :")
print(" 1-Malang \n 2-Bhoot \n 3-Street Dancer \n 4-Love Aaj Kal ")
while True:
choice=input("Which movie you want to watch :").title()
if choice in Films:
age=int(input("How old are you? ").strip())
#check user 's age
if age>= Films[choice][0]:
#checks seats available
seats_available=Films[choice][1]
if seats_available>0:
NoOfTickets=int(input("How many tickets you want to book? : "))
if Films[choice][1]>NoOfTickets:
print(" You want to book {} tickets :".format(NoOfTickets))
Films[choice][1]=Films[choice][1]-NoOfTickets
print("Tickets available : ")
print("Enjoy your movie!! ")
else :
print("OOps!! The no. of seats to book is more than available seats ")
print("Available seats: {} ".format(Films[choice][1]))
else:
print("No seats available!!OOps ")
else :
print("Oops you are too young")
else :
print("Please select movies from list")
print(" 1-Malang \n 2-Bhoot \n 3-Street Dancer \n 4-Love Aaj Kal ")
| false
|
d5d120d1d5cf585b27ced7859623ce562a1a85a8
|
StRobertCHSCS/fabroa-Andawu100
|
/Practice/2_8_1.py
| 233
| 4.25
| 4
|
#Find the value of number
number = int(input("Enter a number: "))
#initialize the total
total = 0
#compute the total from 1 to number
for i in range(1,number+1):
#print(i)
total = total + i
#total output
print(total)
| true
|
dbe390db8a59f54378cdeeec195e3fc81cef6c56
|
PatrickChow0803/Sorting
|
/src/recursive_sorting/recursive_sorting.py
| 1,700
| 4.21875
| 4
|
# TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements # [] are used to create array literals. This gives me multiple [0] to work with.
# TO-DO
i = 0 # Cursor for left array
j = 0 # Cursor for right array
k = 0 # Cursor for merged array
# while left or right is not empty it will compare numbers until one side is empty
while i < len(arrA) and j < len(arrB):
if arrA[i] < arrB[j]:
merged_arr[k] = arrA[i]
i += 1
else:
merged_arr[k] = arrB[j]
j += 1
k += 1
# these two while loops are for grabbing the left elements on either the right side or left and adding it to the end
# of the merged_arr
while i < len(arrA):
merged_arr[k] = arrA[i]
i += 1
k += 1
while j < len(arrB):
merged_arr[k] = arrB[j]
j += 1
k += 1
return merged_arr
# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort( arr ):
# TO-DO
if len(arr) > 1:
# Splits array in half until the length of the array is 1
half = round(len(arr) / 2)
return merge(merge_sort(arr[:(half)]), merge_sort(arr[(half):]))
else:
return arr
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# TO-DO
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort( arr ):
return arr
| true
|
12d26fbb29fbe19013f91cd792a36e1a9a27a299
|
ChengChenUIUC/Data-Structure-Design-and-Implementation
|
/GetRandom.py
| 1,526
| 4.15625
| 4
|
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = dict()
self.arr = []
self.n = 0
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.d:
return False
self.d[val] = self.n
self.arr.append(val)
self.n += 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.d:
return False
else:
#print self.arr,self.d,self.n, val
temp = self.d[val]
self.n -= 1
self.arr[self.n], self.arr[temp] = self.arr[temp], self.arr[self.n]
self.d[self.arr[temp]] = temp
self.d.pop(val)
self.arr.pop(self.n)
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
if self.n != 0:
return random.choice(self.arr)
# RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
| true
|
39cfb4386edcd838bcba5f9ce3e7358350f91cc3
|
pooja-pichad/ifelse
|
/nested.leap year.py
| 381
| 4.34375
| 4
|
# leap year
# we have take one user input and show the year its leap year or not
year=int(input("enter a year"))
x=("%d",year)
if year%4==0:
if year%100==0:
if year%400==0:
print("it is a leap year",year)
else:
print(" no its not a leap year ")
else:
print(" leap year")
else:
print(" not leap year")
| false
|
e882bc324fd047b06271860aef4251990788c3eb
|
pooja-pichad/ifelse
|
/averge.py
| 465
| 4.21875
| 4
|
a=10
b=20
c=30
avg=(a+b+c)/3
print("avg=",avg)
if avg>a and avg>b and avg>c:
print("avg is higher than a,b,c")
elif avg>a and avg>b:
print("avg is higher than a,b")
elif avg>a and avg>c:
print("avg is higher than a,c")
elif avg>b and avg>c:
print("avg is higher than b,c")
elif avg>a:
print("avg is just higher than a")
elif avg>b:
print("avg is just higher than b")
elif avg>c:
print("avg is just higher than c")
else:
print("stop")
| false
|
40783e2766d62c324b30d7b79386a4540a46b585
|
zexhan17/Problem-Solving
|
/python/a1.py
| 984
| 4.4375
| 4
|
"""
There are two main tasks to complete.
(a) Write a function with the exact name get_area which takes the radius of a circle as input and calculates
the area. (You might want to import the value of pi from the math module for this calculation.)
(b) Write another function named output_parameter . This should, again, take in one number as input,
consider this number as the radius of a circle and calculate the parameter of the circle.
However, you area not required to return the parameter. Instead, the function should simply output the
following:
The parameter of the circle with radius (radius) is (parameter)
Answer is down do your self before seeing anwser
--------------
"""
from math import pi
def get_area(rad):
return pi*rad*rad
def output_parameter(rad):
p = 2*pi*rad
print("The parameter of the circle with radius", rad, "is" , p )
if __name__ == "__main__":
radius = 5
print("Area is", get_area(radius) )
output_parameter(radius)
| true
|
80961df9b6d1e81cfcc1166c724e2b0f13b464e6
|
klaudiakryskiewicz/Python-50-recruitment-tasks
|
/04.py
| 421
| 4.40625
| 4
|
"""Jakiej struktury danych użyłbyś do zamodelowania
szafki, która ma 3 szuflady, a w każdej z nich znajdują się
3 przegródki?
Stwórz taki model i umieść stringa "długopis" w
środkowej przegródce środkowej szuflady"""
szafka = [[[], [], []], [[], [], []], [[], [], []]]
szafka[1][1].append("długopis")
print(szafka)
for szuflada in szafka:
print(f"Szuflada {szafka.index(szuflada) + 1}: {szuflada}")
| false
|
a803d1f3ebe89e03956323e1362a122f607c47e4
|
klaudiakryskiewicz/Python-50-recruitment-tasks
|
/33.py
| 341
| 4.28125
| 4
|
"""Do czego w Pythonie służy słowo kluczowe yield ?
Napisz przykładowy kod wykorzystujący yield."""
def generator(n):
for i in range(n):
yield i
for item in generator(5):
print(item)
gen = generator(5)
print(gen) # <generator object generator_function at xxxxxxx>
print(next(gen)) # 0
print(gen.__next__()) # 1
| false
|
efcb902a302311e86683639e8dee8803eb8141d4
|
poliarus/Stepik_Python_course
|
/lesson1.py
| 229
| 4.125
| 4
|
A = int(input("A: ")) # minimum
B = int(input("B: ")) # maximum
H = int(input("H: ")) # current
if A <= H <= B:
print("Это нормально")
elif A > H:
print("Недосып")
else:
print("Пересып")
| false
|
556ad2319af38b153209f918a202c793a646ed55
|
XBOOS/leetcode-solutions
|
/binary_tree_preorder_traversal.py
| 2,500
| 4.375
| 4
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?"""
""" Method 1 using recursion.
adding another argument to the method to adding the return result list"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = list()
return self.preorder(root,res)
def preorder(self,root,res):
if not root:
return res
res.append(root.val)
self.preorder(root.left,res)
self.preorder(root.right,res)
return res
""" Method 2 traverse iteractively using stack. I used queue at first which is false,
queue is for level traversal.
But when using stack, take care to push in right child first and then the left child"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = list()
stack = [root]
while stack:
tmp = stack.pop()
res.append(tmp.val)
if tmp.right:
stack.append(tmp.right)
if tmp.left:
stack.append(tmp.left)
return res
""" Method 3 a good non-recursive solution"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = list()
stack = []
while root or stack:
if root:
res.append(root.val)
stack.append(root)
root = root.left
else:
root = stack.pop()
root = root.right
return res
| true
|
f58f1448011d7be58f03493652af3da8451f8152
|
XBOOS/leetcode-solutions
|
/odd_even_linked_list.py
| 1,581
| 4.25
| 4
|
#!/usr/bin/env python
# encoding: utf-8
# Method 1
# Must loop the walk with stepsize of 2
# could also make dummy starting node then start with head not head.next.next
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
oddHead = odd = head
evenHead = even = head.next
head = head.next.next
while head:
odd.next = head
even.next = head.next
odd = odd.next
even = even.next
if head.next:
head = head.next.next
else:
head = None
odd.next = evenHead
return oddHead
# Method 2
# Time limit exeeds!! walk one step each time
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
odd = head
even = head.next
while even.next:
odd.next = even.next
odd = odd.next
if odd.next:
even.next = odd.next
even = even.next
odd.next = head.next
return head
| true
|
1bdf52e8770eb8dc1061e74a9c53672ddf0c2a48
|
XBOOS/leetcode-solutions
|
/first_bad_version.py
| 1,315
| 4.1875
| 4
|
#!/usr/bin/env python
# encoding: utf-8
"""
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
"""
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
return self.binarySearch(1,n)
def binarySearch(self,l,r):
if l>r:
return -1
elif l==r:
return l
elif l+1==r:
if isBadVersion(l):
return l
else:
return r
i = (l+r)/2
if isBadVersion(i):
return self.binarySearch(l,i)
else:
return self.binarySearch(i,r)
| true
|
3d0375292722763c19960095b2c270e3fe20620d
|
christianhv/python_exercises
|
/ex18.py
| 595
| 4.34375
| 4
|
#!/usr/bin/env python
# This one is like the scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1 = %r, arg2 = %r" % (arg1, arg2)
#Ok, that *args is actually pointless, we can do just this
def print_two_again(arg1, arg2):
print "arg1 = %r, arg2 = %r" % (arg1, arg2)
#This just print one argument
def print_one(arg1):
print "arg1 = %r" % arg1
#this one takes no arguments
def print_none():
print "I got nothing"
def main():
print_two(5, "hola")
print_two_again("bien", "eh")
print_one("Pos nomas uno")
print_none()
main()
| true
|
c448adeef80d1c158d1ed8ead495a9974b173e31
|
erik-vojtas/Algorithms-and-Data-Structure-I
|
/MergeSortAlgorithm.py
| 1,923
| 4.21875
| 4
|
# Merge Sort Algorithm
# https://www.programiz.com/dsa/merge-sort
# split an array into two halves and then again until we get lists which consist one item, merge and sort then two lists together, then again until we get full list which is ordered
# https://www.studytonight.com/data-structures/merge-sort
# Worst Case Time Complexity [Big-O]: O(n*log n)
# Best Case Time Complexity [Big-omega]: O(n*log n)
# Average Time Complexity [Big-theta]: O(n*log n)
# Video:
# https://www.youtube.com/watch?v=M5kMzPswo20
comparisons = 0
recursions = 0
# decorator to count recursion
def countRecursion(fn):
def wrappedFunction(*args):
global recursions
if fn(*args):
recursions += 1
return wrappedFunction
@countRecursion
def mergeSort(list):
global comparisons
global recursions
if len(list) > 1:
mid = len(list) // 2
left_list = list[:mid]
right_list = list[mid:]
print("left list:", left_list)
print("right list:", right_list)
mergeSort(left_list) # recursion
mergeSort(right_list) # recursion
i = j = k = 0
while i < len(left_list) and j < len(right_list):
comparisons += 1
if left_list[i] < right_list[j]:
list[k] = left_list[i]
i += 1
else:
list[k] = right_list[j]
j += 1
k += 1
print("merge lists:", "left:", left_list, "right:", right_list)
while i < len(left_list):
list[k] = left_list[i]
i += 1
k += 1
while j < len(right_list):
list[k] = right_list[j]
j += 1
k += 1
return True
array = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]
print(f"Unsorted array: {array}.")
mergeSort(array)
print(f"Sorted array: {array}, comparisons: {comparisons}, recursions: {recursions}.")
| true
|
f7c20d23f3329603dab4eb4c78067494fa33ec9e
|
chutianwen/LeetCodes
|
/LeetCodes/uber/640. Solve the Equation.py
| 1,868
| 4.28125
| 4
|
'''
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
'''
class Solution:
def parse(self, expression):
# make sure the last accumlated number can be counted
expression += "$"
stop = len(expression)
sum_digit = cur_num = num_x = i = 0
sign = "+"
while i < stop:
letter = expression[i]
if letter.isdigit():
cur_num = cur_num * 10 + int(letter)
i += 1
elif letter == " ":
i += 1
else:
if sign == "-":
cur_num *= -1
if letter == "x":
# to handle 0x case
if i > 0 and expression[i - 1] == "0":
pass
else:
num_x += cur_num if cur_num else 1 if sign == "+" else -1
sign = "+"
else:
sum_digit += cur_num
sign = letter
i += 1
cur_num = 0
return sum_digit, num_x
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
left, right = equation.split("=")
left_digit, left_x = self.parse(left)
right_digit, right_x = self.parse(right)
delta_x_left = left_x - right_x
delta_digit_right = right_digit - left_digit
if delta_x_left == delta_digit_right == 0:
return "Infinite solutions"
elif delta_x_left == 0 and delta_digit_right != 0:
return "No solution"
else:
return "x={}".format(delta_digit_right // delta_x_left)
| true
|
d5998dc7bfc0427f1e471b26732ed1a30d3da004
|
chutianwen/LeetCodes
|
/LeetCodes/Array/MergeSortedArray.py
| 1,192
| 4.1875
| 4
|
"""
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n)
to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
"""
class merge(object):
def merge(self, nums1, m, nums2, n):
"""
**nums1.length satisfies the space need which is L > m + n
and P3 will never be advance than p1, this is the trick.
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
p1 = m - 1
p2 = n - 1
p3 = m + n - 1
while p1 >= 0 and p2 >= 0:
if nums2[p2] >= nums1[p1]:
nums1[p3] = nums2[p2]
p2 -= 1
else:
nums1[p3] = nums1[p1]
p1 -= 1
p3 -= 1
if p1 < 0:
nums1[0: p3 + 1] = nums2[0: p2 + 1]
nums1 = [7, 8, 9, 10, 11, 0, 0, 0, 0]
nums2 = [3, 4, 5, 6]
res = merge().merge(nums1, 5, nums2, 4)
print(nums1)
| true
|
8fbbb5cc859758fb997b4f6bc0bc31190165ca15
|
chutianwen/LeetCodes
|
/LeetCodes/Consistency.py
| 706
| 4.3125
| 4
|
'''
when set includes alphabet letter, then order won't be same every time running program, however, when set has all number
the order seems to be same every time.
Also difference between python2 and python3. Python2 will print same order all the time, python3 won't for letter cases.
'''
a = set(range(5))
print("print out set", a)
b = {1: set(range(5))}
print("print out dictionary value", b[1])
c = set(range(3, 7))
for id in range(1):
print(id, " print out a - c ", a - c)
print(id, " print out b[1] - c ", b[1] - c)
for id in range(5):
d = set(['a', 'b', 'c', 'd', 'e'])
print("d:", d)
a = set(range(5))
print("print out set", a)
e = set([1,2,3,4,5])
print("e ", e)
| true
|
ea63e5c210cf599b45695ffc1d6b58459a844585
|
chutianwen/LeetCodes
|
/LeetCodes/summary/IteratorChange.py
| 260
| 4.1875
| 4
|
# list iterator can change
a = [1,2,3,4]
for x in a:
print(a.pop())
print("*"*100)
# we can append to the iterator like this. -x, "," is important
for x in a:
print(x)
if x > 0:
a += -x,
# set iterator cannot change
b = {1,2,3,4}
for x in b:
b.pop()
| true
|
692b8995a37443f50512dfbcc5d7d799c8ff93e5
|
chutianwen/LeetCodes
|
/LeetCodes/stackexe/NestedListWeightSumII.py
| 2,916
| 4.28125
| 4
|
'''
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.
Example 1:
Given the list [[1,1],2,[1,1]], return 8. (four 1's at depth 1, one 2 at depth 2)
Example 2:
Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17)
'''
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution(object):
def depthSumInverse(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
def dfs(input, depth):
value_times = []
if input is None or len(input) == 0:
return [[0, depth]]
for cur in input:
if cur.isInteger():
value_times.append([cur.getInteger(), depth])
else:
value_times.extend(dfs(cur.getList(), depth + 1))
return value_times
res = dfs(nestedList, 1)
print(res)
max_depth = max(res, key=lambda x: x[1])[1]
sum = 0
for cur in res:
sum += cur[0] * (max_depth + 1 - cur[1])
return sum
def depthSumInverseIterative(selfs, nestedList):
weighted = unweighted = 0
while nestedList:
nextLevel = []
for cur in nestedList:
if cur.isInteger():
unweighted += cur.getInteger()
else:
nextLevel.extend(cur.getList())
nestedList = nextLevel
weighted += unweighted
return weighted
| true
|
6418042ad3eed02e18886ff8352cd892380e95cc
|
VladaOliynik/python_labs_km14_Oliynik
|
/p4_oliynik/p4_oliynik_1.py
| 597
| 4.25
| 4
|
#below we make variables for input
name = input('Enter your name: ')
surname = input('Enter your surname')
number = input('Enter your phone number: ')
street = input('Enter your street name:')
building = input('Enter your building number')
apartment = input('Enter your apartment number')
city = input('Enter your city name')
postcode = input('Enter your postcode:')
country = input('Enter the name of your country:')
#then the data entered in the variable will be displayed
print("{} {}\n{}\nStr.{} {},ap.{} {}\n{}\n{}".format(name,surname,number,street,building,apartment,city,postcode,country))
| true
|
6c003faa8da4af035c548cffcb76b8d67d6eb3a5
|
muon012/python3HardWay
|
/ex44.py
| 2,305
| 4.5625
| 5
|
# INHERITANCE vs COMPOSITION
# =========================================== INHERITANCE ===========================================
# Implicit Inheritance
# The child class inherits and uses methods from the Parent class even though they're not defined in the Child class.
class Parent(object):
def implicit(self):
print("PARENT implicit()")
class Child(Parent):
pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
print("+" * 20)
# Override Explicitly
# The child overrides a method inherited from the Parent class by defining it inside itself(Child class).
class Parent(object):
def override(self):
print("PARENT override()")
class Child(Parent):
def override(self):
print("CHILD override()")
dad = Parent()
son = Child()
dad.override()
son.override()
print("+" * 20)
# Alter Before or After
# Using super()
class Parent(object):
def altered(self):
print("PARENT altered()")
class Child(Parent):
def altered(self):
print("CHILD before PARENT altered()")
super(Child, self).altered()
print("CHILD after PARENT altered()")
dad = Parent()
son = Child()
dad.altered()
son.altered()
# -------------- super() BEST PRACTICE ------------------
# super() enables you to access the methods and members of a parent class without referring to the parent class by name.
# For a single inheritance situation the first argument to super() should be the name of the current child class
# calling super(), and the second argument should be self, that is, a reference to the current object calling super().
# =========================================== COMPOSITION ===========================================
class Other(object):
def override(self):
print("OTHER override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child(object):
def __init__(self):
self.other = Other()
# Remember that 'sef.other' is now a class, so we are using another class here and calling its implicit method.
def implicit(self):
self.other.implicit()
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD before OTHER altered()")
self.other.altered()
print("CHILD after OTHER altered()")
son = Child()
print("\nCOMPOSITION\n")
son.implicit()
son.override()
son.altered()
| true
|
4384f3e5d9625e1f7205d66818781669fe7652d8
|
pyexer/pyBalaji
|
/asg6(08-09-19).py
| 311
| 4.21875
| 4
|
#python code to find distance between two points.
import math
x1=int(input("enter X1:"))
y1=int(input("enter Y1:"))
x2=int(input("enter X2:"))
y2=int(input("enter Y2:"))
distance=math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
print("distance ({0},{1}) and ({2},{3}) is {4}".format(x1,x2,y1,y2,distance))
| false
|
4075b724406894a983abcc3c5c3618e06ea8912f
|
Ellina3008/PisarenkoER
|
/2 урок/8.py
| 352
| 4.125
| 4
|
# -*- coding: utf-8 -*-
# 8 Задание
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
c = int(input("Введите третье число: "))
if (a == b == c):
print("3")
elif (a == b or b == c or a == c):
print("2")
else:
print("0")
print("\n")
| false
|
b04b7bba927f04b8932cb62895dece46929d7479
|
pablomdd/EPI
|
/Primitive/4_7_compute_power.py
| 602
| 4.46875
| 4
|
def power(x: float, y: int) -> float:
result = 1.0
power = y
# tweek for the algorithm work with negative power
if y < 0:
power, x = -power, 1.0 / x
# if power < 0 evaluates False
# that happens when bits shift down to 0 or less
while power:
# evaluates if power is odd
if power & 1:
# If odd, multiply per x to not loose that factor in interger division
result *= x
# right bit shift -> divides by 2
power = power >> 1
# Accumulate power
x = x * x
return result
print(power(2, -13))
| true
|
73c2e0ea222185ecb9e6a506373c09de646288c0
|
schatfield/classes-pizza-joint
|
/UrbanPlanner/building.py
| 1,479
| 4.34375
| 4
|
# In this exercise, you are going to define your own Building type and create several instances of it to design your own virtual city. Create a class named Building in the building.py file and define the following fields, properties, and methods.
# Properties
# designer - It will hold your name.
# date_constructed - This will hold the exact time the building was created.
# owner - This will store the same of the person who owns the building.
# address
# stories
# Methods
# Define a construct() method. The method's logic should set the date_constructed field's value to datetime.datetime.now(). You will need to have import datetime at the top of your file.
# Define a purchase() method. The method should accept a single string argument of the name of the person purchasing a building. The method should take that string and assign it to the owner property.
# Constructor
# Define your __init__ method to accept two arguments
# address
# stories
# Once defined this way, you can send those values as parameters when you create each instance
# eight_hundred_eighth = Building("800 8th Street", 12)
# Creating Your Buildings
# Create 5 building instances
# Have each one get purchased by a real estate magnate
# After purchased, construct each one
# Once all building are purchased and constructed, print the address, owner, stories, and date constructed to the terminal for each one.
# Example
# 800 8th Street was purchased by Bob Builder on 03/14/2018 and has 12 stories.
| true
|
2bd3c4fb23c738e2a77db06e92807ac3546758bd
|
HansMPrieto/CIS-211-Coursework
|
/Mini Projects/waldo-mini-master/dup.py
| 2,447
| 4.25
| 4
|
from typing import List
def every_column_dups(m: List[List[int]]) -> bool:
"""Returns True iff every column has at least one duplicate element.
Examples:
every_column_dups([[0, 1, 2],
[0, 2, 3],
[4, 2, 3]]) == True
every_column_dups([[0, 1, 2],
[1, 1, 2],
[2, 3, 3]]) == False (first column has no duplicates)
every_column_dups([]) == True (vacuous case, no columnns)
every_column_dups([[]]) == True (one row, no columns)
"""
if len(m) == 0:
return True
has = set()
for col_i in range(len(m[0])):
has_dup = True
for row_i in range(len(m)):
if m[row_i][col_i] not in has:
has.add(m[row_i][col_i])
has_dup = False
if not has_dup:
return True
return False
#print(every_column_dups([[0, 1, 2],
#[0, 2, 3],
#[4, 2, 3]]))
#print(every_column_dups([[0, 1, 2],
#[1, 1, 2],
#[2, 3, 3]]))
def in_order(l):
if len(l) == 0:
return True
else:
cur_item = l[0]
for item in l:
if item < cur_item:
return False
cur_item = item
return True
#print(in_order([1, 2, 3, 4]))
#print(in_order([2, 1, 3, 2]))
def some_column_increasing(m: List[List[int]]) -> bool:
"""True if any column of m is non-decreasing.
Example: [[5, 7, 3],
[3, 7, 4],
[8, 8, 3]] -> True because 7, 7, 8 is an increasing sequence
Example: [[5, 7, 3],
[3, 7, 4],
[8, 6, 3]] -> False, no column is increasing
Example: [] -> False (no columns, so none are increasing)
Example: [[]] -> False (no columns, so none are increasing)
Example: [[42]] -> True single value is an increasing sequence
"""
if len(m) == 0:
return False
for col_i in range(len(m)):
is_sorted = True
for row_i in range(len(m[col_i])):
cur_item = m[row_i][0]
item = m[row_i][col_i]
if item < cur_item:
is_sorted = False
item = cur_item
print(some_column_increasing([[5, 7, 3], [3, 7, 4], [8, 8, 3]]))
print(some_column_increasing([[5, 7, 3], [5, 7, 4], [8, 6, 3]]))
| false
|
e7526399cda0a984b8fe03a425beab42c4782344
|
sourav2406/nutonAkash
|
/DataStructure/Stack/queueUsingStack.py
| 905
| 4.15625
| 4
|
#Implementing queue using stack
from stack import Stack
class Queue:
def __init__(self):
self.queueStack = Stack()
def push(self,data):
self.queueStack.push(data)
def popInner(self):
if self.queueStack.is_last():
return self.queueStack.pop()
temp = self.queueStack.pop()
result = self.popInner()
self.queueStack.push(temp)
return result
def pop(self):
if self.queueStack.is_empty() is not True:
self.popInner()
def printQueue(self):
self.queueStack.printStack()
if __name__ == '__main__':
queue = Queue()
queue.push(10)
queue.push(20)
queue.push(30)
queue.push(40)
queue.printQueue()
queue.pop()
queue.printQueue()
queue.pop()
queue.printQueue()
queue.pop()
queue.printQueue()
queue.pop()
queue.printQueue()
queue.pop()
| false
|
376ecda95125c6d26e8983d9971aaabea717ef9e
|
sourav2406/nutonAkash
|
/DataStructure/BinaryTree/reverseLevelOrder.py
| 1,037
| 4.4375
| 4
|
# A recursive python process to print reverse level order
#Basic node for binary tree
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
#compute the height of a binary tree
def _height(node):
if node is None:
return 0
else:
lheight = _height(node.left)
rheight = _height(node.right)
if lheight > rheight:
return lheight + 1
else:
return rheight + 1
#print nodes at a given level
def printGivenLevel(root, level):
if root is None:
return
if level == 1:
print(root.data)
elif level > 1:
printGivenLevel(root.left, level-1)
printGivenLevel(root.right, level-1)
#print reverse order
def reverseLevelOrder(root):
h = _height(root)
for i in reversed(range(1,h+1)):
printGivenLevel(root,1)
#driver programe
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
reverseLevelOrder(root)
| true
|
959618ab34fb6f1f42843fb2c79c0af724c6746b
|
ramachandrajr/lpthw
|
/exercises/ex33.py
| 446
| 4.25
| 4
|
numbers = []
def loop_through(x, inc):
for i in range(x):
print "At the top i is %d" % i
numbers.append(i)
# We do not need this iterator anymore and
# even if we use it the i value will be over
# written by for loop.
# i = i + inc
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
loop_through(10, 2)
print "The numbers: "
for num in numbers:
print num
| true
|
a388c5679b909776fbda190c98f6f57c49ff0193
|
1258488317/master
|
/python/example/continue.py
| 445
| 4.21875
| 4
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# while True:
# s =input('enter something:')
# if s == 'quit':
# break
# if len(s) < 3:
# print('too samall')
# else:
# print('input is of suffivient length')
# print('done')
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
| true
|
bbdc8374a9f16c165ef6252f6715b74457c92616
|
charlescheung3/Intro-HW
|
/Charles Cheung PS16a.py
| 263
| 4.25
| 4
|
#Name: Charles Cheung
#Email: charles.cheung24@myhunter.cuny.edu
#Date: February 11, 2020
#This program prompts the user for the number of kilograms and then print out the number of pounds.
weight = input("Enter weight in kilos:")
weight = float(weight)
kg = weight*2.20462262185
print(kg,"lb")
| true
|
db1af7f0d6e99aadd85081703ab55905fb3dd400
|
charlescheung3/Intro-HW
|
/Charles Cheung PS37.py
| 687
| 4.5
| 4
|
#Name: Charles Cheung
#Email: charles.cheung24@myhunter.cuny.edu
#Date: March 10, 2020
#This program asks the user for a string, then counts and prints the number of characters that are uppercase letters, lowercase letters, numbers and special characters.
codeWord = input("Please enter a codeword:")
number = 0
upper = 0
lower = 0
special = 0
for i in codeWord:
string = ord(i)
if (48 <=string<=57):
number = number +1
elif (65 <=string<=90):
upper = upper+1
elif (97 <=string<=122):
lower = lower+1
else:
special = special+1
print("Your codeword contains", upper,"uppercase letters,",lower,"lowercase letters,",number,"numbers",",and",special,"special characers.")
| true
|
a6eee61b1e72ae980b41dbf283c5b2c67cbb0eb2
|
charlescheung3/Intro-HW
|
/Charles Cheung PS18.py
| 435
| 4.21875
| 4
|
#Name: Charles Cheung
#Email: charles.cheung24@myhunter.cuny.edu
#Date: February 18, 2020
#This program will tell you how many coins your cents input will return
centsinput = int(input("Enter number of cents as an integer"))
quarters = centsinput // 25
print("Quarters:", quarters)
rem = centsinput % 25
dimes = rem // 10
print("Dimes:", dimes)
rem = rem % 10
nickels = rem // 5
print("Nickels:", nickels)
cents = rem % 5
print("Cents:", cents)
| true
|
7119908972cd42c33ca71cfb798b1d4716e13ca6
|
MandeepKaur92/c0800291_EmergingTechnology_assignment1
|
/main.py
| 1,646
| 4.65625
| 5
|
import datetime
def reverse(fname, lname):
print(f"First Name:{fname}\nLast Name:{lname}")
print("---------------reverse------------------ ")
#print name in reverse
print(f"{lname}" + " " + f"{fname}")
def circle_radius(radius):
#calculate area of radius
area=(22/7)*radius**2
print("----------------------------------------------------------------")
#print area of radius
print(f"Radius of circle is {radius} and area of circle is :{str(area)}")
def current_date():
#print current date using build in method datetime.datetime.now() after convert it into string
print("Current date is:" + str(datetime.datetime.now()))
def main():
#print program information
print("This Python program accepts the radius of a circle from the user and compute the area")
print("-------------------------------------------------------------------------------------")
#enter radius from user
radius = float(input("Enter radius of circle:"))
#call circle_radius function
circle_radius(radius)
print("\n This program accepts the user's name and print it in reverse order")
print("----------------------------------------------------------------------")
#enter first and last name from user
fname = input("Please enter your First Name:")
lname = input("Please enter your Last Name:")
#call reverse function to reverse print name
reverse(fname, lname)
print(" \nThis Python program to display the current date and time")
print("-----------------------------------------------------------")
#call function current_date
current_date()
main()
| true
|
9c6f3fdfdb384d75d1fd482f3009148fe0ebb06d
|
tthompson082/Sorting
|
/src/iterative_sorting/iterative_sorting.py
| 2,070
| 4.34375
| 4
|
# TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# create a loop that starts at 1 more than the current index and continues to the end of the array
for j in range(i+1, len(arr)):
# compare each of the remaining items to the current index
if arr[j] < arr[cur_index]:
# if it is less then we will assign a variable to the value of the current index
k = arr[cur_index]
# then we will set the current index to the smaller value
arr[cur_index] = arr[j]
# finally we will set the original index to the current index, "swapping" their positions
arr[j] = k
# TO-DO: swap
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# Create a loop that starts with the last element of the array and works its way to 0 by subtracting one each step
for i in range(len(arr)-1, 0, -1):
# create a loop through the range (ie. if i = 9 loop through 0-8) and assign each value to j
for j in range(i):
# compare arr[j] to arr[j+1]. For the first loop this will be arr[0] and arr[1] then arr[1] and arr[2], etc.
if arr[j] > arr[j+1]:
# if arr[j] is larger then we will assign a variable the value of arr[j]
k = arr[j]
# then we set arr[j] to be equal to arr[j+1]. This is essentailly moving the smaller value to the left by setting it equal to the position we started from
arr[j] = arr[j+1]
# finally we "bubble up" the value. We set arr[j+1] to the variable we stored the original value of arr[j] in.
arr[j+1] = k
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true
|
c50320c505da5dc6e6b4374e755234e068c77057
|
IagoAntunes/Python__learning
|
/Curso em Video[120Horas]/1º Mundo/Exercicio 004.py
| 342
| 4.28125
| 4
|
# Faça um programa que leia algo pela tela do seu computador e mostre na tela
# o seu tipo primitivo e todas as informações possiveis sobre ela
n1 = input("Digite um Numero: ")
print(f"É uma Letra: {n1.isalpha()}")
print(f"É um Numero: {n1.isnumeric()}")
print(f"É um Decimal: {n1.isdecimal()}")
print(f"É Minusculo: {n1.islower()}")
| false
|
0b6bfcf5b82f1c9d0e2098d692cc1c1c2c6a891a
|
IagoAntunes/Python__learning
|
/Curso em Video[120Horas]/1º Mundo/Exercicio 028.py
| 467
| 4.28125
| 4
|
# Escreva um programa que faça o computador “pensar” em um número inteiro entre 0 e 5
# e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
# O programa deverá escrever na tela se o usuário venceu ou perdeu.
from random import randint
usuario = int(input("Adivinhe o Numero.(1 a 5)"))
numero = randint(1,5)
if(usuario == numero):
print("PARABENS VOCE ACERTOU")
else:
print(f"Tente Novamente! \nNumero:{numero}")
| false
|
45c822cf2d953081c2f3ee3435d23bad98a32a99
|
IagoAntunes/Python__learning
|
/Curso em Video[120Horas]/2º Mundo/Exercicio 064.py
| 419
| 4.125
| 4
|
#Crie um programa que leia vários números inteiros pelo teclado.
# O programa só vai parar quando o usuário digitar o valor 999,
# que é a condição de parada. No final, mostre quantos números foram digitados
# e qual foi a soma entre eles
soma = 0
qnt=0
num = 0
while(num != 999):
num = int(input("Digite um Numero:"))
qnt += 1
soma+=num
print(f"Numeros Digitados:{qnt}")
print(f"Soma={soma-999}")
| false
|
b4c7b046b68acb11781f471bd72297bf8de53f80
|
aduo122/Data-Structures-and-Algorithms-Coursera-UCSD
|
/Graph/week5/connecting_points.py
| 1,072
| 4.125
| 4
|
#Uses python3
import sys
import math
import heapq
def minimum_distance(x, y):
result = 0.
#write your code here
#setup parameters
queue = [[0,x[0],y[0],0]]
heapq.heapify(queue)
visited = [0 for _ in range(len(x))]
v_length = 0
while v_length < len(visited):
# select start heap.pop()
temp_node = heapq.heappop(queue)
if visited[temp_node[3]] == 1:
continue
result += temp_node[0]
v_length += 1
#calculate distance, add to heap
for node in range(len(visited)):
if visited[node] == 0:
t_distance = math.sqrt((temp_node[1] - x[node])**2 + (temp_node[2] - y[node])**2)
heapq.heappush(queue,[t_distance, x[node], y[node],node])
#get the closest point, mark
visited[temp_node[3]] = 1
return result
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
x = data[1::2]
y = data[2::2]
print("{0:.9f}".format(minimum_distance(x, y)))
| true
|
b4bc51deb6a766cfc134ba59de57efa3a3729960
|
rampreetha2/python3
|
/natural.py
| 228
| 4.125
| 4
|
num = int(input("Enter the value of n:"))
hold = num
sum = 0
if sum<=0;
print("Enter a whole positive number!")
else:
while num>0:
sum sum + num
num =num -1;
print("Sum of first",hold, "natural numbers is":,sum)
| true
|
f57c76a359ca492ab92052fb995011673bdd8b86
|
Jodabjuan/intro-python
|
/while_loop.py
| 511
| 4.28125
| 4
|
""""
Learn Conditional Repetition
Two types of loops: for-loops and while-loops
"""
counter = 5
while counter !=0:
print(counter)
# Augmented Opperation
counter -=1
counter = 5
while counter:
print(counter)
# Augmented Opperation
counter -=1
# Run forever
while True:
print("Enter a number")
response = input() # 4take user input
if int(response) % 7 == 0: # number divisible by 7
break # exit loop
print ("Outside while loop")
| true
|
122b570d2b95df96d5c9c36db57cdc3cc4d7fc09
|
Jodabjuan/intro-python
|
/me_strings.py
| 1,357
| 4.40625
| 4
|
"""
Learn more about strings
"""
def main():
"""
Test function
:return:
"""
s1 = "This is super cool"
print("Size of s1: ", len(s1))
# concatenation "+"
s2 = "Weber " + "State " + "University"
print(s2)
# join method to connect large strings instead of "+"
teams = ["Real Madrid", "Barcelona", "Manchester United"]
record = ":".join(teams)
print(record)
print("Split Record: ", record.split(":"))
# Partitioning Strings
departure, _, arrival = "London:Edinburgh".partition(":")
# the "_" underscore is a dummy object
print(departure, arrival)
# String formating using format() method
print("The age of {0} is {1}".format("mario", 34))
print("The age of {0} is {1}, and the birthday of {0} is {2}".format(
"Mario", 34, "August 12th"))
# Omitting the index
print("The best numbers are {} and {}".format(4, 22))
# by field name
print("Current position {latitude} {longitude}".format(latitude="60N", longitude="5E"))
# print elements of list
print("Galactic position x={pos[0]}, y={pos[1]}, z={pos[2]}".format(pos=(85.6, 23.3, 99.0)))
# Second version of "format" : print(f"(var)") python 3.7
# fname = "Waldo"
#lname = "Weber"
#print(f"the WSU mascot is {fname} {lname}")
if __name__ == '__main__':
main()
exit(0)
| true
|
0296546419117c17ca88673faf6861ca24a3a51c
|
toxine4610/codingpractice
|
/dcp65.py
| 1,810
| 4.34375
| 4
|
'''
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
'''
def nextDirection(direction):
if direction == "right":
return "down"
elif direction == "down":
return "left"
elif direction == "left":
return "up"
elif direction == "up":
return "right"
def nextPosition(position,direction):
if direction == "right":
return (position[0], position[1]+1)
elif direction == "left":
return (position[0], position[1]-1)
elif direction == "down":
return (position[0]+1, position[1])
elif direction == "up":
return (position[0]-1, position[1])
def shouldChange(M,pos):
'''
returns False if r,c are within the bounds,
if True, then change the direction
'''
Rows = len(M)
Cols = len(M[0])
r,c = pos
isInBoundsR = 0 <= r < Rows
isInBoundsC = 0 <= c < Cols
return not isInBoundsC or not isInBoundsR or M[r][c] is None
def main(M):
numElem = len(M)*len(M[0])
currentDirection = "right"
currentPosition = (0,0)
while numElem > 0:
r,c = currentPosition
print(M[r][c])
# replace printed element with None
M[r][c] = None
numElem -= 1
next_Position = nextPosition(currentPosition, currentDirection)
# if the next position is out of the bounds, then change the print direction,
# also update the position, to prevent the same element from being printed
if shouldChange(M, next_Position):
currentDirection = nextDirection(currentDirection)
currentPosition = nextPosition(currentPosition, currentDirection)
else:
# keep the same direction
currentPosition = next_Position
### Test
M = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
main(M)
| true
|
f77236d54686a8ea79e1989c06329169cd453880
|
toxine4610/codingpractice
|
/dcp102.py
| 808
| 4.25
| 4
|
'''
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4].
'''
def get_contiguous_sum(A, k):
sum_so_far = dict() # this stores the sums and the indices
sum_so_far[0] = -1
L = []
sum = 0
for ind, item in enumerate(A):
sum += item
sum_so_far[sum] = item
#check if the accumulated sum has reached the target and get the start of the sum sequence
# if the sum has not yet been reached, this will return a None
first = sum_so_far.get(sum - k)
if first is not None:
L.append( A[ first : ind + 1 ] )
return L
#### test
A = [1,2,3,4,5]
k = 9
print( get_contiguous_sum(A,k) )
A = [2,1,3,4,5]
print( get_contiguous_sum(A,k))
| true
|
8a7f93265ac05e8ddcb6c1d89bd830b1c450fa26
|
SergeiLSL/PYTHON-cribe
|
/Глава 2. Основы Python/Раздел 3. Условные выражения/Логические операции.py
| 2,541
| 4.21875
| 4
|
""" Логические операции """
"""
Для создания составных условных выражений применяются логические операции.
В Python имеются следующие логические операторы:
"""
# and (логическое умножение)
"""
Возвращает True, если оба выражения равны True
"""
age = 22
weight = 58
result = age > 21 and weight == 58
print(result) # True
"""
В данном случае оператор and сравнивает результаты двух выражений:
age > 21 weight == 58. И если оба этих выражений возвращают True, то
оператор and также возвращает True. Причем в качестве одно из выражений
необязательно выступает операция сравнения: это может быть другая
логическая операция или просто переменная типа boolean,
которая хранит True или False.
"""
age = 22
weight = 58
isMarried = False
result = age > 21 and weight == 58 and isMarried
print(result) # False, так как isMarried = False
# or (логическое сложение)
"""
Возвращает True, если хотя бы одно из выражений равно True
"""
age = 22
isMarried = False
result = age > 21 or isMarried
print(result) # True, так как выражение age > 21 равно True
# not (логическое отрицание)
"""
Возвращает True, если выражение равно False
"""
age = 22
isMarried = False
print(not age > 21) # False
print(not isMarried) # True
"""
Если один из операндов оператора and возвращает False, то другой операнд
уже не оценивается, так как оператор в любом случае возвратит False.
Подобное поведение позволяет немного увеличить производительность, так как
не приходится тратить ресурсы на оценку второго операнда.
Аналогично если один из операндов оператора or возвращает True, то
второй операнд не оценивается, так как оператор в любом случае возвратит True.
"""
| false
|
5f762a882d5976692ad36f4f3c4d8a070f168737
|
SergeiLSL/PYTHON-cribe
|
/Глава 2. Основы Python/Раздел 2. Операции с числами/Арифметические операции с присвоением.py
| 1,023
| 4.5625
| 5
|
"""
Арифметические операции с присвоением
"""
"""
Ряд специальных операций позволяют использовать присвоить результат
операции первому операнду:
+=
Присвоение результата сложения
-=
Присвоение результата вычитания
*=
Присвоение результата умножения
/=
Присвоение результата от деления
//=
Присвоение результата целочисленного деления
**=
Присвоение степени числа
%=
Присвоение остатка от деления
Примеры операций:
"""
number = 10
number += 5
print(number) # 15
number -= 3
print(number) # 12
number *= 4
print(number) # 48
number /= 4
print(number) # 12.0
number //= 3
print(number) # 4.0
number **= 4
print(number) # 256.0
number %= 5
print(number) # 1.0
| false
|
c9e304d2991fcaf640d5c2030d5e5538bda13afb
|
rizkarama/Ujian-Modul-1
|
/Hashtag.py
| 1,199
| 4.1875
| 4
|
# 1
# def Hashtag(string): #bikin fungsinya #menggunakan conditional expression untuk memisahkan jenis pertanyaan.
# if len(string)>25: # menghitung panjang string, lalu membuat batasan yaitu len(string) lebih besar dari 25
# print(string.title()) # apabila panjang string lebih besar dari 25 maka string akan di cetak dan menggunakan fungsi title untuk membuat setiap awal kata menjadi huruf kapital
# elif 1<=len(string)<=25: #karena ada berbagai pertanyaan yang berbeda, maka digunakan elif untuk membuat batasan baru
# print(string.replace(' ','')) #apabila panjang string lebih besar sama dengan 1 dan lebih kecil sama dengan 25 maka, string akan di print dan menggunakan function replace untuk menghilangkan ' ' spasi
# elif len(string)>=140: #karena ada syarat apabila panjang string lebih dari sama dengan 140 maka saya masih menggunakan elif
# print('false') #apabila panjang string lebih besar sama dengan 140 maka akan di print false
# else: #penggunaan else bertujuan untuk membuat fungsi hastag kosong menjadi flase
# print(False)
# Hashtag("Hello there how are you doing")
# Hashtag(" Hello World ")
# Hashtag("")
| false
|
259bf7ad003dc1216b8b5ee22231b910bdda8be1
|
Toras/gb_python_developer
|
/lesson03/task03.py
| 1,142
| 4.1875
| 4
|
"""
3. Создать два списка с различным количеством элементов.
В первом должны быть записаны ключи, во втором — значения.
Необходимо написать функцию, создающую из данных ключей и значений словарь.
Если ключу не хватает значения, в словаре для него должно сохраняться значение None.
Значения, которым не хватило ключей, необходимо отбросить.
"""
def dict_create(keys_list, values_list):
result = {}
for i in range(len(keys_list)):
key = keys_list[i]
value = None
if i < len(values_list):
value = values_list[i]
result[key] = value
return result
if __name__ == '__main__':
keys = ['A', 'B', 'C', 'D']
values = [32, 43, 8]
dict_result = dict_create(keys, values)
print(dict_result)
keys = ['A', 'B']
values = [32, 43, 8]
dict_result = dict_create(keys, values)
print(dict_result)
| false
|
b69667d2cac84aa9a1dab4847b619425a02d2218
|
CanekSystemsHub/Python_Data_Structures
|
/3 Recursion/countdown_start.py
| 296
| 4.28125
| 4
|
# use recursion to implement a countdown counter
global x
x = int(input("Type the number you want to countdwon "))
def countdown(x):
if x == 0:
print("You're done!")
return
else:
print(x, " ... the countdown stills running")
countdown(x-1)
countdown(x)
| true
|
0674fd2e8bd686abf9b8e0be9b54388d720dcdba
|
ddp-danilo/ddp-pythonlearning1
|
/sm7ex1.py
| 251
| 4.1875
| 4
|
#desenho que usa '#' para fazer quadrados
largura = int(input("digite a Largura: "))
altura = int(input("digite a altura: "))
while altura > 0:
ll = largura
while ll > 0:
print("#", end='')
ll -= 1
print()
altura -= 1
| false
|
b1d1901eb536968313a6e3d2e018261728b0a93e
|
MariaLegenda/various-tasks-education-
|
/1_1 - merge_sort.py
| 1,266
| 4.25
| 4
|
# 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50).
# Выведите на экран исходный и отсортированный массивы.
import random
def merge_sort(array):
if len(array) <= 1:
return array
middle = int(len(array)/2)
left = merge_sort(array[:middle])
right = merge_sort(array[middle:])
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
left = left[1:]
else:
result.append(right[0])
right = right[1:]
# добавить остаток
if len(left) > 0:
result += left
if len(right) > 0:
result += right
return result
size = 20
array = [float(random.randint(0, 50)) for i in range(size)]
random.shuffle(array) #перемешать элементы в массиве
print('Исходный массив:\n', array)
print('Отсортированный массив:\n', merge_sort(array))
| false
|
0f4c8ffda99aeaeb8dc8f5dd901a24b8fd0161fb
|
atomicbombvendor/learnPythonTheHardWay
|
/SomeTests/ts_del/t40.py
| 1,143
| 4.25
| 4
|
things = ['a', 'b', 'c', 'd']
print things[1]
things[1] = 'z'
print things[1]
print things
stuff = {'name':'zed', 'age':36, 'height':6*12+2}
print stuff['name']
print stuff['name']
print stuff['age']
print stuff['height']
stuff[1] = 'Wow'
print stuff[1]
stuff[2] = 'Neato'
print stuff[2]
stuff["t"] = 'T'
print stuff["t"]
print stuff
del stuff['t']
del stuff[1]
#############
cities = {'CA':"San Francisco", 'MI':'Detroit', 'FL':'JacksonVille'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def print_city(themap):
for city in themap.items():
print city,
def print_city2(themap):
for city in themap:
print city,
print "Now print items"
print_city(cities)
print "\nNow print dicts"
print_city2(cities)
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# OK pay attention!
cities['_find'] = find_city
while True:
print "\nState? (Enter to quit)",
state = raw_input("> ")
if not state: break
# this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
| false
|
db10b6b1bffd0450adc01ae4a8a7b1925a39f37d
|
htbit/Python-project
|
/5 день/project-2.py
| 361
| 4.21875
| 4
|
def vowel_count(str):
count = 0
vowel = set("aeiouAEIOUёуеыаоэяиюЁУЕЫАОЭЯИЮ")
for alphabet in str:
if alphabet in vowel:
count = count + 1
print("Всего было использовано гласных:", count)
str = input('Введите слово или предложение: ')
vowel_count(str)
| false
|
e411395d691e88bd43c137eef6556c2d90d8fe07
|
PoornishaT/positive_num_in_range
|
/positive_num.py
| 344
| 4.25
| 4
|
input_list = input("Enter the elements of the list separated by space : ")
mylist = input_list.split()
print("The entered list is : \n", "List :", mylist)
# convert into int
for i in range(len(mylist)):
mylist[i] = int(mylist[i])
print("The positive terms in list is :\n")
for x in mylist:
if x > 0:
print(x, end=" ")
| true
|
567ecb1015e77b44c6e5840b1363887c00e94019
|
SushantBabu97/HackerRank_30Days_Python_Challenge-
|
/Day28.py
| 907
| 4.59375
| 5
|
# RegEx, Patterns, and Intro to Databases
"""
Task
Consider a database table, Emails, which has the attributes First Name and Email ID. Given n rows of data simulating the
Emails table, print an alphabetically-ordered list of people whose email address ends in @gmail.com.
Sample Input:::
6
riya riya@gmail.com
julia julia@julia.me
julia sjulia@gmail.com
julia julia@gmail.com
samantha samantha@gmail.com
tanya tanya@gmail.com
Sample Output:::
julia
julia
riya
samantha
tanya
"""
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
lst=[]
for N_itr in range(N):
firstNameEmailID = input().split()
firstName = firstNameEmailID[0]
emailID = firstNameEmailID[1]
if re.search(".+@gmail\.com$",emailID):
lst.append(firstName)
lst.sort()
for name in lst:
print(name)
| true
|
92367542b27c2e121bd491fe2d9e3469caf3016d
|
lokitha0427/pythonproject
|
/day 7- Patterns/strong number.py
| 293
| 4.21875
| 4
|
n=int(input("enter the number"))
sum=0
t=n
while t>0:
fact=1
digit=t%10
for i in range(1,digit+1):
fact=fact*i
sum=sum+fact
t//=10
if(sum==n):
print("the given number is a strong number")
else:
print("the given number is not a strong number")
| true
|
de14dd2a4fbf0b572a89f648f02ba459b5ea42ce
|
lokitha0427/pythonproject
|
/day 3-conditional/monkey trouble.py
| 359
| 4.125
| 4
|
#monkey trouble
a_smile=False
b_smile=False
if ((a_smile and b_smile) or (not a_smile and not b_smile)):
print("true")
else:
print("false")
'''
a_smile=bool(input("enter the a monkey"))
b_smile=bool(input("enter the b monkey"))
if True:
print(((a_smile and b_smile) or (not a_smile and not b_smile)))
else:
print("false")
'''
| false
|
0721265e0f7f1dfb6345120b4a79b72b978f1ec3
|
khanshoab/pythonProject1
|
/Function.py
| 1,776
| 4.375
| 4
|
# Function are subprograms which ar used to compute a value or perform a task.
# Type of function
# 1. built in function e.g print() , upper(), lower().
# 2. user-defined function
# ** Advantage of Function **
# write once and use it as many time as you need. This provides code re-usability.
# Function facilities case of code maintenance.
# Divide large task into small task so it will help you to debug code.
# You can remove or add new feature to a function anytime.
# ** Function Definition **
# We can define a function using def keyword followed by function name with parentheses.
# This is also called as Creating a Function, Defining a Function.
# ** Calling A Function **
# A function runs only when we call it, function can not run on its own.
# ** How Function Work **
# write once and use it as many time as you need.
# Defining a Function
def show():
name = "Independence"
print("Today is", name)
# Calling a Function
show()
# Diving Large task into many small task, helpful for de-bugging code.
# Defining Function
def add():
x = 10
y = 20
c = x + y
print(c)
add()
# Separate function for addition
def sub():
x = 20
y = 10
c = x - y
z = x + y
m = x * y
print(c)
print(z)
print(m)
sub()
# Function without Argument and Parameter
# Defining a function without Parameter
# no parameter
def hhh():
a = 10
b = 20
c = a + b
print(c)
# Calling a function without Argument
hhh()
# Calling a function with parameter
def sss(b):
a = 10
c = a + b
print(c)
print(a + 50)
print(a + b)
print(f"Formatted output {a+b:5.2f}")
print(f"Formatted output {a-b:5.10f}")
print(f"Formatted output {a*b:5.2f}")
# Calling a function with Argument
sss(20.444)
| true
|
93035b2efc77dab6e1d7cbb2aa8a398446f3ff36
|
khanshoab/pythonProject1
|
/mul+di+arr.py
| 262
| 4.15625
| 4
|
# Multi-dimensional Array means 2d ,3d ,4d etc.
# It is also known as array of arrays.
# create 2d array using array () function.
from numpy import *
a = array([[23,33,32,43],
[54,23,35,23]])
print(a,dtype)
print(a[1][3])
a[0][1] = 100
print(a[0][1])
| true
|
e8613d9746bb6c1a99ea312d84132ffe00409f98
|
khanshoab/pythonProject1
|
/repetition+operator.py
| 224
| 4.125
| 4
|
# Repetition operator is used to repeat the string for several times.
# It is denoted by *
print("$" * 10)
str1 = "MyMother "
print(str1 * 10)
# slicing string
str2 = "my dream "
print(str2[0:2] * 5) # To printing the 'my
| true
|
e6f6c9b17fc7c8e400d26b16940c127b31504852
|
Maxud-R/FizzBuzz
|
/FizzBuzz.py
| 1,557
| 4.1875
| 4
|
#Algorithm that replaces every third word in the letter to Fizz, and every fifth letter in the word to Buzz.
#Length of the input string: 7 ≤ |s| ≤ 100
class FizzBuzz:
def replace(self, rawstr):
if len(rawstr) < 7 or len(rawstr) > 100 or not (rawstr in rawstr.lower()) or rawstr.isdigit():
raise Exception("Wrong input string, str length must be 7 <= s <= 100 and string must consist only of lowercase letters a-z")
#this part splits string into words and words into parts, 5 char length, and add it to list in list
wordList = rawstr.split(" ")
for word in range(0, len(wordList)):
tempWord = wordList[word]
wordList[word] = []
for a in range(round(len(tempWord)/5)):
if len(tempWord[5:]):
wordList[word].append(tempWord[:5])
tempWord = tempWord[5:]
wordList[word].append(tempWord)
#replace each fifth(last) letter of the part to Buzz
for word in range(len(wordList)):
for part in range(len(wordList[word])):
if len(wordList[word][part]) >= 5:
wordList[word][part] = wordList[word][part][:-1]+"Buzz"
wordList[word] = "".join(wordList[word]) #join parts into words back
#now wordList[word] is a list of words. Next code replace every third word to Fizz
for word in range(2, len(wordList), 3):
wordList[word] = "Fizz"
return " ".join(wordList)
| true
|
644a34827d6c7fc97d7c5afb3c3a95bba6263c29
|
brandon98/variables
|
/string exercise 2.py
| 297
| 4.21875
| 4
|
#Brandon Dickson
#String exercise 2
#8-10-2014
quote=input("Please enter quote:")
replacement= input( "What word would you like to replace?")
replacement2=input( "What word would you like to replace it with?")
answer= quote.capitalize()
output= quote.replace(replacement, replacement2)
print(output)
| true
|
1f2b406a39f0a5094c5206899dd2795f12d043ad
|
Hu-Wenchao/leetcode
|
/prob218_the_skyline_problem.py
| 2,271
| 4.3125
| 4
|
"""
A city's skyline is the outer contour of the silhouette formed
by all the buildings in that city when viewed from a distance.
Now suppose you are given the locations and height of all the
buildings as shown on a cityscape photo (Figure A), write a
program to output the skyline formed by these buildings
collectively (Figure B).
The geometric information of each building is represented by a
triplet of integers [Li, Ri, Hi], where Li and Ri are the x
coordinates of the left and right edge of the ith building,
respectively, and Hi is its height. It is guaranteed that 0 ≤ Li,
Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all
buildings are perfect rectangles grounded on an absolutely flat
surface at height 0.
For instance, the dimensions of all buildings in Figure A are
recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
The output is a list of "key points" (red dots in Figure B) in
the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely
defines a skyline. A key point is the left endpoint of a horizontal
line segment. Note that the last key point, where the rightmost
building ends, is merely used to mark the termination of the skyline,
and always has zero height. Also, the ground in between any two adjacent
buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:
[[2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
"""
class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
sky = [[-1, 0]]
position = set([b[0] for b in buildings] + [b[1] for b in buildings])
live = []
i = 0
for t in sorted(position):
while i < len(buildings) and buildings[i][0] <= t:
heapq.heappush(live, (-buildings[i][2], buildings[i][1]))
i += 1
while live and live[0][1] <= t:
heapq.heappop(live)
h = -live[0][0] if live else 0
self.addsky(sky, t, h)
return sky[1:]
def addsky(self, sky, pos, height):
if sky[-1][1] != height:
sky.append([pos, height])
| true
|
f1fa96f1a965889d29151b30eb26d039a7840bf7
|
MrShashankBisht/Python-basics-
|
/Class 11th complete/7) Continue_Breake_Statement/break.py
| 406
| 4.3125
| 4
|
# this is a programe to break your loop and make your programe to jump unconditionaly from loop
# in this programe we take inpute from user and quit loop(uncondionaly break the middle term )
num = int(input('Enter the Ending limit of the loop '))
for i in range (num):
print("you are in loop and this is looping number := ",i)
if(i % 3 == 0):
break
print('at the end of the loop')
| true
|
194f0af0d91d825b2e4542432d69ee6e54791d99
|
MrShashankBisht/Python-basics-
|
/Class 11th complete/7) Continue_Breake_Statement/Continue.py
| 377
| 4.125
| 4
|
# this is a programe to continue to loop and make your programe to jump unconditionaly from loop
for i in range(0,3):
a = int(input("enter first number"))
b = int(input("enter second number "))
if(b == 0): #here we use conditional operater ==
print("b can't be zero ")
continue
c = a/b
print(c)
print(i)
| true
|
1ecac5332ee8f10bc949e07ef955d3d6e7880124
|
jf4rr3ll/IS211_Assignment6
|
/conversion.py
| 2,876
| 4.3125
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module provides various temperature conversions"""
ABSOLUTE_DIFFERENCE = 273.15
def fahrenheit_to_celsius(degrees):
"""Defines a function that converts Fahrenheit to Celsius.
Args:
degrees (float): Degrees in Fahrenheit.
Returns:
decimal: Degrees converted to Celsius.
Examples:
>>> fahrenheit_to_celsius(212)
Decimal('100')
>>> fahrenheit_to_celsius(32)
Decimal('0')
"""
return (degrees - 32) * 5 / 9
def celsius_to_fahrenheit(degrees):
"""Defines a function that converts Fahrenheit to Celsius.
Args:
degrees (float): Degrees in Fahrenheit.
Returns:
decimal: Degrees converted to Celsius.
Examples:
>>> celsius_to_fahrenheit(100)
Decimal('212')
>>> celsius_to_fahrenheit(0)
Decimal('32')
"""
return (degrees * 1.8) + 32
def celsius_to_kelvin(degrees):
"""Defines a function that converts Celsius to Kelvin
Args:
degrees (float): Degrees in Celsius.
Returns:
decimal: Degrees converted to Kelvin.
Examples:
>>> celsius_to_kelvin(100)
Decimal('373.15')
>>> celsius_to_kelvin(0)
Decimal('273.15')
"""
return degrees + ABSOLUTE_DIFFERENCE
def kelvin_to_celsius(degrees):
"""Defines a function that converts Celsius to Kelvin
Args:
degrees (float): Degrees in Celsius.
Returns:
decimal: Degrees converted to Kelvin.
Examples:
>>> kelvin_to_celsius(0)
Decimal('-273.15')
>>> kelvin_to_celsius(150)
Decimal('123.15')
"""
return degrees - ABSOLUTE_DIFFERENCE
def fahrenheit_to_kelvin(degrees):
"""Defines a function that converts Fahrenheit to Kelvin
Args:
degrees (float): Degrees in Fahrenheit
Returns:
decimal: Degrees convertet to Kelvin
Examples:
>>> fahrenheit_to_kelvin(212)
Decimal('373.15')
>>>fahrenheit_to_kelvin(32)
Decimal('273.16')
"""
return celsius_to_kelvin(fahrenheit_to_celsius(degrees))
def kelvin_to_fahrenheit(degrees):
"""Defines a function that converts Fahrenheit to Kelvin
Args:
degrees (float): Degrees in Fahrenheit
Returns:
decimal: Degrees convertet to Kelvin
Examples:
>>> fahrenheit_to_kelvin(212)
Decimal('373.15')
>>>fahrenheit_to_kelvin(32)
Decimal('273.16')
"""
return celsius_to_fahrenheit(kelvin_to_celsius(degrees))
def meters_to_yards(dist):
return dist * 1.09361
def yards_to_meters(dist):
return dist * 0.9144
def meters_to_miles(dist):
return dist * 0.000621371
def miles_to_meters(dist):
return dist * 1609.34
def yards_to_miles(dist):
return dist * 0.000568182
def miles_to_yards(dist):
return dist * 1760
| false
|
854e176dbc979a4b3b77d0f6b479fddcf3ec144c
|
renatodev95/Python
|
/aprendizado/curso_em_video/desafios/desafio100.py
| 804
| 4.125
| 4
|
# Faça um programa que tenha uma lista chamada números e duas funções chamadas
# sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-
# los dentro da lista e a segunda função vai mostrar a soma entre todos os
# valores PARES sorteados pela função anterior.
from random import randint
from time import sleep
def sorteia(lista):
print('Sorteando 5 valores da lista: ', end='')
for c in range(5):
n = randint(1, 10)
lista.append(n)
print(f'{n} ', end='')
sleep(0.3)
print('PRONTO!')
def somaPar(lista):
soma = 0
for i in lista:
if i % 2 == 0:
soma += i
print(f'Somando os valores pares de {lista}, temos {soma}')
numeros = []
sorteia(numeros)
somaPar(numeros)
| false
|
f0def89d7131bde3120c64444498b86686601291
|
renatodev95/Python
|
/aprendizado/codewars/find_the_unique_number.py
| 582
| 4.25
| 4
|
# There is an array with some numbers. All numbers are equal except for one. Try to find it!
def find_uniq(arr):
arr.sort()
if arr[0] == arr[1]:
return arr[-1]
else:
return arr[0]
lista = [ 1, 1, 1, 2, 1, 1 ] # exemplo
print(find_uniq(lista))
# Primeiramente é feita a organização da lista em ordem crescente. Se o primeiro valor da lista organizada for igual ao segundo valor, o programa deve retornar o último valor da lista. Caso contrário, deve ser retornado o primeiro valor da lista. Em ambos os casos será retornado o valor único.
| false
|
6e9bfef9a57a241c80fe0b28905a4bbbb44a92ee
|
Kylekibet/days_to_birthday
|
/no_of_days_to_birthday.py
| 1,674
| 4.59375
| 5
|
#!/usr/bin/python3
import datetime
# Get todays date
dttoday = datetime.date.today()
print("today is {}".format(dttoday))
while True:
# Get users birtday date.
bday = input("\nPlease enter you birthday(year-month-day) : ")
# Check weather user entered date in the formart provided(year-month-day)
try:
# Split birtday date into three variables year, month and day.
year, month, day = bday.split('-')
break
except:
# Prints out incase of errors occured during spliting of bday
print('Please Enter date in the correct format.\nMake sure you are using python3')
# Converting date enter by user from string to integer
year = int(year)
month = int(month)
day = int(day)
# Creats birthday date form date entered by user
bday = datetime.date(dttoday.year, month, day)
# Calculate how old you are
year_old = dttoday.year - year
# Creates Delta-time for remaining days till birthday
days_remaining = bday - dttoday
# Creates Futher birthday
fbday = datetime.date(dttoday.year+1, month, day)
# Gets Number of days remaining till next year's birthday
days_remaining_to_next_bday = fbday - dttoday
# Conditional statement to check weather birthday has passed or not
if days_remaining.days >= 1:
print('\n{} days remaining to your birthday. You will turn {}.\n'.format(days_remaining.days,year_old))
elif days_remaining.days == 0:
print('\nHappy birthday!!! Today you turn {}. CONGRATULATIONS!!!\n'.format(year_old))
else:
print('\nYou birth day has passed this year. You will turn {} next year.\nDays remaining from today till next birthday is {}\n'.format(year_old + 1, days_remaining_to_next_bday.days))
| true
|
a04d9c7f8d8d7b7685e33f5125b77eac1ed0a763
|
damianquijano/PythonCurso3
|
/Scripts2/Clases/clase.py
| 1,472
| 4.15625
| 4
|
class Animal:#Mayúscula
Mision= "Vivir"
def caminar(self):# self toma el valor del nombre de la variable instanciada u objeto.
print("Caminando")
def soy(self,clase):
print("Soy animal del tipo: "+ clase)
def MiMision(self,vmision):
print("Mi misión es: "+ self.Mision+ " y " + vmision)
#Uso del punto para acceder a los atributos y métodos.
print(Animal.Mision)
#Instancias, perro y gallina son instancias u objetos.
perro=Animal()
perro.caminar()
print(perro.Mision)
perro.soy("Perro")
perro.Mision="Ladrar"
print(perro.Mision)
# gallina=Animal()
# # print(gallina.Mision)
# # gallina.soy("Gallina")
# perro.Mision="Ladrar"
# gallina.Mision="Poner huevos"
#
# print(perro.Mision)
# print(gallina.Mision)
#Uso del self en la clase al referirse a Mision.
# perro.MiMision("Ladrar")
#Demostración que ambos objetos contienen valores diferentes
# perro.Mision="Vivir y ladrar"
# gallina.Mision="Vivir y poner huevos"
# print(perro.Mision) #con las variables no usas paréntesis al final, sólo con los métodos.
# print(gallina.Mision)
#No se puede:
#cerdo=perro()
#Si se puede:
#cerdo=perro #no es una instancia
#Lo siguiente sale error, a menos que quites el self, pero entonces no puede instanciar.Volver más tarde sobre este asunto.
#Animal.soy("Pescado")
#Polimorfismo
# perro=Mamifero("Perro")
# quecome(perro,"carne")
# perro.caminar()
| false
|
c123970f36c7f6c7b9c19a1bf21104ff1f196f27
|
gokadroid/pythonExample-2
|
/pythonExample2.py
| 571
| 4.34375
| 4
|
#Simple program to reverse a string character by character to show usage of for loop and range function
def reverseString(sentence):
reversed=[] #create empty list
for i in range(len(sentence),0,-1): #starting from end, push each character of sentence into list as a character
reversed.append(sentence[i-1])
return "".join(reversed) #join the individual character elements of a list into a string
print(reverseString("My name is xyz")) #returns zyx si eman yM
print(reverseString("Banana")) #returns ananaB
print(reverseString("BeE")) #returns EeB
| true
|
b259a0b53eabfcf8f3f31e4e7742bc1c7312c173
|
abbhowmik/PYTHON-Course
|
/Chapter 6.py/pr no.5.py
| 267
| 4.15625
| 4
|
a = input("Enter a name : \n: ")
list = ["mohan", "rahul", "Ashis", "Arjun", "Sourav", "Amit"]
if(a in list ):
print("The name you choice from the list is present in the list ")
else:
print("The name you choice from the list is not present in the list")
| true
|
6eae4ee9fb61284dfa148637bf2f8c971cae3379
|
abbhowmik/PYTHON-Course
|
/practice 4.py
| 1,022
| 4.53125
| 5
|
# name = input("Enter your name\n")
# print("Good Afternoon," + name)
# a = input("Enter your name\n")
# print("Good Afternoon," + a )
letter = '''Dear <|Name|>,
you are selected!,welcome to our coding family
and we are noticed that you are scoring well in exam as before like. That's why your selected
in our partnership and very very welcome
Date: <|Date|>
'''
name = input("Enter your name\n")
date = input("Enter Date\n")
letter = letter.replace("<|Name|>", name)
letter = letter.replace("<|Date|>", date)
print(letter)
# letter =''' Dear <|Name|>,
# # You are selected! in our company,,,,congratulation;and the date is
# # Date:<|Date|>\n You should come in this particular day and we are\'s celebrating in this date as an important day...
# '''
# name = input("Enter your name\n")
# date = input("Enter date\n")
# letter = letter.replace("<|Name|>", name)
# letter = letter.replace("<|Date|>", date)
# print(letter)
#Assignment Operators
# a = 3
# a += 2
# a -= 2
# a *= 8
# a/= 8
# print(a)
| true
|
fd5a9faf7610477b3ba53f57764a5deed927fe47
|
mkhlvlkv/random
|
/like.py
| 952
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
def like(text, pattern, x='*'):
""" simple pattern matching with * """
if pattern.startswith(x) and pattern.endswith(x):
return pattern.strip(x) in text
elif pattern.startswith(x):
return text.endswith(pattern.strip(x))
elif pattern.endswith(x):
return text.startswith(pattern.strip(x))
elif x in pattern:
start, end = pattern.split(x)
return text.startswith(start) and text.endswith(end)
else:
return text == pattern
if __name__ == '__main__':
text = 'thankspleasesorry'
assert like(text, text)
assert like(text, '*thanks*')
assert like(text, '*please*')
assert like(text, '*sorry*')
assert like(text, 'thanks*')
assert like(text, '*sorry')
assert not like(text, '*thanks')
assert not like(text, '*please')
assert not like(text, 'please')
assert not like(text, 'please*')
assert not like(text, 'sorry*')
| true
|
c707df33626c32086a61f0ae1086b667bf500bce
|
ManiNTR/python
|
/Adding item in tuple.py
| 290
| 4.3125
| 4
|
values=input("Enter the values separated by comma:")
tuple1=tuple(values.split(","))
print("The elements in the tuple are:",tuple1)
key=input("Enter the item to be added to tuple:")
list1=key.split(",")
list2=list(tuple1)
list2.extend(list1)
print("The tuple elements are: ",tuple(list2))
| true
|
2e471dab649540a085eee4b0730b18cca2902002
|
ManiNTR/python
|
/RepeatedItemTuple.py
| 307
| 4.46875
| 4
|
#Python program to find the repeated items of a tuple
values=input("Enter the values separated by comma:")
list1=values.split(",")
tuple1=tuple(list1)
l=[]
for i in tuple1:
if tuple1.count(i)>1:
l.append(i)
print("The repeated item in tuple are: ")
print(set(l))
| true
|
7a8c0d75d17d2fa9464fc8a21375947234310df9
|
SARANGRAVIKUMAR/python-projects
|
/dice.py
| 275
| 4.21875
| 4
|
import random # select a random number
min = 1
max = 6
roll="yes"
while(roll == "yes"or roll=="y"):
print ("dice is rolling\n")
print("the values is")
print (random.randint(min,max)) #selecting a random no from max and min
roll = input("Roll the dices again?")
| true
|
30a86473eb301d9f0bd2a5f8f7a382a451c85b7b
|
NEDianfaiza/python-assignment
|
/Assignment no 4.py
| 1,569
| 4.1875
| 4
|
#Question1:
'''dic={
'first_name':input("Enter First Name"),
'last_name':input("Enter Last Name"),
'age':int(input("Enter Age")),
'city':input("Enter City")
}
print(dic)
dic["qualification"]="High Academic Level"
print(dic)
del dic["qualification"]
print(dic)'''
#Question2:
'''cities={
'Karachi':{
'country':"Pakistan",
'population':"14.91 million",
'fact':"It is called City of Lights"
},
'Chicago':{
'country':"USA",
'population':"2.716 million",
'fact':"It has an iconic John Hancock Center, 1,451-ft."
},
'Dubai':{
'country':"United Arab Emirates",
'population':"3.137 million",
'fact':"It has Burj Khalifa, an 830m-tall tower."
}
}
print(cities['Karachi'])
print(cities['Chicago'])
print(cities['Dubai'])'''
#Question3:
'''while True:
age = int(input("Enter Age:"))
if age<=3:
print('Ticket is free')
elif age>3 and age<=12:
print('Ticket is of $10')
else:
print('Ticket is of $15')'''
#Question4:
'''def favorite_book(title):
print('One of my favorite books is',title)
favorite_book('Cinderella')'''
#Question5:
import random
count = 0
a = random.randint(1, 30)
for count in range(3):
inp = int(input("Enter Number between 1 to 30:"))
if inp==a:
print("Correct")
break
elif a>inp:
print("Hidden num is greater than input")
elif a<inp:
print("Hidden num is smaller than input")
| false
|
34419cbbbbcd1e10d1c6205f2f9ec62a234dfb7e
|
SeanUnland/Python
|
/Python Day 5/main.py
| 1,869
| 4.28125
| 4
|
# for loops
fruits = ["Apple", "Pear", "Peach"]
for fruit in fruits:
print(fruit)
print(fruit + " Pie")
# CODING EXERCISE
# 🚨 Don't change the code below 👇
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
total_height = 0
for height in student_heights:
total_height += height
# print(total_height)
number_of_students = 0
for student in student_heights:
number_of_students += 1
# print(number_of_students)
average_height = round(total_height / number_of_students)
print(average_height)
# CODING EXERCISE
# 🚨 Don't change the code below 👇
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
# max() function returns highest value in array
print(max(student_scores))
# min() function returns lowest value in array
print(min(student_scores))
highest_score = 0
for score in student_scores:
if score > highest_score:
highest_score = score
print(f"The highest score in the class is {highest_score}")
# for loop with range() function
for number in range(1, 11, 3):
print(number)
total = 0
for number in range(1, 101):
total += number
print(total)
# CODING EXERCISE
total = 0
for number in range(2, 101, 2):
total += number
print(total)
# FIZZBUZZ CODING EXERCISE
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("fizz")
elif number % 5 == 0:
print("buzz")
else:
print(number)
| true
|
92d2d9fcf49f71a8e65805fba8bab48eb5eda9a7
|
codingscode/curso_python
|
/Work001/file032_funcoes_c_retorno.py
| 2,400
| 4.28125
| 4
|
"""
Funções com retorno
"""
numeros = [20, 8, 34, 15, 43]
retorno_de_pop = numeros.pop()
print(f'retorno de pop: {retorno_de_pop}')
impressao_print = print('oi')
print(f'retorno de impressao_print: {impressao_print}')
print('-------------------------')
def quadrado_7():
print(7**2) # aqui não é retorno, e sim impressão
ret = quadrado_7() # chamando
print(f'ret: {ret}')
# OBS: Em Python, quando uma função não retorna nenhum valor, o retorno é None
print('-------------')
# refatorando função para te retorno
def triplo_de_4():
return 3*4
ret2 = triplo_de_4()
print(f'ret2: {ret2}')
print(f'{triplo_de_4()} || seu tipo: {type(triplo_de_4())}') # tipo do retorno
# OBS: Não precisamos necessariamente criar uma variavel para receber o retorno de uma
# função. Podemos passar a execução da função para outras funções ou mesmo para um print.
print('------------------------')
"""
Obs sobre a palavra reservada 'return'
1 - ela finaliza a função, ou seja, ela sai da execução da função
2 - Podemos ter, em uma função, diferentes returns
3 - Podemos, em uma função, retornar qualquer tipo de dado e até mesmo múltiplos valores
"""
# exemplo do 1
def numero_10():
print('Estou sendo executado antes do retorno...')
return 10
print('Estou sendo executado após o retorno...') # não é executada
print(numero_10())
print('----------------')
# exemplo do 2
def outra_funcao():
variavel = True
if variavel:
return 4
elif variavel is None:
return 3.2
else:
return 'b'
print(outra_funcao())
print('-----------------')
# exemplo do 3
def outra_funcao2():
return 30, 18, 6, 4
num1, num2, num3, num4 = outra_funcao2()
print(num1, num2, num3, num4)
print(outra_funcao2())
print('---------------------')
# criando função para jogar moeda
from random import random
def jogar_moeda():
valor = random()
if valor > 0.5:
return 'Cara'
return 'Coroa'
print(jogar_moeda())
print('-----------------')
# Erros comuns na utilização do retorno, que na verdade nem é erro, mas sim
# codificação desnecessário
def eh_impar():
numero = 5
if numero % 2 != 0:
return True
else:
return False
print(eh_impar())
| false
|
efb6c8645ad458976400a2c8f16dcb21da9b7768
|
codingscode/curso_python
|
/Work001/file095_MRO.py
| 1,794
| 4.125
| 4
|
"""
POO :
MRO - Method resolution order
Resolução de ordem de métodos -> é a ordem de execução dos métodos (quem será executado primeiro)
Em Python, nós podemos conferir a ordem de execução dos métodos (MRO) de 3 formas:
- Via propriedade da classe __mro__
- Via metodo mro()
- Via help
"""
class Animal:
def __init__(self, nome):
self.__nome = nome
def cumprimentar(self):
return f'Eu sou {self.__nome}'
class Aquatico(Animal):
def __init__(self, nome):
super().__init__(nome)
def nadar(self):
return f'{self._Animal__nome} está nadando.'
def cumprimentar(self):
return f'Eu sou {self._Animal__nome} do mar'
class Terrestre(Animal):
def __init__(self, nome):
super().__init__(nome)
def andar(self):
return f'{self._Animal__nome} está andando'
def cumprimentar(self):
return f'Eu sou {self._Animal__nome} da terra'
class Pinguim(Aquatico, Terrestre):
def __init__(self, nome):
super().__init__(nome)
#def cumprimentar(self): # experimentar descomentar
# return f'Pinguim'
linu = Pinguim('Pingo')
print(linu.andar())
print(linu.nadar())
print(linu.cumprimentar())
"""
saída:
Pingo está andando
Pingo está nadando.
Eu sou Pingo do mar
"""
print('1-----------------------------------------')
from file095_MRO import Pinguim
print('2-----------------------------------------')
print(Pinguim.__mro__)
print('3-----------------------------------------')
print(Pinguim.mro())
print('4-----------------------------------------')
help(Pinguim)
print('5-----------------------------------------')
print('6-----------------------------------------')
| false
|
27d1b401280b87feb6208faeb48d5026e8b399e5
|
codingscode/curso_python
|
/Work001/file040_listas_aninhadas.py
| 1,167
| 4.46875
| 4
|
"""
algumas linguagens de programação possuem uma estrutura de dados chamadas de arrays:
- unidimensionais (arrays/vetores), - multidimensionais(matrizes ou listas aninhadas)
"""
listas = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(listas)
print(type(listas))
print(listas[1])
print(listas[2][1])
print(listas[0][2])
print(listas[2])
print(listas[-1])
print(listas[-2][-1])
print('----------------------------------')
# Iterando com loops em uma lista aninhada
for el_linha in listas:
for el_coluna in el_linha:
print(el_coluna)
print('------------------------------')
# Iterando com list comprehension
[[print(el) for el in linha] for linha in listas]
print('------------------------------')
#gerando um tabuleiro/matriz
tabuleiro = [[numero for numero in range(1, 4)] for valor in range(1, 5)] # [[0 for numero in range(1, 4)] for valor in range(1, 4)]
print(tabuleiro)
# gerando jogadas para o jogo da velha
velha = [['x' if numero % 2 == 0 else 'O' for numero in range(1, 4)] for valor in range(1, 4)]
print(velha)
# gerando valores iniciais
print([['*' for i in range(1, 4)] for j in range(1, 3)])
| false
|
af62551ed65edef450040bfc1f0a5b1c96a8d804
|
codingscode/curso_python
|
/Work001/file039_list_comprehension2.py
| 1,960
| 4.25
| 4
|
"""
List Comprehension
Usando a podemos gerar novas listas com dados processados a partir de outro iterável.
# Sintaxe da List Comprehension
[dado for dado in iteravel]
"""
numeros = [3, 7, 2, 50]
res = [cada*10 for cada in numeros]
print(res)
def divisivelp2(valor):
return valor % 2 == 0
res2 = [divisivelp2(cada) for cada in numeros]
print(res2)
print('--------------------')
# list comprehension x loop
numeros_dobrados = []
for cada in numeros:
numeros_dobrados.append(cada*2)
print(numeros_dobrados)
print([cada*2 for cada in numeros])
print('--------------------')
nome = 'Curso Python'
print([letra.upper() for letra in nome])
def caixa_alta(valor): # string é imutavel
#print('--------------', valor.replace(valor[2], valor[2].upper()))
return valor.replace(valor[2], valor[2].upper(), 1)
amigos = ['vicente', 'larissa', 'rafaela', 'simom']
transportes = ['bicicleta', 'onibus', 'carro', 'aviao', 'navio']
print([amigo[0].upper() for amigo in amigos])
print([amigo.title() for amigo in amigos])
print([caixa_alta(amigo) for amigo in amigos])
print([caixa_alta(cada) for cada in transportes])
print('----------------------------')
print([indice*3 for indice in range(1, 6)])
print([bool(cada) for cada in [0, [], '', True, 1, 3.14]])
print([str(cada) for cada in [2, 3, 4, 5]])
print('----------------------------------\n parte 2\n')
"""
Podemos adicionar estruturas condicionais lógicas às nossas list comprehension
"""
numeros2 = [3, 7, 42, 21, 12, 15, 30]
print(numeros2)
pares = [cada for cada in numeros2 if cada % 2 == 0]
print('pares:', pares)
print('pares:', [cada for cada in numeros2 if not cada % 2]) # 0 é False
print('impares:', [cada for cada in numeros2 if cada % 2]) # numero positivo é True
print('------------------------')
res3 = [cada*2 if cada % 2 == 0 else cada/2 for cada in numeros2]
print(res3)
| false
|
e9d862d3ede36849b703a4c24bac276c5f493c5e
|
codingscode/curso_python
|
/ifsp/012 - rasc.py
| 1,278
| 4.40625
| 4
|
# Orientação a Objetos
"""
"""
class Usuario:
contador = 0
def __init__(self, nome, email): # construtor
self.nome = nome
self.email = email
Usuario.contador += 1
def diga_ola(self):
print(f'Olá, meu nome é {self.nome} e meu email é {self.email}')
usuario1 = Usuario(nome="Simon", email="simon11@gmail.com")
usuario1.diga_ola()
print(usuario1.nome)
# alterando e acessando propriedades
usuario1.nome = 'Robson'
usuario1.diga_ola()
print(usuario1.nome)
print(f'usuario1 tem propriedade "nome" ?: {hasattr(usuario1, "nome")} ')
print(f'usuario1 tem propriedade "idade" ?: {hasattr(usuario1, "idade")} ')
print(f'acessar valor email de usuario1 : {getattr(usuario1, "email")}')
setattr(usuario1, 'nome', 'Mauricio S.')
setattr(usuario1, 'idade', 23)
print(f'acessar valor nome de usuario1 : {getattr(usuario1, "nome")}')
print(f'acessar idade de usuario1 : {getattr(usuario1, "idade")}')
# delattr(usuario1, 'idade')
print(f'nome : {getattr(usuario1, "nome")}')
print('----------------------')
usuario2 = Usuario(nome="Raul", email="raul2@gmail.com")
print(Usuario.contador) # quantas vezes a classe Usuario é recebida por uma constante
print('----------------------')
| false
|
e770de7e9bac485af103a2d747628f06e9dff368
|
codingscode/curso_python
|
/Work001/file044_map.py
| 1,393
| 4.59375
| 5
|
"""
Map
Map ≠ mapas
- mapeamento função valor
- Com map, fazemos mapeamento de valores função.
"""
import math
def area(raio):
return math.pi * raio**2
print(area(2))
print(area(1))
print('---------------------')
raios = [0.5, 3, 4.2, 8]
# Forma comum
areas = []
for r in raios:
areas.append(area(r))
print(areas)
print('------------------')
# Forma 2: usando Map
areas2 = map(area, raios) # função/um iteravel
print(list(areas2))
print(areas2)
print(list(areas2)) # é usado apenas uma vez
print(type(areas2))
print(type(area))
print(type(raios))
print('------------------')
# Forma 3: Map com lambda
print(list(map(lambda r: math.pi * r ** 2, raios)))
# OBS: Após utilizar a função map() depois da primeira utilização do resultado, ele zera.
print('------------------')
"""
Para fixar Map
Temos dados iteraveis
dados: a1, a2, ..., an
Temos uma função:
Função: f(x)
Utilizamos a função map(f, dados) onde map irá 'mapar' cada elemento dos dados e aplicar a função.
O Map object: f(a1), f(a2), f(...), ..., f(an)
"""
cidades = [('campo grande', 31), ('porto alegre', 23), ('rio de janeiro', 34), ('teresina', 38), ('nova york', 12)]
print(cidades)
# f = 9/5 * (celsius) + 32
c_para_f = lambda dado: (dado[0], (9/5)*dado[1] + 32)
print(list(map(c_para_f, cidades)))
| false
|
7d95f0f76e21a20a13047bd2686f6f64c51aeb02
|
codingscode/curso_python
|
/Work001/file048_generators.py
| 2,133
| 4.21875
| 4
|
"""
Generators (Generator Expression)
= tuple comprehensions
"""
nomes = ['Cecília', 'Caroline', 'Cassia', 'Carl', 'Roberto']
print(any(nome[0] == 'C' for nome in nomes)) # pelo menos 1
print(any([nome[0] == 'C' for nome in nomes])) # aqui não é generator
print(any((nome[0] == 'C' for nome in nomes))) # aqui é generator
print((nome[0] == 'C' for nome in nomes)) # é generator
print([nome[0] == 'C' for nome in nomes])
print({nome[0] == 'C' for nome in nomes})
print('-------------------------------')
generator = (nome[0] == 'C' for nome in nomes)
print(tuple(generator)) # usado só uma vez
print(tuple(generator))
print('-------------------------------')
# list comprehension
res1 = [nome[0] == 'C' for nome in nomes]
print(type(res1))
print(res1)
# generator -> é mais performático
res2 = (nome[0] == 'C' for nome in nomes)
print(type(res2))
print(res2)
print('-------------------------------')
from sys import getsizeof
# getsizeof() -> retorna a quantidade de bytes em memória do elemento passado como parametro
print(getsizeof('Python Coding')) # quanto de bytes ocupa em memória
print(getsizeof(2))
print(getsizeof(14))
print(getsizeof(True))
print('-------------------------------')
# Gerando uma lista de numeros com List comprehension
list_comp = getsizeof([x*10 for x in range(50)])
# Gerando uma lista de numeros com Set comprehension
set_comp = getsizeof({x*10 for x in range(50)})
# Gerando uma lista de numeros com Dictionary comprehension
dict_comp = getsizeof({x: x*10 for x in range(50)})
# Gerando uma lista de numeros com Generator
gen = getsizeof(x*10 for x in range(50))
print('mesma tarefa, gasto em memória:')
print(f'list comprehension: {list_comp} bytes')
print(f'set comprehension: {set_comp} bytes')
print(f'dictionary comprehension: {dict_comp} bytes')
print(f'generator expression: {gen} bytes')
print('-------------------------------')
# Iterando com Generator Expression
gen2 = (cada * 10 for cada in range(10))
print(gen2)
print(type(gen2))
for num in gen2:
print(num)
| false
|
096fb3fe3a21ca1ec5ef8e54ee299b813905ad41
|
codingscode/curso_python
|
/Work001/file122_tipos_em_comentarios.py
| 1,176
| 4.125
| 4
|
"""
Tipos em comentarios
"""
import math
"""
def circunferencia(raio):
# type: (float) -> float
return 2 * math.pi * raio
print(circunferencia(5)) # nao dá erro
#print(circunferencia('geek'))
"""
#"""
def circunferencia(raio): # def circunferencia(raio: float) -> float:
# type: (float) -> float
return 2 * math.pi * raio
print(circunferencia(5)) # nao dá erro
print(circunferencia('geek')) # no terminal deveria dar erro
#"""
"""
testar tambem no terminal: mypy file122_tipos_em_comentarios.py
"""
print('1---------------------')
def cabecalho(texto, alinhamento=True):
# type: (str, bool) -> str
if alinhamento:
return 'a'
else:
return 'b'
print(cabecalho(texto=43, alinhamento='geek'))
print(cabecalho(texto=43, alinhamento=0))
print('2---------------------')
def cabecalho2(
texto, # type: str
alinhamento=True # type: bool
): # type: (...) -> str
if alinhamento:
return 'a'
else:
return 'b'
print(cabecalho2(texto=42, alinhamento='geek'))
nome = 'Geek University' # type: str
print('3---------------------')
| false
|
63ac44be4b0e3bb805c7ea95cd7a9f782902ab13
|
python240419/05.07.2019
|
/dictionary.py
| 563
| 4.15625
| 4
|
# Dictionary
# Hashmap -- key : value
# key may appear only once - single appearence
#12 -- moshe
#14 -- moshe
#12 -- danny
# 2 keys have the same value
#
#
# 3,4,5 moshe, danny, tamar
#
# key - may be anything
# [1,2,3] #adress 4005
# [1,2,3]
# create dictionary for cities population
# TLV, LONDON, PARIS, TOKYO
# input city name -- print population
popMap = { 'TEL AVIV' : 443939, 'LONDON' : 8825000, 'PARIS' : 0,'TOKYO' : 13929286}
cityName = input("Please enter a city name: ")
print(f'{cityName} population is: {popMap[cityName.upper()]}')
| false
|
90ab88a33387a70de53d0eea736072ed7faad3ff
|
olszebar/tietopythontraining-basic
|
/students/marta_herezo/lesson_02/for_loop/adding_factorials.py
| 257
| 4.15625
| 4
|
# Given an integer n, print the sum 1!+2!+3!+...+n!
print('Enter the number of factorials to add up: ')
n = int(input())
factorial = 1
sum = 0
for i in range(1, n + 1):
factorial = factorial * i
sum += factorial
print('Result = ' + str(int(sum)))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.