blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5f111a2967558285ab96d83966b029eebe29a3d2 | saisrikar8/C1-Dictionary | /main.py | 1,797 | 4.125 | 4 | '''
03/08/2021
Review
List:
mutable, []
List functions
LIST.insert(INDEX, ELEMENT)
LIST.append(ELEMENT)
LIST.remove(ELEMENT)
LIST.pop(INDEX)
LIST[INDEX] = ELEMENT
Tuple
immutable, ()
___________________________________________________
Dictionary
Another type of list, stores data/values inside the curly brackets, {}.
Similar to a list, it is mutable, however the index is a key, which is liked to data/values.
Ex.
student = {}
student["name"] = "John"
student["age"] = 12
student["weight"] = "120lbs"
student["school"] = "Evergreen"
student["Python"] = True
print(student["age"])
print(student["weight"])
print(student["Python"])
Time
Handles time-related tasks
Formula
import time # Importing the time library
Useful Time functions
1. time.time()
- returns floating-point numbers in seconds passed since epoch(Jan. 1st 1970, 00:00 UTC)
- Use it for Date arthmetic (etc. duration)
import time
print (time.time())
2. time.sleep(NUMBER)
- Suspends(delays) execution of the current thread for the given number of seconds
import time
for x in range(10):
print(str(x) + " seconds has passed")
time.sleep(60)
'''
# Exercise 1
'''
Expected output:
*
* *
* * *
* * * *
* * * * *
'''
print("Exercise 1")
for x in range(5):
print("* " * (x + 1))
# Exercise 2
'''
Expected output:
* * * * *
* * * *
* * *
* *
*
'''
print("\nExercise 2")
for i in range(5):
print("* " * (5 - i))
#Exercise 3
'''
*
* *
* * *
* * * *
* * * * *
'''
print("\nExercise 3")
for y in range(5):
print(" " * 3 * (4 - y) + "* " * (y+1))
#Exercise 4
print("\nExercise 4")
'''
* * * * *
* * * *
* * *
* *
*
'''
for z in range(5):
print(" " * 3 * z + "* " * (5 - z)) | true |
a010b033f58c902cfcf9979e4ab456c78795f2d7 | chernish2/py-ml | /01_linear_regression_straight_line.py | 2,976 | 4.3125 | 4 | # This is my Python effort on studying the Machine Learning course by Andrew Ng at Coursera
# https://www.coursera.org/learn/machine-learning
#
# Part 1. Linear regression for the straight line y = ax + b
import pandas as pd
import numpy as np
from plotly import express as px
import plotly.graph_objects as go
# Hypothesis function, or prediction function
def hypothesis(x, θ):
return x[0] * θ[0] + x[1] * θ[1]
# Cost function aka J(θ) is MSE (Mean Squared Error)
def cost_function(x, y, θ):
m = len(x) # number of rows
sqr_sum = 0
for i in range(m):
sqr_sum += pow(hypothesis(x[i], θ) - y[i], 2)
return sqr_sum / (2 * m)
# Gradient descent algorithm
def gradient_descent(x, y, α, normalize=True):
steps_l = [] # list for visualizing data
n_iter = 500 # number of descent iterations
visualize_step = round(n_iter / 20) # we want to have 20 frames in visualization because it looks good
m = len(x) # number of rows
θ = np.array([0, 0])
# normalizing feature x_1
x_norm = x.copy()
if normalize:
max_x1 = max(np.abs(x[:, 1]))
x_norm[:, 1] = x_norm[:, 1] / max_x1
# gradient descent
for iter in range(n_iter):
sum_0 = 0
sum_1 = 0
for i in range(m):
y_hypothesis = hypothesis(x_norm[i], θ)
sum_0 += (y_hypothesis - y[i]) * x_norm[i][0]
sum_1 += (y_hypothesis - y[i]) * x_norm[i][1]
if iter % visualize_step == 0: # add visualization data
steps_l.append([x[i][1], y_hypothesis, iter])
new_θ_0 = θ[0] - α * sum_0 / m
new_θ_1 = θ[1] - α * sum_1 / m
θ = [new_θ_0, new_θ_1]
cost = cost_function(x, y, θ)
if iter % visualize_step == 0: # debug output to see what's going on
print(f'iter={iter}, cost={cost}, θ={θ}')
print(f'Gradient descent is done with θ_0={θ[0]} and θ_1={θ[1]}')
# visualizing gradient descent
df = pd.DataFrame(np.array(steps_l), columns=['x', 'y', 'step'])
fig = px.scatter(df, x='x', y='y', animation_frame='step')
fig.add_trace(go.Scatter(x=x[:, 1], y=y, mode='markers'))
global figure_n
fig.update_layout(title={'text': f'Figure {figure_n}. α={α}, normalize={normalize}', 'x': 0.5, 'y': 0.9}, font={'size': 18})
fig.show()
figure_n += 1
# Generating dataset for our function y = ax + b
# In this case y = 36.78 * x - 150
def generate_dataset():
a = 36.78
b = -150
x = np.arange(-10, 10, step=0.1)
y_dataset = a * x + b
noise_ar = np.random.random(y_dataset.shape) * 100 # add some noise to the data
x_dataset = np.array([[1, x] for x in x]) # adding feature x_0 = 1
y_dataset = y_dataset + noise_ar
return x_dataset, y_dataset
x, y = generate_dataset()
α_l = [0.0605, 0.06, 0.05975, 0.05]
figure_n = 1
for α in α_l:
gradient_descent(x, y, α, False)
α_l = [0.3, 0.03]
for α in α_l:
gradient_descent(x, y, α)
| true |
21f96178fa5517739532612710192bcb8edb93c4 | akankshashetty/python_ws | /Q5.py | 341 | 4.34375 | 4 | """5. Write a program to print the Fibonacci series up to the number 34.
(Example: 0,1,1,2,3,5,8,13,… The Fibonacci Series always starts with 0 and 1, the numbers that follow are arrived at by
adding the 2 previous numbers.)"""
a = 0
b = 1
c = 0
print(a,b,end=" ")
while not c==34:
c=a+b
print(c,end=" ")
a,b=b,c
| true |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
b74c18f10daa14b813dff047f81d76fa6fef9edc | lyoness1/skills-cd-data-structures-2 | /recursion.py | 2,907 | 4.59375 | 5 | # --------- #
# Recursion #
# --------- #
# 1. Write a function that uses recursion to print each item in a list.
def print_item(my_list):
"""Prints each item in a list recursively.
>>> print_item([1, 2, 3])
1
2
3
"""
if not my_list:
return
print my_list[0]
print_item(my_list[1:])
# 2. Write a function that uses recursion to print each node in a tree.
def print_all_tree_data(tree):
"""Prints all of the nodes in a tree.
>>> class Node(object):
... def __init__(self, data):
... self.data=data
... self.children = []
... def add_child(self, obj):
... self.children.append(obj)
...
>>> one = Node(1)
>>> two = Node(2)
>>> three = Node(3)
>>> one.add_child(two)
>>> one.add_child(three)
>>> print_all_tree_data(one)
1
2
3
"""
print tree.data
for child in tree.children:
print_all_tree_data(child)
# 3. Write a function that uses recursion to find the length of a list.
def list_length(my_list):
"""Returns the length of list recursively.
>>> list_length([1, 2, 3, 4])
4
"""
if not my_list:
return 0
return 1 + list_length(my_list[1:])
# 4. Write a function that uses recursion to count how many nodes are in a tree.
nodes = []
def num_nodes(tree):
"""Counts the number of nodes.
>>> class Node(object):
... def __init__(self, data):
... self.data=data
... self.children = []
... def add_child(self, obj):
... self.children.append(obj)
...
>>> one = Node(1)
>>> two = Node(2)
>>> three = Node(3)
>>> four = Node(4)
>>> one.add_child(two)
>>> one.add_child(three)
>>> two.add_child(four)
>>> num_nodes(one)
4
"""
# nodes.append(tree.data)
# if tree.children:
# for child in tree.children:
# num_nodes(child)
# return len(nodes)
# I spent three hours on this one... it's super easy to use a list or counter
# globally, but I can't, for the life of me, figure out how to do this without
# the global variable :(
count = 1
for child in tree.children:
count += num_nodes(child)
return count
# UPDATE: After I wrote lines 86-94, I came up with lines 96-99 in about 10 min
# I've never felt such a love-hate relationship with anyone or anything as I do
# with recursion!!
#####################################################################
# END OF ASSIGNMENT: You can ignore everything below.
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "ALL TESTS PASSED. GOOD WORK!"
print
| true |
5b95b484392c7e58a9bf5a98cb8db1cf91e400b4 | jorgeaugusto01/DataCamp | /Data Scientist with Python/21_Supervised_Learning/Cap_2/Pratices4_5.py | 2,944 | 4.21875 | 4 | #Train/test split for regression
#As you learned in Chapter 1, train and test sets are vital to ensure that your supervised learning model
# is able to generalize well to new data. This was true for classification models, and is equally true for
# linear regression models.
#In this exercise, you will split the Gapminder dataset into training and testing sets,
# and then fit and predict a linear regression over all features.
# In addition to computing the R2 score, you will also compute the Root Mean Squared Error (RMSE),
# which is another commonly used metric to evaluate regression models.
# The feature array X and target variable array y have been pre-loaded for you from the DataFrame df.
# Import necessary modules
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
import pandas as pd
import numpy as np
# Read the CSV file into a DataFrame: df
df = pd.read_csv('../../DataSets/gapminder/gapminder.csv')
# Create arrays for features and target variable
y = df['life'].values
X = df['fertility'].values
# Reshape X and y
y = y.reshape(-1, 1)
X = X.reshape(-1, 1)
# Create training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=42)
# Create the regressor: reg_all
reg_all = LinearRegression()
# Fit the regressor to the training data
reg_all.fit(X_train, y_train)
# Predict on the test data: y_pred
y_pred = reg_all.predict(X_test)
# Compute and print R^2 and RMSE
print("R^2: {}".format(reg_all.score(X_test, y_test)))
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print("Root Mean Squared Error: {}".format(rmse))
#5-fold cross-validation
#Cross-validation is a vital step in evaluating a model. It maximizes the amount of data that is used to
# train the model, as during the course of training, the model is not only trained, but also tested on all of
# the available data.
# In this exercise, you will practice 5-fold cross validation on the Gapminder data.
# By default, scikit-learn's cross_val_score() function uses R2 as the metric of choice for regression.
# Since you are performing 5-fold cross-validation, the function will return 5 scores. Your job is to compute
# these 5 scores and then take their average.
# The DataFrame has been loaded as df and split into the feature/target variable arrays X and y. The modules pandas and numpy have been imported as pd and np, respectively.
# Import the necessary modules
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
# Create a linear regression object: reg
reg = LinearRegression()
# Compute 5-fold cross-validation scores: cv_scores
cv_scores = cross_val_score(reg, X, y, cv=5)
# Print the 5-fold cross-validation scores
print(cv_scores)
print("Average 5-Fold CV Score: {}".format(np.mean(cv_scores)))
| true |
e56eb114b90742ca083d9812ce7e11e5d9504c2e | daniloaleixo/30DaysChallenge_HackerRank | /Day08_DictionairesAndMaps/dic_n_maps.py | 2,134 | 4.3125 | 4 | # Objective
# Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video!
# Task
# Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead.
# Note: Your phone book should be a Dictionary/Map/HashMap data structure.
# Input Format
# The first line contains an integer, , denoting the number of entries in the phone book.
# Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend's name, and the second value is an -digit phone number.
# After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.
# Note: Names consist of lowercase English alphabetic letters and are first names only.
# Constraints
# Output Format
# On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise, print the full and in the format name=phoneNumber.
# Sample Input
# 3
# sam 99912222
# tom 11122222
# harry 12299933
# sam
# edward
# harry
# Sample Output
# sam=99912222
# Not found
# harry=12299933
n = int(raw_input())
phone_book = {}
inputs = []
for i in range(0, n):
line = raw_input().strip().split(' ')
phone_book[line[0]] = line[1]
# print phone_book
# line = raw_input().strip()
# # print line
# while line != None and len(line) > 0:
# inputs.append(line)
# line = raw_input().strip()
while True:
try:
line = raw_input().strip()
inputs.append(line)
except EOFError:
break
# print inputs
for elem in inputs:
if elem in phone_book:
print elem + '=' + phone_book[elem]
else:
print 'Not found'
# print inputs, phone_book
| true |
b8c2b94be9e48ae10bf5c47817f6af19109ced0c | LouisTuft/RSA-Calculator-and-Theory | /1.RSAValues.py | 2,147 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 30 02:13:03 2020
@author: Louis
"""
"""
The theory behind RSA is explained in the Readme file in the repository. This
python file is the first of three that form a complete RSA system. This file
in particular will allow you to construct your own set of keys for RSA. The
goal of this file is to establish the size of primes required to encrypt the
message you have and then provide you with an encryption and decryption key.
Currently the user has to input there own encryption key, in the future I hope
to add a 'choosingE():' function thatwill allow the user to pick from one of
many random possible values of e or input their own. Due to this the user is
required to know how to pick a 'good' value for e (and p,q), this information
can be found in the readme file.
"""
def valuesRSA(p,q): #Calculates n and phi(n) from two input primes p,q.
n = p*q
phi = (p-1)*(q-1)
return [n,phi]
def calculatingD(e,phi): #After choosing the encryption key, this function
if e == 0: #calculates the decryption key. (Bezout's Theorem).
return (phi, 0, 1)
else:
gcd, x, y = calculatingD(phi%e,e)
return (gcd, y-(phi//e)*x,x)
def signOfD(d,phi): #Occasionally d is negative, but since we work
if d < 0: #modulo phi(n), we can change this easily.
return d + phi
else:
return d
def main():
message = input('Input the message you wish to encrypt with RSA: ')
p = int(input('Input a prime with roughly ' + str(len(message)+1) + ' digits: '))
q = int(input('Input another prime with at least ' + str(2*len(message)-len(str(p))+1) + ' digits: '))
n = valuesRSA(p,q)[0]
phi = valuesRSA(p,q)[1]
e = int(input('Input a value for e: '))
print('')
d = calculatingD(e,phi)[1]
d = signOfD(d,phi)
print('message = ' + message)
print('p = ' + str(p))
print('q = ' + str(q))
print('n = ' + str(n))
print('phi(n) = ' + str(phi))
print('e = ' + str(e))
print('d = ' + str(d))
return
main()
"""
The RSA encryption key is (e,n) and decryption key is (d,n).
"""
| true |
b14350b1729a7ad4dca30edae721cd6f82b04d42 | anirudhagaikwad/Python10Aug21 | /PythonWorkPlace/Python_DataTypes/Manipulations/PythonSetExmpl.py | 709 | 4.1875 | 4 |
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)#Union is performed using | operator.
print(A.union(B))#union using Function
#Intersection of A and B is a set of elements that are common in both sets.
print(A & B) #Intersection is performed using & operator.
# Intersection can be accomplished using the method intersection().
print(A.intersection(B))
print(A - B)#Difference is performed using - operator.
""""
Difference of A and B (A - B) is a set of elements that are only in A
but not in B.
B - A is a set of element in B but not in A.
"""
#Same can be accomplished using the method difference().
print(A.difference(B)) | true |
f70aa44924847d48183279a297ef6cda93f1b3d0 | anirudhagaikwad/Python10Aug21 | /PythonWorkPlace/Python_DataTypes/Python_Tuple.py | 1,153 | 4.6875 | 5 | #tuples are immutable.
#defined within parentheses () where items are separated by commas
#Tuple Index starts form 0 in Python.
x=('python',2020,2019,'django',2018,20.06,40j,'python') #Tuple
# you can show tuple using diffrent way
print('Tuple x : ',x[:]) # we can use the index with slice operator [] to access an item in a tuple. Index starts from 0.
print('Tuple x : ',x[:])
print('Tuple x : ',x[0:])
print('Tuple x : ',x)
# extract/access specific element from tuple
print('Tuple x[0] : ',x[0])
print('Tuple x[1:5] : ',x[1:5]) # characters from position(index) 1 (included) to position(index) 5 (excluded i.e. 5-1) it will print index 1 element to index 4 element
""""
Python allows negative indexing for its sequences.The index of -1 refers to the last item,
-2 to the second last item and so on.
"""
print('Tuple negative indexing x[-2]: ',x[-2])
print('Tuple negative indexing x[0:-4]: ',x[0:-4])
print('Tuple negative indexing x[:-4]: ',x[:-4])
z =x.count('python') # Returns the number of items x
print(z,'number of python string found in tuple')
z=x.index(2019) # Returns the index of the item
print('index number of 2019 is : ',z)
| true |
c3f0fe5252715fd2df8084c40d654f73913977b7 | anirudhagaikwad/Python10Aug21 | /PythonWorkPlace/Python_DataTypes/Python_Dictionary.py | 1,315 | 4.5625 | 5 |
""""
dictionaries are defined within braces {}
with each item being a pair in the form key:value.
Key and value can be of any type.
"""
#keys must be of immutable type and must be unique.
d = {1:'value_of_key_1','key_2':2} #Dictionary
print('d is instance of Dictionary : ',isinstance(d,type(d)))
#To access values, dictionary uses keys.
print("using key access value d[1] = ", d[1])
print("using key access value d['key_2'] = ", d['key_2'])
print('access values using get() : ',d.get(1))#access values using get()
# update value
d[1] = 'Banana'
print('update d[1] = Banana : ',d[1])
# add item
d['Dry Fruit'] = 'Badam'
print('add item d[Dry Fruit] = Badam',d)
print('d.items() :',d.items()) #To access the key value pair, you would use the .items() method
print('d.keys() :',d.keys()) #To access keys separately use keys() methos
print('d.values() :',d.values()) #To access values separately use values() methos
#print("d[2] = ", d[2]); # Generates error
# remove dict pair
d.pop(1) #remove a particular item, returns its value
print('after d.pop(1) : ',d)
d.popitem() #remove an arbitrary item,return (key,value)
print('after d.popitem() : ',d)
# remove all items
d.clear()
print('after use function clear() : ',d)
# delete the dictionary itself
del d
#print('after delete dictionary : ',d) | true |
a0fe310c8be1f85b9fbeb61c83c833104ebdd6ef | morganhowell95/TheFundamentalGrowthPlan | /Data Structures & Algorithms/Queues & Stacks/LLImplOfStack.py | 1,460 | 4.28125 | 4 | #Stack is a Last In First Out (LIFO) data structure
#Data is stored by building the list "backwards" and traversing forwards to return popped values
class Stack:
def __init__(self):
self.tail = None
def push(self, d):
#create new node to store data
node = Stack.Node(d)
#link new node "behind" the old node
if not self.is_empty():
old_node = self.tail
self.tail = node
self.tail.next = old_node
#if no linked list currently exists, create a node associated with tail pointer
else:
self.tail = Stack.Node(d)
def peek(self):
if not self.is_empty():
return self.tail.data
else:
return None
def pop(self):
if not self.is_empty():
rdata = self.tail.data
self.tail = self.tail.next
return rdata
else:
return None
def is_empty(self):
return not self.tail
#Local class representing the nodes of our linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
#Minor crude tests of our Stack
s = Stack()
for i in range(0,10):
s.push(i)
def notExpected(op):
raise Exception('Stack not functioning as expected on ' + op)
if s.is_empty() != False:
notExpected('empty')
if s.peek() != 9:
notExpected('peek')
if s.pop() != 9:
notExpected('pop')
if s.peek() != 8:
notExpected('peek')
while not s.is_empty():
s.pop()
if s.is_empty() != True:
notExpected('empty')
print ("Your stack works as expected")
| true |
14901244b9c06406fa9c8e721febc1108f2885c9 | masterbpk4/matchmaker_bk | /matchmaker_bk.py | 2,927 | 4.1875 | 4 | ##Brenden Kelley 2020 All Rights Reserved
##Just kidding this is all open source
##Just make sure you credit me if you realize that this is a marvel of coding genius and decide to use it in the future
##First we need to get our questions placed in an array and ready to be pulled on command, we'll also need an empty array to keep track of the user's score
question = ["- Cats are better than dogs." , "- Mountains are better than beaches." , "- Sitting down and watching anime is a good pastime" , "- I enjoy tabletop rpgs or would be interested in trying them." , "- I prefer sweet snacks over salty ones."]
score = []
finalscore = []
##We need an introduction to our program
def Intro():
print("=".center(120, "="))
print("Hello and Welcome to The Ultimate Matchmaker! You will be given a series of statements where you are asked to rate how\n much you agree or disagree with them on a scale of 1 to 5 where 1 is strongly disagree and 5 is strongly agree.")
print("=".center(120, "="))
##Next we need to figure out what to do with user inputs
def userInputs():
k = 0
while k < 1:
try:
k = int(input("Your answer: "))
if k == 1 or k == 2 or k == 3 or k == 4 or k == 5:
score.append(k)
else:
raise ValueError
except ValueError:
k = 0
print("Please enter a number between 1 and 5")
##Next we need the function to ask the questions to the user
def askquestions():
for i in range(0, len(question)):
print("=".center(120, "="))
print("Question #"+str(i+1))
print(question[i])
print("=".center(120, "="))
print("Please Type Your Answer: ")
userInputs()
print("=".center(120, "="))
##Now we need to do math on the scores to determine if the user is a good match
def scorecalcs():
for n in range(0, len(score)):
if n == 0 or n == 4:
p = int(score[n])
p = 5 - abs(5-p)
finalscore.append(p)
elif n == 1 or n == 3:
p = int(score[n])
p = 5 - abs(5-p)
p = 3 * p
finalscore.append(p)
elif n == 2:
p = int(score[n])
p = 5 - abs(5-p)
p = p * 2
finalscore.append(p)
##And now we need to make the final score
def results():
total = 0
for m in range(0, len(finalscore)):
total = total + finalscore[m]
total = total * 2
if total < 40:
print("I hope we never meet, you got a score of: " + str(total))
elif total >= 40 and total < 80:
print("I think we would be good friends, you got a score of: " + str(total))
elif total >= 80:
print("I think we were made for each other! You got a score of: "+ str(total))
##Now it's time to put everything we've done to work
Intro()
input("Press any key to continue. . .")
askquestions()
scorecalcs()
results() | true |
6bf9042e0c296379fbe1c557904bfc04c224f31f | rajatpanwar/python | /Dictonary/Dictionary.py | 2,580 | 4.625 | 5 | /// A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets
<--------example1------->
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
<-------example2--------->
// how to access the element in dictionary
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
x=detail["Name"]
print(x)
<-----------example 3----- ------------>
//access the element
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
print("Name :%s "%detail["Name"])
print("sapid :%d "%detail["sapid"])
print("Roll no :%d "%detail["Roll no"])
print("course :%s "%detail["course"])
<------------example4------------------->
// add new data in the dictionary
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
print(detail)
print("<------enter new detail---------->")
detail["Name"]=input("Name ")
detail["sapid"]=int(input("sapid "))
detail["Roll no"]=int(input("Roll no "))
detail["course"]=input("course ")
print("-----printing the new data-------")
print(detail)
<-------example5-------------->
//similiar to example3
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
x=detail.get("Name") //we can use get function to access the element
print(x)
<-------example6------------>
//print all the attribute on by one using for loop
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
for i in detail:
print(i) //output is --- Name,sapid,Rollno,course
<-------------example7--------------------->
//print all the value of key attribute
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
for i in detail:
print(detail[i])
//output is--- Rajat Panwar
500069414
80
B.Tech
<------------example8------------------------>
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
for i,j in detail.items(): //using items() function we can print key and value both
print(i,j)
<-----------------------example9---------------->
detail= {
"Name":"Rajat panwar",
"sapid":500069414,
"Roll no":80,
"course":"B.Tech",
}
del detail["sapid"] // use del we can remove the key and value for the dctionary
print(detail)
| true |
a0444ca1776cae4cc5a73af7e82a9dc4f4577080 | mornville/Interview-solved | /LeetCode/September Challenge/word_pattern.py | 950 | 4.21875 | 4 | """
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
"""
class Solution(object):
def wordPattern(self, pattern, str):
words = str.split(' ')
if len(set(list(pattern))) != len(set(words)):
return False
wordDict = {}
index = 0
length = len(pattern)
for i in words:
if index >= length:
return False
key = pattern[index]
if key in wordDict and wordDict[key] != i:
return False
elif key not in wordDict:
wordDict[key] = i
index += 1
return True
| true |
0c359a7b16b7fbece29a96fa1b19e49aaddfed73 | bluella/hackerrank-solutions-explained | /src/Arrays/Minimum Swaps 2.py | 974 | 4.375 | 4 | #!/usr/bin/env python3
"""
https://www.hackerrank.com/challenges/minimum-swaps-2
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n]
without any duplicates. You are allowed to swap any two elements.
Find the minimum number of swaps required to sort the array in ascending order.
"""
import math
import os
import random
import re
import sys
def minimumSwaps(arr):
"""
Args:
arr (list): list of numbers.
Returns:
int: min number of swaps"""
i = 0
count = 0
# since we know exact place in arr for each element
# we could just check each one and swap it to right position if thats
# required
while i < len(arr):
if arr[i] != i + 1:
arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1]
count += 1
else:
i += 1
return count
if __name__ == "__main__":
ex_arr = [1, 2, 3, 5, 4]
result = minimumSwaps(ex_arr)
print(result)
| true |
e477ab371361b476ded3fbeb89c663c253ee77a6 | bluella/hackerrank-solutions-explained | /src/Warm-up Challenges/Jumping on the Clouds.py | 1,623 | 4.1875 | 4 | #!/usr/bin/env python3
"""
https://www.hackerrank.com/challenges/jumping-on-the-clouds
There is a new mobile game that starts with consecutively numbered clouds.
Some of the clouds are thunderheads and others are cumulus.
The player can jump on any cumulus cloud having a number that
is equal to the number of the current cloud plus 1 or 2.
The player must avoid the thunderheads. Determine the minimum number of jumps
it will take to jump from the starting postion to the last cloud.
It is always possible to win the game.
For each game, you will get an array of clouds numbered 0
if they are safe or 1 if they must be avoided. """
import math
import os
import random
import re
import sys
#
# Complete the 'jumpingOnClouds' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY c as parameter.
#
def jumpingOnClouds(c):
"""
Args:
c (int): array of ones and zeros.
Returns:
int: min number of jumps"""
current_cloud = 0
jumps = 0
len_c = len(c)
# count jumps whilst looping over the clouds
while current_cloud < len_c - 1:
if len_c > current_cloud + 2:
# check if we are able to do long jump
if c[current_cloud + 2] == 0:
current_cloud += 2
# else do short jump
else:
current_cloud += 1
else:
current_cloud += 1
jumps += 1
# print(current_cloud, jumps)
return jumps
if __name__ == "__main__":
jumps_arr = [0, 1, 0, 0, 0, 1, 0]
result = jumpingOnClouds(jumps_arr)
print(result)
| true |
a5259c0f1618344c5788637a406943352a01b5d9 | anoubhav/Project-Euler | /problem_3.py | 971 | 4.15625 | 4 | from math import ceil
def factorisation(n):
factors = []
# 2 is the only even prime, so if we treat 2 separately we can increase factor with 2 every step.
while n%2==0:
n >>= 1
factors.append(2)
# every number n can **at most** have one prime factor greater than sqrt(n). Thus, we have the upper limit as sqrt(n). If after division with earlier primes, n is not 1, this is the prime factor greater than sqrt(n).
for i in range(3, ceil(n**0.5) + 1, 2):
while n%i == 0:
n //= i
factors.append(i)
if n!=1:
factors.append(n)
# it has a prime factor greater than sqrt(n)
return factors
n = 600851475143
print(max(factorisation(n)))
# Proof: Every number n can at most have one prime factor greater than n. https://math.stackexchange.com/questions/1408476/proof-that-every-positive-integer-has-at-most-one-prime-factor-greater-than-its/1408496
| true |
97f21e92543f97bf7be3a7603c366c371fbbe0a8 | luabras/Angulo-vetores | /AnguloEntreVetores.py | 1,829 | 4.28125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def plotVectors(vecs, cols, alpha=1):
"""
Plot set of vectors.
Parameters
----------
vecs : array-like
Coordinates of the vectors to plot. Each vectors is in an array. For
instance: [[1, 3], [2, 2]] can be used to plot 2 vectors.
cols : array-like
Colors of the vectors. For instance: ['red', 'blue'] will display the
first vector in red and the second in blue.
alpha : float
Opacity of vectors
Returns:
fig : instance of matplotlib.figure.Figure
The figure of the vectors
"""
plt.figure()
plt.axvline(x=0, color='#A9A9A9', zorder=0)
plt.axhline(y=0, color='#A9A9A9', zorder=0)
for i in range(len(vecs)):
x = np.concatenate([[0,0],vecs[i]])
plt.quiver([x[0]],
[x[1]],
[x[2]],
[x[3]],
angles='xy', scale_units='xy', scale=1, color=cols[i],
alpha=alpha)
#funcao para calcular angulo entre vetores
def ang2Vet(v, u):
#calculando o produto escalar entre v e u
vInternoU = v.dot(u)
#calculando os modulos de v e u
vModulo = np.linalg.norm(v)
uModulo = np.linalg.norm(u)
#calculando o cosseno do angulo entre v e u
r = vInternoU/(vModulo*uModulo)
#angulo em radianos
ang = np.arccos(r)
#retornando em graus
return (180/np.pi)*ang
#criando vetores
u = np.array([0,1])
v = np.array([1, 0])
#definindo as cores dos vetores para plotar o grafico
red = 'red'
blue = 'blue'
#usando funcao do matplotlib para plotar vetores
plotVectors([u, v], [red, blue])
plt.xlim(-5, 10)
plt.ylim(-5, 5)
plt.show()
#usando a funcao criada para calcular o angulo entre u e v
angulo = ang2Vet(u, v)
print(angulo) | true |
31c247fdb56a75015b434f3721249b5711901b57 | 2pack94/CS50_Introduction_to_Artificial_Intelligence_2020 | /1_Knowledge/0_lecture/0_harry.py | 1,540 | 4.125 | 4 | from logic import *
# Create new classes, each having a name, or a symbol, representing each proposition.
rain = Symbol("rain") # It is raining.
hagrid = Symbol("hagrid") # Harry visited Hagrid.
dumbledore = Symbol("dumbledore") # Harry visited Dumbledore.
# Save sentences into the Knowledge Base (KB)
knowledge = And(
Implication(Not(rain), hagrid), # ¬(It is raining) → (Harry visited Hagrid)
Or(hagrid, dumbledore), # (Harry visited Hagrid) ∨ (Harry visited Dumbledore).
Not(And(hagrid, dumbledore)), # ¬(Harry visited Hagrid ∧ Harry visited Dumbledore) i.e. Harry did not visit both Hagrid and Dumbledore.
dumbledore # Harry visited Dumbledore.
)
# The query is: Is it raining?
# The Model Checking algorithm is used to find out if the query is entailed by the KB.
query = rain
print(modelCheck(knowledge, query))
# If the KB does not contain enough information to conclude the truth value of a query, model check will return False.
# Example:
# knowledge = dumbledore
# query = rain
# The enumerated models would look like this:
# dumbledore rain KB
# ------------------------------
# False False False
# False True False
# True False True
# True True True
# For the model dumbledore -> True and rain -> False, the KB is true, but the query is False.
# If the query would have been: query = Not(rain)
# Then for the model dumbledore -> True and rain -> True, the KB is true, but the query is False.
| true |
182456c4be118753b0ca6ece47d81a041e3aa3db | zackkattack/-CS1411 | /cs1411/Program_01-1.py | 500 | 4.65625 | 5 | # Calculate the area and the circumfrence of a circle from its radius.
# Step 1: Prompt for radius.
# Step 2: Apply the formulas.
# Step 3: Print out the result.
import math
# Step 1
radius_str = input("Enter the radius of the circle: ")
radius_int = int(radius_str) # Convert radius_str into a integer
# Step 2
circumfrence = 2*math.pi*radius_int
area = (math.pi)*(radius_int**2)
# Step 3
print
print "The area of the circle is:", area
print "The circumfrence of the circle is:" , circumfrence
| true |
70de8dc6a37fd9e059bb23d8a96ec2139ffc8257 | WinnyTroy/random-snippets | /4.py | 670 | 4.1875 | 4 | # # Order the list
values = [1, 3, -20, -100, 200, 30, 201, -200, 9, 3, 4, 2, -9, 92, 99, -10]
# # a.) In ascending Order
values.sort()
print values
# # b.) In descending Order
values.reverse()
print(values)
# # c.) Get the maximum number in the list
print max(values)
# # d.) Get the minimum number in the list
print min(values)
# # e.) Get the average of the list
average = sum(values)/len(values)
print average
# f.) list of dictionaries from the list with the key being the absolute value of an element and the value being the cube of that element
final = []
for x in values:
ans = zip(str(abs(x)), str(x**3))
final.append(ans)
print final
| true |
c3cae72e8baded407d00e9bd9ad6c50bfce2547e | nabin2nb2/Nabin-Bhandari | /introEx2.py | 246 | 4.53125 | 5 |
#2.Gets the radius of a circle and computes the area.
Radius = input("Enter given Radius: ")
Area = (22/7)*int(Radius)**2 #Formula to calculate area of circle
print ("The area of given radius is: "+ str(Area.__round__(3)))
| true |
ca18170a10f6b4ecfa367cdb6b90aa1b8c9b2efe | skalunge1/python-p | /DictPgm.py | 1,004 | 4.71875 | 5 | # How to access elements from a dictionary?
# 1. with the help of key :
# 2. using get() method : If the key has not found, instead of returning 'KeyError', it returns 'NONE'
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
print(my_dict.get('name'))
# Output: 26
print(my_dict.get('age'))
print(my_dict['age'])
# get() : If the key has not found, instead of returning 'KeyError', it returns 'NONE'
print(my_dict.get('adress'))
# with the help of key only : If the key has not found, returning 'KeyError'.
#print(my_dict['adress'])
# How to change or add elements in a dictionary?
# dictionary is mutable.We can add or edit existing values using assignment operator
# if key is already present, value gets updated else new key:value pair get added
my_dict = {'Name' : 'Smita', 'Adress' : 'Pune', 'Age': 29}
my_dict['Name'] = 'Deepika'
print("Name value after change :{}".format(my_dict['Name']))
my_dict['Age'] = 30
print("Age after change : {}".format(my_dict['Age']))
| true |
b4e460797dcf9d15466f25559adcaa19b0cd86eb | skalunge1/python-p | /DemoDeleteDict.py | 1,261 | 4.46875 | 4 | # How to delete or remove elements from a dictionary?
# 1. pop() : Remove particular item from list
# : It removes particular item after providing key and returns removed value
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.pop(4))
print(squares.pop(2))
print(squares)
print(squares.popitem())
print(squares)
print("*********")
# popitem() : used to remove and return an arbitrary item (key, value) form the dictionary.
# 2. removes 5:25 , 4:16, 3:9, 2:4, and last removes 1:1
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.popitem())
print(squares.popitem())
print(squares.popitem())
print(squares.popitem())
print(squares.popitem())
# after removing all items, it displays empty list
print(squares)
print("*********")
# 3. clear() : All the items can be removed at once using the clear() method.
# It returns None
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.clear())
print("After deletion of all the itmes :{}".format(squares))
print("*********")
# 4. 'del' keyword: We can also use the del keyword to remove individual items
# or remove the entire dictionary itself.
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
del squares[4]
del squares[5]
del squares
# print squares after deletion of entire dictionary, throws error
#print(squares)
| true |
cce65666f67ef2fb7a33c9372f03cdacf67ac500 | FabrizioFubelli/machine-learning | /05-regressor-training.py | 1,269 | 4.25 | 4 | #!/usr/bin/env python3
"""
Machine Learning - Train a predictive model with regression
Video:
https://youtu.be/7YDWaTKtCdI
LinearRegression:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html
"""
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
import numpy as np
np.random.seed(2)
dataset = load_boston()
# X contains the features
X = dataset['data']
# y contains the target we want to find
y = dataset['target']
X_train, X_test, y_train, y_test = train_test_split(X, y)
model = LinearRegression()
model.fit(X_train, y_train) # Train model from data
p_train = model.predict(X_train) # Predict X_train after training
p_test = model.predict(X_test) # Predict X_test after training
mae_train = mean_absolute_error(y_train, p_train)
mae_test = mean_absolute_error(y_test, p_test)
print('MAE train', mae_train)
print('MAE test', mae_test)
# We need to know the model mean squared error
mse_train = mean_squared_error(y_train, p_train)
mse_test = mean_squared_error(y_test, p_test)
print('MSE train', mse_train)
print('MSE test', mse_test)
| true |
754e26560f3768a87fc88f9f4ce9fbc2b9648d40 | FabrizioFubelli/machine-learning | /01-hello-world.py | 1,390 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Machine Learning - Hello World
Video:
https://www.youtube.com/watch?v=hSZH6saoLBY
1) Analyze input data
2) Split features and target
3) Split learning data and test data
4) Execute learning with learning data
5) Predict result of learning data and test data
6) Compare the accuracy scores between learning and test data
"""
from sklearn import datasets
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# The input data is an iris flower dataset.
# The desired output is the class of flower, by analyzing
# the following parameters:
# - Sepal length
# - Sepal width
# - Petal length
# - Petal width
iris_dataset = datasets.load_iris()
X = iris_dataset.data # Features
y = iris_dataset.target # Target
print(iris_dataset['DESCR'])
print()
# Split data into training and test data
X_train, X_test, y_train, y_test = train_test_split(X, y)
# The test data is not used during learning, but is needed to measure
# the final model learning quality
# Execute learning
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
predicted_train = model.predict(X_train)
predicted_test = model.predict(X_test)
print('Train accuracy')
print(accuracy_score(y_train, predicted_train))
print('Test score')
print(accuracy_score(y_test, predicted_test))
| true |
950c0661c44ff43eaef662c124d1d3a9057122e1 | EgorKolesnikov/YDS | /Python/Chapter 01/01. Basics/02. Shuffling the words.py | 1,095 | 4.15625 | 4 | ## Egor Kolesnikov
##
## Shuffling letters in words. First and last letters are not changing their positiona.
##
import sys
import random
import string
import re
def shuffle_one_word(word):
if len(word) > 3:
temp_list = list(word[1:-1])
random.shuffle(temp_list)
word = word[0] + ''.join(temp_list) + word[-1]
return word
def check_scientists_theory(whole_text):
pattern = re.compile("[^a-zA-Z_]")
only_words = re.sub(pattern, ' ', whole_text).split()
position = 0
word_count = 0
while position < len(whole_text):
if whole_text[position].isalpha():
shuffled = shuffle_one_word(only_words[word_count])
length = len(shuffled)
whole_text = (whole_text[0:position] +
shuffled +
whole_text[(position + length):])
word_count += 1
position += length
else:
position += 1
return whole_text
text = sys.stdin.read()
result = check_scientists_theory(text)
print(result)
| true |
3127d121f6f06faa85a09de26f6879220b6fd00d | paarubhatt/Assignments | /Fibonacci series.py | 634 | 4.34375 | 4 | #Recursive function to display fibonacci series upto 8 terms
def Fibonacci(n):
#To check given term is negative number
if n < 0:
print("Invalid Input")
#To check given term is 0 ,returns 0
elif n == 0:
return 0
# To check given term is either 1 or 2 because series for 1 or 2 terms will be 0 1
elif n == 1 or n == 2:
return 1
#Return a series until term value exceeds
else:
return Fibonacci(n-1)+Fibonacci(n-2)
#initialized term value
term = 8
#For loop prints the fibonacci series upto 8 terms
for i in range(term):
print(Fibonacci(i)) | true |
a48e9a490f51dbd08f9cec47f9de5bd6eab47712 | megha-20/String_Practice_Problems | /Pattern_Matching.py | 544 | 4.34375 | 4 | # Function to find all occurrences of a pattern of length m
# in given text of length n
def find(text,pattern):
t = len(text)
p = len(pattern)
i = 0
while i <= t-p:
for j in range(len(p)):
if text[i+j] is not pattern[j]:
break
if j == m-1:
print("Pattern occurs with shift",i)
i = i+1
# Program to demonstrate Naive Pattern Matching Algorithm in Python
text = "ABCABAABCABAC"
pattern = "CAB"
find(text,pattern)
| true |
8f70983510f211453fb51f8f9c396f58eaee33b7 | pauleclifton/GP_Python210B_Winter_2019 | /students/douglas_klos/session8/examples/sort_key.py | 1,286 | 4.3125 | 4 | #!/usr/bin/env python3
"""
demonstration of defining a sort_key method for sorting
"""
import random
import time
class Simple:
"""
simple class to demonstrate a simple sorting key method
"""
def __init__(self, val):
self.val = val
def sort_key(self):
"""
sorting key function --used to pass in to sort functions
to get faster sorting
Example::
sorted(list_of_simple_objects, key=Simple.sort_key)
"""
return self.val
def __lt__(self, other):
"""
less than --required for regular sorting
"""
return self.val < other.val
def __repr__(self):
return "Simple({})".format(self.val)
if __name__ == "__main__":
N = 10000
a_list = [Simple(random.randint(0, 10000)) for i in range(N)]
# print("Before sorting:", a_list)
print("Timing for {} items".format(N))
start = time.clock()
sorted(a_list)
reg_time = time.clock() - start
print("regular sort took: {:.4g}s".format(reg_time))
start = time.clock()
sorted(a_list, key=Simple.sort_key)
key_time = time.clock() - start
print("key sort took: {:.4g}s".format(key_time))
print("performance improvement factor: {:.4f}".format((reg_time / key_time)))
| true |
0bd34168459f1da60426f683ac7ce4ffb5eebc4a | pauleclifton/GP_Python210B_Winter_2019 | /students/jeremy_m/lesson03_exercises/slicing_lab.py | 1,499 | 4.5 | 4 | #!/usr/bin/env python3
# Lesson 03 - Slicing Lab
# Jeremy Monroe
def first_to_last(seq):
""" Swaps the first and last items in a sequence. """
return seq[-1] + seq[1:-1] + seq[0]
# print(first_to_last('hello'))
assert first_to_last('dingle') == 'eingld'
assert first_to_last('hello') == 'oellh'
def every_other(seq):
""" Returns a sequence with every other item removed """
return seq[::2]
# print(every_other('hello'))
assert every_other('hello') == 'hlo'
assert every_other('cornholio') == 'crhlo'
def first_four_last_four(seq):
""" Removes the first four and last four items and then removes every other
item from what is left. """
return seq[4:-4:2]
# print(first_four_last_four("I'll need a long sequence for this"))
assert first_four_last_four("I'll need a long sequence for this") == ' edaln eunefr'
assert first_four_last_four('Many mangy monkeys') == ' ag o'
def reverso(seq):
""" Returns a sequence in reverse order. """
return seq[::-1]
# print(reverso('ham sammich'))
assert reverso('ham sammich') == 'hcimmas mah'
assert reverso('Turkey sandwhich') == 'hcihwdnas yekruT'
def thirds_reversal(seq):
""" Returns a sequence with what was the last third now first, followed by
the first third, and middle third. """
return seq[-(len(seq) // 3):] + seq[:-(len(seq) // 3)]
# print(thirds_reversal('easy string'))
assert thirds_reversal('easy string') == 'ingeasy str'
assert thirds_reversal('twelve letters ') == "ters twelve let" | true |
4e71942f4dfb235107981620e653050980bd8f5d | pauleclifton/GP_Python210B_Winter_2019 | /students/jesse_miller/session02/print_grid2-redux.py | 931 | 4.375 | 4 | #!/usr/local/bin/python3
# Asking for user input
n = int(input("Enter a number for the size of the grid: "))
minus = (' -' * n)
plus = '+'
"""Here, I'm defining the variables for printing. Made the math easier this
way"""
def print_line():
print(plus + minus + plus + minus + plus)
"""This defines the tops and bottoms of the squares"""
def print_post():
print('|' + (' ' * (2*n) ) + '|' + (' ' * (2*n) ) + '|'),
"""This defines the column markers. The 2*n is to compensate for the length of
the column being double the length of a row in print"""
def print_grid():
"""The remainder of the magic. It doubles the above function and prints
the last row"""
print_line()
for line in range(2):
for post in range(n):
print_post()
print_line()
print_grid()
"""This defines the grid function. It executes print_row twice through do_two,
and the print_line to close the square."""
| true |
4bad0ec8024dea5b25d678ea50a74313474066f5 | pauleclifton/GP_Python210B_Winter_2019 | /students/elaine_x/session03/slicinglab_ex.py | 1,915 | 4.40625 | 4 | '''
##########################
#Python 210
#Session 03 - Slicing Lab
#Elaine Xu
#Jan 28,2019
###########################
'''
#Write some functions that take a sequence as an argument, and return a copy of that sequence:
#with the first and last items exchanged.
def exchange_first_last(seq):
'''exchange the first and last items'''
first = seq[len(seq)-1:len(seq)]
mid = seq[1:len(seq)-1]
last = seq[0:1]
return first+mid+last
#with every other item removed.
def remove_every_other(seq):
'''remove every other item'''
return seq[::2]
#with the first 4 and the last 4 items removed, and then every other item in the remaining sequence.
def remove_4_every_other(seq):
'''remove the first 4 and last 4, the nevery other item'''
seq1 = seq[4:-4]
seq2 = seq1[::2]
return seq2
#with the elements reversed (just with slicing).
def reverse_element(seq):
'''reverse the elements'''
return seq[::-1]
#with the last third, then first third, then the middle third in the new order.
def last_first_mid(seq):
'''with the last third, then first third, then the middle third in the new order'''
mid_seq = len(seq)//2
return seq[-3:]+seq[:3]+seq[mid_seq-1:mid_seq+2]
#tests
A_STRING = "this is a string"
A_TUPLE = (2, 54, 13, 12, 5, 32)
B_TUPLE = (2, 54, 13, 12, 5, 32, 2, 5, 17, 37, 23, 14)
assert exchange_first_last(A_STRING) == "ghis is a strint"
assert exchange_first_last(A_TUPLE) == (32, 54, 13, 12, 5, 2)
assert remove_every_other(A_STRING) == "ti sasrn"
assert remove_every_other(A_TUPLE) == (2, 13, 5)
assert remove_4_every_other(A_STRING) == " sas"
assert remove_4_every_other(B_TUPLE) == (5, 2)
assert reverse_element(A_STRING) == "gnirts a si siht"
assert reverse_element(A_TUPLE) == (32, 5, 12, 13, 54, 2)
assert last_first_mid(A_STRING) == "ingthi a "
assert last_first_mid(A_TUPLE) == (12, 5, 32, 2, 54, 13, 13, 12, 5)
print("test completed")
| true |
9e2062f46a32508373a55afb7fb110dda8579d4e | markuswesterlund/beetroot-lessons | /python_skola/rock_paper_scissor.py | 651 | 4.28125 | 4 | import random
print("Let's play rock, paper, scissor")
player = input("Choose rock, paper, scissor by typing r, p or s: ")
if player == 'r' or player == 'p' or player == 's':
computer = random.randint(1, 3)
# 1 == r
# 2 == p
# 3 == s
if (computer == 1 and player == 'r' or computer == 2 and player == 'p' or computer == 3 and player == 's'):
print("It is a draw")
elif (computer == 1 and player == 'p' or computer == 2 and player == 's' or computer == 3 and player == 'r'):
print("Gz, you win!")
else:
print("You lost noob!")
else:
print("Your input was in the wrong format, no game for you") | true |
d57b6adc5a6e62ce236f104c577c1329925b84ae | markuswesterlund/beetroot-lessons | /python_skola/Beetroot_Academy_Python/Lesson 4/guessing_game.py | 557 | 4.25 | 4 | import random
print("Try to guess what number the computer will randomly select: ")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
player = input("Choose a number between 1-10: ")
if int(player) in numbers:
computer = random.randint(1, 10)
if player == computer:
print("The computers number was:", computer, "and your number was:", player)
print("You win!")
else:
print("The computers number was:", computer, "and your number was:", player)
print("You lose!")
else:
print("Sorry this game really isn't for you")
| true |
6e3ce3b082ca45aa478ee73fdc200b84f13e7b45 | manuel-garcia-yuste/ICS3UR-Unit6-04-Python | /2d_list.py | 1,456 | 4.46875 | 4 | #!/usr/bin/env python3
# Created by: Manuel Garcia Yuste
# Created on : December 2019
# This program finds the average of all elements in a 2d list
import random
def calculator(dimensional_list, rows, columns):
# this finds the average of all elements in a 2d list
total = 0
for row_value in dimensional_list:
for single_value in row_value:
total += single_value
total = total/(rows*columns)
return total
def main():
# this function places random integers into a 2D list
dimensional_list = []
# Input
rows = (input("How many rows would you like: "))
columns = (input("How many columns would you like: "))
try:
# Process
rows = int(rows)
columns = int(columns)
for rows_loop in range(0, rows):
temp_column = []
for column_loop in range(0, columns):
random_int = random.randint(1, 50)
temp_column.append(random_int)
# Output 1
print("Random Number " + str(rows_loop + 1) + ", "
+ str(column_loop + 1) + " is " + str(random_int))
dimensional_list.append(temp_column)
print("")
# Output 2
averaged = calculator(dimensional_list, rows, columns)
print("The average of the random numbers is: {0} ".format(averaged))
except Exception:
print("Invalid input")
if __name__ == "__main__":
main()
| true |
9981b9084b75157e002eeab791beda9a40af6555 | Linh-T-Pham/Study-data-structures-and-algorithms- | /palindrome_recursion.py | 1,326 | 4.34375 | 4 | """ Write a function that takes a string as a parameter and returns
True if the string is a palindrome,
False otherwise. Remember that a string is a palindrome
if it is spelled the same both forward and backward.
For example: radar is a palindrome.
for bonus points palindromes can also be phrases,
but you need to remove the spaces and punctuation before checking.
for example: madam i’m adam is a palindrome.
Other fun palindromes include:
>>> recursive_palin("kayak")
True
>>> recursive_palin("aibohphobia")
True
>>> recursive_palin("able was i ere i saw elba")
True
>>> recursive_palin("kanakanak")
True
>>> recursive_palin("wassamassaw")
True
>>> recursive_palin("Go hang a salami; I’m a lasagna hog")
True
"""
def recursive_palin(string):
""" use recursion to solve this problem """
# slice_string = string[::-1].lower()
# if string == slice_string:
# return True
# return False
if len(string) <= 1:
return True
if string[0] == string[len(string)-1]:
return recursive_palin(string[1: len(string)-1])
return False
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. GO GO GO!\n")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.