blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5c3678aa0497ab0e117ce37102264cb667a13a26 | hanzhg/aoc2020 | /day1b.py | 382 | 3.59375 | 4 | def main():
with open('input.txt') as f:
lines = [line.rstrip() for line in f]
result = 0
for line in lines:
for line1 in lines:
value1 = 2020 - (int(line) + int(line1))
if str(value1) in lines:
result = int(line) * int(line1) * value1
print(result)
if __name__ == "__main__":
main()
|
2584d7f13ace7722c952ed40e0afa3a3c30eeebe | wilbertgeng/LintCode_exercise | /DP&Memorization/724.py | 895 | 3.515625 | 4 | """
724. Minimum Partition
"""
class Solution:
"""
@param nums: the given array
@return: the minimum difference between their sums
"""
def findMin(self, nums):
# write your code here
###
target = sum(nums) // 2
n = len(nums)
dp = [[False] * (target + 1) for _ in range(2)]
dp[0][0] = True ## !!! Don't forget this!
for i in range(1, n + 1):
dp[i % 2][0] = True
for j in range(target + 1):
if nums[i - 1] > j:
dp[i % 2][j] = dp[(i - 1) % 2][j]
else:
dp[i % 2][j] = dp[(i - 1) % 2][j] or dp[(i - 1) % 2][j - nums[i - 1]]
for j in range(target, -1, -1):
if dp[n % 2][j] == True:
return (sum(nums) - 2 * j) ## !!! Becareful what value needs to be returned
return -1
|
51b8415553ad64d14e63a55652436820fc3e1e40 | brown9804/Python_DiversosAlgortimos | /AgregarLineasTXT.py | 681 | 3.703125 | 4 | #Python3
# Permite ejemplificar como agregar lineas de texto a un archivo extension .txt
#Agregando lineas a un archivo de texto
archivo = open("Himno.txt", "w")
archivo.write("¡Noble patria!, tu hermosa bandera\n")
archivo.write("expresión de tu vida nos da;\n")
archivo.write("bajo el límpido azul de tu cielo\n")
archivo.write("blanca y pura descansa la paz.\n")
archivo.close()
#Cediendo permisos para leer el archivo
#archivo = open("Himno.txt", "r")
#for linea in archivo:
#print(linea)
#archivo.close()
#Eliminando los saltos de linea \n
archivo = open("Himno.txt", "r")
for linea in archivo:
hilera = linea.replace("\n","")
print(hilera)
archivo.close()
|
ddb29ec69b25ce0d5bd1981d4102fa2f2cd134ea | Gyczero/Leetcode_practice | /动态规划和贪心/Easy/leetcode_70.py | 469 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-09-14 18:19
# @Author : Frenkie
# @Site :
# @File : leetcode_70.py
# @Software: PyCharm
class Solution:
def climbStairs(self, n: int) -> int:
"""
clib(n) = clib(n-1) + clib(n-2)
:param n:
:return:
"""
clib_list = [1, 2]
for i in range(2, n):
clib_list.append(clib_list[i-1] + clib_list[i-2])
return clib_list[n-1]
|
08de1d23eaddeaac19bf707aba6e2088bfe184e2 | ikamilov/AlgorithmsQuestions | /AlgorithmDesignManual/increment.py | 109 | 3.828125 | 4 | y = 8
if y == 0:
print("1")
else:
if y % 2 == 1:
x = 2 * (y / 2)
print(x)
else:
y = y + 1
print(y) |
2f1804a2de2a5b7b3a9eec6c49d343ad50132e4e | JakubTesarek/projecteuler | /src/problem_005.py | 292 | 3.765625 | 4 | #!/usr/bin/env python
"""https://projecteuler.net/problem=5"""
if __name__ == '__main__':
primes = []
result = 1
for x in range(1, 21):
for prime in primes:
if x % prime == 0:
x /= prime
primes.append(x) # not really primes, we use number 1 too
result *= x
print(result) |
7ae09408fa4cc36227c45f48042969e8d30bd86f | appltini/clever-bee | /kalman.py | 1,040 | 3.59375 | 4 | # Import python libraries
import cv2, numpy as np
class Kalman(object):
"""Kalman Filter class keeps track of the estimated state of
the system and the variance or uncertainty of the estimate.
Predict and Correct methods implement the functionality
Reference: https://en.wikipedia.org/wiki/Kalman_filter
Attributes: None
"""
def __init__(self, initial_point):
self.kalman = cv2.KalmanFilter(4,2)
self.kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32)
self.kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],np.float32)
self.kalman.processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],np.float32) * 0.03
self.kalman.statePost = np.array([[initial_point[0]], [initial_point[1]], [0], [0]], dtype=np.float32)
def predict(self):
val = tuple(self.kalman.predict())
return val;
def correct(self, mp):
val = self.kalman.correct(np.array(mp, dtype=np.float32))
return val
|
364ad89c54a3e0020e1b61647e807305742e8268 | Copenbacon/code-katas | /katas/test_triangle.py | 823 | 3.546875 | 4 | import pytest
from triangle import is_triangle
TRIANGLE_TABLE = [
[1, 2, 2, True],
[7, 2, 2, False],
[1, 2, 3, False],
[1, 3, 2, False],
[3, 1, 2, False],
[5, 1, 2, False],
[1, 2, 5, False],
[2, 5, 1, False],
[4, 2, 3, True],
[5, 1, 5, True],
[2, 2, 2, True],
[-1, 2, 3, False],
[1, -2, 3, False],
[1, 2, -3, False],
[0, 2, 3, False]
]
"""Random sides."""
from random import randint
def solution(a, b, c):
a, b, c = sorted([a, b, c])
return a + b > c
@pytest.mark.parametrize("val1, val2, val3, result", TRIANGLE_TABLE)
def test_is_triangle(val1, val2, val3, result):
"""Test the smaller examples."""
assert is_triangle(val1, val2, val3) == result
def test_randos():
for _ in range(40):
a, b, c = [randint(-2, 10) for i in range(3)]
assert is_triangle(a, b, c) == solution(a, b, c) |
0fab9deff0b6a3e034c9872a748c8710370ee1ab | elidinkelspiel/GoalTrak | /Old_Versions/v.0.0.3.py | 3,567 | 3.796875 | 4 | #####GoalTrak version v. 0.0.3 (alpha version 3)#####
###March 28th, 2014###
#By Eli Dinkelspiel#
#This version's functionality:
#1) Can add names to a list database of Students
#2) Recognizes if name is already in list
#3) Refreshes listbox upon adding new name
#4) Quit button
#5) I started documenting cause I'm cool like that. You can thank me later.
#Changes from last version:
#Everything cause I just started documenting
#Goals for next version#
#Remove names from list
#Display a simple piece of data upon name selection (arbitrary, doesn't have to have any relevance or functionality
import Tkinter
import tempfile #Prolly will use later
student_list_temp = []
#Loads data from a save#
with open('GoalTrak/StudentList.txt') as fd:
for ln in fd:
Student_Name = ln
student_list_temp.append(Student_Name[:-1])
fd.close()
###The Big Cheese###
class GoalTrak(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariable = Tkinter.StringVar() #Entry Box#
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
self.entry.grid(column=0,row=1,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Enter new student here.")
self.quitButton = Tkinter.Button(self,text=u"Quit", command=self.OnButtonClick) #Quit button#
self.quitButton.grid(column=1,row=1)
self.labelVariable = Tkinter.StringVar() #Banner#
label = Tkinter.Label(self,textvariable=self.labelVariable, \
anchor="w",fg="white",bg="navy")
label.grid(column=0,row=0,columnspan=2,sticky='EW')
self.labelVariable.set(u"Welcome to GoalTrak")
self.StudentListDisplay = Tkinter.Listbox(self) #First widget I wrote myself!
self.StudentListDisplay.grid(row=2,column=0,columnspan=2,sticky='W')
for student in student_list_temp:
self.StudentListDisplay.insert(Tkinter.END, student)
self.grid_columnconfigure(0,weight=1) #This makes it so the window is resizable#
self.resizable(True,True)
self.update()
self.geometry(self.geometry())
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnButtonClick(self):
GoalTrak.destroy(self) #Question: is this legit?
def OnPressEnter(self,event): #Enters students into save file#
hold = self.entryVariable.get()
hold = str(hold)
with open('GoalTrak/StudentList.txt', 'a') as textfile: #This appends students to the already existing document of students
if (hold) not in student_list_temp:
student_list_temp.append(hold)
textfile.write(hold + '\n')
self.labelVariable.set( self.entryVariable.get() + " added" )
self.StudentListDisplay.delete(0, Tkinter.END)
for student in student_list_temp:
self.StudentListDisplay.insert(Tkinter.END, student)
else: #If student is already in list, aborts#
self.labelVariable.set( self.entryVariable.get() + " is already in list" )
textfile.close()
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
if __name__ == "__main__": #Looper: Starring app.mainloop#
app = GoalTrak(None)
app.title('GoalTrak v. 0.0.3')
app.mainloop() |
c232ca500a07d2ddb5bd9dacbced209f7e593698 | Sntsh176/LeetCode_Apr_Problems | /subarray_sum_equal.py | 1,901 | 3.9375 | 4 | """
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
Hide Hint #1
Will Brute force work here? Try to optimize it.
Hide Hint #2
Can we optimize it by using some extra space?
Hide Hint #3
What about storing sum frequencies in a hash table? Will it be useful?
Hide Hint #4
sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
"""
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""
Param:
nums : List of items
k : the sum value which needed to be find in count using subarray
return:
return type will be int , count
"""
# The approach here is to calculate the sum of each item in one loop of list and store the sum into dictionary
# we will check if the item of list ,sum and sum - k is equal to k or not
# This will confirm th count of subarray
sum_dict = {0:1}
# here we have taken one entry in dictionary as if sum - k = 0 this means there is a subarray whose sum = k
sum = 0
# initializing count variable
count = 0
# now will loop with each item and parallely will calculate the sum and store the same into the dictionary
for num in nums:
sum += num
if sum-k in sum_dict:
count += sum_dict[sum-k]
if sum in sum_dict:
sum_dict[sum] += 1
else:
sum_dict[sum] = 1
return count
|
0636a2cb9e1e293e0f04103923bdd1d80eb720ee | MoMoLT/KeySim | /dist/资源/createFile.py | 2,579 | 3.546875 | 4 | def writeKeyName(fileName='KeyName.txt'):
with open(fileName, 'w') as f:
# 写入鼠标键
mouseName = ('左键', '右键', '中键')
for i in mouseName:
f.write(i+'\n')
# 写入字符键
for i in range(65, 91):
ch = chr(i)
f.write(ch+'\n')
# 写入数字键
for i in range(48, 58):
ch = chr(i)
f.write(ch+'\n')
# 写入数字盘上的数字键
for i in range(0, 10):
ch = 'n_'+str(i)
f.write(ch+'\n')
for i in ('*', '+', 'Enter', '-', '.', '/'):
ch = 'n_'+i
f.write(ch+'\n')
# 写入功能按键
for i in range(1, 13):
ch = 'F' + str(i)
f.write(ch+'\n')
# 写入控制按键的键码
keyName = ('BackSpace', 'Tab', 'Clear', 'Enter', 'Shift',
'Control', 'Alt', 'CapeLock', 'Esc', 'Spacebar',
'Page Up', 'Page Down', 'End', 'Home', 'Left Arrow',
'Up Arrow', 'Right Arrow', 'Down Arrow', 'Insert', 'Delete',
'Num Lock', ';:', '=+', ',<', '-_', '.>', '/?', '`~',
'[{', '\|', '}]', ''' '" ''', 'win')
for i in keyName:
f.write(i+'\n')
# 写入多媒体按键
keyName2 = ('加音量', '减音量', '静音')
for i in keyName2:
f.write(i+'\n')
def writeKeyId(fileName='KeyId.txt'):
with open(fileName, 'w') as f:
# 写入鼠标键
mouseName = (1, 2, 4)
for i in mouseName:
f.write(str(i)+'\n')
# 写入字符键
for i in range(65, 91):
ch = str(i)
f.write(ch+'\n')
# 写入数字键
for i in range(48, 58):
ch = str(i)
f.write(ch+'\n')
# 写入数字盘上的数字键写入功能按键
for i in range(96, 124):
ch = str(i)
f.write(ch+'\n')
# 写入控制按键的键码
keyName = (8, 9, 12, 13, 16, 17, 18, 20, 27, 32, 33, 34, 35,
36, 37, 38, 39, 40, 45, 46, 144, 186, 187, 188, 189,
190, 191, 192, 219, 220, 221, 222, 91)
for i in keyName:
f.write(str(i)+'\n')
# 写入多媒体按键
keyName2 = (175, 174, 173)
for i in keyName2:
f.write(str(i)+'\n')
writeKeyName()
writeKeyId()
|
93e25bbb15fd058a4ded801a8206b7fbe8eab4ed | qmnguyenw/python_py4e | /geeksforgeeks/python/medium/23_13.py | 1,599 | 4.25 | 4 | stdev() method in Python statistics module
Statistics module in Python provides a function known as **stdev()** ,
which can be used to calculate the standard deviation. stdev() function only
calculates standard deviation from a sample of data, rather than an entire
population.
To calculate standard deviation of an entire population, another function
known as **pstdev()** is used.
** _Standard Deviation_** is a measure of spread in Statistics. It is used to
quantify the measure of spread, variation of a set of data values. It is very
much similar to variance, gives the measure of deviation whereas variance
provides the squared value.
A low measure of Standard Deviation indicates that the data are less spread
out, whereas a high value of Standard Deviation shows that the data in a set
are spread apart from their mean average values. A useful property of the
standard deviation is that, unlike the variance, it is expressed in the same
units as the data.
Standard Deviation is calculated by :

where x1, x2, x3.....xn are observed values in sample data,
 is the mean value of observations and
N is the number of sample observations.
> **Syntax :**
|
ce7c6e856cf572673562d0d35406ebb49404fc0a | huanhuancao/Python-programming-exercises | /github_100_python_questions/11.py | 186 | 3.671875 | 4 | # -*-coding:utf-8-*-
value = []
nums = [num for num in raw_input().split(',')]
for num in nums:
n = int(num, 2)
if n % 5 == 0:
value.append(num)
print(','.join(value))
|
467c27b5014ad09a8fd1d645e1584ca3ea2e18ec | evaristofm/curso-de-python | /PythonExerciocios/ex004.py | 357 | 3.8125 | 4 | algo = input('Digite algo: ')
print('Seu tipo primitivo é {}'.format(type(algo)))
print('É um número? {}'.format(algo.isnumeric()))
print('É uma letra? {}'.format(algo.isalpha()))
print('Tem letras e números? {}'.format(algo.isalnum()))
print('Está em maiúsculo? {}'.format(algo.isupper()))
print(('Está em minúsculo? {}'.format(algo.islower())))
|
bf20e59e54dba56847f37b9c38913dbff1d431e5 | shahbaz-pycread/Python_Notes | /list/lists.py | 6,547 | 4.625 | 5 | print(
"""
A list is a collection which is ordered and changeable.
It allows duplicate members.
In Python, lists are written with Square Brackets.
----------------------------------------------
"""
)
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
# Print the type
print(type(football_countries))
# Access the items
print(
'''
We can access the list items by referring to the index number.
--------------------------------------------
'''
)
# To access the first item of the list
print('The first element of the list is ' + football_countries[0])
# Negative Indexing
print(
'''
Negative Indexing means beginning from the end, -1 refers to the last item.
-2 refers to the second last item etc.
----------------------------------------------------
'''
)
#To access the last item of the list
print('The last item of the list is ' + football_countries[-1])
#List Length
print(
'''
To determine how many items a list has, use the `len()` function.
---------------------------------------------
'''
)
# Number of items in the lists
print(f'The list has {len(football_countries)} items.')
#Loop through a lists
print(
'''
We can loop through the list using a `for` loop.
-----------------------------------
'''
)
#Looping
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
for x in football_countries:
print(x)
# Range of Indexes
print(
'''
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
---------------------------------------
'''
)
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
#Return the second, third:
print(football_countries[1:3])
print(
'''
By leaving out the start value, the range will start at the first item.
-------------------------------------
''')
#The example returns the items from the beginning to Spain
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
print(football_countries[:4])
print(
'''
By leaving out the end value, the range will go on to the end of the list.
------------------------------------------
'''
)
#The example returns the items from the beginning to end of the list.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
print(football_countries[0:])
#Change Item value
print(
'''
To change the value of a specific item, refer to the index number.
---------------------------------
'''
)
#Change the Fifth item
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
football_countries[4] = 'England'
print(football_countries)
#Check of item exists in the list
print(
'''
To determine if a specified item is present in a list
use the `in` keyword.
----------------------------------------------
''')
#Check if 'Italy' is present in the list
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
if "Italy" in football_countries:
index = football_countries.index('Italy')
print(f"Yes, Index of Italy is {index}.")
#Add items
print(
'''
To add an item to the end of the list,
use the `append()` method.
---------------------------------------
''')
#Using the append() method to append an item.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
football_countries.append('England')
print('England has been added to the list.')
print(
'''
To add an item at the specified index,
use the insert() method.
----------------------------------------
''')
#Insert an item in the second position
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
football_countries.insert(1,"Portugal")
print(football_countries)
#Remove item
print(
'''
There are several methods to remove items from the list.
----------------------------------------
a)remove()
b)pop()
c)del keyword
d)clear()
'''
)
#The `remove()` method removes the specified item.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
football_countries.remove("France")
print(football_countries)
#The `pop()` method removes the specified index, (or the last item if index is not specified.)
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
football_countries.pop()
print(football_countries)
#The `del` keyword removes the specified index.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
del football_countries[5]
print(football_countries)
#The `del` keyword can also delete the list completely.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
del football_countries
#The `clear()` method empties the list.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
football_countries.clear()
print(football_countries)
#Copy a list
print(
'''
We cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1,
and changes made in list1 will automatically also be made in list2.
There are ways to make a copy,
a) One way is to use the built-in List method copy().
b) Another way to make a copy is to use the built-in method list().
------------------------------------
''')
#Make a copy of list with the copy() method.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
top_countries = football_countries.copy()
print(top_countries)
#Make a copy of list with the list() method.
football_countries = ["Argentina","Brazil","Germany","Spain","Italy","France"]
top_countries = list(football_countries)
print(top_countries)
#Join two lists
print(
'''
There are several ways to join,
or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
----------------------------------
'''
)
#Join two lists
team1 = ["MI","DC","RCB","KKR"]
team2 = ["SRH","CSK","KP"]
teams = team1 + team2
print(teams)
#Another way to join two lists are by appending all the items from list2 into list1, one by one:
team1 = ["MI","DC","RCB","KKR"]
team2 = ["SRH","CSK","KP"]
for x in team2:
team1.append(x)
print(team1)
#We can use the extend() method, which purpose is to add elements from one list to another list:
team1 = ["MI","DC","RCB","KKR"]
team2 = ["SRH","CSK","KP"]
team1.extend(team2)
print(team1)
|
26e4dddea51c477b6fbc636bfdebf8fe27a06733 | logantillman/cs365 | /hw7/frequency.py | 862 | 4.03125 | 4 | # Author: Logan Tillman
import sys
# Reading in the file name
file = sys.argv[1]
# Reading the data from the file
with open(file, 'r') as f:
data = f.read()
# Splitting the words into a list
splitData = data.split()
# Creating the dictionary to hold our information
wordDict = {}
# Populating the dictionary
for word in splitData:
# Grabbing the current word count, 0 if the word isn't found in the dictionary
count = wordDict.get(word, 0)
# Incrementing the word's count in the dictionary (inserting if it didn't already exist)
wordDict.update({word: count + 1})
# Sorting the dictionary based on frequency, then the word itself
sortedDict = sorted(wordDict.items(), key=lambda word: (word[1], word[0]))
# Formatting and printing the information
for pair in sortedDict:
line = '{0:20s} {1:5d}'.format(pair[0], pair[1])
print(line) |
37e1793c33b6bce48451dce00f5b3c0b628266d2 | Celmad/learning-python-with-vim | /039-builtin-libraries.py | 196 | 3.78125 | 4 | import random
for i in range(3):
print(random.random())
print(random.randint(10, 20))
members = ['Manuel', 'Elias', 'Jose Luis', 'Antonio']
leader = random.choice(members)
print(leader)
|
819f6f6246c99bc7e296e81825840829074892e9 | sumanmukherjee03/practice-and-katas | /python/grokking-coking-interview/sliding-window/avg-subarr-size-k/main.py | 2,210 | 3.78125 | 4 | def describe():
desc = """
Problem : Given an array, find the average of all subarrays of K contiguous elements in it.
Ex : Given Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5
Output: [2.2, 2.8, 2.4, 3.6, 2.8]
"""
print(desc)
# Time complexity = O(n^2)
def brute_force_find_averages_of_subarrays(K, arr):
result = []
print("Length of arr is : {}, K is : {}, Var i will iterate upto (not including) : {}".format(len(arr), K, len(arr)-K+1))
for i in range(len(arr)-K+1):
# find sum of next 'K' elements
_sum = 0.0
for j in range(i, i+K):
_sum += arr[j]
result.append(_sum/K) # calculate average
return result
# Time complexity = O(n)
# Maintain a container for collecting the result
# Maintain a pointer for the start of the window and one for the end of the window
# Move end pointer from start one by one UNTIL it is of the length of the sliding window
# Calculate aggregate, and insert into the results collection
# Move end pointer by one element right and start pointer by one element right
def find_averages_of_subarrays(K, arr):
result = []
windowSum, windowStart = 0.0, 0
for windowEnd in range(len(arr)):
# add the next element - keep adding the next element until you hit the length of the sliding window
windowSum += arr[windowEnd]
# slide the window, we don't need to slide if we've not hit the required window size of 'k'
# ie, the index of the end pointer of the window should be start of window + K or more.
# if windowEnd >= windowStart + K - 1:
if windowEnd >= windowStart + K - 1:
result.append(windowSum / K) # calculate the average
windowSum -= arr[windowStart] # subtract the element going out
windowStart += 1 # slide the window ahead
return result
def main():
describe()
result1 = brute_force_find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])
print("Averages of subarrays of size K (solution 1): " + str(result1))
result2 = find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])
print("Averages of subarrays of size K (solution 2): " + str(result2))
main()
|
6e848cdacf2855debfa5adb7ee6164758a53f8e7 | susoooo/IFCT06092019C3 | /Riker/python/08.py | 232 | 3.609375 | 4 | # 1-Escriba un programa que pida dos números enteros y que calcule su división, escribiendo si la división es exacta o no.
n1 = int(input("n1? "))
n2 = int(input("n2? "))
if (n1%n2 == 0):
print("yes")
else:
print("no")
|
eea5eee7082d42273340511727ebd1cfe9a95e27 | medishettyabhishek/Abhishek | /Abhishek/Section 9/Section 9-1/find and replace.py | 131 | 3.859375 | 4 | import re
string = ("hello my name is John")
pattern = r"John"
newstring = re.sub(pattern , "abhishek",string)
print(newstring)
|
ba08a92fa65af167884cf5fd766c6833d2d72f30 | lilac/mini-nn | /src/network.py | 3,689 | 3.625 | 4 | import numpy as np
def sigmoid(x):
return 1.0 / (1 + np.exp(-x))
def derivatives(x, y, z):
"""
Given the loss function C(x, y) = (f(x, w, b) - y)^2
f(x, w, b) = sigmoid(g(x, w, b))
g(x, w, b) = wx + b
the partial derivatives d.C / d.b = 2(f(x, w, b) - y) * (d.f(x, w, b) / d.b)
and it's known that
d.sigmoid(x) / d.x = sigmoid(x) * (1 - sigmoid(x))
d.g(x, w, b) / d.b = 1
d.g(x, w, b) / d.w = x^T (x transpose)
so
d.C / d.b = 2(f(x, w, b) - y) * sigmoid(g(x, w, b)) * (1 - sigmoid(g(x, w, b)) * (d.g(x, w, b) / d.b)
= 2 (z - y) z (1 - z)
where z = f(x, w, b)
d.C / d.w = d.C / d.b * x^T
:param x:
:param y:
:param z: z = f(x, w, b)
:return: d.C / d.w, d.C / d.b
"""
bDerivative = (z - y) * z * (1 - z)
wDerivative = bDerivative * x.transpose()
return wDerivative, bDerivative
class Network(object):
def __init__(self, sizes):
self.nLayers = len(sizes)
self.sizes = sizes
self.weight = [np.random.randn(r, c) for c, r in zip(sizes[:-1], sizes[1:])]
self.bias = [np.random.randn(r, 1) for r in sizes[1:]]
def feed_forward(self, x):
for w, b in zip(self.weight, self.bias):
z = np.dot(w, x) + b
x = sigmoid(z)
return x
def feed(self, x):
xs = [x] # input layer by layer
zs = [] # weighted sum layer by layer
for w, b in zip(self.weight, self.bias):
z = np.dot(w, x) + b
zs.append(z)
x = sigmoid(z)
xs.append(x)
return xs, zs
def back_propagation(self, x, y):
wGrad = [np.zeros(w.shape) for w in self.weight]
bGrad = [np.zeros(b.shape) for b in self.bias]
xs, zs = self.feed(x)
wGrad[-1], bGrad[-1] = derivatives(xs[-2], y, xs[-1])
for l in xrange(2, self.nLayers):
# Todo: add explanation to this formula
# bGrad[-l] = np.dot(bGrad[-l + 1], self.weight[-l + 1]) * (1 - xs[-l]) * xs[-l]
bGrad[-l] = np.dot(self.weight[-l + 1].transpose(), bGrad[-l + 1]) * xs[-l] * (1 - xs[-l])
wGrad[-l] = bGrad[-l] * xs[-l - 1].transpose()
return wGrad, bGrad
def learn(self, batch, eta):
wGradSum = [np.zeros(w.shape) for w in self.weight]
bGradSum = [np.zeros(b.shape) for b in self.bias]
for x, y in batch:
wGrad, bGrad = self.back_propagation(x, y)
wGradSum = [s + w for s, w in zip(wGradSum, wGrad)]
bGradSum = [s + b for s, b in zip(bGradSum, bGrad)]
self.weight = [w - eta / len(batch) * delta for w, delta in zip(self.weight, wGradSum)]
self.bias = [b - eta / len(batch) * delta for b, delta in zip(self.bias, bGradSum)]
def infer(self, x):
return np.argmax(self.feed_forward(x))
def evaluate(self, data):
results = [(self.infer(x), y) for x, y in data]
return sum(int(z == y) for z, y in results)
def train(self, data, epochs, batch_size, eta, validation_data=None):
import random
import time
startTime = time.time()
for i in xrange(epochs):
random.shuffle(data)
batches = [data[j: j + batch_size] for j in xrange(0, len(data), batch_size)]
for batch in batches:
self.learn(batch, eta)
runningTime = time.time() - startTime
if validation_data:
num = self.evaluate(validation_data)
print "{} Epoch {}: {} / {} correct".format(runningTime, i, num, len(validation_data))
else:
print "{} Epoch {} complete".format(runningTime, i)
|
066282e51de275bba77fc48a871cd77625a34a27 | rayankikavitha/InterviewPrep | /PRAMP/draw_H_recursively.py | 1,024 | 4.1875 | 4 | import math
import Graphics
def drawLine(x1, y1, x2, y2):
# draws line, assume implementation available
point1 = Graphics.point
Graphics.Line(point1, point2)
def drawHTree(x, y, length, depth):
# recursion base case
if depth == 0:
return
x0 = x - length / 2
x1 = x + length / 2
y0 = y - length / 2
y1 = y + length / 2
# draw the 3 line segments of the H-Tree
drawLine(x0, y0, x0, y1) # left segment
drawLine(x1, y0, x1, y1) # right segment
drawLine(x0, y, x1, y) # connecting segment
# at each stage, the length of segments decreases by a factor of √2
newLength = length /math.sqrt(2)
# decrement depth by 1 and draw an H-tree
# at each of the tips of the current ‘H’
drawHTree(x0, y0, newLength, depth - 1) # lower left H-tree
drawHTree(x0, y1, newLength, depth - 1) # upper left H-tree
drawHTree(x1, y0, newLength, depth - 1) # lower right H-tree
drawHTree(x1, y1, newLength, depth - 1) # upper right H-tree
|
1765a4c0fdc25bd38a12656f98c8387e2f0e6a04 | metodiev/PythonOverview | /age_notificator_2.py | 597 | 4.125 | 4 | #If age is 5 go to Kindergarten
#Ages 6 through 17 goes to grades 1 through 12
#if age is grater then 17 say go to college
#Try to complete with 10 or less lines
#Ask for the age
age = eval(input("Enter age: "))
#Handle if age < 5
if age < 5 :
print("Too Young for School")
#Special output just for age 5
elif age == 5:
print("Go to the Kindergarten")
#Since a number is the result for age 6 - 17 we can check them all with 1 condition
elif (age > 5) and (age <=17):
grade = age - 5
print("Go to {} grade".format(grade))
#Handle everyone else
else:
print("Go to College") |
3d7e3d7042d93cec14ecc34baf6c766496d140a5 | jcperdomo/182finalproject | /state.py | 3,159 | 3.53125 | 4 | from copy import deepcopy
import cards
class State(object):
"""Docstring for State. """
def __init__(self, playedCards, whosTurn,
topCard=None, lastPlayed=None, finished=[]):
"""Initialization for State.
:playedCards: list of card count dictionaries representing how many of
each card each player has played.
:whosTurn: Index of player whose turn it is.
:topCard: (numPlayed, whichCard) of the last play (None if empty deck).
:lastPlayed: Last player who played on this deck (None if empty deck).
:finished: list of player indices who have played all their cards in
order from president to asshole.
"""
self.playedCards = playedCards
self.numPlayers = len(self.playedCards)
self.whosTurn = whosTurn
self.topCard = topCard
self.lastPlayed = lastPlayed
self.finished = finished
# compute numRemaining
self.initHandSize = 52 / self.numPlayers
self.numRemaining = [self.initHandSize - sum(played.itervalues())
for played in playedCards]
def getChild(self, action):
"""Gets the next state given an action.
:action: The action taken, represented as (numCards, whichCard).
:returns: The next state.
"""
numCards, whichCard = action
# set defaults
nextPlayedCards = deepcopy(self.playedCards)
nextWhosTurn = (self.whosTurn + 1) % self.numPlayers
nextTopCard = self.topCard
nextLastPlayed = self.lastPlayed
nextFinished = deepcopy(self.finished)
# if a real move was made, update next state
if numCards > 0:
nextPlayedCards[self.whosTurn][whichCard] += numCards
nextTopCard = action
nextLastPlayed = self.whosTurn
# if no move was made and it's gone all the way around, clear deck
elif nextWhosTurn == nextLastPlayed:
nextTopCard = None
nextLastPlayed = None
# create next state
nextState = State(nextPlayedCards, nextWhosTurn,
nextTopCard, nextLastPlayed, nextFinished)
# if player ran out of cards at this transition, add to finished list
if (self.numRemaining[self.whosTurn] > 0 and
nextState.numRemaining[self.whosTurn] == 0):
nextState.finished.append(self.whosTurn)
return nextState
def isFinalState(self):
"""Returns True if all but the final player has finished, otherwise False.
:returns: True if the game is over, False otherwise.
"""
numDone = len(self.finished)
# if all but one have used all their cards, the game is over
if numDone >= self.numPlayers:
return True
else:
return False
def isInitialState(self):
"""Returns True if this is the first play of the game, i.e., all
playedCards entries are empty.
:returns: True if it's the first play of the game, False otherwise.
"""
return all(cards.empty(played) for played in self.playedCards)
|
ccc82a2ea33fc6da2e5d070845e7de9199c13826 | erenerdo/algorithms | /Data Structures/HashMap.py | 4,915 | 4.03125 | 4 | # Eren Erdogan
# YCharts Coding Challenge
# Setting up the Linked List Class to be used in the Hash Map for
# seperate chaining implementation
# Linked List Node Class
class LListNode:
def __init__ (self, key, value, nextNode):
self.key = key
self.value = value
self.nextNode = nextNode
# Lined List Class
class LList:
# Constructor
def __init__ (self):
self.head = None
def set (self, key, value):
# Check to see if the key is already in the list
# If so then we need to update it
ptr = self.head
while ptr != None:
# If it is, update value, and return
if ptr.key == key:
ptr.value = value;
return "Updated Key"
ptr = ptr.nextNode
# Key not found so lets add it to the list
newNode = LListNode(key, value, None)
# If empty linked list
# Edge Case
if self.head == None:
self.head = newNode
else:
newNode.nextNode = self.head
self.head = newNode
return "New Key"
def get (self, key):
# Create pointer
ptr = self.head
# Traverse Linked List and look for key
while ptr != None:
if ptr.key == key:
return ptr.value
ptr = ptr.nextNode
# Key not found return None
return None
def remove (self, key):
ptr = self.head
## Edge case, need to remove the head
if (ptr.key == key):
self.head = ptr.nextNode;
return True;
# Look for node to remove
while (ptr.nextNode != None):
if (ptr.nextNode.key == key):
# Remove by bypassing node in LL
ptr.nextNode = ptr.nextNode.nextNode
return True
ptr = ptr.nextNode
return False
def contains (self, key):
ptr = self.head
while (ptr != None):
if (ptr.key == key):
return True
ptr = ptr.nextNode
return False
def printLL (self):
ptr = self.head
llKeys = []
while (ptr != None):
llKeys.append(str(ptr.key))
ptr = ptr.nextNode
if len(llKeys) == 0:
return "None"
else:
return " -> ".join(llKeys) + " -> None"
##################################################################
##################################################################
# Setting up HashMap class now
# Hash Function
def hashKey(key, size):
hashedKey = 0
if isinstance(key, str):
for i in range(len(key)):
hashedKey += ord(key[i])
return hashedKey % size
elif isinstance(key, int):
hashedKey = key % size
return hashedKey
elif isinstance(key, float):
hashedKey = int(key % size)
return hashedKey
return None
# HashMap Class
class HashMap:
def __init__ (self, bucketSize = 10):
self.buckets = []
self.bucketSize = bucketSize
self.count = 0;
# Initialze all values in buckets to an empty LinkedList
for i in range(self.bucketSize):
self.buckets.append(LList())
def set (self, key, value):
hashIndex = hashKey(key, self.bucketSize)
# Throw error if valid key not inputted
if hashIndex == None:
raise ValueError('Invalid data type for key in HashMap')
# Insert the key and see if it was a new one or an updated one
insert = self.buckets[hashIndex].set(key, value)
# Increment count only if a new key is added
if insert == "New Key":
self.count += 1
# Check if we need to rehash our hashtable with a bigger bucket size
if self.count == 2 * self.bucketSize:
self.rehash(2 * self.bucketSize)
# return self for chaining
return self
def get (self, key):
hashIndex = hashKey(key, self.bucketSize)
return self.buckets[hashIndex].get(key)
def isEmpty (self):
return self.count == 0
def size (self):
return self.count
def clear (self):
self = self.__init__(self.bucketSize)
def containsKey(self, key):
hashIndex = hashKey(key, self.bucketSize)
return self.buckets[hashIndex].contains(key)
def remove(self, key):
hashIndex = hashKey(key, self.bucketSize)
# See if we actually removed an element
didRemove = self.buckets[hashIndex].remove(key)
if didRemove:
self.count -= 1
# Check if we need to rehash and if we are wasting memory
if (self.count < self.bucketSize // 2):
self.rehash(self.bucketSize // 2)
return didRemove;
def rehash(self, newBucketSize):
# Copy all keys and values to an array
keyValPairs = []
for i in range(self.bucketSize):
ptr = self.buckets[i].head
while (ptr != None):
keyValPairs.append([ptr.key, ptr.value])
ptr = ptr.nextNode
# Reinitialize HashMap
self.__init__(newBucketSize)
# Add values back in
for i in range(len(keyValPairs)):
self.set(keyValPairs[i][0], keyValPairs[i][1])
return True
# Used to see how the hashmap is looking under the hood
def printHashMap (self):
for i in range(len(self.buckets)):
print(i, ":", self.buckets[i].printLL())
|
785fdb1b44e5a9e89b8c8a58d622c4e37da641cc | dwdii/py-sandbox | /src/utillib/unionfind.py | 2,026 | 3.984375 | 4 | #
# Author: Daniel Dittenhafer
#
# Created: May 21, 2019
#
# Description: Coursera Algorithms
#
__author__ = 'Daniel Dittenhafer'
import random
"""
Union-Find Data Structure
"""
class union_find:
class entry:
def __init__(self, id):
self.rank = 0
self.parent = None
self.id = id
@property
def rank(self):
return self._rank
@rank.setter
def rank(self, r):
self._rank = r
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, p):
self._parent = p
@property
def id(self):
return self._id
def __repr__(self):
return "entry[{0}]: r={1}; p={2}".format(self.id, self.rank, self.parent)
def __init__(self, keys):
self.data = {}
self.clusters = len(keys)
for k in keys:
self.data[k] = self.entry(k)
def find(self, x):
i = x
done = False
while not done:
if self.data.has_key(i):
e = self.data[i]
p = e.parent
done = p is None or p == i
if not done:
i = p
elif p == 1:
e.parent = None
return e
def union(self, x, y ):
s1 = self.find(x)
s2 = self.find(y)
if s2.rank > s1.rank:
s1.parent = s2.id
elif s1.rank > s2.rank:
s2.parent = s1.id
else:
s2.parent = s1.id
s1.rank += 1
self.clusters -= 1
def main():
tests_correct = 0
tests = [
# path to graph file, finishing times dict, leaders dict
#("D:\\Code\\Python\\py-sandbox\\data\\graph-small2-dijkstra.txt", [1,2,3,4,5,6,7], {}, [0,5,3,4,5,6,6])
]
uf = union_find([1,2,3,4,5,6,7,8,9,0])
uf.find(1)
uf.union(1,2)
uf.union(7,8)
uf.union(5,6)
uf.union(3,4)
uf.union(1,5)
if __name__ == "__main__":
main()
|
9b467fe9aefb0dab880a0877c494d5a6e7e97905 | kimmyoo/python_leetcode | /A_ENUMERATION/contains_duplicate_ii/solution.py | 1,408 | 3.65625 | 4 | """
Given an array of integers and an integer k, find out whether there are two
distinct indices i and j in the array such that nums[i] = nums[j] and the
difference between i and j is at most k.
"""
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
# initiate a dictionary
# fill up the dictionary in loop with d[e] = i
# but before doing that check whether the same element has been
# put in the dictionary, if it's in there, check whether the newly
# added element has difference of at least k,
# if yes, than return Ture
# requires a dictionary space complexity: n
# time complexity: n
d = {}
for i, e in enumerate(nums):
if e in d:
#print (d[e]) # for understanding the code
if i - d[e] <= k:
return True
# only is there a duplicate,
# index of the most recent of occurence of e will be remembered
# and it's totaly fine to assign different keys to the same element
# but not the othe way around
d[e] = i
#print (d[e], e) # for understanding the code
return False
args1 = [[1, 0, 1, 0, 1, 2, 2], 1]
s = Solution()
print(s.containsNearbyDuplicate(*args1))
|
ce6f839b522c4713e5537261427befa879ead1b0 | Osama-Khan/bscs-na | /Mid/Q2.py | 472 | 3.65625 | 4 | # Write python code to find the solution of given set of equations using
# Seidel Method with initial conditions x, y, z = 1, 1, 1 [for 10 iterations only]
def f1(y, z): return (-4*y + z + 32)/28
def f2(x, z): return (-2*x - 4*z + 35)/17
def f3(x, y): return (-x - 3*y + 24)/10
x, y, z = 1, 1, 1
print("k", "x", "y", "z", sep="\t")
for k in range(0, 10):
x = round(f1(y, z), 4)
y = round(f2(x, z), 4)
z = round(f3(x, y), 4)
print(k, x, y, z, sep="\t")
|
883c2c3ac11c439d47be84f927fa282f8aa5dd18 | igormcoelho/goat-in-door-challenge | /goat.py | 1,636 | 3.875 | 4 | #!/usr/bin/python3
import random
import statistics
# simulate game
turns=1000000
print("running ", turns)
player1_static_wins=0
player2_dyn_wins=0
for i in range(turns):
goat = random.randint(1,3)
##print("goat on ", goat)
selected = play1_bet = play2_bet = random.randint(1,3)
# same bet for both players (this helps simplifying some code ahead...)
#play2_bet = random.randint(1,3)
##print("play1 ", play1_bet)
##print("play2 ", play2_bet)
# if WIN_IMMEDIATE, calculate and finish already the game
# not doing this...
#time to open door with no goat
doors = list(range(1,4))
doors.remove(goat)
#doors.remove(selected)
if goat != selected: # just avoid duplication of .remove() for same element
doors.remove(selected) # same bet for play1 and play2
no_goat = doors[random.randint(0,len(doors)-1)]
#player1 will keep its door
play1_bet = play1_bet
#player2 will change
p2doors = list(range(1,4))
p2doors.remove(no_goat) # shown door eliminated
p2doors.remove(play2_bet) # must change its bet (play2 strategy)
play2_bet = p2doors[0] # takeslast option
# compute wins
if play1_bet == goat:
player1_static_wins+=1
if play2_bet == goat:
player2_dyn_wins+=1
# if goat cannot appear on first round, chance is 1/3 and 2/3=66.6%
# if goat can appear (and win immediately), then chance is 1/3 and (4/3+1)/3=77.7% (see WIN_IMMEDIATE option)
print("player1 = ", player1_static_wins, " -> ",player1_static_wins/turns, '%')
print("player2 = ", player2_dyn_wins, " -> ",player2_dyn_wins/turns, '%')
|
235f877dbd294deb6e9927b62181682a8435a5ff | VfromNN1909/ArtezioHomeTasks | /Lesson VI/Iterators and Generators/hw6.3.py | 986 | 3.578125 | 4 | # импортируем json,дабы красиво вывести словарь
import json
# для генерации значений
# если ввести значение < количество ключей + 1(27)
# то вместо недостающих значений будет None
# если ввести больше,то лишние значения будут игнорироваться
limit = int(input('Введите лимит: '))
# генерируем ключи - буквы от a до z
keys = [chr(int(i)) for i in range(ord('a'), ord('z') + 1)]
# генерируем ключи - числа от 1 до limit'а
vals = [int(i) for i in range(1, limit)]
# словарь - результат
res = {}
# слияние 2ух листов в словарь
[res.update({keys[i]: vals[i]}) if i < len(vals) else res.update({keys[i]: None}) for i in range(len(keys))]
# красиво выводим словарь
print(json.dumps(res, indent=1))
|
1de339b2152f1a0bda7a0fa52ec300234adcbee0 | himanshus97/Linear_Regression_py | /linear_reg.py | 1,142 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 1 19:30:30 2018
@author: himanshu
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the data
dataset = pd.read_csv("sample_data.csv") #add your data here
X=dataset.iloc[:,:-1].values #make changes here as according to your dataset
y = dataset.iloc[:,1].values
#splitting data sets
from sklearn.cross_validation import train_test_split
X_train , X_test , y_train , y_test = train_test_split(X,y,test_size= 1/3,random_state =0)
#fitting data
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(X_train,y_train)
#prediction
y_pred = reg.predict(X_test)
#plotting training data
plt.scatter(X_train,y_train, color="red")
plt.plot(X_train,reg.predict(X_train), color ="blue")
plt.title("Salary v/s Experience (Training data)")
plt.xlabel("Experience")
plt.ylabel("salary")
plt.show()
#plotting test data
plt.scatter(X_test,y_test, color="red")
plt.plot(X_train,reg.predict(X_train), color ="blue")
plt.title("Salary v/s Experience (Test data)")
plt.xlabel("Experience")
plt.ylabel("salary")
plt.show()
|
a3b16f747683a27637453da9da8bfd8555648e14 | boboriska/PythonMIIGAIK | /Task_4/Task_4.py | 1,502 | 3.734375 | 4 | # Задача 1 «Длина отрезка» (1 балл)
m = input('Введите число: ').split(" ")
m[0] = int(m[0])
m[1] = int(m[1])
m[2] = int(m[2])
m[3] = int(m[3])
def distance(x1, y1, x2, y2):
return ((x2 - x1)**2 + (y2-y1)**2)**0.5
print(distance(m[0],m[1],m[2],m[3]))
# Задача 3 (1 балл)
stroka = input('Введите строку: ')
print(''.join([j for i,j in enumerate(stroka) if j not in stroka[:i]]))
# Задача 7 Кегельбан (2 балла)
import random
Kegl = int(input('Ввкдите колличесво кеглей: '))
Sh = int(input('Ввкдите колличесво шаров: '))
def Remove(s, l, r):
i = l
while i <= r:
if s[i]:
s[i] = "."
i += 1
Skittles = []
for i in range(Kegl):
Skittles.append("I")
for i in range(Sh):
l = random.randint(0, Kegl - 1)
r = random.randint(0, Kegl - 1)
if l > r:
l, r = r, l
Remove(Skittles, l, r)
print("".join(Skittles))
# Задача 9 «Диагонали, параллельные главной» (1 балл)
def massiv(n):
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(n):
a[i][j] = abs(i - j)
return a
for row in (massiv(7)):
print(' '.join([str(elem) for elem in row]))
# Задача 10 Числа Фибоначчи (3 балла)
n = int(input('Введите число: '))
def fib(n):
if n<3:
return 1
return fib(n-1)+fib(n-2)
print(fib(20))
|
ce2690ee101b5fa749519fbe04b528bf95ee3e47 | heshengbang/pylearn | /100examples/1.py | 167 | 3.84375 | 4 | #!/usr/bin/python
count =0
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
if (a!=b and b!=c and a!=c):
print a,b,c
count+=1
print count |
c52488cea975fde4e1264bf1f9796325dda9783f | linguang-up/python_code | /day1/passwd.py | 381 | 3.953125 | 4 | #!/usr/bin/env python
# Author:Lin Guang
name = input("name:")
age = input("age:")
salary = input("salary:")
# info = '''------------information %s ------------
# NAME:%s
# AGE:%s
# salary:%s
# ''' % (name,name,age,salary)
info = '''------------information {_name} ------------
NAME:{_name}
AGE:{_age}
salary:{_salary}
'''.format (_name=name,_age=age,_salary=salary)
print(info) |
e741a4968936eab9cfc48d1b07cf3a113639e9e9 | OWEN-JUN/python_study | /day1/tri_ex.py | 272 | 3.84375 | 4 | def drawdiamond(num):
for i in range(1, num + 1):
print(" " * (num - i),"*" * (2 * i - 1))
for i in range(num - 1, 0, -1):
print(" " * (num - i),"*" * (2 *i -1))
diamond = int(input("만들어질 다이아몬드 줄수>>"))
drawdiamond(diamond)
|
fa4062ca2eb80c11819d607cff84dafd8b31dc9e | sadrayan/connected-vehicle-iot | /src/Servo.py | 828 | 3.546875 | 4 |
import Adafruit_PCA9685
class Servo:
def __init__(self):
self.angleMin=18
self.angleMax=162
self.pwm = Adafruit_PCA9685.PCA9685()
self.pwm.set_pwm_freq(50) # Set the cycle frequency of PWM
#Convert the input angle to the value of pca9685
def map(self,value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
def setServoAngle(self,channel, angle):
if angle < self.angleMin:
angle = self.angleMin
elif angle >self.angleMax:
angle=self.angleMax
date=self.map(angle,0,180,102,512)
#print(date,date/4096*0.02)
self.pwm.set_pwm(channel, 0, int(date))
# Main program logic follows:
if __name__ == '__main__':
print("Now servos will rotate") |
3f8e0269c489ef326443abc8df82174eed309d8f | pedrohcf3141/CursoEmVideoPython | /CursoEmVideoExercicios/Desafio023.py | 459 | 3.859375 | 4 | # Desafio 23
nro = input('Informe um numero ')
nro = '0000'+nro
print(' o numero tem {} Unidades '.format(nro[-1]))
print(' o numero tem {} Dezenas'.format(nro[-2]))
print(' o numero tem {} Centenas '.format(nro[-3]))
print(' o numero tem {} Milhares '.format(nro[-4]))
nro = int(nro)
print('Unidades {}'.format(nro%10))
print('Dezenas {}'.format(((nro//10)%10)))
print('Centenas {}'.format(((nro//100)%10)))
print('Milhares {}'.format(((nro//1000)%10)))
|
f1f926a47452bbd548c08433ac470f5720a827d6 | qtvspa/offer | /LeetCode/increasing_number.py | 903 | 3.703125 | 4 |
# 单调递增的数字
# https://leetcode-cn.com/problems/monotone-increasing-digits/
# 思路:见注释
def monotone_increasing_digits(n: int) -> int:
list_n = list(str(n))
r = len(list_n) - 1
res = []
# 从右往左遍历
while r - 1 >= 0:
# 如果当前元素大于或等于前一个元素,则将当前元素加入res
if list_n[r] >= list_n[r - 1]:
res.append(list_n[r])
# 否则把刚刚加入res的所有值全变成'9',并将前一个元素减1
else:
list_n[r - 1] = str(int(list_n[r - 1]) - 1)
res = ['9'] * (len(res) + 1)
r -= 1
# 考虑第一个元素是否为0,不为0,则加入res
if list_n[r] != '0':
res.append(list_n[r])
# 返回res的逆序
return int(''.join(res[::-1]))
if __name__ == '__main__':
print(monotone_increasing_digits(963856657))
|
de57334bcbb07150146941ee80d780f07a6f10d5 | Leahxuliu/Data-Structure-And-Algorithm | /Python/贪心/区间问题/56. Merge Intervals.py | 894 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/05/25
'''
Method - greedy
Steps:
1. sort intervals based on interval[0]
2. append intervals[0] into res
3. traverse intervals[1:] (start, end)
4. compare start with res[-1][1]
if start <= res[-1][1], res[-1][1] = max(end, res[-1][1]) 包括相等
else, append [start, end] into res
5. return res
Time: O(nlogn)
Space: O(n)
'''
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if intervals == [] or intervals == [[]]:
return []
intervals.sort(key = lambda x:x[0])
res = [intervals[0]]
for start, end in intervals[1:]:
pre_end = res[-1][1]
if start <= pre_end:
res[-1][1] = max(pre_end, end)
else:
res.append([start, end])
return res |
9baa38f9cf403a3789da6e5089462a440e1f58ef | Un-knownCoder/Python-Repository | /Exercises/perfetto.py | 664 | 3.8125 | 4 | # Per stabilire se un numero e' perfetto bisogna
# calcolare se e' dato dalla somma dei suoi divisori
class Perfetto:
def calculate(self, num):
P = Perfetto()
value = p.getDivisori(num)
out = 0
for i in range(0, len(value)):
out += value[i]
if(out == num):
return True
else:
return False
def getDivisori(self, num):
array = []
for i in range(1, (num/2)+1):
if(num % i == 0):
array.append(i)
return array
p = Perfetto()
Number = int(input("Inserisci num... "))
print(p.calculate(Number))
|
d68ff9fec6be7beb4b001ea1d9ce0cb3d1af57ea | Brian-Mascitello/UCB-Third-Party-Classes | /Udacity-Intro-To-Computer-Science/Lesson 12/Lesson 12 - Quizzes/Product List.py | 506 | 4.21875 | 4 | # Define a procedure, product_list,
# that takes as input a list of numbers,
# and returns a number that is
# the result of multiplying all
# those numbers together.
def product_list(list_of_numbers):
product = 1
for number in list_of_numbers:
product = product * number
return product
# print product_list([9])
# >>> 9
# print product_list([1,2,3,4])
# >>> 24
# print product_list([])
# >>> 1
print(product_list([9]))
print(product_list([1, 2, 3, 4]))
print(product_list([]))
|
81fbdba5a8723fef6fdaec04d7da14984b2eaefa | daniel-reich/ubiquitous-fiesta | /ygeGjszQEdEXE8R8d_4.py | 815 | 3.546875 | 4 |
from copy import deepcopy
class Move:
dirn = {'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1)}
def __init__(self, mat):
self.height = len(mat)
self.width = len(mat[0])
for r, c in [(r,c) for r in range(self.height) for c in range(self.width)]:
if mat[r][c] == 1:
break
self.r, self.c, self.mat = r, c, deepcopy(mat)
def make_move(self, m):
if m == 'stop':
return self.mat
if m in self.dirn:
self.set_pos(self.r, self.c, 0)
dr, dc = self.dirn[m]
self.r = (self.r + self.height + dr) % self.height
self.c = (self.c + self.width + dc) % self.width
self.set_pos(self.r, self.c, 1)
return self.make_move
def set_pos(self, r, c, v):
self.mat[r][c] = v
def move(mat):
return Move(mat).make_move
|
c3a063f96474b634ba373dc46e45dce59ad28b8c | allegit/cs50w | /openFile.py | 766 | 3.71875 | 4 | """openFile.py
Reads a file containing scores then prints the data as-is, sorts and prints and then reverses
and prints
"""
scores = [] # Array to hold scores
names = [] # Array to hold names
result_f = open('results.txt')
for line in result_f:
(name,score) = line.split()
scores.append(float(score))
names.append(name)
result_f.close()
print("The contents of the results file:")
i = 0
for i in range(len(scores)):
print(names[i] + ' with ' + str(scores[i]))
scores.sort()
names.sort()
print("The contents after a sort:")
for i in range(len(scores)):
print(names[i] + ' with ' + str(scores[i]))
scores.reverse()
names.reverse()
print("The contents after a reverse:")
for i in range(len(scores)):
print(names[i] + ' with ' + str(scores[i]))
|
8320aabb883c1ef1fc8205039bdeeaa8653b7a8f | LesterAGarciaA97/OnlineCourses | /08. Coursera/20. Data visualization with Python/Module 1/Week 01/Program/PythonDataV/task2.py | 552 | 3.765625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Create the dataframe using the json file...
df = pd.read_json (r'./rain.json')
plt.figure(figsize=(17,5))
plt.plot( df['Month'], df['Temperature'], label='Temperature')
plt.show()
#Plot rainfall
plt.figure(figsize=(17,5))
plt.plot( df['Month'], df['Rainfall'], label='Rainfall')
plt.show()
#Plot temperature and rainfall together
plt.plot( df['Month'], df['Rainfall'], label='Rainfall')
plt.plot( df['Month'], df['Temperature'], label='Temperature')
plt.legend()
plt.show() |
b82e7ae66d5160d03d67c3bd8ef6a0c5d2408118 | TheAutomationWizard/learnPython | /pythonUdemyCourse/Interview_Questions/LogicMonitor/string_based.py | 1,353 | 3.75 | 4 | def get_first_non_repetitive_Case_sensitive(input):
position_holder = 0
unique_flag = False
for character in input:
position_holder += 1
sub_position_holder = 0
for other_char in input.lower():
sub_position_holder += 1
if position_holder == sub_position_holder:
continue
if other_char == character.lower():
unique_flag = False
break
unique_flag = True
if unique_flag:
return character
return ""
print(get_first_non_repetitive_Case_sensitive('sTress'))
print(get_first_non_repetitive_Case_sensitive('srress'))
print(get_first_non_repetitive_Case_sensitive('srrEess'))
print(get_first_non_repetitive_Case_sensitive('srrEessX'))
def cyclic_sub_string(input):
counter = 0
while input[:counter + 1] in input[counter + 1:]:
counter += 1
if not input[:counter + 1] in input[counter + 1 :]:
if ((input + input[counter:])[len(input[counter:]):]) == input:
return len(input[counter:])
return len(input)
print('cyclic length : ', cyclic_sub_string('cabca')) # 3
print('cyclic length : ', cyclic_sub_string('caabcaa')) # 4
print('cyclic length : ', cyclic_sub_string('ccabocca')) # 5
print('cyclic length : ', cyclic_sub_string('aabbox')) # 6
|
7c35f6e372f479d2d5a5dd1f2e90fedf030afda0 | indo-seattle/python | /Sandesh/Week3_0324-0330/CollectionDataTypes/10_CountEachStatefromList.py | 458 | 4.03125 | 4 | #Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times each state appeared in the list.
mylist = ["WA", "CA", "NY", "IL", "WA", "CA", "WA"]
for x in mylist:
print(mylist.count(x),x)
print("WA is", mylist.count("WA"), "in the list")
print("CA is", mylist.count("CA"), "in the list")
print("NY is", mylist.count("NY"), "in the list")
print("IL is", mylist.count("IL"), "in the list") |
83c38ad389ac23abb0ee84ce31e45675c7e007ff | Pegasids/Introduction-to-the-Foundations-of-Computation-I | /Lab Assignments/Lab 12/Lab 12.py | 1,397 | 3.65625 | 4 | from wordplay import *
import os
import random
s = ""
all_pron = all_homophones()
all_anag = all_anagrams()
inv = invert_dict(all_homophones())
count = 0
txtfile = str(input("File name: "))
while True:
if os.path.isfile(txtfile):
fin = open(txtfile, 'r')
break
else:
print("File DNE.")
txtfile = str(input("File name: "))
print("File does not exist.")
new = "new_" + txtfile
opt = input("Number of lines to be changed: ")
if opt == "all" or "All" or "ALL":
opt = False
else:
opt = int(opt)
for line in fin:
count += 1
line = line.split()
each_line = []
for word in line:
pron = pronunciation(word, all_pron)
sign = signature(word)
word1 = all_anag.get(sign)
if pron != "":
lst_of_word = inv.get(pron)
if len(lst_of_word) > 1 :
while True:
sample_word = random.choice(lst_of_word)
if sample_word != word:
word = sample_word
break
elif word1 != None:
word = random.choice(word1)
each_line.append(word)
for each in each_line:
print(each, end = " ")
print()
if count == opt:
break
s += "\n"
fin.close()
'''
print(s)
out = open(new,'w')
out.write(s)
out.close() ''' |
f1b9ad5eb0054536bbe4f1a6badaca082711c675 | annasochavan777/Python-Assignment | /Assignment-3/Assignment3_5.py | 1,241 | 4.25 | 4 | ##################################################################################################
# Write a program which accept N numbers from user and store it into List. Return addition of all
# prime numbers from that List. Main python file accepts N numbers from user and pass each
# number to ChkPrime() function which is part of our user defined module named as
# MarvellousNum. Name of the function from main python file should be ListPrime().
# Input : Number of elements : 11
# Input Elements : 13 5 45 7 4 56 10 34 2 5 8
# Output : 32 (13 + 5 + 7 +2 + 5)
# Author : Annaso Chavan
###################################################################################################
from MarvellousNum import *
import functools
# function to return frequency of that number from List
def ListPrime(arr):
return list(filter(ChkPrime,arr))
def main():
arr = []
number = int(input("Number of elements :"))
for i in range(number):
no = int(input("enter {} element :".format(i+1)))
arr.append(no)
print("Enter Data :",arr)
prime_arr = ListPrime(arr) # call ListPrime function
sum = functools.reduce(Add,prime_arr)
print("Sum of Prime number is :",sum) # print result
# code starter
if __name__ == "__main__":
main() |
c8f9261b705be99057e3b9dd382cdb5c1db6b628 | fzelkhamouri/Regression_NN | /NN2.py | 2,865 | 3.78125 | 4 | import numpy as np
class Neural_Network(object):
def __init__(self):
# Parametters
self.inputSize = 2
self.outputSize = 1
self.hiddenSize = 3
# Weights
self.W1 = np.random.randn(self.inputSize, self.hiddenSize) # (2x3) weight matrix size
print(self.W1)
self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # (3x1) weight matrix size
print(self.W2)
def forward(self,X):
# Forward propagation through the network
self.z = np.dot(X, self.W1) # dot products of input with firt set of 2x3 weights
self.z2 = self.sigmoid(self.z) # activation function
self.z3 = np.dot(self.z2, self.W2) # dot product of hidden layer z2 and second set of 3x1 weights
o = self.sigmoid(self.z3) # Final activation Function
return o
def sigmoid(self, s):
# activation function
return 1/(1 + np.exp(-s))
def sigmoidPrime(self, s):
# Derivative of sigmoid
return s * (1 - s)
def backward(self, X, y, o):
# Backward propagation through the network
self.o_error = y - o # error in output
self.o_delta = self.o_error * self.sigmoidPrime(o)
self.z2_error = self.o_delta.dot(self.W2.T)
self.z2_delta = self.z2_error * self.sigmoidPrime(self.z2)
self.W1 += X.T.dot(self.z2_delta)
self.W2 += self.z2.T.dot(self.o_delta)
def train(self, X, y):
o = self.forward(X)
self.backward(X, y, o)
def saveWeights(self):
np.savetxt("w1.txt", self.W1, fmt = "%s")
np.savetxt("w2.txt", self.W2, fmt = "%s")
def predict(self):
print("Predictive Data Based on trained Weights: ")
print("Input (Scaled): \n" + str(xPredicted))
print("Output: \n" + str(self.forward(xPredicted)))
# X = (hours studying, hours sleeping), y = score in test, xPredicted = 4 hours studying
X = np.array(([2,9], [1,5], [3,6]), dtype = float)
y = np.array(([92],[86],[89]), dtype = float)
xPredicted = np.array(([4,8]), dtype = float)
# scale units
print(X)
X = X/np.amax(X, axis = 0) # Maximum of X array
print(X)
print(xPredicted)
xPredicted = xPredicted/np.amax(xPredicted, axis = 0)
print(xPredicted)
y = y/100 # max test score
NN = Neural_Network()
for i in range(10): # Trains the NN 1000 times
print("#" + str(i) + "\n")
print("Input (scaled): \n" + str(X))
print("Actual output: \n" + str(y))
print("Predicted output: \n" + str(NN.forward(X)))
print("Loss: \n" + str(np.mean(np.square(y-NN.forward(X)))))
print("\n")
NN.train(X, y)
NN.saveWeights()
NN.predict()
|
f00a03b511b3337e9eb3d2d4895d9e48a5540e89 | aa-arora/Data_Structure_Algorithms_Utility | /integer_square_root.py | 333 | 3.96875 | 4 | def binary_search_square_root(target):
low = 0
high = target
while low <= high:
mid = (low + high) // 2
square_num = mid ** 2
if square_num > target:
high = mid - 1
elif square_num <= target:
low = mid + 1
return low - 1
print(binary_search_square_root(300))
|
529f85257c2e7c61f517ab276e020ea0117cfb97 | MEng-Alejandro-Nieto/Python-3-Udemy-Course | /10 TEST 1.py | 2,825 | 4.71875 | 5 | # write a brief description of all the following object types and data structures we have learned about:
# Number: number can be of two different types, integers such as (1, 13, 300) or float such as (1.2, 35.159, 0,004)
# Strings: this is basically text that can be indexing or sliced
# List: a list is a colection of ordered elements, this elements can be integer, float, string or a list and they can be mutable or change
mylist=["Hello World",5,10.3, ["List",5]]
print(mylist[0])
print(mylist[1])
print(mylist[2])
print(mylist[3])
# Dictionaries: is a colection of unordered elements that can be of any type, is similar to a list, but the difference is that the data inside is not tracked by a number but by a key value
mydictionary={"value 1":2,"value 2":"string","value 3":["Hello World",5,10.3, ["List",5]]}
print(mydictionary["value 1"])
print(mydictionary["value 2"])
print(mydictionary["value 3"])
# Tuples: a tuple is the same as a list however these are immutable and are enclosed by curved brackets
mytuple= (1,"string",[2,3])
print(mytuple[0])
print(mytuple[1])
print(mytuple[2])
# STRINGS
# Given the "Hello" give and index command that returns "e".
name="Hello"
print(name[1])
# Reverse the string "Hello" using slicing:
reverse=name[::-1]
print(reverse)
# Given the string "Hello", give two methods of producing the letter "o" using indexing.
print(name[-1])
print(name[4])
# LISTS
# Build this list [0,0,0] two separate ways
mylist=[0,0,0]
a=[0]
newlist=a*3
print(mylist)
print(newlist)
#Reasign "Hello" in the folowing nested list to say "goodbye" instead
list3=[1,2,[3,4,"Hello"]]
list3[2][2]="goodbye"
print(list3)
# Sort the list below:
list4=[5,3,4,6,1]
list4.sort()
print(list4)
# DICTIONARIES
# Use keys and indexing,grab the "hello" from the following dictionaries
d={"simple key":"hello"}
print(d["simple key"])
d={"k1":{"k2":"hello"}}
print(d["k1"]["k2"])
d={"k1":[{"nest_key":["this is deep",["hello"]]}]}
print(d["k1"][0]["nest_key"][1][0])
# can u sort a dictionary? a dictionary can be sort since by nature is unordered
# TUPLES
# what is the major difference between a tuple and a list? the tuples are immutable
# how do you create a tuple?
mytuple=(1,["string",2.2],{"deep":2})
print(mytuple)
# SETS
# what is unique about sets? a set is like a list of unique values
mylist=[1,1,9,8,6,6,2,4,7,6,7,3,6]
print(set(mylist))
# BOOLEAN
print(1<2) # 1 menor que 2?
print(1>2) # 1 mayor que 2?
print(1==1) # 1 igual a 1?
print(1==0) # 1 igual a 0?
print(1!=1) # 1 no es igual a 1?
# final question
# what is the boolean output of the cell block below?
one=[1,2,[3,4]]
two=[1,2,{"k1":4}]
a=one[2][0]>=two[2]["k1"] # is this true or false?
print(f"this is {a}")
|
87e9dc0937a256f39dc4ee51335452adbc20ba35 | arifaulakh/Project-Euler | /10-Summation-of-Primes/main.py | 269 | 3.671875 | 4 | def primes(n):
primes = []
sieve = [True] * (n + 1)
for p in range(2, n + 1):
if sieve[p]:
primes.append(p)
for i in range(p * p, n + 1, p):
sieve[i] = False
return primes
P = primes(2000000)
print(sum(P)) |
fcb3030677d9919b1d74de6adc239fde2aba0be6 | trgreenman88/CS_21 | /greenman_futval.py | 869 | 3.78125 | 4 | # Trent Greenman
# CS 21, Fall 2018
# Program: futval.py (Modification #4)
def main():
print("This program calculates the future value")
print("of a 10-year investment.")
# Get inputs for yearly amount, interest rate, number of years for the
# investment, number of times compounded, and set the total amount equal to 0
yearly_amt = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annual interest rate: "))
time = eval(input("Enter the number of years for your investment:"))
num_compound = eval(input("Enter the number of compounding periods per year:"))
total_amt = 0
# for loop to evaluate the equation 'time' times
for i in range(0,time):
total_amt = (yearly_amt + total_amt) * (1 + apr / num_compound)**num_compound
print("The value in", time, "years is:", total_amt)
main()
|
a0b99e48935984eb5c6f2d08f99f58adf26b4694 | rodrigohuila/python_scripts | /MyScripts/splitPdf.py | 2,524 | 3.671875 | 4 | #! python3
#! /usr/bin/python3
import os
import PyPDF2
from tkinter import filedialog as FileDialog
from tkinter import messagebox as MessageBox
from os import system
from os.path import basename
path = r"D:/Users/victo/Downloads/"
path2 = r"D:/Users/victo/Desktop/RenamePDF/"
contentAll = ''
def clear(): # BORRAR PANTALLA
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
def openFile(path): # DIALOG TO CHOOSE A FILE
pdfName = FileDialog.askopenfilename(
initialdir=path,
filetypes=(
("Archivos PDF", "*.pdf"), ("All files", "*.*")
),
title="Escoja el archivo PDF a dividir."
)
name = basename(pdfName)
print('\nEl nombre del archivo inicial es: ' + name + '\n')
return(pdfName)
def pdf_splitter(pdfName, pdfReader): #SPLIT A PDF DOCUMENT
os.chdir(path2)
if os.path.isdir((os.path.splitext(basename(pdfName))[0])):
MessageBox.showwarning(
"Advertencia","""Hay una carpeta con el mismo nombre del PDF, es decir, ya se había dividido este PDF o un archivo con el mismo nombre.\n
Los archivos se sobreescribiran""")
#print('Advertencia:\nHay una carpeta con el mismo nombre del PDF, es decir, ya se había dividido este PDF o un archivo con el mismo nombre.\nLos archivos se sobreescribiran:\n')
newDir = (os.path.splitext(basename(pdfName))[0])
else:
os.mkdir(os.path.splitext(basename(pdfName))[0])
newDir = (os.path.splitext(basename(pdfName))[0]) # Crear una carpeta con el mismo nombre del archivo requerido
for pageNum in range(pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(pageObj)
output_filename = 'page_{}_{}'.format(
pageNum+1, basename(pdfName))
os.chdir(path2 + newDir) # Guardar en una carpeta con el mismo nombre del archivo requerido
with open(output_filename, 'wb') as out:
pdfWriter.write(out)
print('Created: {}'.format(output_filename))
return(pageObj)
def main ():
clear ()
pdfName = openFile(path)
# Open the pdf file
pdfFileObj = open( pdfName, 'rb')
# Read info
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pdf_splitter(pdfName, pdfReader)
print ('\nEl documento tiene: ' + str(pdfReader.numPages) + ' páginas')
if __name__ == '__main__':
main()
os.system('pause') # Press a key to continue |
042dd4d4dbe40949fbd577771d29161342565944 | Sharvari07/Functional-programming-in-python | /practice problems/last element of list.py | 463 | 3.703125 | 4 | import random
ls = [random.randint(0,20) for i in range(10)]
print (ls)
l = len(ls)
'''
for x in range(l):
if x == l-1:
print("last number is:", ls[x])
'''
'''
last = [print("Last no is:",ls[x]) for x in range(l) if x==(l-1)]
def find_last(list, index):
if index == len(list) - 1:
return list[index]
else:
find_last(list, index+1)
find_last(list, 0)
[n in next_prime(100)]
map(find_last, list_of_lsitsfind_last(x)
''' |
8b93e1e66783a2348b65a465094cdd0e8daa0bf9 | BarberAlec/Common-Interview-Questions | /code/mostFreqInt.py | 405 | 3.65625 | 4 | def mostFreqInt(my_list):
d = dict()
for val in my_list:
key = str(val)
if key in d:
d[str(val)] += 1
else:
d[str(val)] = 1
max_val = -1
max_key = None
for key,freq in d.items():
if freq>max_val:
max_val = freq
max_key = key
return int(key)
print(mostFreqInt([1,2,3,2,2,2,1,1,3,2,2,2])) |
a5c1513e205100031be9a2327067929f87a7429b | xidaodi/AILearn | /pandas_test.py | 258 | 3.71875 | 4 | import numpy as np
import pandas as pd
# create a pandas dataframe
arr=np.array([["Zhang",30,100],
["Chang",100,100],
["Huang",30,60]]
)
df=pd.DataFrame(arr,index=[1,2,3],columns=["name","math","english"])
print(df) |
b6cd7a9b0c9c6b6fb12b25de83844936bc09b736 | chloe-wong/pythonchallenges | /A214.py | 1,308 | 3.703125 | 4 | #exercise1
dictionary = {}
sentence = input()
b = sentence.lower()
a = b.replace(" ","")
for x in range(len(a)):
if a[x] in dictionary:
dictionary[a[x]] = dictionary[a[x]]+1
else:
dictionary[a[x]] = 1
dictionaryitems = list(dictionary.items())
dictionaryitems.sort()
for y in range(len(dictionaryitems)):
print(dictionaryitems[y])
#exercise2
a) 35: asks for value of bananas in d
b) 4: the program added an item, so there are now 4 in d
c) True: checked if grapes were a key in d
d) KeyError: 'pears': pears are not in d
e) 0: since pears are not in d, the program returns 0
f) ['apples', 'bananas', 'grapes', 'oranges']: returns the keys of d in alphabetical order
g) False: apples have been deleted so are no longer in d
def add_fruit(inventory, fruit, quantity=0):
inventory[fruit] = quantity
return
#exercise3
towrite = open("alice_words.txt",w)
toread = open("aliceplain.txt",r)
count = {}
for line in toread:
a = line.split()
for x in range(len(a)):
if a[x] in dictionary:
dictionary[a[x]] = dictionary[a[x]]+1
else:
dictionary[a[x]] = 1
dictionaryitems = list(dictionary.items())
dictionaryitems.sort()
for y in range(len(dictionaryitems)):
print(dictionaryitems[y])
towrite.append(dictionaryitems[y])
|
280e584e3820bcf8802d26926b200f79612e231a | xshen1122/Python-practice-1 | /lambda_p1.py | 384 | 3.828125 | 4 | # lambda_p1.py
# coding: utf-8
'''
format lambda x: x*x
匿名函数有个限制,
就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
'''
print map(lambda x: x*x, [1,4,5,7,9])
'''
Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。
'''
def build(x,y):
return lambda: x*x + y*y
print build(5,7)() |
fe006f5dbb34fe5eb0a42b6ebc4e074b528dec00 | huangketsudou/leetcode_python | /List Node/postorder.py | 625 | 3.65625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
from collections import deque
if not root: return []
stack = deque()
stack.append(root)
res = []
while stack:
node = stack.popleft()
res.append(node.val)
if node.children is not None:
for child in node.children:
stack.appendleft(child)
res=list(reversed(res))
return res
|
8c434d869f2fec10c6eeb4e1089455fc91920024 | Jownao/Provas-Laboratorio-e-Introducao-a-progamacao | /provas de prog/LABORATORIO/Prova3/Docente.py | 611 | 3.53125 | 4 | import Funcionario as fu
class docente(fu.funcionario):
def __init__(self):
super().__init__()
self.disciplina = ''
self.salario = 0.0
self.titulacao = ''
def cadastrar(self):
super().cadastrar()
print('Dados do Docente'.center(50, '-'))
self.disciplina = input('Entre com a disciplina: ')
self.titulacao = input('Entre com a titulação: ')
def exibir(self):
super().exibir()
print('Dados do Docente'.center(50, '-'))
print(self.disciplina)
print(self.titulacao)
|
538d2022fc0bc46e92c0c3881a4e604e56ad1eed | tonydo2020/CPSC_Security | /final_version.py | 3,798 | 3.53125 | 4 | import random
D = [('F', 'P', 'Z'),
('G', 'Q'),
('I', 'S'),
('J', 'T'),
('A', 'K', 'U'),
('B', 'L', 'V'),
('C', 'M', 'W'),
('D', 'N', 'X'),
('E', 'O', 'Y'),
]
symbol_list = ['!', '@', '#', '$', '%']
def getString():
user_string = input("Enter in your string")
return user_string
def displayPlainText():
print("b")
def displayText():
print("c")
def Quit():
quit()
def cypher(user_string):
print("a")
def encrypt(k, string):
print("d")
def getKey():
number = random.randint(0, 4)
return symbol_list[number]
def getEncrypt(keylist, string):
pkey = ""
pkey_count = 0
c = ""
for a in range(len(keylist)):
c = keylist[a]
if c == '(':
pkey = keylist[a + 1]
break
for b in range(len(keylist)): # starting at the next key value after the (
if keylist[b] == pkey:
pkey_count = pkey_count + 1
operation_list = []
for a in range(pkey_count):
string = encrypt_string(pkey, pkey_count, keylist, string, operation_list)
print("operation list is: ", operation_list)
fully_encrypt_list = []
fully_encrypt_string = ""
for a in range(len(string)):
fully_encrypt_string += string[a]
for b in range(len(operation_list[a])):
fully_encrypt_string += operation_list[a][b]
print("fully_encrypt_string: ", fully_encrypt_string)
def append_character_exclam(character, position, inner_list, rule_list):
if character == '+' or character == '-':
return
elif ord(character) < 222:
num = ord(character) + 33
num_char = chr(num)
inner_list.insert(position + 1, num_char)
rule_list.insert(position + 1, '+')
elif ord(character) > 222:
num = ord(character) - 33
num_char = chr(num)
inner_list.append(num_char)
rule_list.append('-')
def encrypt_string(pkey, pkey_count, keylist, string, operation_list):
print("pkey_count is: ", pkey_count)
encrypted_string = ""
print("passed string is: ", string)
for a in range(pkey_count):
if pkey == '!':
if keylist[a + 1] == '!':
print("here")
inner_list = []
rule_list = []
counter = 0
for b in string:
append_character_exclam(b, counter, inner_list, rule_list)
counter += 1
print("inner list is: ", inner_list)
print("rule list is: ", rule_list)
for a in range(len(inner_list)):
encrypted_string += inner_list[a]
operation_list.append(rule_list)
print("encrypted string is: ", encrypted_string)
return encrypted_string
def switch_state(argument):
print("argument is:", argument)
if int(argument) == 1: # THIS IS ARGUMENT 1
string = getString()
print("Received String is: ", string)
length = random.randint(1, 10)
keylist = ""
for a in range(length):
keylist += getKey()
keylist = '(!!!' + keylist + ')'
print(keylist)
# print("keylist is: (" + keylist + ")")
getEncrypt(keylist, string)
elif int(argument) == 2:
displayPlainText()
elif int(argument) == 3:
displayText()
else:
Quit()
def main():
run = True
while run:
print("1 Encrypt Text")
print("2 Decrypt Text")
print("3 Print Encrypted")
print("Anything else to quit")
user_input = input("Please enter an option\n")
switch_state(user_input)
if user_input == 4:
run = False
if __name__ == "__main__":
main()
|
ed62f625098ef8ddc379da6983c9cf5f507d7b6c | onlykevinpan/Summer-Lecture-for-Teacher-With-Python | /Linkedlist & Tree/LinkedList.py | 1,699 | 3.8125 | 4 | class Node:
#一個節點含兩個數值及下一個節點所在位置
def __init__(self):
self.coeff = None
self.power = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
#插入節點時即依照次方做排序
def addNode(self, coeff, power):
curr = self.head
if curr is None:
n = Node()
n.coeff = coeff
n.power = power
self.head = n
return
if curr.power < power:
n = Node()
n.coeff = coeff
n.power = power
n.next = curr
self.head = n
return
while curr.next is not None:
if curr.next.power < power:
break
curr = curr.next
n = Node()
n.coeff = coeff
n.power = power
n.next = curr.next
curr.next = n
return
def output(ll):
#輸出控制
c = ll.head
while c is not None:
che = c.next
if(che != None):
if(che.coeff > 0):
print(str(c.coeff)+"X^"+str(c.power)+"+", end="")
else:
print(str(c.coeff)+"X^"+str(c.power), end="")
else:
if(c.power == 0):
print(str(c.coeff))
else:
print(str(c.coeff)+"X^"+str(c.power))
c = c.next
def main():
#輸入0 0 時結束
ll = LinkedList()
coeff, power = map(int, input("input coefficient and power: ").split())
while coeff != 0:
ll.addNode(coeff, power)
coeff, power = map(int, input("input coefficient and power: ").split())
output(ll)
main()
|
329ec125b3b8acd9eb527bbf42b198fc21c33ecf | venkatr21/python_coding | /codeforces1.py | 195 | 3.59375 | 4 | n=int(input())
counter=0
if n>9:
n=n-9
counter+=1
while n>=20:
n=n-20
counter+=1
if n%2:
print(counter)
else:
print(n//2-1)
else:
print(n)
|
4bd7d6a90e3fbae7e711145bf2622621b94c43df | Aluriak/rollin-function | /rollin.py | 688 | 3.5 | 4 | def somme_chiffre(nb:int) -> int:
return sum(map(int, str(nb).replace('-', '').replace('.', '')))
def rollin(annee) -> int:
"""Calcule le nombre de Rollin pour l'année donnée
>>> rollin(2005)
3
>>> rollin(1922)
5
>>> rollin(0)
0
"""
nb = ((-52 * annee) + (sum(map(int, str(annee)[1:])) * 21947)) / 73
while len(str(nb)) > 1:
nb = somme_chiffre(nb)
return nb
assert rollin(2005) == 3
assert rollin(1922) == 5
def annees_rollin(start=1922, end=2018) -> [int]:
"""Génère les années Rollin trouvées entre les bornes (incluses)"""
for year in range(start, end+1):
if rollin(year) == 3:
yield year
|
8e16aebf403570874b7c817c1c79ca1a900cd46e | vale314/Seminario-Algoritmia | /Actividad 9/grafo.py | 832 | 3.703125 | 4 | import pprint
grafo = dict() #{}
while True:
print('1 Crear Conexión')
print('2 Mostrar Grafo')
print('0 Salir')
op = input(': ')
if op == '1':
origen= input('origen: ').upper()
destino = input('Destino: ').upper()
peso = int(input('Peso: '))
if origen in grafo:
grafo[origen].append((destino,peso))
else:
grafo[origen] = [(destino,peso)]
if destino in grafo:
grafo[destino].append((origen,peso))
else:
grafo[destino] = [(origen,peso)]
elif op == '2':
#pprint.pprint(grafo,width=40)
str = pprint.pformat(grafo,width=40)
print(str)
elif op == '0':
break
grafo['A'] = [('B',10),('C',2)]
grafo['B'] = [('A',10)]
grafo['C'] = [('A',2)]
pprint.pprint(grafo,width=40) |
8e062b298f4bb2175a534bd0f69ea4948a78afbf | lxmii/SWE2018 | /rle.py | 861 | 3.5625 | 4 |
def rle_encoder(txt):
""" RLE encoder modetager en streng og returner en streng
med så gentagne bogstaver bilver erstattet med bogstavet og
antallet af gentagelser
"bbbkkk" bliver "b3k3"
"""
c = txt[0]
i = 1
res = []
for x in txt[1:]:
if x == c:
i += 1
else:
res.append(f'{c}{i}')
c=x
i=1
res.append(f'{c}{i}')
return ''.join(res)
def rle_decoder(txt):
# 'l'*3 ->'lll'
c = txt[0]
res = []
for x in txt[1:]:
if x.isdigit():
res.append(c*int (x))
else:
c=x
return ''.join(res)
if __name__=="__main__":
args= sys.argv
print(args)
if argv[1]=='-d':
rle_decoder(args[2])
else:
rle_encoder(args[2])
|
0538ed593bd1d7b21099d8c27b6d5785aded085e | stunningspectacle/code_practice | /python/python_cookbook/c04_iterator_generator.py | 2,501 | 3.53125 | 4 | #!/usr/bin/python3
from unittest import TestCase, main
def do_iter():
items = [1, 2, 3, 4]
it = iter(items)
print(it)
try:
while True:
a = next(it)
print(a)
except StopIteration:
pass
def do_reversed():
class CountDown:
def __init__(self, start):
self.start = start
def __iter__(self):
start = self.start
while start > 0:
yield start
start -= 1
def __reversed__(self):
i = 1
while i <= self.start:
yield i
i += 1
for i in CountDown(5):
print(i)
for i in reversed(CountDown(5)):
print(i)
def do_enumerate():
from collections import defaultdict
simple_dict = defaultdict(list)
with open("sample.txt") as f:
for index, line in enumerate(f, 1):
words = [w.strip().lower() for w in line.split()]
for word in words:
simple_dict[word].append(index)
print(simple_dict)
def do_zip():
headers = ['name', 'shares', 'price']
values = ['ACME', 100, 490.1]
s = zip(headers, values)
print(list(s))
s = dict(zip(headers, values))
print(s)
def do_pipe():
import os
def gen_filenames():
for path, dirlist, filelist in os.walk("/home/leo/study/code_practice/python"):
for f in filelist:
if f.endswith(".sh"):
yield os.path.join(path, f)
def gen_opener(filenames):
for filename in filenames:
f = open(filename)
yield f
f.close()
def gen_counter(opened_files):
for f in opened_files:
for index, line in enumerate(f):
#print(index, line)
yield len(line.strip().split())
filenames = gen_filenames()
opener = gen_opener(filenames)
print(sum(gen_counter(opener)))
def do_flatten():
from collections import Iterable
items = [1, 2, [3, 4, [5, 6], 7], 8]
def flatten(items, ignore_types=(str, bytes)):
for i in items:
if isinstance(i, Iterable) and not isinstance(i, ignore_types):
yield from flatten(i)
else:
yield i
print(list(flatten(items)))
class C03TestCase(TestCase):
def test_test(self):
do_flatten()
print("---------Test Done--------")
if __name__ == '__main__':
main()
|
f7539ed431d2efed86248b43bbf319a52c58e5a4 | Jeysi2004/GRUPO-5 | /PAR O IMPAR 1.py | 200 | 3.859375 | 4 | def verificarNumero(numero):
if numero%2==0:
print ("El número es par")
else:
print ("El número es impar")
n1=int(input("Ingrese un número: "))
verificarNumero(n1)
|
4ed86cc5c076a5afc15d7fedf5502a31c1e26fad | vfaldasz/practice | /arrays_and_strings.py | 5,145 | 4.09375 | 4 | def is_unique(string):
"""1.1 Implement an algorithm to determine if a string has all unique characters."""
unique = []
for char in string:
if char in unique:
return False
else:
unique.append(char)
return True
string = "asdifF"
print (is_unique(string))
def is_unique(string):
unique = {}
for letter in string:
counter = unique.get(letter, 0)+1
unique[letter]= counter
if counter > 1:
return False
return True
string = "asdifzFffff"
print (is_unique(string))
def is_unique(string):
"""Solve problem without data structures. Runtime is n^2"""
for i in range(len(string)):
for j in range(i+1, len(string)):
if string[i] == string[j]:
return False
return True
string= "pqqrz"
print(is_unique(string))
def is_permutation(string1, string2):
"""1.2 Given two strings, write a method to decide if one is a permutation of the other."""
dict1 = {}
dict2 = {}
for letter in string1:
value = dict1.get('letter', 0)+1
dict1['letter']=value
for letter in string2:
value = dict2.get('letter', 0)+1
dict2['letter']=value
for item in dict1.items():
if item in dict2.items():
return True
return False
string1= 'odor'
string2= 'door'
print(is_permutation(string1, string2))
def make_url(string):
"""1.3 Write a method to replace all spaces in a string with '%20.'"""
return string.replace(" ", "%20")
string= "Mr John Smith "
print(make_url(string))
def make_url2(string):
letters = list(string)
i = len(letters) - 1
j = i
while letters[i] == " ":
i -= 1
while j != i:
if letters[i] == " ":
letters[j-2] = "%"
letters[j-1] = "2"
letters[j] = "0"
j -= 2
else:
letters[j] = letters[i]
i -= 1
j -= 1
return ''.join(letters)
string= "Mr John Smith "
print(make_url2(string))
def perm_of_palindrome(string):
""" 1.4 Given a string, determine if it is a permutation of a palindrome"""
dict={}
for letter in string:
value =dict.get(letter, 0)+1
dict[letter]= value
counter = 0
for value in dict.values():
if value % 2 == 1: #if values is evenly divisible by 2, then we know its a palindrome. We can allow for only one odd value (i.e in radar 'd' is your odd value. However, radars (d and s is your odd value, therefore it would not be a palindromee))
counter +=1
if counter > 1:
return False
return True
string = "tacocat"
print(perm_of_palindrome(string))
def sum_of_unique_nums(x,y):
for item in x:
if item not in y:
y.append(item)
print (y)
#return y
result= 0
for item in y:
result= result + item
return result
n= [2,4,4,6,8,8]
m= []
#print (sum_of_unique_nums(n,m))
def one_away(str1, str2):
# Determine whether the edit distance between two strings is less than 2.
len_diff = abs(len(str1) - len(str2))
if len_diff > 1:
return False
elif len_diff == 0:
difference_count = 0
for i in xrange(len(str1)):
if str1[i] != str2[i]:
difference_count += 1
if difference_count > 1:
return False
return True
else:
if len(str1) > len(str2):
longer, shorter = str1, str2
else:
longer, shorter = str2, str1
shift = 0
for i in xrange(len(shorter)):
if shorter[i] != longer[i + shift]:
if shift or (shorter[i] != longer[i + 1]):
return False
shift = 1
return True
# Write a function that takes in 3 integers as arguments and returns a list of numbers from 1 to 100 (inclusive), containing only integers that are evenly divisible by at least one of the integers.
# For example, given 50, 30, and 29, return [29, 30, 50, 58, 60, 87, 90, 100].
def divisible(x,y,z):
num = 1
a=[]
while num<101:
if (num % x == 0) or (num % y == 0) or (num % z == 0):
a.append(num)
num +=1
return a
l= 50
m= 30
n= 29
#print (divisible(l,m,n))
def modifying_hello(x):
for index, item in enumerate(x):
if item in m:
x[index]="*"
return x
x= ["h", "e", "l", "l", "o"]
m= ["a", "e", "i", "o", "u"]
#print (modifying_hello(n))
def sum_of_odd_nums(x):
m= []
result= 0
for item in x:
if item % 2 ==1:
m.append(item)
result+= item
return result
x= [1,2,3,4,5]
#print (sum_of_odd_nums(x)
#given tuples of number of minutes a person viewed a movie, implement a function that calculates the total minutes a person viewed a movie.
# i.e. (0,10) (35-55) (5,15) (40,60)
def sum_of_min():
length = max
seen =[0] * length
for lo, hi in pairs:
sum[lo:hi] = 1
return sum(seen)
def sum_of_unique_nums(x,y):
for item in x:
if item not in y:
y.append(item)
print (y)
#return y
result= 0
for item in y:
result= result + item
return result
n= [2,4,4,6,8,8]
m= []
|
058bd3191b3b92636e1c30815a101ca226a937b1 | zzy1120716/my-nine-chapter | /ch02/related/0141-sqrtx.py | 1,715 | 4.0625 | 4 | """
141. x的平方根
实现 int sqrt(int x) 函数,计算并返回 x 的平方根。
样例
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
挑战
O(log(x))
"""
import math
# 二分法
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
start, end = 0, x
while start + 1 < end:
mid = (start + end) // 2
if mid * mid == x:
return mid
elif mid * mid < x:
start = mid
else:
end = mid
if start * start == x:
return start
if end * end == x:
return end
return start
class Solution0:
def sqrt(self, x: int) -> int:
low, high = 1, x
ans = 0
while low <= high:
mid = (low + high) // 2
if mid ** 2 <= x:
low = mid + 1
ans = mid
else:
high = mid - 1
return ans
class Solution1:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
return int(math.sqrt(x))
# 牛顿迭代法,令t = sqrt(x), 根据 x = sqrt(x) * sqrt(x)构造不动点
class Solution2:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
guess = 1.0
while abs(x - guess * guess) > 0.1:
guess = (x / guess + guess) / 2
return int(guess)
if __name__ == '__main__':
print(Solution0().sqrt(3))
print(Solution0().sqrt(4))
print(Solution0().sqrt(5))
print(Solution0().sqrt(10))
|
e99ebb2b5c9bb51f31070f70f8720ed8186b127a | garytryan/dp2 | /knapsack/recursive/problem.py | 404 | 3.90625 | 4 | # Given items with a weight and profit.
# Put the items in the knapsack to get the maximum profit.
# The knapsack a weight capacity.
# You can only take at most 1 of each item.
# Example:
# Capacity: 3
# Given the following items.
# profit: [1, 2, 3]
# weight: [2, 1, 2]
# The maximum profit is: 5 (using items at index 1, 2)
def solution(profit: [int], weight: [int], capacity: int) -> int:
pass
|
caa2faecb9d4cae55544b064c3842176bbdf04fe | Geeky-har/Python-Files | /oop.py | 547 | 4.09375 | 4 | class Student:
no_of_keys = 3 # class variable, will shared by all the objects, objects cannot change this
pass
harsh = Student() # object created
aditya = Student() # object created
harsh.marks = 89
harsh.thappad = 2
harsh.kisses = 99
aditya.marks = 70
aditya.thappad = 10
aditya.kisses = 6
print(aditya.no_of_keys)
Student.marks = 4 # New class variable created
print(Student.marks)
print(Student.__dict__)
aditya.no_of_keys = 10 # new instance variable created
print(aditya.no_of_keys)
print(aditya.__dict__) |
1a5c97ef69cf56caba71e9653c42eb2013453b3d | sirajmuneer123/anand_python_problems | /2_chapter/reverse.py | 188 | 3.875 | 4 | def reverse(num):
length=len(num)
i=0
temp=[]
while length!=0:
temp.append(num[length-1])
length=length-1
return temp
f=reverse([1,2,3,4,5,6,7])
print "revere is =%s" %f
|
9eb7dcc3c3f72492aae0c9fee3bbe0e62fb78d0d | philippegirard/square-weebly-parser | /orderParser.py | 4,907 | 3.578125 | 4 | import pandas
import csv
from dataclasses import LineOrder
df = pandas.read_csv('splitting-11-13.csv')
print(list(df.columns))
lineOrderList = []
for index, row in df.iterrows():
# print(row[0], row[1])
orderNum = row['OrderNum']
date = row['Date']
firstName = row['Shipping First Name']
lastName = row['Shipping Last Name']
email = row['Shipping Email']
productId = row['Product Id']
productOptions = row['Product Options']
productQty = row['Product Quantity']
productPrice = row['Product Price']
productOptionPrice = row['Product Options Total Price']
productPaidPrice = row['Product Total Price']
coupon = row['Coupon']
# get line order if exists in list
lineOrder = None
for lo in lineOrderList:
if lo.orderNum == orderNum:
lineOrder = lo
# add line order if not exist in list
if lineOrder is None:
lineOrder = LineOrder(orderNum, date, firstName, lastName, email, coupon)
lineOrderList.append(lineOrder)
lineOrder.addProduct(productId, productOptions, productQty, productPrice, productOptionPrice, productPaidPrice)
# print(orderNum, date, firstName, lastName, email, productId, productOptions, productQty, coupon)
# for lo in lineOrderList:
# print(lo.orderNum, lo.albumPrice, lo.albumNum, lo.activitePrice, lo.activite)
def correct(a):
if a is None:
return None
return a.replace('é', 'é').replace('É', 'É').replace('ë', 'ë').replace('è', 'è')
def cc(a):
if a is None:
return
if len(a) > 0:
return correct(a[0])
with open('OUTPUT.csv', mode='w', newline='') as csv_file:
fieldnames = ['orderNum', 'date', 'firstName', 'lastName', 'email', 'coupon', 'totalPrice', 'totalDiscount',
'totalPaid', 'joncSize', 'joncInvite', 'joncParrain', 'joncParrainName',
'casinoTicketNumber', 'b1Occupation', 'b1C1', 'b1C2', 'b1C3',
'b2Occupation', 'b2C1', 'b2C2', 'b2C3', 'b2AccompOccup', 'b2AccompName', 'b2Vege', 'b2VegeAccomp',
'allergie', 'activite', 'albumNum', 'cotonVertOption', 'cotonNoirOption', 'bockOption', 'joncQty',
'joncTicketQty', 'casinoTicketQty', 'B1Qty', 'b2Qty',
'activiteQty', 'albumQty', 'cotonVertQty', 'cotonNoirQty', 'bockQty', 'joncPrice', 'joncTicketPrice',
'casinoPrice',
'b1price', 'b2price', 'activitePrice', 'albumPrice', 'cotonVertPrice', 'cotonNoirPrice', 'bockPrice']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for lo in lineOrderList:
writer.writerow({'orderNum': lo.orderNum, 'date': lo.date, 'firstName': lo.firstName, 'lastName': lo.lastName,
'email': lo.email, 'coupon': lo.coupon, 'totalPrice': lo.loTotalProductPrice,
'totalDiscount': lo.loTotalProductDiscount, 'totalPaid': lo.loTotalProductPaidPrice,
'joncSize': cc(lo.joncSize), 'joncInvite': cc(lo.joncInvite),
'joncParrain': cc(lo.joncParrain), 'joncParrainName': cc(lo.joncParrainName),
'casinoTicketNumber': lo.casinoTicketNumber,
'b1Occupation': cc(lo.b1Occupation), 'b1C1': cc(lo.b1C1), 'b1C2': cc(lo.b1C2),
'b1C3': cc(lo.b1C3), 'b2Occupation': cc(lo.b2Occupation), 'b2C1': cc(lo.b2C1),
'b2C2': cc(lo.b2C2), 'b2C3': cc(lo.b2C3), 'b2AccompOccup': cc(lo.b2AccompOccup),
'b2AccompName': cc(lo.b2AccompName), 'b2Vege': cc(lo.b2Vege),
'b2VegeAccomp': cc(lo.b2VegeAccomp), 'allergie': cc(lo.allergie), 'albumNum': lo.albumNum,
'cotonVertOption': correct(lo.cotonVertOption), 'cotonNoirOption': correct(lo.cotonNoirOption),
'bockOption': correct(lo.bockOption),
'joncQty': lo.joncqty, 'joncTicketQty': lo.joncTicketQty,
'casinoTicketQty': lo.casinoTicketNumber, 'B1Qty': lo.b1qty, 'b2Qty': lo.b2qty,
'activiteQty': lo.activiteQty,
'albumQty': lo.albumNum,
'cotonVertQty': lo.cotonVertQty, 'cotonNoirQty': lo.cotonNoirQty, 'bockQty': lo.bockQty,
'activite': correct(lo.activite),
'joncPrice': lo.joncPrice, 'joncTicketPrice': lo.joncTicketPrice,
'casinoPrice': lo.casinoPrice,
'b1price': lo.b1price, 'b2price': lo.b2price, 'activitePrice': lo.activitePrice,
'albumPrice': lo.albumPrice,
'cotonVertPrice': lo.cotonVertPrice, 'cotonNoirPrice': lo.cotonNoirPrice,
'bockPrice': lo.bockPrice})
print(len(lineOrderList))
|
3445b472f3db7716fd7c3a20e6dcb8af2542a66e | jonjelinek/euler-python | /problems/4.py | 1,818 | 4.25 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
import sys
sys.setrecursionlimit(100000)
import time
largest_pal = {
'pal': 0,
'n1': 0,
'n2': 0,
}
def is_palindrome(num: any):
# print("is_palindrome({})".format(num))
if type(num) is int:
num = str(num)
if len(num) <= 1:
return True
# Use negative indexing to get last character of string [-1]
# print("comparing {} == {}".format(num[0], num[-1]))
if num[0] != num[-1]:
return False
else:
if len(num) == 2:
return True
else:
# recursively call function using inner substring
# print("r call {}".format(num[1:-1]))
return is_palindrome(num[1:-1])
assert is_palindrome(9009) is True
assert is_palindrome(12345) is False
assert is_palindrome(900099) is False
# start at 999 * 999 = something, is_palindrome(something) == True, if not then decrement 1 side ( might be issue here)
def find_largest_palindrome(n1, n2):
# print("checking {} and {} ".format(n1, n2))
if is_palindrome(n1 * n2):
# print("found palindrome {} x {} = {}".format(n1, n2, n1*n2))
return {
'pal': n1*n2,
'n1': n1,
'n2': n2,
}
else:
# print("trying {} x {}".format(n1, n2-1))
return find_largest_palindrome(n1, n2-1)
start = time.time()
for i in range(999,800,-1):
tmppal = find_largest_palindrome(i, 999)
if tmppal['pal'] > largest_pal['pal']:
largest_pal = tmppal
# print(largest_pal)
print("Largest Palindrome: {}".format(largest_pal))
end = time.time()
print(f"Runtime {end - start}") |
ed926906171a42e2a7dd009817389b18c77647af | noamRoditi/Logic | /code/propositions/tautology.py | 5,043 | 3.640625 | 4 | """ (c) This file is part of the course
Mathematical Logic through Programming
by Gonczarowski and Nisan.
File name: code/propositions/tautology.py """
from propositions.syntax import *
from propositions.proofs import *
from propositions.deduction import *
from propositions.semantics import *
from propositions.axiomatic_systems import *
def formulae_capturing_model(model):
""" Return the list of formulae that capture the given model: for each
variable x that is assigned the value True in the model, the
corresponding capturing formula is 'x', and for each variable that is
assigned the value False, the corresponding capturing formula '~x'.
The list of these formulae should be returned, ordered alphabetically
by the name of the variable. Example: if the model is {'p2': False,
'p1': True, 'q': True} then the list of formulae represented by 'p1',
'~p2', 'q', in this order, should be returned """
assert is_model(model)
# Task 6.1a
def prove_in_model(formula, model):
""" If formula evaluates to True in model, return a proof of formula from
the formulae that capture model as assumption (in the order returned
by formulae_capturing_model) via AXIOMATIC_SYSTEM. If formula evaluates
to False in model, return a proof of ~formula from the same assumptions
via AXIOMATIC_SYSTEM. formula may contain no operators beyond '->' and
'~' """
assert type(formula) is Formula
assert formula.operators().issubset({'->', '~'})
assert is_model(model)
# Task 6.1b
def reduce_assumption(proof_from_affirmation, proof_from_negation):
""" Given two proofs of the same conclusion via the same set of inference
rules, where the assumptions of the two proofs coincide except for the
last assumption of each, where the last assumption of
proof_from_negation is the negation of the last assumption of
proof_from_affirmation, return a proof of the same conclusion, from only
the common assumptions, via the same set of inference rules, and in
addition MP, I0, I1, I2, R. E.g., the two input proofs may be of
[p, q] ==> (q->p) and of [p, ~q] ==> (q->p), and in this case the
returned proof should be of [p] ==> (q->p) """
assert proof_from_affirmation.statement.conclusion == \
proof_from_negation.statement.conclusion
assert proof_from_affirmation.statement.assumptions[:-1] == \
proof_from_negation.statement.assumptions[:-1]
assert Formula('~', proof_from_affirmation.statement.assumptions[-1]) == \
proof_from_negation.statement.assumptions[-1]
assert proof_from_affirmation.rules == proof_from_negation.rules
assert proof_from_affirmation.is_valid() and proof_from_negation.is_valid()
# Task 6.2
def prove_tautology(tautology, model={}):
""" Given a tautology and a model of some (possibly empty) prefix of its
variables (with respect to the alphabetical order), return a proof of
tautology via AXIOMATIC_SYSTEM from the assumptions that capture model.
tautology may contain no operators beyond '->' and '~'. In particular,
when model is the empty dictionary, the function returns a proof of
tautology from an empty list of assumptions """
assert is_tautology(tautology)
assert is_model(model)
assert sorted(tautology.variables())[:len(model)] == sorted(model.keys())
# Task 6.3a
def proof_or_counterexample(formula):
""" Return either a proof of formula from no assumptions via
AXIOMATIC_SYSTEM, or a model where formula does not hold. formula may
contain no operators beyond '->' and '~' """
assert type(formula) is Formula
# Task 6.3b
def encode_as_formula(rule):
""" Given an inference rule with assumptions [p1, p2, ..., pn] and
conclusion q, return its "encoding" as a formula
(p1->(p2->...(pn->q)...)) """
assert type(rule) is InferenceRule
# Task 6.4a
def prove_sound_inference(rule):
""" Return a proof of the given sound inference rule via AXIOMATIC_SYSTEM
"""
assert is_sound_inference(rule)
# Task 6.4b
def model_or_contradiction(formulae):
""" Return either a model that satisfies (all of) formulae, or a proof of
'~(p->p)' via AXIOMATIC_SYSTEM from formulae as assumptions. No formula
in formulae may contain operators beyond '->' and '~' """
for formula in formulae:
assert type(formula) is Formula
# Task 6.5
def prove_in_model_full(formula, model):
""" If formula evaluates to True in model, return a proof of formula from
the formulae that capture model as assumption (in the order returned
by formulae_capturing_model) via AXIOMATIC_SYSTEM_FULL. If formula
evaluates to False in model, return a proof of ~formula from the same
assumptions via AXIOMATIC_SYSTEM_FULL """
assert type(formula) is Formula
assert is_model(model)
# Optional Task 6.6
|
de43611d9e400049a7482e4a0ce0ce84b92a1960 | biniama/python-tutorial | /lesson10_classes/student.py | 572 | 4.15625 | 4 | class Student:
"""Class is like a house blueprint.
Then, you can create as many Objects as you want"""
def __init__(self, id, first_name, last_name, department, result):
"""assigning arguments from outside to self i.e. the Student"""
self.id = id
self.first_name = first_name
self.last_name = last_name
self.department = department
self.result = result
def full_name(self):
"""This concatenates first name and last name and returns the value"""
return f'{self.first_name} {self.last_name}'
|
393e1bbea31f9ae2e3dd805d4785cbcf8ffbdde6 | owenhu99/pizza-parlour-api | /src/drink.py | 1,755 | 4.03125 | 4 | from src.food_item import FoodItem
class Drink(FoodItem):
'Drinks and their relevant data are defined here'
def get_price(self):
"""Returns the drink price and reads price from data file if price
is not initialized"""
if self.price is None:
return self.data['drink'][self.item_type][self.size]
return self.price
def set_inputs(self, item_data):
"""Sets the drink variables to the drink_data.
Only call this if you have already checked drink_data."""
self.item_type = item_data[0]
self.size = item_data[1]
def check_inputs(self, item_data):
"""Returns boolean according to if there exists a valid drink under the
given inputs"""
if not item_data[0] in self.data['drink']:
print('type: ' + item_data[0])
print('Error: Drink type does not exist.')
return False
if not item_data[1] in self.data['drink'][item_data[0]]:
print('size: ' + item_data[1])
print('Error: Drink size does not exist for ' + item_data[1] + '.')
return False
return True
def update(self, drink_data):
"""Updates drink type and/or size according to parameters
and checks validity"""
if drink_data[0] == -1:
drink_data[0] = self.item_type
if drink_data[1] == -1:
drink_data[1] = self.size
if self.check_inputs(drink_data):
self.set_inputs(drink_data)
return True
return False
def get_dict(self):
"""Return drink data in dictionary format"""
return {
"type": self.item_type,
"size": self.size,
"price": self.price
}
|
e7be76a71ffa4d5a7712da7487f4eee57a089f9c | Ramyhemdan2018/100-Days-of-Python | /BMI calculator.py | 654 | 4.25 | 4 | weight = float(input("What is your weight? "))
shbr = float(input("enter your hight with shbr: "))
shbr_to_meter = (shbr * 11.592) /100
print("your hight with metres is: ", shbr_to_meter)
height = float(input("What is your hight? "))
bmi = round(weight / height ** 2)
if bmi < 18.5:
print(f"Your bmi is {bmi}, you are underweight.")
elif bmi > 18.5 and bmi < 25:
print(f"Your bmi is {bmi}, you are normal weight.")
elif bmi < 30 and bmi > 25:
print(f"our bmi is {bmi}, you are overweight.")
elif bmi < 35 and bmi > 30:
print(f"Your bmi is {bmi}, you are obese")
else:
print(f"Your bmi is {bmi}, you are clinically obese")
|
ce0427c83935136181994cc94dd36a9974604ab2 | alannesta/algo4 | /src/python/data_structure/stack/150_eval_RPN.py | 1,212 | 3.96875 | 4 | """
150. Evaluate Reverse Polish Notation
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
"""
from typing import List
import math
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
operators = ('+', '-', '*', '/')
stack = []
for token in tokens:
if token in operators:
op = token
num2 = stack.pop()
num1 = stack.pop()
if op == '+':
stack.append(num1 + num2)
elif op == '-':
stack.append(num1 - num2)
elif op == '*':
stack.append(num1 * num2)
elif op == '/':
# stack.append(num1 // num2)
result = num1 / num2
if result > 0:
stack.append(math.floor(result))
else:
stack.append(math.ceil(result))
else:
stack.append(int(token))
return stack.pop()
|
b0f60a95e1dc12fb08eacccf42b24df7f060555d | vip7265/ProgrammingStudy | /leetcode/sjw_trapping_rain_water.py | 1,538 | 3.9375 | 4 | """
Problem URL: https://leetcode.com/problems/trapping-rain-water/
"""
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
# return self.bruteForce(height) # O(n^2), 2460ms
return self.dynamicProgramming(height) # O(n), 60ms
def bruteForce(self, height):
""" In each point, find highest bar in both left and right side """
answer = 0
n = len(height)
for idx in range(1, n-1):
left_max = max(height[:idx])
right_max = max(height[idx+1:])
area = min(left_max, right_max) - height[idx]
answer += max(area, 0) # if area < 0, does not add
return answer
def dynamicProgramming(self, height):
""" Instead of find all leftmax and rightmax in bruteForce(), memorize
it in seperate list which requires O(n) memories """
if not height:
# empty height
return 0
n = len(height)
left_max, right_max = [0]*n, [0]*n
left_max[0] = height[0]
for idx in range(1, n):
left_max[idx] = max(left_max[idx-1], height[idx])
right_max[n-1] = height[n-1]
for idx in reversed(range(n-1)):
right_max[idx] = max(right_max[idx+1], height[idx])
answer = 0
for idx in range(n):
area = min(left_max[idx], right_max[idx]) - height[idx]
area = max(area, 0)
answer += area
return answer
s = Solution()
s.trap([0,1,0,2,1,0,1,3,2,1,2,1]) |
08178fdac1b3d2e973e9f2ee62834a25287fe202 | vkjangid/python | /loop4.py | 432 | 4.03125 | 4 | '''a=input('enter any number')
a=int(a)
for i in range(1,a+1):
b=0
while b<i:
print("*",end='')
b+=1
print()'''
'''a=1
b=input('enter any number')
b=int(b)
while a<=b:
for i in range(a):
print("*",end='')
print()
a+=1'''
a=input('enter any number')
a=int(a)
for i in range(a):
b=i
while a>b:
print("*",end='')
b+=1
print()
|
b46fee95748992d068ccca081fde99257d1fa29d | xcgoner/gluon-exp | /docs/tutorials/classification/dive_deep_imagenet.py | 11,100 | 3.578125 | 4 | """5. Train Your Own Model on ImageNet
==========================================
``ImageNet`` is the most well-known dataset for image classification.
Since it was published, most of the research that advances the state-of-the-art
of image classification was based on this dataset.
Although there are a lot of available models, it is still a non-trivial task to
train a state-of-the-art model on ``ImageNet`` from scratch.
In this tutorial, we will smoothly walk
you through the process of training a model on ``ImageNet``.
.. note::
The rest of the tutorial walks you through the details of ``ImageNet`` training.
If you want a quick start without knowing the details, try downloading
this script and start training with just one command.
:download:`Download train_imagenet.py<../../../scripts/classification/imagenet/train_imagenet.py>`
The commands used to reproduce results from papers are given in our
`Model Zoo <../../model_zoo/index.html>`__.
.. note::
Since real training is extremely resource consuming, we don't actually
execute code blocks in this tutorial.
Prerequisites
-------------
**Expertise**
We assume readers have a basic understanding of ``Gluon``, we suggest
you start with `Gluon Crash Course <http://gluon-crash-course.mxnet.io/index.html>`__ .
Also, we assume that readers have gone through previous tutorials on
`CIFAR10 Training <dive_deep_cifar10.html>`_ and `ImageNet Demo <demo_imagenet.html>`_ .
**Data Preparation**
Unlike ``CIFAR10``, we need to prepare the data manually.
If you haven't done so, please go through our tutorial on
`Prepare ImageNet Data <../examples_datasets/imagenet.html>`_ .
**Hardware**
Training deep learning models on a dataset of over one million images is
very resource demanding.
Two main bottlenecks are tensor computation and data IO.
For tensor computation, it is recommended to use a GPU, preferably a high-end
one.
Using multiple GPUs together will further reduce training time.
For data IO, we recommend a fast CPU and a SSD disk. Data loading can greatly benefit
from multiple CPU threads, and a fast SSD disk. Note that in total the compressed
and extracted ``ImageNet`` data could occupy around 300GB disk space, thus a SSD with
at least 300GB is required.
Network structure
-----------------
Finished preparation? Let's get started!
First, import the necessary libraries into python.
.. code-block:: python
import argparse, time
import numpy as np
import mxnet as mx
from mxnet import gluon, nd
from mxnet import autograd as ag
from mxnet.gluon import nn
from mxnet.gluon.data.vision import transforms
from gluoncv.model_zoo import get_model
from gluoncv.utils import makedirs, TrainingHistory
In this tutorial we use ``ResNet50_v2``, a network with balanced prediction
accuracy and computational cost.
.. code-block:: python
# number of GPUs to use
num_gpus = 4
ctx = [mx.gpu(i) for i in range(num_gpus)]
# Get the model ResNet50_v2, with 10 output classes
net = get_model('ResNet50_v2', classes=1000)
net.initialize(mx.init.MSRAPrelu(), ctx = ctx)
Note that the ResNet model we use here for ``ImageNet`` is different in structure from
the one we used to train ``CIFAR10``. Please refer to the original paper or
GluonCV codebase for details.
Data Augmentation and Data Loader
---------------------------------
Data augmentation is essential for a good result. It is similar to what we have
in the ``CIFAR10`` training tutorial, just different in the parameters.
We compose our transform functions as following:
.. code-block:: python
jitter_param = 0.4
lighting_param = 0.1
transform_train = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomFlipLeftRight(),
transforms.RandomColorJitter(brightness=jitter_param, contrast=jitter_param,
saturation=jitter_param),
transforms.RandomLighting(lighting_param),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
Since ``ImageNet`` images have much higher resolution and quality than
``CIFAR10``, we can crop a larger image (224x224) as input to the model.
For prediction, we still need deterministic results. The transform function is:
.. code-block:: python
transform_test = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
Notice that it is important to keep the normalization consistent, since trained
model only works well on test data from the same distribution.
With the transform functions, we can define data loaders for our
training and validation datasets.
.. code-block:: python
# Batch Size for Each GPU
per_device_batch_size = 64
# Number of data loader workers
num_workers = 32
# Calculate effective total batch size
batch_size = per_device_batch_size * num_gpus
data_path = '~/.mxnet/datasets/imagenet'
# Set train=True for training data
# Set shuffle=True to shuffle the training data
train_data = gluon.data.DataLoader(
imagenet.classification.ImageNet(data_path, train=True).transform_first(transform_train),
batch_size=batch_size, shuffle=True, last_batch='discard', num_workers=num_workers)
# Set train=False for validation data
val_data = gluon.data.DataLoader(
imagenet.classification.ImageNet(data_path, train=False).transform_first(transform_test),
batch_size=batch_size, shuffle=False, num_workers=num_workers)
Note that we set ``per_device_batch_size=64``, which may not suit GPUs with
Memory smaller than 12GB. Please tune the value according to your specific configuration.
Path ``'~/.mxnet/datasets/imagenet'`` is the default path if you
prepared the data `with our script <../examples_datasets/imagenet.html>`_.
Optimizer, Loss and Metric
--------------------------
Optimizer is what improves the model during training. We use the popular
Nesterov accelerated gradient descent algorithm.
.. code-block:: python
# Learning rate decay factor
lr_decay = 0.1
# Epochs where learning rate decays
lr_decay_epoch = [30, 60, 90, np.inf]
# Nesterov accelerated gradient descent
optimizer = 'nag'
# Set parameters
optimizer_params = {'learning_rate': 0.1, 'wd': 0.0001, 'momentum': 0.9}
# Define our trainer for net
trainer = gluon.Trainer(net.collect_params(), optimizer, optimizer_params)
For classification tasks, we usually use softmax cross entropy as the
loss function.
.. code-block:: python
loss_fn = gluon.loss.SoftmaxCrossEntropyLoss()
With 1000 classes the model may not always rate the correct answer with the highest
rank. Besides top-1 accuracy, we also consider top-5 accuracy as a measurement
of how well the model is doing.
At the end of every epoch, we record and print the metric scores.
.. code-block:: python
acc_top1 = mx.metric.Accuracy()
acc_top5 = mx.metric.TopKAccuracy(5)
train_history = TrainingHistory(['training-top1-err', 'training-top5-err',
'validation-top1-err', 'validation-top5-err'])
Validation
----------
At the end of every training epoch, we evaluate it on the validation data set,
and report the top-1 and top-5 error rate.
.. code-block:: python
def test(ctx, val_data):
acc_top1_val = mx.metric.Accuracy()
acc_top5_val = mx.metric.TopKAccuracy(5)
for i, batch in enumerate(val_data):
data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0)
label = gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0)
outputs = [net(X) for X in data]
acc_top1_val.update(label, outputs)
acc_top5_val.update(label, outputs)
_, top1 = acc_top1_val.get()
_, top5 = acc_top5_val.get()
return (1 - top1, 1 - top5)
Training
--------
After all these preparation, we can finally start training!
Following is the main training loop:
.. code-block:: python
epochs = 120
lr_decay_count = 0
log_interval = 50
num_batch = len(train_data)
for epoch in range(epochs):
tic = time.time()
btic = time.time()
acc_top1.reset()
acc_top5.reset()
train_loss = 0
if lr_decay_period == 0 and epoch == lr_decay_epoch[lr_decay_count]:
trainer.set_learning_rate(trainer.learning_rate*lr_decay)
lr_decay_count += 1
for i, batch in enumerate(train_data):
data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0)
label = gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0)
with ag.record():
outputs = [net(X) for X in data]
loss = [L(yhat, y) for yhat, y in zip(outputs, label)]
ag.backward(loss)
trainer.step(batch_size)
acc_top1.update(label, outputs)
acc_top5.update(label, outputs)
train_loss += sum([l.sum().asscalar() for l in loss])
if log_interval and not (i + 1) % log_interval:
_, top1 = acc_top1.get()
_, top5 = acc_top5.get()
err_top1, err_top5 = (1-top1, 1-top5)
print('Epoch[%d] Batch [%d]\tSpeed: %f samples/sec\ttop1-err=%f\ttop5-err=%f'%(
epoch, i, batch_size*opt.log_interval/(time.time()-btic), err_top1, err_top5))
btic = time.time()
_, top1 = acc_top1.get()
_, top5 = acc_top5.get()
err_top1, err_top5 = (1-top1, 1-top5)
train_loss /= num_batch * batch_size
err_top1_val, err_top5_val = test(ctx, val_data)
train_history.update([err_top1, err_top5, err_top1_val, err_top5_val])
print('[Epoch %d] training: err-top1=%f err-top5=%f loss=%f'%(epoch, err_top1, err_top5, train_loss))
print('[Epoch %d] time cost: %f'%(epoch, time.time()-tic))
print('[Epoch %d] validation: err-top1=%f err-top5=%f'%(epoch, err_top1_val, err_top5_val))
We can plot the top-1 error rates with:
.. code-block:: python
train_history.plot(['training-top1-err', 'validation-top1-err'])
If you train the model with ``epochs=120``, the plot may look like:
|image-imagenet-curve|
Next Step
---------
`Model Zoo <../../model_zoo/index.html>`_ provides scripts and commands for
training models on ``ImageNet``.
If you want to know what you can do with the model you just
trained, please read the tutorial on `Transfer learning <transfer_learning_minc.html>`__.
Besides classification, deep learning models nowadays can do other exciting tasks
like `object detection <../examples_detection/index.html>`_ and
`semantic segmentation <../examples_segmentation/index.html>`_.
.. |image-imagenet-curve| image:: https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/classification/resnet50_v2_top1.png
"""
|
fd53e562b00bb22268cedc8e6074f2a5cf72bbec | edu-athensoft/stem1401python_student | /py200325_python1/py200501/homework/stem1401_python_homework_11_max.py | 134 | 3.859375 | 4 | """
Homework 11: Print out a matrix by 3x4
"""
matrix = [[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
]
print(matrix) |
a37fbdd53f26fcc7b312c3a776c212b5b4832fe5 | Aleksandra1101/k | /create.py | 9,837 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def f(x_point):
x1 = x_point[0] # х координата
x2 = x_point[1] # у координата
print('x1 ->', x1)
print('x2 ->', x2)
# функция Розенброка:
fx = 100.0 * (x1 ** 2.0 - x2) ** 2.0 + (x1 - 1) ** 2.0
print('f(x) =', fx, '\n')
return fx
x0 = np.array([-1.2, 0], float) # начальная точка
eps = 0.000000001 # задаем точность вычислений
alpha = 3 # при удачном шаге
beta = -0.5 # при неудачном шаге
d1 = np.array([1, 0], float) # вектор (1, 0)
d2 = np.array([0, 1], float) # вектор (0, 1)
delta1 = 0.000001 # дельты принятые на первом шаге
delta2 = 0.000001 # дельты принятые на первом шаге
N = 3 # ??? максимальное число неудачных серий шагов
n = 1 # максимальное число неудачных серий шагов
l = 0 # выполнено серий неудачных шагов
a = np.array([[0, 0]], float)
y = np.array([x0]) # массив точек у
x = np.array([x0]) # массив точек х
lamb = np.array([[0, 0]], float) # массив лямбд для шага 4
k = 0 # ???
i = 0 # текущая итреация 2-го шага
delta = [delta1, delta2] # создаем массив из выше написанных дельт
d = np.array([d1, d2]) # создаем массив из выше написанных д
STOP = False # условие окончания
z = 0
while not STOP:
z += 1
print('---------------------------------- z :', z)
# Шаг 2
print('\n\n-------- Шаг 2 --------')
if f(y[-1] + delta[i] * d[i]) >= f(y[-1]):
print('# шаг неудачен')
y = np.append(y, [y[-1]], axis=0)
delta[i] = delta[i] * beta
else:
print('# шаг удачен')
y = np.append(y, [y[-1] + delta[i] * d[i]], axis=0)
delta[i] = delta[i] * alpha
# Конец Шаг 2
# Шаг 3
print('\n\n-------- Шаг 3 --------')
if i < n: # перейти к Шаг 2
i = i + 1
else:
l = l + 1
if f(y[-1]) < f(y[0]): # перейти к Шаг 2
print('# шаг неудачен')
i = 0
y = np.array([y[-1]])
else:
print('# шаг удачен')
if f(y[-1]) < f(x[-1]): # перейти к Шаг 4
print('')
# Шаг 4
print('\n\n-------- Шаг 4 --------')
x = np.append(x, [y[-1]], axis=0)
if np.sqrt(np.sum(np.square(x[-1] - x[-2]))) > eps:
point = np.array([x[-1][0] - x[-2][0], x[-1][1] - x[-2][1]])
left_side = np.array([[d[0][0], d[1][0]], [d[0][1], d[1][1]]], float)
right_side = np.array([point[0], point[1]], float)
res_for_lambda = np.linalg.solve(left_side, right_side)
lamb[0] = np.array(res_for_lambda)
print(lamb[0])
# print(lamb_search(lamb[0]))
a1 = lamb[0][0] * d[0] + lamb[0][1] * d[1]
b1 = np.copy(a1)
a2 = lamb[0][1] * d[1]
d1_new = b1 / (np.sqrt(np.sum(np.square(b1))))
b2 = a2.T - (a2 @ d1_new.T) * d1_new.T
d2_new = b2 / (np.sqrt(np.sum(np.square(b2))))
i = 0
k = k + 1
d = np.array([d1_new, d2_new.T])
print('d1 => ', d[0])
print('d2 => ', d[1])
delta = [delta1, delta2]
y = np.array([x[-1]])
# Конец Шаг 4
else:
if abs(np.sort(delta)[0]) < eps and abs(np.sort(delta)[-1]) < eps: # возможно ответ
print('Результат: ', y[-1])
STOP = True
else: # перейти к Шаг 2
i = 0
successful_step = 0
y = np.array([y[-1]])
# Конец Шаг 3
plt.plot(x.T[0], x.T[1])
plt.plot(x.T[0], x.T[1], 'ro')
plt.xlabel('x1', size=14)
plt.ylabel('x2', size=14)
plt.grid()
plt.show()
print('Точок було побудовано:', len(x))
ДОДАТОК Б
Лістинг програми 2
import numpy as np
import matplotlib.pyplot as plt
def f(x_point):
x1 = x_point[0] # х координата
x2 = x_point[1] # у координата
print('x1 ->', x1)
print('x2 ->', x2)
# функция, пока еще НЕ Розенброка:
# fx = 100.0 * (x1 ** 2.0 - x2) ** 2.0 + (x1 - 1) ** 2.0
if (x1 ** 2 + x2 ** 2 - 4) >= 0:
fx = 100.0 * (x1 ** 2.0 - x2) ** 2.0 + (x1 - 1) ** 2.0
else:
fx = 100.0 * (x1 ** 2.0 - x2) ** 2.0 + (x1 - 1) ** 2.0 + 1 / (x1 ** 2 + x2 ** 2 - 1)
print('f(x) =', fx, '\n')
return fx
def rosen_check(x_point):
x1 = x_point[0] # х координата
x2 = x_point[1] # у координата
res = 100.0 * (x1 ** 2.0 - x2) ** 2.0 + (x1 - 1) ** 2.0
return res
x0 = np.array([-1.2, 0], float) # начальная точка
eps = 0.000000001 # задаем точность вычислений
alpha = 3 # при удачном шаге
beta = -0.5 # при неудачном шаге
d1 = np.array([1, 0], float) # вектор (1, 0)
d2 = np.array([0, 1], float) # вектор (0, 1)
delta1 = 0.000001 # дельты принятые на первом шаге
delta2 = 0.000001 # дельты принятые на первом шаге
N = 3 # ??? максимальное число неудачных серий шагов
n = 1 # максимальное число неудачных серий шагов
l = 0 # выполнено серий неудачных шагов
a = np.array([[0, 0]], float)
y = np.array([x0]) # массив точек у
x = np.array([x0]) # массив точек х
lamb = np.array([[0, 0]], float) # массив лямбд для шага 4
k = 0 # ???
i = 0 # текущая итреация 2-го шага
delta = [delta1, delta2] # создаем массив из выше написанных дельт
d = np.array([d1, d2]) # создаем массив из выше написанных д
STOP = False # условие окончания
z = 0
while not STOP:
z += 1
print('---------------------------------- z :', z)
# Шаг 2
print('\n\n-------- Шаг 2 --------')
if f(y[-1] + delta[i] * d[i]) >= f(y[-1]):
print('# шаг неудачен')
y = np.append(y, [y[-1]], axis=0)
delta[i] = delta[i] * beta
else:
print('# шаг удачен')
y = np.append(y, [y[-1] + delta[i] * d[i]], axis=0)
delta[i] = delta[i] * alpha
# Конец Шаг 2
# Шаг 3
print('\n\n-------- Шаг 3 --------')
if i < n: # перейти к Шаг 2
i = i + 1
else:
l = l + 1
if f(y[-1]) < f(y[0]): # перейти к Шаг 2
print('# шаг неудачен')
i = 0
y = np.array([y[-1]])
else:
print('# шаг удачен')
if f(y[-1]) < f(x[-1]): # перейти к Шаг 4
print('')
# Шаг 4
print('\n\n-------- Шаг 4 --------')
x = np.append(x, [y[-1]], axis=0)
if np.sqrt(np.sum(np.square(x[-1] - x[-2]))) > eps:
point = np.array([x[-1][0] - x[-2][0], x[-1][1] - x[-2][1]])
left_side = np.array([[d[0][0], d[1][0]], [d[0][1], d[1][1]]], float)
right_side = np.array([point[0], point[1]], float)
res_for_lambda = np.linalg.solve(left_side, right_side)
lamb[0] = np.array(res_for_lambda)
print(lamb[0])
# print(lamb_search(lamb[0]))
a1 = lamb[0][0] * d[0] + lamb[0][1] * d[1]
b1 = np.copy(a1)
a2 = lamb[0][1] * d[1]
d1_new = b1 / (np.sqrt(np.sum(np.square(b1))))
b2 = a2.T - (a2 @ d1_new.T) * d1_new.T
d2_new = b2 / (np.sqrt(np.sum(np.square(b2))))
i = 0
k = k + 1
d = np.array([d1_new, d2_new.T])
print('d1 => ', d[0])
print('d2 => ', d[1])
delta = [delta1, delta2]
y = np.array([x[-1]])
# Конец Шаг 4
else:
if abs(np.sort(delta)[0]) < eps and abs(np.sort(delta)[-1]) < eps: # возможно ответ
# print('Результат: ', y[-1])
STOP = True
else: # перейти к Шаг 2
i = 0
successful_step = 0
y = np.array([y[-1]])
# Конец Шаг 3
# circle2 = plt.Circle((0, 0), 0.5, color='b', linewidth=2, fill=False)
circle2 = plt.Circle((0, 0), 1, color='g', linewidth=2, fill=False)
# circle3 = plt.Circle((0, 0), 2, color='r', linewidth=2, fill=False)
ax = plt.gca()
plt.plot(x.T[0], x.T[1])
plt.plot(x.T[0], x.T[1], 'ro')
plt.xlabel('x1', size=14)
plt.ylabel('x2', size=14)
ax.grid()
ax.add_artist(circle2)
# ax.add_artist(circle3)
ax.set_xlim((-2.7, 2.7))
ax.set_ylim((-2, 2))
plt.show()
print('Точок було побудовано:', len(x))
print('Результат: ', rosen_check(y[-1]))
|
707007dd4a1b8a9a939f2666033bdefa3030fb7b | JonathanKutsch/Python-Schoolwork | /Quizzes/Quiz6/main.py | 1,051 | 3.78125 | 4 | # By submitting this assignment, I agree to the following:
# Aggies do not lie, cheat, or steal, or tolerate those who do
# I have not given or received any unauthorized aid on this assignment
#
# Name: Jonathan Kutsch
# Section: 514
# Assignment: Quiz 6 - Plotting
# Date: 15 November 2020
import matplotlib.pyplot as plt
# import necessary libraries
x = []
engineers = []
non_engineers = []
# create empty lists
for i in range(0, 61):
x.append(i)
engineers.append(1 / 60 * ((i - 100)**2) + 10)
non_engineers.append((-1 / 8) * i + 30)
# utilize loop to populate lists for plotting
plt.plot(x, engineers, color="blue", linewidth=1.0, label="Engineering Majors")
plt.plot(x, non_engineers, color="red", linewidth=1.0, label="Non-Engineering Majors")
plt.legend(loc="upper right")
plt.title('Excitement Level by Major for the Release of "The Mandalorian" Season 2', fontsize=9.5)
plt.xlabel("Days until Release")
plt.ylabel("Excitement Level")
plt.show()
# plot data with proper labels
|
ebe79e6a70789e7431270c1c6112995aee8e4d6b | damminhtien/python-concurrent | /21_status_thread.py | 1,021 | 4.1875 | 4 | """Event instances are similar to a “sticky” flag that allows threads to wait for something
to happen. Initially, an event is set to 0. If the event is unset and a thread waits on the
event, it will block (i.e., go to sleep) until the event gets set. A thread that sets the event
will wake up all of the threads that happen to be waiting (if any). If a thread waits on an
event that has already been set, it merely moves on, continuing to execute.
"""
from threading import Thread, Event
import time
# Code to execute in an independent thread
def countdown(n, started_evt):
started_evt.set()
print('Countdown starting')
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5)
# Create the event object that will be used to signal startup
started_evt = Event()
# Launch the thread and pass the startup event
print('Launching countdown')
t = Thread(target=countdown, args=(10, started_evt))
t.start()
# Wait for the thread to start
started_evt.wait()
print('Countdown is running')
|
5ba833b9ed3f202560cf8a867952e4c0934a3ee5 | yoderw/math121 | /hw/hw7/remainder.py | 281 | 3.6875 | 4 | def remainder(n, d):
if n == 0:
return 0
if n < 0:
if n + d > 0:
return d + n
else:
return remainder(n + d, d)
if n > 0:
if n + d < 0:
return d - n
else:
return remainder(n - d, d)
|
05297c055934945412ad77d5226361dd4978bd64 | gen0v/Extruder_Corrector | /extrudorcorrector.py | 777 | 3.6875 | 4 | def main():
print("ExtruderCorrector v0.1")
print("Measure 120mm of filament of the edge of your extruder and mark it")
print("Let the extruder run for 100mm")
print("Now measure the remaining filament of the edge to the mark")
old_steps = float(input("Please enter the STEPS/MM of your printer : "))
measured_length = float(input("Please enter the measured length : "))
real_length = 120 - measured_length
if(measured_length > 20):
new_steps = (old_steps / real_length) * 100
elif(measured_length == 20):
pass
else:
new_steps = (old_steps / real_length) * 100
print("Please configure the steps of your printer to be : " + str(new_steps))
print("Then test again.")
if __name__=='__main__':
main()
|
a40c323df9a720e12c07a6e0be9c6b9cc0393340 | NirvanSinghania/Bomberman-Game | /persons.py | 1,234 | 3.75 | 4 | from game_board import board
class Person:
def __init__(self, x, y):
self.x = x
self.y = y
self.alive = 1
def clear(self):
""" Fill air in place of Person's position"""
board.change_grid(self.x, self.y, 0)
""" Movement functions for the Person """
def move_right(self):
if board.check_valid(self.x, self.y + 1) and self.check_obstacle(self.x, self.y + 1):
self.clear()
self.y += 1
def move_left(self):
if board.check_valid(self.x, self.y - 1) and self.check_obstacle(self.x, self.y - 1):
self.clear()
self.y -= 1
def move_up(self):
if board.check_valid(self.x - 1, self.y) and self.check_obstacle(self.x - 1, self.y):
self.clear()
self.x -= 1
def move_down(self):
if board.check_valid(self.x + 1, self.y) and self.check_obstacle(self.x + 1, self.y):
self.clear()
self.x += 1
""" Explicit destructor for Person . It changes the value of alive variable"""
def kill(self):
self.alive = 0
def check_in_explosion(self):
L = [self.x, self.y]
if L in board.Explosion_list:
self.kill()
|
f56da44cc89b1f282d82a3dd09b59ba8d23c79d7 | peterept/mazes-for-programmers | /Chapter-01/gridy.py | 2,902 | 3.640625 | 4 | #!/usr/bin/env python3
class GridCell:
def __init__(self, grid: "Grid", x: int, y: int):
self.grid = grid
self.x = x
self.y = y
self.links = []
@property
def n(self):
return self.grid[self.x, self.y - 1]
@property
def s(self):
return self.grid[self.x, self.y + 1]
@property
def e(self):
return self.grid[self.x + 1, self.y]
@property
def w(self):
return self.grid[self.x - 1, self.y]
def is_linked(self, cell: "GridCell") -> bool:
if cell:
return cell in self.links
return False
def carve_e(self):
cell = self.grid[self.x + 1, self.y]
if cell != None:
self.link_cell(cell)
def carve_n(self):
cell = self.grid[self.x, self.y + 1]
if cell != None:
self.link_cell(cell)
def link_cell(self, cell: "GridCell"):
if cell != None:
if not cell in self.links:
print(f"link_cell: {self.x},{self.y} to {cell.x},{cell.y}")
self.links.append(cell)
print(self.links)
if not self in cell.links:
cell.links.append(self)
class Grid:
def __init__(self, width: int, height: int):
"""Create a grid of specified width and height"""
self.width = width
self.height = height
self.cells = [[None for x in range(0, width)] for y in range(0, height)]
for y in range(height):
for x in range(width):
self.cells[y][x] = GridCell(self, x, y)
def __getitem__(self, xy) -> GridCell:
"""Get the cell at grid[x,y]"""
x, y = xy
if x in range(self.width) and y in range(self.height):
return self.cells[y][x]
return None
def __repr__(self) -> str:
"""Output grid as a string"""
rows = []
for row in self.cells:
s1 = ""
s2 = ""
for cell in row:
s1 += " "
s1 += " " if cell.is_linked(cell.e) else "|"
s2 += " " if cell.is_linked(cell.s) else "-"
s2 += "+"
rows.append(s1[:-1])
rows.append(s2[:-1])
hdr = "#" * (self.width * 2 + 1) + "\n"
return hdr + "#" + "#\n#".join(rows[:-1]) + "#\n" + hdr
def __iter__(self):
return GridIterator(self)
@property
def rows(self):
return self.cells
class GridIterator:
def __init__(self, grid: Grid):
self.itery = iter(grid.cells)
self.iterx = None
def __next__(self) -> GridCell:
if self.iterx == None:
self.iterx = iter(next(self.itery))
try:
cell = next(self.iterx)
except StopIteration:
self.iterx = iter(next(self.itery))
cell = next(self.iterx)
return cell
|
7d09a94fa31919e40a83b9164093d16203b591cf | Bacon911/git-lookup | /po.py | 453 | 4.09375 | 4 | x = input("Введите первое число:")
print("Ваше первое число:" + x)
y = input("Введите второе число:")
print("Ваше второе число:" + y)
x = float(x)
y = float(y)
a = x + y
b = x - y
c = x * y
d = x / y
print ("Результат суммы чисел:", a)
print ("Результат отнимания чисел:", b)
print ("Результат умножения чисел:", c)
#test |
8b9546839f48cd3ae52848433a2822baef6f03c7 | nikhil-shukla/GitDemo | /pythonProject/List (Ordered collection of Objects)/ListDemo4.py | 247 | 4.15625 | 4 | list1=[12,89,58,66,52,0,3,6,8]
print(list1)
list1.reverse() #reverse order
print(list1)
list1.sort() #sorting
print(list1)
#lists of list
myList=[10,9,20,["Nikhil","Python","Selenium"]]
print(myList)
print(myList[3][::-1]) #access using indexing |
9e5e1602bb68f13a461c93a6585e348290abcc34 | yilak1/machine_learning_study | /effective_python/study1.py | 1,002 | 3.5 | 4 | '''
effective python1
'''
import os
from urllib.parse import parse_qs
# python3 bytes and str
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value #Instance of str
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value #Instance of bytes
'''with open('test.txt','w') as f:
f.write(os.urandom(10)) #TypeError: write() argument must be str, not bytes'''
with open('test.txt','wb') as f:
f.write(os.urandom(10)) #Using bytes to open
my_values = parse_qs('red=5&blue=0&green=', keep_blank_values=True)
print(repr(my_values)) #repr一般将对象转换成字符串,str则是将数值转换成字符串
print('Red ', my_values.get('red'))
print('Blue ', my_values.get('blue'))
print('Opacity ', my_values.get('opacity')) # get获得字典的键值
|
1daf8888f6f499a0968f4119fb638bc442c7defb | entrekid/BOJ | /bronze/2739/2739.py | 84 | 3.765625 | 4 | num = int(input())
for i in range(9):
print(num, "*", i + 1, "=", num *(i + 1))
|
62885b72bf14633859217d592b35bf703f0ccd1b | hellokayas/Codewars-Solutions | /human_read.py | 501 | 3.546875 | 4 | IN_SECONDS = (('year', 31536000), ('day', 86400), ('hour', 3600),
('minute', 60), ('second', 1))
def format_duration(seconds):
if not seconds:
return 'now'
times = []
words = 0
for name, num in IN_SECONDS:
q, seconds = divmod(seconds, num)
if q:
times.append('{} {}{}'.format(q, name, 's' if q > 1 else ''))
words += 1
return times[0] if words == 1 else \
'{} and {}'.format(', '.join(times[:-1]), times[-1])
|
acdc04bb0e71b9ad27515b7a3029f7f38179285a | thanhluan208/Ex1 | /Hello.py | 109 | 3.78125 | 4 | print("Hello world")
n = input("what your name")
b = input("birthday")
# print("Hi", n, end =" ")
print (b)
|
9edf024a83f21bf4e00c8f2287cce12cefac1c38 | kashyapa/interview-prep | /revise-daily/epi/revise-daily/6_greedy_algorithms/1_compute_optimum_task_assignment.py | 594 | 3.734375 | 4 | from collections import deque
from collections import namedtuple
PairedTasks = namedtuple('PairedTasks', ('task_1', 'task_2'))
def compute_task_assignment(task_durations: list):
durations = deque(sorted(task_durations))
total_time = 0
while durations:
total_time = max(total_time, durations.popleft() + durations.pop())
# return total_time
task_durations.sort()
return [
PairedTasks(task_durations[i], task_durations[~i]) for i in range(len(task_durations)//2)
]
if __name__ == '__main__':
print(compute_task_assignment([3, 8, 1, 4,])) |
369847af02af13ded9ba0d768187188f072a44fc | tush922/PythonAssignments | /Assignment4_5.py | 827 | 3.546875 | 4 | from functools import *
def chkprime(num):
for i in range(2, num//2):
if (num % i) == 0:
return False;
break
else:
return True;
def createlist():
size = int(input("Number of elements:"))
nolist = list();
for i in range(size):
print("Input elements:",i+1)
no=int(input());
nolist.append(no);
print("List is",nolist)
return nolist;
def mult(no):
return no*2;
def maxno(no1,no2):
if no1<no2:
return no2
data=list(createlist())
print("Input List ",data)
filtereddata=list(filter(chkprime,data))
print("List after filter ",filtereddata)
mapdata=list(map(mult,filtereddata))
print("List after map",mapdata)
reduceddata=reduce(maxno,mapdata)
print("Output of reduce",reduceddata) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.