blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
97418f962b13e93c360d82177843a8bb08f43dbb | KishorP6/PySample | /If Conditions.py | 654 | 3.734375 | 4 | cont_One_capacity = int (input())
cont_Two_capacity = int (input())
cont_Three_capacity = int (input())
cont_4_capacity = int (input())
total_cargo = int (input())
if (total_cargo - cont_One_capacity) <= 0 :
print ("1")
else :
if (total_cargo - cont_One_capacity-cont_Two_capacity) <= 0 :
print ("2")
else :
if (total_cargo - cont_One_capacity-cont_Two_capacity-cont_Three_capacity) <= 0 :
print ("3")
else :
if (total_cargo - cont_One_capacity-cont_Two_capacity-cont_Three_capacity-cont_4_capacity) <= 0 :
print ("4")
else :
print ("Not Possible") |
bb4106131795f1fbd9aab229e517b06891629b3f | aorchini/FlameCode | /test/derivsnew.py | 7,630 | 3.796875 | 4 | __author__ = 'Alessandro Orchini'
# !/usr/bin/python
"""Functions that evaluate finite different derivatives or differentiation matrices
names: mehtodN_stencilM_return
- method:
-# FD = FiniteDifference
-# NU = NonUniform (Finite Difference)
-# CB = Chebyshev
- N = order of derivative
- stencil:
-# CT = Central
-# FW = Forward
-# BW = Backward
-# CB = Chebyshev
- M = order of accuracy
- return:
-# D = Derivative
-# DM = Differentiation Matrix
"""
import numpy as np
def FD1_CT2_D(f, dx):
"""
Returns f first derivative, second order dx accurate, finite difference centered
:param f: function
:param dx: grid space
:return: df/dx
"""
dfdr = np.zeros([len(f), len(f)])
# First point use forward scheme first order
dfdr[0, 0] = -1.5
dfdr[0, 1] = +2.0
dfdr[0, 2] = -0.5
for ii in range(1, len(f) - 1):
dfdr[ii][ii - 1] = -0.5
dfdr[ii][ii + 1] = +0.5
# Last point use backward scheme first order
dfdr[-1, -1] = +1.5
dfdr[-1, -2] = -2.0
dfdr[-1, -3] = +0.5
return np.dot(dfdr / dx, f)
def FD1_FW2_D(f, dx):
"""
Returns f first derivative, second order dx accurate, finite difference forward
:param f: function
:param dx: grid space
:return: df/dx
"""
dfdr = np.zeros([len(f), len(f)])
for ii in range(0, len(f) - 2):
dfdr[ii][ii] = -1.5
dfdr[ii][ii + 1] = +2.0
dfdr[ii][ii + 2] = -0.5
# Vorlast point use centered scheme to keep second order
dfdr[-2, -3] = -0.5
dfdr[-2, -1] = +0.5
# Last point use backward scheme first order
dfdr[-1, -1] = +1.5
dfdr[-1, -2] = -2.0
dfdr[-1, -3] = +0.5
return np.dot(dfdr / dx, f)
def FD1_BW2_D(f, dx):
"""
Returns f first derivative, second order dx accurate, finite difference backward
:param f: function
:param dx: grid space
:return: df/dx
"""
dfdr = np.zeros([len(f), len(f)])
# First point use forward scheme first order
dfdr[0, 0] = -1.5
dfdr[0, 1] = +2.0
dfdr[0, 2] = -0.5
# Second point use centered scheme to keep second order
dfdr[1, 0] = -0.5
dfdr[1, 2] = +0.5
for ii in range(2, len(f)):
dfdr[ii][ii] = +1.5
dfdr[ii][ii - 1] = -2.0
dfdr[ii][ii - 2] = +0.5
return np.dot(dfdr / dx, f)
def FD2_CT2_D(f, dx):
"""
Returns f second derivative, second order dx accurate, finite difference centered
:param f: function
:param dx: grid space
:return: df/dx
"""
dfdr = np.zeros([len(f), len(f)])
# First point use forward scheme first order
dfdr[0, 0] = +1.0
dfdr[0, 1] = -2.0
dfdr[0, 2] = +1.0
for ii in range(1, len(f) - 1):
dfdr[ii][ii - 1] = +1.0
dfdr[ii][ii] = -2.0
dfdr[ii][ii + 1] = +1.0
# Last point use backward scheme first order
dfdr[-1, -1] = +1.0
dfdr[-1, -2] = -2.0
dfdr[-1, -3] = +1.0
return np.dot(dfdr / (dx * dx), f)
def NU1_BW2_D(f, dx):
"""
Returns f first derivative, second order dx accurate, finite difference backward, nonuniform mesh
:param f: function
:param dx: vector of grid spacings
:return: df/dx
"""
if len(dx)+1 != len(f):
print 'Error: dimensions of N and dx mismatch in nonuniform differentiation matrix calculation'
return
dfdr = np.zeros([len(f), len(f)])
# First point, use forward scheme
dfdr[0,0] = -(2.0*dx[0] + 1.0*dx[1]) / (dx[0] * (dx[0] + dx[1]))
dfdr[0,1] = +(dx[0] + dx[1]) / (dx[0] * dx[1])
dfdr[0,2] = -(dx[0]) / (dx[1] * (dx[0] + dx[1]))
# Second point, use centered scheme
dfdr[1,0] = -(dx[1]) / (dx[0] * (dx[1] + dx[0]))
dfdr[1,1] = (dx[1] - dx[0]) / (dx[0] * dx[1])
dfdr[1,2] = +(dx[0]) / (dx[1] * (dx[0] + dx[1]))
for ii in range(2, len(f)):
dfdr[ii, ii] = (2. * dx[ii - 1] + dx[ii - 2]) / (dx[ii - 1] * (dx[ii - 1] + dx[ii - 2]))
dfdr[ii, ii - 1] = -(dx[ii - 2] + dx[ii - 1]) / (dx[ii - 2] * dx[ii - 1])
dfdr[ii, ii - 2] = +(dx[ii - 1]) / ((dx[ii - 2] + dx[ii - 1]) * dx[ii - 2])
return np.dot(dfdr,f)
def FD1_CT2_DM(N, dx):
"""
Returns first differentiation matrix, second order dx accurate, finite difference centered
:param N: matrix dimension
:param dx: grid space
:return: d/dx
"""
dfdr = np.zeros([N, N])
# First point use forward scheme
dfdr[0, 0] = -1.5
dfdr[0, 1] = +2.0
dfdr[0, 2] = -0.5
for ii in range(1, N - 1):
dfdr[ii][ii - 1] = -0.5
dfdr[ii][ii + 1] = +0.5
# Last point use backward scheme
dfdr[-1, -1] = +1.5
dfdr[-1, -2] = -2.0
dfdr[-1, -3] = +0.5
return dfdr / dx
def FD1_FW2_DM(N, dx):
"""
Returns first differentiation matrix, second order dx accurate, finite difference forward
:param N: matrix dimension
:param dx: grid space
:return: d/dx
"""
dfdr = np.zeros([N, N])
for ii in range(0, N - 2):
dfdr[ii][ii] = -1.5
dfdr[ii][ii + 1] = +2.0
dfdr[ii][ii + 2] = -0.5
# Vorlast point use centered scheme
dfdr[-2, -3] = -0.5
dfdr[-2, -1] = +0.5
# Last point use backward scheme
dfdr[-1, -1] = +1.5
dfdr[-1, -2] = -2.0
dfdr[-1, -3] = +0.5
return dfdr / dx
def FD1_BW2_DM(N, dx):
"""
Returns first differentiation matrix, second order dx accurate, finite difference backward
:param N: matrix dimension
:param dx: grid space
:return: d/dx
"""
dfdr = np.zeros([N, N])
# First point use forward scheme
dfdr[0, 0] = -1.5
dfdr[0, 1] = +2.0
dfdr[0, 2] = -0.5
# Second point use centered scheme
dfdr[1, 0] = -0.5
dfdr[1, 2] = +0.5
for ii in range(2, N):
dfdr[ii][ii] = +1.5
dfdr[ii][ii - 1] = -2.0
dfdr[ii][ii - 2] = +0.5
return dfdr / dx
def FD2_CT2_DM(N, dx):
"""
Returns second differentiation matrix, second order dx accurate, finite difference centered
:param N: matrix dimension
:param dx: grid space
:return: d/dx
"""
dfdr = np.zeros([N, N])
# First point use forward scheme
dfdr[0, 0] = +1.0
dfdr[0, 1] = -2.0
dfdr[0, 2] = +1.0
for ii in range(1, N - 1):
dfdr[ii][ii - 1] = +1.0
dfdr[ii][ii] = -2.0
dfdr[ii][ii + 1] = +1.0
# Last point use backward scheme
dfdr[-1, -1] = +1.0
dfdr[-1, -2] = -2.0
dfdr[-1, -3] = +1.0
return dfdr / (dx * dx)
def NU1_BW2_DM(N, dx):
"""
Returns first differentiation matrix, second order dx accurate, finite difference backward, nonuniform mesh
:param N: matrix dimension
:param dx: vector of grid spacings
:return: d/dx
"""
if len(dx)+1 != N:
print 'Error: dimensions of N and dx mismatch in nonuniform differentiation matrix calculation'
return
dfdr = np.zeros([N, N])
# First point, use forward scheme
dfdr[0,0] = -(2.0*dx[0] + 1.0*dx[1]) / (dx[0] * (dx[0] + dx[1]))
dfdr[0,1] = +(dx[0] + dx[1]) / (dx[0] * dx[1])
dfdr[0,2] = -(dx[0]) / (dx[1] * (dx[0] + dx[1]))
# Second point, use centered scheme
dfdr[1,0] = -(dx[1]) / (dx[0] * (dx[1] + dx[0]))
dfdr[1,1] = (dx[1] - dx[0]) / (dx[0] * dx[1])
dfdr[1,2] = +(dx[0]) / (dx[1] * (dx[0] + dx[1]))
for ii in range(2, N):
dfdr[ii, ii] = (2. * dx[ii-1] + dx[ii - 2]) / (dx[ii-1] * (dx[ii-1] + dx[ii - 2]))
dfdr[ii, ii - 1] = -(dx[ii - 2] + dx[ii - 1]) / (dx[ii - 2] * dx[ii - 1])
dfdr[ii, ii - 2] = (dx[ii - 1]) / ((dx[ii - 2] + dx[ii - 1]) * dx[ii - 2])
return dfdr |
0c153fde9e69c555d9a66eb4f0dfc3bc81d822af | priestd09/flexx | /flexx/properties/__init__.py | 1,011 | 3.578125 | 4 | """
The properties module provides a system to add properties to classes,
that are validated, provide means for notification and serialization.
To use props, simply assign them as class attributes::
class Foo(HasProps):
size = Int(3, 'The size of the foo')
title = Str('nameless', 'The title of the foo')
To create new props, inherit from Prop and implement ``validate()``::
class MyProp(Prop):
_default = None # The default for when no default is given
def validate(self, val):
assert isinstance(val, int, float) # require scalars
return float(val) # always store as float
Any prop can only store hashable objects. This includes tuples, provided
that the items it contains are hashable too. A prop may accept
nonhashable values (e.g. list), but the data must be stored as an
immutable object.
Need more docs.
"""
from .base import Prop, HasProps, HasPropsMeta
from .props import Bool, Int, Float, Str, Tuple, FloatPair, Color, Instance
|
7e2ea330dcfaa99976104796a35a44f8e224edb5 | zhanyiduo/leetcode_practise | /222. Count Complete Tree Nodes.py | 974 | 3.953125 | 4 | '''
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
'''
class Solution:
def countNodes(self, root: TreeNode) -> int:
if root == None:
return 0
next_level = [root]
res = 0
level = 0
while next_level:
current_level = next_level
res += len(current_level)
next_level = []
while current_level:
ele = current_level.pop(0)
if ele.left != None:
next_level.append(ele.left)
if ele.right !=None:
next_level.append(ele.right)
return res |
f403d0d38fa9ffb94c038ed9c7f81ed76afc4759 | davidmp/FundamentosProg2020II | /EstSelectiva/EjemploEstSelectiva.py | 774 | 4 | 4 | def calcularPrecioLapiz():
#Datos Entrada
cantidadL=int(input("Ingresa la cantidad de lapices a comprar:"))
#Proceso
if(cantidadL>=1000):
costoPagar=cantidadL*0.85
else:
costoPagar=cantidadL*0.9
#Datos de salida
print("El costo total a pagar es: ", costoPagar)
def identificarNumeroMayor():
#datos entrada
num1=int(input("Ingrese el Primer valor numerico:"))
num2=int(input("Ingrese el Segundo valor numerico:"))
num3=int(input("Ingrese el Tercer valor numerico:"))
#proceso
if(num1>num2 and num1>num3):
numMayor=num1
elif num2>num1 and num2>num3:
numMayor=num2
else:
numMayor=num3
#Datos de Salida
print("El numero mayor es:", numMayor)
#calcularPrecioLapiz()
identificarNumeroMayor()
|
597447d024d178066077d36c3cae84f147a0e8bd | manojkumar-ch/py-thony-three | /vowelandconstant.py | 135 | 3.796875 | 4 | k=['a','e','i','o','u','A','E','I','O','U'];
r=str(input("Enter the letter:"))
if(r in k):
print("vowel")
else:
print("consonant")
|
c3f65c2ffeca4a18cc016f44a931f1d614e85727 | ChihChaoChang/Leetcode | /050.py | 507 | 3.75 | 4 | '''
Pow(x, n)
Implement pow(x, n).
'''
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
flag= -1
else:
flag = 1
result =1
n=abs(n)
while n >0:
if (n&1) ==1:
result = result *x
n>>=1
x*=x
if flag <0:
result = 1/ result
return result
|
fc8634dbbc5151e74996b1529b7a2aeb182cbc00 | deepak1214/CompetitiveCode | /Hackerrank_problems/Nested Lists/solution.py | 780 | 3.984375 | 4 | grades = [] #list to store grades
N = int(input())
secondscore = 0.0 #secondscore to get the 2nd lowest grade
def sortSecond(val):
return val[1],val[0] #sorting with respect to grades primarily and then names as names are present in index 0 and grades in index 1
for _ in range(0,N):
string = input().split() #taking the inputs
grd = float(input())
string.append(grd)
grades.append(string)
grades.sort(key = sortSecond)
secondscore = grades[0][1]
for _ in range(1,N):
if(grades[_][1]>secondscore):
secondscore = grades[_][1] #finding out the second lowest score from the list
break
for _ in range(0,N):
if(float(grades[_][1])==secondscore): #printing the names corresponding to the second lowest score
print(grades[_][0])
|
5d493ceeb55bad4799661a691e16a5159b3cdf27 | amritachaudri/Text-Based-Captcha | /login.py | 627 | 3.515625 | 4 | from tkinter import*
from tkinter import messagebox
top=Tk()
def nex():
if (len(e1.get())==0):
messagebox.showinfo("NEXT",("Please enter ID"))
elif(len(e2.get())==0):
messagebox.showinfo("NEXT",("Please enter password"))
else:
import dbms
l1=Label(top,text="ID.:")
l1.grid(row=0)
e1=Entry(top,bd=4,bg="light blue",fg="black")
e1.grid(row=0,column=1)
l2=Label(top,text="Password:")
l2.grid(row=1)
e2=Entry(top,bd=4,bg="light blue",fg="black")
e2.grid(row=1,column=1)
b1=Button(top,text="Next",command=nex)
b1.grid(row=2,columnspan=2)
|
a482b1a4d830002ae87c7be39e37c27b7b6e3601 | penroselearning/pystart_code_samples | /04 Strings - Text Casing.py | 233 | 4.1875 | 4 | name=input("Enter your name:\n").title().strip()
course=input("What course you are learning?\n").title().strip()
website=input("Which website are you learning from?\n").lower().strip()
print(name,'is learning',course,'from',website) |
4a892f1d3de28bd0cf6551ce200c2ea5f93e4d8b | elainechan/python_drills | /rangoli.py | 1,916 | 4.1875 | 4 | '''
rangoli.py
Design a function that prints an alphabet rangoli of size n.
Input: An integer n where: 0 < n < 27
Output: Print the alphabet rangoli.
The center of the rangoli has the first alphabet letter a,
The boundary has the last alphabet letter indicated.
'''
import string
def rangoli(n):
alpha = list(string.ascii_lowercase) # Last letter is alphabet[n - 1]
# Map n to number of dashes on each side of first row
side_dashes = dict(list({0:0, 1:0}.items()) + list(dict(zip(range(2, 27), range(2, 52, 2))).items()))
k = side_dashes.keys()
v = side_dashes.values()
# List elements, each of length 27 including when n = 0:
letters = [0, 1] + list(range(2, 27)) # Number of letters
dash_len = [0, 0] + list(range(2, 52, 2)) # Number of dashes in first row
row_num = [0] + list(range(1, 53, 2)) # Number of rows = n * 2 - 1
row_len = [0, 1, 5, 9, 13, 17]
# Print rows until all letters have been used, then reverse print pattern
# Padding on each side of letter string: pad = '-'
# Separator between letters: delimiter = '-'
print(side_dashes)
print(dash_len)
print(row_len)
# Rules:
# 1) Number of rows = n * 2 - 1
# 2) row_len =
# 3) Start in descending order
# 4) Always print a dash between two letters
# 5) Always use the last letter as boundary
# 6) Row numbers are always odd except for 0
# Example: let n = 3
# 1 ----c---- Row length = 9
# 2 --c-b-c--
# 3 c-b-a-b-c
# 4 --c-b-c-- Repeats Row 2
# 5 ----c---- Repeats Row 1
# Note: on each row, if the position index is even, there is a dash.
# Pseudocode for manual n = 3 example:
# Row 1: print v dashes, 'c', v dashes
# print('-' * v + alphabet[n - 1] + '-' * v)
# Row 2: print v - 2 dashes, 'c', dash, 'b', dash, 'c', v - 2 dashes
# print('-' * (v - 2), alphabet[n - 1], '-', alphabet[n - 2], ...)
# Row 3: print c dash b dash a dash b dash c
# Row 4 = Row 2
# Row 5 = Row 1
|
ff3ff64f0e75507f6c24942892817f45a067c0f7 | vinceajcs/all-things-python | /algorithms/array/interval/meeting_rooms_ii.py | 1,011 | 3.984375 | 4 | """Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
Idea: We can use a min heap to store end times of each interval.
The room at the top of the min heap is then the one that will be free at the earliest time.
If the room at the top is not free, no other room is. In this case, we allocate a new room.
Time: O(nlogn)
Space: O(n)
"""
def min_meeting_rooms(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x.start)
heap = [] # stores the end time of intervals
for i in intervals:
if heap and i.start >= heap[0]:
# means two intervals can use the same room
heapq.heapreplace(heap, i.end) # pop then push
else:
# a new room is allocated
heapq.heappush(heap, i.end)
return len(heap)
|
c82f5f0517ad5fa2d0615af8fabe310a2b00109e | supvigi/python-first-project | /Tasks/2020_12_05/Begin/Begin13.py | 299 | 4.1875 | 4 | r1 = int(input("Write the length of the first radius: "))
r2 = int(input("Write the length of the second radius: "))
pi = 3.14
s2 = pi*r2**2
s1 = pi*r1**2
print("S2 =", s2)
print("S1 =", s1)
if s1 > s2:
print("S3 =", s1 - s2)
elif s1 < s2:
print("S3 =", s2 - s1)
else:
print("S3 =", 0) |
23e8ee360c06cd02a66ae1f61bcb6847711e5b6b | divyamadhurikalluri/pythonprogramming | /binary''.py | 94 | 3.640625 | 4 | S=raw_input()
if((S.count('0') + S.count('1'))==len(S)):
print("yes")
else:
print("no")
|
39bd8cbbd7a12597f31811fe4eee0732c8af4f76 | pavanmsvs/hackeru-python | /number guessing.py | 606 | 4.03125 | 4 | import random
print("For 1.easy (0-5) \n 2.hard(0-10) ")
choice = int(input("Enter the level \n"))
if (choice==1):
num=int(input("Enter a number to Guess \n"))
r=random.randint(0,5)
# print(r)
if (num==r):
print("You Guessed it right")
else:
print("Sorry your Guess was wrong,correct guess was",r," try again")
elif (choice==2):
num =int(input("Enter a number to Guess \n"))
r=random.randint(0,10)
if (num==r):
print("You Guessed it right")
else:
print("Sorry your Guess was wrong,correct guess was",r," try again")
|
1c1e839914957ed334ac9ec5ea2e4e285acd2687 | dm36/interview-practice | /leetcode/divides.py | 1,854 | 3.875 | 4 | # For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times)
#
# Return the largest string X such that X divides str1 and X divides str2.
#
# Example 1:
#
# Input: str1 = "ABCABC", str2 = "ABC"
# Output: "ABC"
# Example 2:
#
# Input: str1 = "ABABAB", str2 = "ABAB"
# Output: "AB"
# Example 3:
#
# Input: str1 = "LEET", str2 = "CODE"
# Output: ""
#
#
# Note:
#
# 1 <= str1.length <= 1000
# 1 <= str2.length <= 1000
# str1[i] and str2[i] are English uppercase letters.
# from collections import Counter
#
# def gcdOfStrings(str1, str2):
# l1, l2 = len(str1), len(str2)
# if l2 > l1:
# gcdOfStrings(str2, str1)
#
# if l1 % l2 == 0:
# count = l1 / l2
# final_str = ""
#
# while count:
# final_str += str2
# count -= 1
#
# if final_str == str1:
# return str2
#
# if not set(Counter(str2).keys()).issubset(Counter(str1).keys()):
# return ""
# elif str1 not in str2 and str2 not in str1:
# return ""
def gcdOfStrings(str1, str2):
# if the two strings are equal (base case)
# return the first string
# otherwise return ''
if len(str1) == len(str2):
return str1 if str1==str2 else ''
else:
if len(str1) < len(str2):
str1,str2 = str2,str1
if str1[:len(str2)] == str2:
return gcdOfStrings(str1[len(str2):],str2)
else:
return ''
# since ABAB and ABAB match
# would call gcd on "AB" and "ABAB"
# which would then call gcd on "AB", "AB"
# which would return "AB"
gcdOfStrings("ABABAB", "ABAB")
#
# str1 = "ABCABC"
# str2 = "ABC"
# print (gcdOfStrings(str1, str2))
#
# str1 = "ABABAB"
# str2 = "ABAB"
# print (gcdOfStrings(str1, str2))
#
# str1 = "LEET"
# str2 = "CODE"
# print (gcdOfStrings(str1, str2))
|
70fafeceabda1d1356af62b5723e65412c03023a | daniel-reich/ubiquitous-fiesta | /u9mxp7LLxogAjAGDN_15.py | 331 | 3.515625 | 4 |
def factors(num):
counter = 2
for val in range(2, num//2 + 1):
if num%val == 0:
counter += 1
return counter
def factor_sort(lst):
factor_lst = sorted(list(zip(lst, [factors(num) for num in lst])), key=lambda elm: (elm[1], elm[0]), reverse=True)
return [elm[0] for elm in factor_lst]
|
0e4e6e5a06682832e9ce0c311f6d86afd3b1786a | GirlsFirst/SIP-Facilitator | /Unit2-Python/U2L2/loops_solutions.py | 1,474 | 4.34375 | 4 | '''
loops_solutions.py
Description: Intro Python Loops Solutions File for you to practice writing loops
and explore variable operations
Author: GWC Curriculum Team
Date Created: May 2020
'''
#TODO: Create an integer variable and set it equal to 0
num = 0
#TODO: Write a while loop that prints out the value of your integer variable and repeats for 25 iterations
while (num < 25):
print(num)
num += 1
#TODO: Write a while loop that prints out all the odd numbers starting from 25 and ending at 1
num = 25
while (num > 0):
print(num)
num -= 2
#TODO: Write a while loop that prints out the multiples of 5 starting from 5 up to 100
num = 5
while (num >= 100):
print (num)
num+=5
#TODO: Write a while loop that prints out the powers of 2 up to 1024: 2, 4, 8, 16, 32, ...
num = 2
while (num <= 1024):
print (num)
num *= 2
#Extensions (Optional)
#TODO: Write a while loop that executes 20 iterations but prints out numbers between 5-10
num = 0
while (num < 20):
if (num >= 5 and num <= 10):
print (num)
num+=1
#TODO: Write a while loop that calculates the factorial of 4 or noted as 4!
prod = 1
index = 4
while (index > 0):
prod*=index
index-=1
print (prod)
#TODO: Print out the first 10 fibonacci numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
fib1 = 1
fib2 = 1
print (fib1)
print (fib2)
index = 3
while (index <=10):
nextFib = fib1+fib2
print(fib1+fib2)
fib1 = fib2
fib2 = nextFib
index+=1
|
390c1ac4c9de944fb14fca44e85b23312cdf0a48 | greggoren/robustness | /results_test.py | 63 | 3.609375 | 4 | a = ["t"]
if "t" not in a:
print("f")
else:
print("a")
|
b4b6a3b977f8764695b77381cb5e092bca431624 | AndrewLevy395/GKHA20 | /logic.py | 886 | 3.515625 | 4 | import pygame
import glovars
def sortFunc(e):
return e["points"]
#logic to calculate which team is top of the rankings and then sorts them accordingly
def calculateRankings(f):
teampoints = [{"mascot": "Thunder", "name": "Alaskan Thunder", "points": 0},
{"mascot": "Revolution", "name": "American Revolution", "points": 0},
{"mascot": "Whales", "name": "Boondock Beluga Whales", "points": 0},
{"mascot": "Tropics", "name": "Florida Tropics", "points": 0},
{"mascot": "Chippewas", "name": "Smashville Chippewas", "points": 0},
{"mascot": "Spartans", "name": "Southside Spartans", "points": 0}]
teamdata = f["teamdata"][0]
for i in range(len(teamdata)):
teampoints[i]["points"] = (teamdata[glovars.defaultTeams[i].name][0]["wins"] * 2) + (teamdata[glovars.defaultTeams[i].name][0]["overtimelosses"])
teampoints.sort(reverse=True, key=sortFunc)
return teampoints
|
6523b010f38b863cc9e9812dd7f82a5c1d300f93 | prashant97sikarwar/leetcode | /Tree/Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py | 1,028 | 3.859375 | 4 | # Problem Link :- https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
"""Given inorder and postorder traversal of a tree, construct the binary tree."""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def buildTree(self, inorder, postorder):
return self.helper(len(postorder)-1,0,len(inorder)-1,postorder,inorder)
def helper(self,poststart,instart,inend,postorder,inorder):
if poststart < 0 or instart > inend:
return
node = TreeNode(postorder[poststart])
for i in range(len(inorder)):
if inorder[i] == node.val:
index = i
break
node.right = self.helper(poststart-1,index+1,inend,postorder,inorder)
node.left = self.helper(poststart - (inend-index+1),instart,index-1,postorder,inorder)
return node |
b27777916d27fe3c98b80718729e79ffd0c9d66b | flogothetis/Technical-Coding-Interviews-Algorithms-LeetCode | /Grokking-Coding-Interview-Patterns/9. Two Heaps/nextInterval.py | 1,656 | 3.765625 | 4 | '''
Next Interval (hard) #
Given an array of intervals, find the next interval of each interval. In a list of intervals, for an interval ‘i’ its
next interval ‘j’ will have the smallest ‘start’ greater than or equal to the ‘end’ of ‘i’.
Write a function to return an array containing indices of the next interval of each input interval.
If there is no next interval of a given interval, return -1. It is given that none of the intervals
have the same start point.
'''
from heapq import *
class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
# Time Complexity : O(NlogN)
# Space Complexiry : O(N)
def find_next_interval(intervals):
result = []
next_interval_heap = []
current_interval_heap =[]
for idx in range (len(intervals)):
heappush(current_interval_heap, (intervals[idx].end, intervals[idx].start, idx))
heappush(next_interval_heap, (intervals[idx].start, intervals[idx].end, idx))
for _ in range (len(intervals)):
curr_end, curr_start, curr_idx = heappop(current_interval_heap)
next_idx = -1
while (next_interval_heap and next_interval_heap[0][0]< curr_end):
heappop(next_interval_heap)
if(next_interval_heap):
next_start, next_end, next_idx = heappop(next_interval_heap)
result.append(next_idx)
return result
def main():
result = find_next_interval(
[Interval(2, 3), Interval(3, 4), Interval(5, 6)])
print("Next interval indices are: " + str(result))
result = find_next_interval(
[Interval(3, 4), Interval(1, 5), Interval(4, 6)])
print("Next interval indices are: " + str(result))
main()
|
2e1fd26f62781ba9df41587ee8cbae5e72f487e1 | jz33/LeetCodeSolutions | /913 Cat and Mouse.py | 4,078 | 3.921875 | 4 | '''
913. Cat and Mouse
https://leetcode.com/problems/cat-and-mouse/
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.
During each player's turn, they must travel along one edge of the graph that meets where they are.
For example, if the Mouse is at node 1, it must travel to any node in graph[1].
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in 3 ways:
If ever the Cat occupies the same node as the Mouse, the Cat wins.
If ever the Mouse reaches the Hole, the Mouse wins.
If ever a position is repeated (ie. the players are in the same position as a previous turn,
and it is the same player's turn to move), the game is a draw.
Given a graph, and assuming both players play optimally, return 1 if the game is won by Mouse,
2 if the game is won by Cat, and 0 if the game is a draw.
Example 1:
Input: [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
Output: 0
Explanation:
4---3---1
| |
2---5
\ /
0
Note:
3 <= graph.length <= 50
It is guaranteed that graph[1] is non-empty.
It is guaranteed that graph[2] contains a non-zero element.
'''
from collections import deque, Counter
DRAW, MOUSE, CAT = 0, 1, 2
class Solution:
def getParents(self, graph, m, c, t):
'''
get parent states of (m, c, t)
'''
if t == MOUSE:
return [(m, p, 3-t) for p in graph[c] if p != 0]
elif t == CAT:
return [(p, c, 3-t) for p in graph[m] if p != 0]
def catMouseGame(self, graph):
'''
Let (m,c,t) be the state of the game. m is the mouse location,
c is cat location, t is 1 means it's mouse's turn,
t is 2 means it's cat' turn.
Then the algorithm is to mark all the states to 3 colors.
'''
# childrenCount[s] : the number of children state of this state
childrenCount = {}
for m in range(len(graph)):
for c in range(len(graph)):
# mouse can move to anywhere
childrenCount[m,c,MOUSE] = len(graph[m])
# cat cannot move to 0
childrenCount[m,c,CAT] = len(graph[c]) if 0 not in graph[c] else len(graph[c]) - 1
# Mark colors of initial states.
# Default color is DRAW
colors = Counter() # {[m,c,t] : color}
# mouse at node 0, mouse wins
for i in range(len(graph)):
colors[0, i, MOUSE] = MOUSE
colors[0, i, CAT] = MOUSE
# mouse and cat at same node other that 0, cat wins
for i in range(1, len(graph)):
colors[i, i, MOUSE] = CAT
colors[i, i, CAT] = CAT
# starting nodes are already determined states
queue = deque(colors.keys())
# Iterate, mark colors
while queue:
m, c, t = queue.popleft()
color = colors[m, c, t]
for pm, pc, pt in self.getParents(graph, m, c, t):
if colors[pm, pc, pt] == DRAW:
# If parent node is mouse to move and current node is mouse win, or
# parent node is cat to move and current node is cat win, parent's is a win
if pt == color:
colors[pm, pc, pt] = color
queue.append((pm, pc, pt))
# Otherwise, if parent's all children cannot determine its color,
# its color, it is lost, which is to mark its color as opposite of turn
else:
childrenCount[pm, pc, pt] -= 1
if childrenCount[pm, pc, pt] == 0:
colors[pm, pc, pt] = 3 - pt
queue.append((pm, pc, pt))
# Mouse starts at 1, cat starts at 2, mouse moves first
return colors[1, 2, 1]
|
43f369e183be6d97cabd8de57437fc9789cd7592 | YanbinZuo/pygame | /main.py | 8,365 | 3.59375 | 4 | import math
import random
import pygame
# mixer class helps us handle all kinds of music inside of our project
from pygame import mixer
"""
Name: Yanbin Zuo
Date: 8/25/2021
NOTE: THIS PROJECT IS LEARNED FROM YOUTUBE VIDEO https://youtu.be/FfWpgLFMI7w
THE ORIGINAL CREATER IS FROM freeCodeCamp.org
"""
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
GREY = (118, 128, 128)
TURQUOISE = (64, 224, 208)
# first, need to intialize the pygame
# REMEMBER: MUST HAVE THIS LINE, AND IT HAS TO BE FIRST
pygame.init()
# create teh screen with width(left to right) 800, and high(up to down) 600
screen = pygame.display.set_mode((800, 600))
# Title and Icon
# it has a default title in the upper left corner of the window, which
# named "pygame window" and default icon
# we change to our own title and icon
# www.flaticon.com --> find image (spaceship)
pygame.display.set_caption("Space Invaders")
# icon is 32px
icon = pygame.image.load('Images/ufo.png')
pygame.display.set_icon(icon)
# create background
# background image: pixabay.com
bgImg = pygame.image.load('Images/background.jpg')
def background():
screen.blit(bgImg, (0,0))
# background music
mixer.music.load('Sounds/background.wav')
# if don't add anything in play(), it will only play once and stop
# add -1 means play on loop
mixer.music.play(-1)
# create player image (arcade space) 64px
playerImg = pygame.image.load('Images/space-invaders.png')
# play image applear index (x, y with the upper left of the image)
playerX = 370
playerY = 480
playerX_change_value = 0.5
playerX_change = 0
def player(x, y):
# blit means to draw
screen.blit(playerImg, (x, y))
# create bullet: image 32px
bulletImg = pygame.image.load('Images/bullet.png')
# will set x index to player x index
bulletX = -1
# a little bit below the player
bulletY = 490
bulletY_change = 1
# ready - you can't see the bullet on the screen
# fire - the bullet is currently moving
bullet_state = 'ready'
def fire_bullet(x, y):
# player image is 32px, we put bullet in center of player, so x + 32/2
screen.blit(bulletImg, (x + 16, y))
# create enemy: image 64px
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = 60
enemy_number = 6
for i in range(enemy_number):
enemyImg.append(pygame.image.load('Images/enemy.png'))
enemyX.append(10 + i*100)
enemyY.append(120)
enemyX_change.append(0.2)
def enemy(i, x, y):
screen.blit(enemyImg[i], (x, y))
def isCollision(x1, y1, x2, y2):
distance = math.sqrt(math.pow(x1-x2,2) + math.pow(y1-y2,2))
if distance < 27:
return True
else:
return False
# score
score_value = 0
scoreX = 10
scoreY = 10
# this is one free font inside of pygame, 32 is size
# go to https://www.dafont.com/ to download and upzip other free font files and
# paste the ttf file inside this project folder to use other fonts
score_font = pygame.font.Font('Sushi Delivery.ttf', 32)
# score_value is integer, convert it to string
def score(x, y):
score_render = score_font.render("Score: " + str(score_value), True, WHITE)
screen.blit(score_render, (x, y))
# game over text
game_over_font = pygame.font.Font('Sushi Delivery.ttf', 64)
def gameover():
game_over_render = game_over_font.render("GAME OVER", True, WHITE)
screen.blit(game_over_render, (200,250))
# Game Loop
# without loop, the screen displayed, and then the program end, then the
# screen will disappear quickly
running = True
while running:
# everything that you want to be persistent inside the game window (appears
# continuously, it can be image or text), it has to go inside the while loop
# change the background color
# make sure every other draws will below this method, otherwise, they will
# covered by this background color
# (...) is a tuple
# give RGB values (RED, GREEN, BLUE)
# google color to rgb
# screen.fill(CYAN) --> this also work, default is black also
screen.fill((0, 255, 255))
# some background image might be very big(e.g. 1000KB), the while loop need time
# to load the image, cause the player and enemy run slow
background()
# go through the list of events that are happening inside the game window
# (any kind of input control) one by one to check which event is happening
# events could include any keystrock that is pressed on a keyboard, and
# mouse click...and so on
for event in pygame.event.get():
# the right up corner cross button is pygame.QUIT event
# if click cross button, end the loop, which will end the program
if event.type == pygame.QUIT:
running = False
# check if a keystroke is pressed
# 如果一直按着按键不松开,只会相应一次
if event.type == pygame.KEYDOWN:
# check whether it is right or left
if event.key == pygame.K_LEFT:
# print('Left arrow is pressed') --------------> PRACTICE CODE
playerX_change = -1 * playerX_change_value
if event.key == pygame.K_RIGHT:
# print('Right arrow is pressed') --------------> PRACTICE CODE
playerX_change = playerX_change_value
# check for bullet fire
if event.key == pygame.K_SPACE:
# only ready to fire, then change state, otherwise, don't update
if bullet_state == 'ready':
# add bullet sound.
# if sound is very short, use sound instead of music
bullet_sound = mixer.Sound('Sounds/laser.wav')
bullet_sound.play()
# change bullet state
bullet_state = 'fire'
# get the current x coordinate of the spaceship
bulletX = playerX
# check if a keystroke is released
if event.type == pygame.KEYUP:
# if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
# # print('Keystroke has been released') ---------> PRACTICE CODE
# check condition that both left key and right key are pressed
if ((event.key == pygame.K_LEFT and playerX_change == -1 * playerX_change_value) or
(event.key == pygame.K_RIGHT and playerX_change == playerX_change_value)):
playerX_change = 0
# player
# show player image and its position
playerX += playerX_change
# add boundary
# without restriction, ship will go beyond the window
if playerX <= 0:
playerX = 0
# since winwon is 800, and image is 64px, so right limit is :800 - 64 = 736
elif playerX >= 736:
playerX = 736
player(playerX, playerY)
# bullet
if bulletY <= 0:
bulletY = 490
bullet_state = 'ready'
# only if the bullet state is 'fire', then show bullet image and move
if bullet_state == 'fire':
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
# enemy
for i in range(enemy_number):
# check game over
# 60*7=420 60*8 = 480
if enemyY[i] >= 400:
# if game over, remove all enemies
for j in range(enemy_number):
enemyY[j] = 1000
gameover()
break
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 0.2
enemyY[i] += enemyY_change
elif enemyX[i] >= 736:
enemyX_change[i] = -0.2
enemyY[i] += enemyY_change
enemy(i, enemyX[i], enemyY[i])
# collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
# add colission sound
collision_sound = mixer.Sound('Sounds/explosion.wav')
collision_sound.play()
# update everything
score_value += 1
enemyX[i] = random.randint(0, 736)
enemyY[i] -= enemyY_change
bullet_state = 'ready'
bulletY = 490
# score
score(scoreX, scoreY)
# if add anything inside window, need update
# REMEMBER: MUST HAVE THIS LINE, AND IT IN THE BOTTON OF THE LOOP
pygame.display.update()
|
c52beb770f9693d6344e2ac2e9115bf61f2ec608 | Viniciusadm/Python | /exerciciosCev/Mundo 3/Aula 19/092.py | 541 | 3.78125 | 4 | from datetime import date
pessoa = dict()
anoAtual = date.today().year
pessoa['Nome'] = str(input('Nome: '))
pessoa['Idade'] = anoAtual - int(input('Ano de Nascimento: '))
pessoa['CTPS'] = int(input('Carteira de Trabalho: '))
if pessoa['CTPS'] != 0:
pessoa['Contratação'] = int(input('Ano de Contratação: '))
pessoa['Salário'] = float(input('Salário: '))
pessoa['Aposentadoria'] = (pessoa['Contratação'] - (anoAtual - pessoa['Idade'])) + 35
print(40 * '=')
for c, d in pessoa.items():
print(f'{c} tem o valor {d}') |
d3653557105926be903239d5e12f7ff7912fd580 | dabinlee708/SUTD | /VISA/cipher.py | 765 | 3.84375 | 4 | def cipher(plaintext, keylength):
totalLength=len(plaintext)
outputString=""
for a in range(keylength):
i=a
# print i,a
while i<totalLength:
# print i
outputString=outputString+plaintext[i]
i+=keylength
pad=len(plaintext)%keylength
i=1
while i<=pad:
if i%4==1:
outputString+="a"
if i%4==2:
outputString+="b"
if i%4==3:
outputString+="c"
if i%4==0:
outputString+="d"
i+=1
print outputString.upper()
data=["DELHI",1,"thankyouforyourcooperation"]
print len(data[2])
keylength=len(data[0])
for a in data:
if a==data[0] or a==data[1]:
pass
else:
cipher(a,keylength) |
9de180e4e176f4cc49a24f6e48441d7f35eb8bff | lovehhf/LeetCode | /31_下一个排列.py | 2,325 | 3.609375 | 4 | # -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
1. 从右往左遍历 找到第一个不是顺序排列的数字,而不是第一个比最右的数小的数
2. 找到了这个数i之后再最后的数开始往右遍历,找到第一个比i大的数j与i交换,然后再对i后面的所有数重新排序
eg: 2302431 -> 2303124
从右往左遍历先找到第一个比右边小的数字2,然后找到从右往左找到第一个比2大的数字3,交换这两个数字,然后421重新排序为124
最后得到2303124
"""
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = n - 1
while i > 0:
if nums[i - 1] < nums[i]:
for j in range(n - 1, i - 1, -1):
if nums[j] > nums[i - 1]:
nums[i - 1], nums[j] = nums[j], nums[i - 1]
break
break
i -= 1
if i == 0:
nums.sort()
else:
# tmp = sorted(nums[i:])
# for j in range(i,n):
# nums[j] = tmp[j-i]
nums[i:] = sorted(nums[i:])
def nextPermutation2(self, nums):
n = len(nums)
i = n - 1
if sorted(nums)[::-1] == nums: # 逆序
nums[:] = sorted(nums)
return
for i in range(n - 2, -1, -1):
if nums[i] < nums[i + 1]:
for j in range(n - 1, i, -1):
if nums[j] > nums[i]:
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = sorted(nums[i + 1:])
break
break
nums[i + 1:] = sorted(nums[i + 1:])
nums = [2, 3, 0, 2, 4, 1]
s = Solution()
s.nextPermutation(nums)
print(nums)
|
dd37183e8482cd46606d330d52aea933a61162e5 | roysegal11/Python | /conditions/Targil1.py | 162 | 4.25 | 4 | num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = num1 + num2
if num3%2 == 0:
print("Even")
else:
print("Odd") |
203ab9709864286dc8daf254830589ba8e02da31 | zcielz/zciel-python | /pythoneBase/cn/zciel/selfstudy01/009.使用dict和set.py | 3,531 | 3.890625 | 4 | # Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]
# 给定一个名字,要查找对应的成绩,就先要在names中找到对应的位置,再从scores取出对应的成绩,list越长,耗时越长。
# 如果用dict实现,只需要一个“名字”-“成绩”的对照表,直接根据名字查找成绩,无论这个表有多大,查找速度都不会变慢。用Python写一个dict如下:
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])
# 为什么dict查找速度这么快?因为dict的实现原理和查字典是一样的。假设字典包含了1万个汉字,我们要查某一个字,一个办法是把字典从第一页往后翻,直到找到我们想要的字为止,这种方法就是在list中查找元素的方法,list越大,查找越慢。
# 第二种方法是先在字典的索引表里(比如部首表)查这个字对应的页码,然后直接翻到该页,找到这个字。无论找哪个字,这种查找速度都非常快,不会随着字典大小的增加而变慢。
# dict就是第二种实现方式,给定一个名字,比如'Michael',dict在内部就可以直接计算出Michael对应的存放成绩的“页码”,也就是95这个数字存放的内存地址,直接取出来,所以速度非常快。
# 把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
d['Adam'] = 67
print(d['Adam'])
# 由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉
d['Jack'] = 90
print(d['Jack'])
d['Jack'] = 88
print(d['Jack'])
# 如果key不存在,dict就会报错
# print(d['Thomas']) KeyError: 'Thomas'
# 要避免key不存在的错误,有两种办法,一是通过in判断key是否存在
print('Thomas' in d)
print('Jack' in d)
# 二是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value
print(d.get('Thomas'))
print(d.get('Thomas', -1))
# 要删除一个key,用pop(key)方法,对应的value也会从dict中删除
print(d)
print(d.pop('Bob'))
print(d)
# 和list比较,dict有以下几个特点:
# 查找和插入的速度极快,不会随着key的增加而变慢;
# 需要占用大量的内存,内存浪费多。
# 而list相反:
# 查找和插入的时间随着元素的增加而增加;
# 占用空间小,浪费内存很少。
# 所以,dict是用空间来换取时间的一种方法。
# 牢记的第一条就是dict的key必须是不可变对象。
# 因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了。这个通过key计算位置的算法称为哈希算法(Hash)。
# list是可变的,就不能作为key
# set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
s = set([1, 2, 3, 1])
print(s)
# 通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果,通过remove(key)方法可以删除元素
# set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。试试把list放入set,看看是否会报错。
|
e1c1849e47acb2f89e320751aea8647119936e88 | chao-ji/LeetCode | /python/linked_list/lc86.py | 2,291 | 3.828125 | 4 | """86. Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
##############
# KEY Insight:
# Use two pointers `lt` and `ge`, initially pointing to dummy nodes
# Get another pointer `node`, initially pointing to `head` of linked list
# initially, input linked list:
# [] =====> [] ======> ... =======> []
# head
# node
# disconnect `node` from the remaining of linked list:
#
# [] =====> None, [] =======> ... =======> []
# node next
# In each iteration,
# Either `lt` or `ge` grows by incorporating `node`
# reset `node` to the next node:
#
# [] =======> ... =======> []
# next
# node
# Eventually, the input linked list in partition into
# [] ======> [] ===> ... ===> []
# dummy_lt a lt
#
# [] ======> [] ===> ... ===> []
# dummy_ge b ge
# joins the two partitions: `lt.next` = `dummy_ge`
#
# [] ======> [] ===> ... ===> [] ===> [] ===> ... ===> []
# dummy_lt a lt b ge
lt = dummy_lt = ListNode(0)
ge = dummy_ge = ListNode(0)
node = head
while node:
# take note of the next node of `node`:
next = node.next
# disconnect node from the remaining of linked list
node.next = None
# grow either `lt` or `ge`
if node.val < x:
lt.next = node
lt = lt.next
else:
ge.next = node
ge = ge.next
# `node` points to the next node
node = next
# joins the two parts
lt.next = dummy_ge.next
return dummy_lt.next
|
5b63ec60657358f02381269732401a2579322fee | suhassrivats/Data-Structures-And-Algorithms-Implementation | /DataStructures/3_Stacks/Implementation/stacks_using_ll.py | 1,537 | 4.34375 | 4 | # Implement a stack using singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def isempty(self):
if self.head == None:
return True
else:
return False
def push(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def pop(self):
if self.isempty():
return None
else:
popnode = self.head
self.head = self.head.next
popnode.next = None
return popnode.data
def peek(self):
if self.isempty():
return None
else:
return self.head.data
def display(self):
if self.isempty():
print("Linked List is empty")
else:
temp = self.head
while(temp):
print(temp.data, "->", end=" ")
temp = temp.next
return
##########
# Driver code
MyStack = Stack()
MyStack.push(11)
MyStack.push(22)
MyStack.push(33)
MyStack.push(44)
# Display stack elements
MyStack.display()
# Print top elementof stack
print("\nTop element is ", MyStack.peek())
# Delete top elements of stack
MyStack.pop()
MyStack.pop()
# Display stack elements
MyStack.display()
# Print top elementof stack
print("\nTop element is ", MyStack.peek())
|
8596e32a0938083a636d6c3f3feb04a037770352 | hz336/Algorithm | /LeetCode/DFS/H Sudoku Solver.py | 1,942 | 3.90625 | 4 | """
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character '.'.
"""
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if board is None or len(board) != 9 or len(board[0]) != 9:
return
self.dfs(board)
def dfs(self, board):
for i in range(9):
for j in range(9):
if board[i][j] == '.':
for c in range(1, 10):
c = str(c)
if self.is_valid(board, i, j, c):
board[i][j] = c
if self.dfs(board):
return True
else:
board[i][j] = '.'
return False
return True
def is_valid(self, board, row, col, c):
for i in range(9):
# check row
if board[row][i] == c:
return False
# check column
if board[i][col] == c:
return False
# check box
if board[(row // 3) * 3 + i // 3][(col // 3) * 3 + i % 3] == c:
return False
return True
|
c5fc13f6ff9dfb426a903bbeca5ddcd6ea3897a9 | smahamkl/ScalaSamples | /sep2020challenge/BinaryTreeSort.py | 3,296 | 4.03125 | 4 | from typing import List
'''
Given two binary search trees root1 and root2.
Return a list containing all the integers from both trees sorted in ascending order.
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]
Example 3:
Input: root1 = [], root2 = [5,1,7,0,2]
Output: [0,1,2,5,7]
Example 4:
Input: root1 = [0,-10,10], root2 = []
Output: [-10,0,10]
Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]
Constraints:
Each tree has at most 5000 nodes.
Each node's value is between [-10^5, 10^5].
'''
class TreeNode:
def __init__(self, data):
self.val = data
self.left = None
self.right = None
class Solution:
def buildTree(self, nodes: List[int], curVal: int, root: TreeNode) -> TreeNode:
if curVal < len(nodes):
root = TreeNode(nodes[curVal])
root.left = self.buildTree(nodes, ((2 * curVal) + 1), root.left)
root.right = self.buildTree(nodes, ((2 * curVal) + 2), root.right)
return root
def inorderTraversal(self, root: TreeNode, elements: List[int]) -> List[int]:
#print(root.val)
if root != None:
if root.left != None:
self.inorderTraversal(root.left, elements)
if root.val != None:
elements.append(root.val)
if root.right != None:
self.inorderTraversal(root.right, elements)
return elements
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
list1 = sol.inorderTraversal(root1, [])
list2 = sol.inorderTraversal(root2, [])
res = []
i = 0
j = 0
while (i < len(list1)) | (j < len(list2)):
if i >= len(list1):
res.append(list2[j])
j+=1
elif j >= len(list2):
res.append(list1[i])
i+=1
elif list1[i] > list2[j]:
res.append(list2[j])
j+=1
elif list2[j] > list1[i]:
res.append(list1[i])
i+=1
else:
res.append(list1[i])
res.append(list2[j])
i+=1
j+=1
return res
if __name__ == "__main__":
sol = Solution()
root1 = sol.buildTree([2, 1, 4], 0, None)
root2 = sol.buildTree([1, 0, 3], 0, None)
print(sol.getAllElements(root1, root2))
root3 = sol.buildTree([0, -10, 10], 0, None)
root4 = sol.buildTree([5,1,7,0,2], 0, None)
print(sol.getAllElements(root3, root4))
root3 = sol.buildTree([], 0, None)
root4 = sol.buildTree([5,1,7,0,2], 0, None)
print(sol.getAllElements(root3, root4))
root3 = sol.buildTree([0,-10, 10], 0, None)
root4 = sol.buildTree([], 0, None)
print(sol.getAllElements(root3, root4))
root3 = sol.buildTree([1, None, 8], 0, None)
root4 = sol.buildTree([8, 1], 0, None)
print(sol.getAllElements(root3, root4))
#print(treeNode1.val)
#print(treeNode1.right.val)
#print(treeNode1.left.left.val)
# print(sol.inorderTraversal(root1, []))
# print(sol.inorderTraversal(root2, []))
# print(sol.inorderTraversal(root3, []))
|
43ae7f2eb5524133e9505ab2a7f37eab701c15c8 | fmxFranky/deep_rl_codebase | /deep_rl_codebase/single_process/utils.py | 1,430 | 3.671875 | 4 | import time
import numpy as np
class WindowStat(object):
""" Tool to maintain statistical data in a window.
"""
def __init__(self, window_size):
self.items = [None] * window_size
self.idx = 0
self.count = 0
def add(self, obj):
self.items[self.idx] = obj
self.idx += 1
self.count += 1
self.idx %= len(self.items)
@property
def mean(self):
if self.count > 0:
return np.mean(self.items[:self.count])
else:
return None
@property
def min(self):
if self.count > 0:
return np.min(self.items[:self.count])
else:
return None
@property
def max(self):
if self.count > 0:
return np.max(self.items[:self.count])
else:
return None
class TimeStat(object):
"""A time stat for logging the elapsed time of code running
Example:
time_stat = TimeStat()
with time_stat:
// some code
print(time_stat.mean)
"""
def __init__(self, window_size=1):
self.time_samples = WindowStat(window_size)
self._start_time = None
def __enter__(self):
self._start_time = time.time()
def __exit__(self, type, value, tb):
time_delta = time.time() - self._start_time
self.time_samples.add(time_delta)
@property
def mean(self):
return self.time_samples.mean
@property
def min(self):
return self.time_samples.min
@property
def max(self):
return self.time_samples.max
|
bce57991ca0c7745e428597eb55f96b80535c28d | billgoo/LeetCode_Solution | /Related Topics/Tree/Traversal/99. Recover Binary Search Tree.py | 1,550 | 3.75 | 4 | # 99. Recover Binary Search Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.max_node, self.min_node = None, None
# prev and curr are the node in order of inorder traversal
# so, prev < curr
self.prev, self.curr = None, None
self.inorder_traverse(root)
self.swap(self.max_node, self.min_node)
def swap(self, first: Optional[TreeNode], second: Optional[TreeNode]) -> None:
first.val, second.val = second.val, first.val
def inorder_traverse(self, root: Optional[TreeNode]) -> None:
if not root:
return
# left
self.inorder_traverse(root.left)
# inorder for root
self.prev, self.curr = self.curr, root
# if we find one of the reverse order pair
if self.prev and self.curr and self.prev.val > self.curr.val:
# check if we have find the max node for root
# if find max value, just update the min value else both value
if not self.max_node:
# no max value
self.max_node = self.prev
self.min_node = self.curr
# right
self.inorder_traverse(root.right) |
ceeac5dbfa948d9e5fd7f8969ff8a21adec7b5dc | soraerae/python-challenge | /PyPoll/main.py | 2,250 | 3.921875 | 4 | # import csv file
import os
import csv
election_csv = os.path.join('.', 'election_data.csv')
# open csv file
with open(election_csv, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# skip header row
csvheader = next(csvreader)
# create variables and set to zero, create list for candidates and dictionary for candidates & votes
ttl_votes = 0
candidates = []
candidate_votes = {}
winning_votes = 0
# iterate over rows to find total number of votes
for row in csvreader:
ttl_votes = ttl_votes + 1
candidate = row[2]
# add candidates into candidate list if not already there, and set vote count to zero
if candidate not in candidates:
candidates.append(candidate)
candidate_votes[candidate] = 0
# add row's vote to candidate vote counter
candidate_votes[candidate] = candidate_votes[candidate] + 1
# get total votes for each candidate
for candidate, votes in candidate_votes.items():
votes = candidate_votes.get(candidate)
# find winning number of votes and corresponding candidate
if votes > winning_votes:
winning_votes = votes
winning_candidate = candidate
# print election results
print("Election Results\n------------------------")
print(f"Total Votes : {str(ttl_votes)}")
print("------------------------")
for candidate, votes in candidate_votes.items():
print(f"{candidate} : {round(votes / ttl_votes * 100, 2)}% ({votes})")
print("------------------------")
print(f"Winner : {winning_candidate}")
print("------------------------")
# output to text file
text_file = open("polling_summary.txt", "w")
text_file.write("Election Results\n")
text_file.write("------------------------\n")
text_file.write(f"Total Votes : {str(ttl_votes)}\n")
text_file.write("------------------------\n")
for candidate, votes in candidate_votes.items():
text_file.write(f"{candidate} : {round(votes / ttl_votes * 100, 2)}% ({votes})\n")
text_file.write("------------------------\n")
text_file.write(f"Winner : {winning_candidate}\n")
text_file.write("------------------------\n")
text_file.close()
|
72c406b5faa957e628a27e9560f0824d415dc96f | essanhaji/python-3-tp | /exo/trening/loopsFor.py | 223 | 3.90625 | 4 | numbers = [10, 23, 13, 5, 87, 21]
print(10 in numbers)
for index in range(len(numbers)):
# print(index)
# print(str(index) + " = ", numbers[index])
print("the index {:d} = {:d}".format(index, numbers[index]))
|
848736eaebbf10dd09bfd92bf325cfbd65e5ddc1 | wangrui0/python-base | /com/day06/demo06_packet_disassembly.py | 166 | 4.125 | 4 | # 拆包是针对元组
tuple = (1, 2)
# 输出方式一:
print(tuple[0])
print(tuple[1])
# 输出方式二:拆包
a, b = tuple
print(a)
print(b)
'''
1
2
1
2
'''
|
1d269a675804c839c77e132846fbea0445708042 | EduardoGarciaBautista/py-basics | /number_game.py | 447 | 3.859375 | 4 | import random
def run():
random_number = random.randint(1, 100)
message = 'Type a number between 1 and 100: '
user_number = int(input(message))
while user_number != random_number:
if user_number < random_number:
message = 'Type a high number: '
else:
message = 'Type a low number: '
user_number = int(input(message))
print('!You win¡')
if __name__ == '__main__':
run()
|
1d1d500a6d23219c72370db07f532e51f809c4f7 | tasfia-makeschool/SPD-2.31-Testing-and-Architecture | /lab/refactoring-pep8/docstrings_blank_lines.py | 4,262 | 3.71875 | 4 | # by Kami Bigdely
# Docstrings and blank lines
class OnBoardTemperatureSensor:
"""
This is a class for the onboard temperature sensor.
Attributes: None
"""
VOLTAGE_TO_TEMP_FACTOR = 5.6
def __init__(self):
"""
Constructor for OnboardTemperatureSensor.
Parameters: None
"""
pass
def read_voltage(self):
"""
Read voltage from onboard temperature sensor.
Returns:
float: The voltage.
"""
return 2.7
def get_temperature(self):
"""
Calculate the temperature from voltage.
Returns:
int: The temperature in celcius.
"""
return self.read_voltage() \
* OnBoardTemperatureSensor.VOLTAGE_TO_TEMP_FACTOR # [celcius]
class CarbonMonoxideSensor:
"""
This is a class for the carbon monoxide sensor.
Attributes:
on_board_temp_sensor (int): The onboard temperature.
carbon_monoxide (float): The carbon monoxide level.
"""
VOLTAGE_TO_CO_FACTOR = 0.048
def __init__(self, temperature_sensor):
"""
The constructor for the CarbonMonoxideSensor class.
If argument "temperature_sensor" is not defined, then create a new
OnBoardTemperatureSensor object.
Args:
temperature_sensor (float): The onboard temperature.
"""
self.on_board_temp_sensor = temperature_sensor
if not self.on_board_temp_sensor:
self.on_board_temp_sensor = OnBoardTemperatureSensor()
def get_carbon_monoxide_level(self):
"""
Get the carbon monoxide level and save it as an attribute.
Returns:
float: The carbon monoxide level.
"""
sensor_voltage = self.read_sensor_voltage()
self.carbon_monoxide = \
CarbonMonoxideSensor.convert_voltage_to_carbon_monoxide_level(
sensor_voltage, self.on_board_temp_sensor.get_temperature()
)
return self.carbon_monoxide
def read_sensor_voltage(self):
"""
Read the sensor voltage.
In real life, it should read from hardware.
Returns:
float: The sensor voltage.
"""
return 2.3
def convert_voltage_to_carbon_monoxide_level(self, voltage, temperature):
"""
Convert the voltage to carbon monoxide level.
Args:
voltage (float): The voltage.
temperature (float): The temperature.
Returns:
float: The carbon monoxide level.
"""
return voltage * CarbonMonoxideSensor.VOLTAGE_TO_CO_FACTOR \
* temperature
class DisplayUnit:
"""
This is a class to display messages.
Attributes:
string (str): Unknown.
"""
def __init__(self):
"""The constructor for the DisplayUnit class."""
self.string = ''
def display(self, msg):
"""
Print a message to the console.
Args:
msg (str): Message to be displayed.
Returns: None
"""
print(msg)
class CarbonMonoxideDevice():
"""
This is a class for the carbon monoxide device.
Attributes:
co_sensor (CarbonMonoxideSensor): The carbon monoxide sensor.
display_unit (DisplayUnit): The display unit.
"""
def __init__(self, co_sensor, display_unit):
"""
The constructor for the CarbonMonoxideDevice class.
Args:
co_sensor (CarbonMonoxideSensor): The carbon monoxide sensor.
display_unit (DisplayUnit): The display unit.
"""
self.carbonMonoxideSensor = co_sensor
self.display_unit = display_unit
def Display(self):
"""
Create a message that displays the carbon monoxide level.
Return: None
"""
msg = 'Carbon Monoxide Level is : ' \
+ str(self.carbonMonoxideSensor.get_carbon_monoxide_level())
self.display_unit.display(msg)
if __name__ == "__main__":
temp_sensor = OnBoardTemperatureSensor()
co_sensor = CarbonMonoxideSensor(temp_sensor)
display_unit = DisplayUnit()
co_device = CarbonMonoxideDevice(co_sensor, display_unit)
co_device.Display()
|
7f0b2705c2ff4d93e4be8927c220cd96acd3ed4d | dayf0rdie1999/Chemistry_Project | /Testing_Numpy.py | 948 | 3.59375 | 4 | import numpy as np
import sympy as sp
def main():
'''a,b,c,d = sp.symbols('a,b,c,d')
A = np.array([[3*a, 0*b, -1*c], [8*a, 0*b, 0*c], [0*a, 2*b, -2*c]])
b = np.array([0*d, -2*d, -1*d])
x = np.linalg.solve(A, b)
print(x)'''
letter = sp.symbols('a,b,c,d')
eq1 = sp.Eq(1*letter[0] - 1*letter[2], 0)
eq2 = sp.Eq(1*letter[0] - 2*letter[3], 0)
eq3 = sp.Eq(2*letter[1] - 1*letter[2],0)
equation_list = [1*letter[0] - 1*letter[2],1*letter[0] - 2*letter[3],2*letter[1] - 1*letter[2]];
system_equation = [];
for equation in equation_list:
system_equation.append(sp.Eq(equation,0));
solv = sp.solve(system_equation,[letter[0],letter[1],letter[2],letter[3]]);
#solv =sp.solve([eq1, eq2, eq3],[letter[0],letter[1],letter[2],letter[3]])
print(solv)
b = solv.get(letter[1]);
b = str(letter[1]);
for element in b:
print(element)
if __name__ == "__main__":
main() |
296e89f93f80b101088a1e3e89b2d889eb50fa05 | vinceajcs/all-things-python | /algorithms/graph/bfs/valid_tree.py | 1,342 | 4.15625 | 4 | """Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
Assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
A tree is connected, acyclic, and contains n-1 edges, where n is the number of nodes.
We can use BFS to check if there's a cycle and only one connected component in the graph.
Time: O(m+n)
Space: O(m+n)
"""
def valid_tree(n, edges):
lookup = {i: set() for i in range(n)} # n nodes from 0 to n-1
# create graph
for x, y in edges:
lookup[x].add(y)
lookup[y].add(x)
visited = set()
queue = collections.deque([list(lookup.keys())[0]])
while queue:
node = queue.popleft()
if node in visited: # cycle
return False
visited.add(node)
for neighbour in lookup[node]:
queue.append(neighbour)
lookup[neighbour].remove(node)
lookup.pop(node)
return not lookup # if there are any nodes left, that means there is more than one connected component
|
0563e9fe907bea828235a25f872b0f14ba7313c0 | dmitra100/dmitra100.github.io | /find_avg_num.py | 382 | 4.25 | 4 | #!/usr/bin/env python
total_sum= 0
num = input("Enter required no of inputs to find the sum: ")
elapsed_input = num - 1
for i in range(num):
s = float(input("Enter a num for addition: "))
total_sum = total_sum + s
e = elapsed_input - i #No of values yet to be entered
print "Num of inputs pending", e
avg = total_sum/num
print 'Avg of all the numbers: ', avg
|
8c8b1047df946dd698ab850c86754dc8c9c75452 | lunatic-7/python_course_noob-git- | /exercise_3.1.py | 905 | 4.125 | 4 | # EXERCISE NUMBER GUESSING GAME.
import random # to run random function. 1st we have to import random func.
winning_no = random.randint(1, 10) # this func. is use to bring any random no.
guess = 1
number = int(input("guess a no. b/w 1 to 10 :"))
game_over = False
while not game_over:
if number == winning_no:
print(f"you win, and you guessed the no. in {guess} times.")
game_over = True
else:
if number < winning_no:
print("too low!")
guess += 1
number = int(input("guess again : "))
else:
print("too high!")
guess += 1
number = input("guess again : ")
# number == winning_no:
# print(winning_no)
# print("YOU WIN!!!!")
# else: # this condition is called nested if else.
# if number < winning_no:
# print("too low!")
# else:
# print("too high!") |
cf5e1e9fc35bbce784f1f686ca4f2becdcee1054 | cutz-j/TodayILearned | /MLP/lec9-1.py | 842 | 3.640625 | 4 | class MulLayer:
def __init__(self):
self.x = None
self.y = None
def foward(self, x, y):
self.x = x
self.y = y
out = x * y
return out
def backward(self, dout):
dx = dout * self.y
dy = dout * self.x
return dx, dy
class AddLayer(MulLayer):
def __init__(self):
pass
def fowrard(self, x, y):
out = x + y
return out
apple = 100
apple_num = 2
tax = 1.1
mul_apple_layer = MulLayer()
mul_tax_layer = MulLayer()
# 순전파 #
apple_price = mul_apple_layer.foward(apple, apple_num)
price = mul_tax_layer.foward(apple_price, tax)
dprice = 1
dapple_price, dtax = mul_tax_layer.backward(dprice)
daaple, dapple_num = mul_apple_layer.backward(dapple_price)
print(price)
print(daaple)
print(dapple_num)
print(dtax) |
88a2382c12bc3eb031d48cb8134d5419ab5551cd | makakris/Hacker_rank-sols | /Anagram_queue.py | 520 | 3.984375 | 4 | class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
self.queue.insert(0,dataval)
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
def revq(self):
return "".join(self.queue)
TheQueue = Queue()
s1= "pop"
s2="psp"
for i in s1:
TheQueue.addtoq(i)
if s2==TheQueue.revq():
print("Anagram")
else:
print("Not Anagram") |
03f17fb7659944397c5229fd9f94ac201fe05400 | fhmurakami/Python-CursoemVideo | /Exercicios/Mundo 02 - Estruturas de Controle/Aula 13 - Estruturas de repetição for/ex046.py | 294 | 3.53125 | 4 | # Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artifício, indo de 10 até 0,
# com uma pausa de 1 segundo entre eles.
from time import sleep
for c in range(10, 0, -1):
print('{}!!!'.format(c))
sleep(1)
print('Pew! Pew! Pew! Booom!') |
5a6790abad9b2754707d81d4e91bea6c7ebc6d4f | cdsl-research/bootcamp | /bootcamp/tuple_list.py | 268 | 3.984375 | 4 | tuple1=(1,2,3,4,5)
tuple2 = tuple1+(6,7,8,9,10)
print(tuple2)
print(tuple2[0:5])
list1=[1,2,3,4,5]
list1.append(6)
list1.append(5)
print(list1)
print(list1.index(5))
print(list1.count(5))
list2=list1
list2.remove(6)
print(list2)
print(list2.pop(0))
print(list2)
|
8ab547ef2e1a016d5b9d98623386a1dbad5620f9 | ConPagnon/conpagnon | /conpagnon/utils/pre_preprocessing.py | 5,009 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 6 17:04:32 2017
@author: db242421 (dhaif.bekha@cea.fr)
Useful pre-processing step before doing statistical test.
"""
from nilearn.connectome import sym_matrix_to_vec, vec_to_sym_matrix
import numpy as np
def fisher_transform(symmetric_array):
"""Return the Fisher transform of all coefficient in a symmetric array.
Parameters
----------
symmetric_array : numpy.ndarray, shape(..., number of regions, numbers of regions)
A symmetric numpy array, typically correlation, or partial correlation
subject connectivity matrices.
Returns
-------
output : numpy.ndarray, shape(..., number of regions, numbers of regions)
The fisher transform of the ndimensional array.
Notes
-----
The fisher transform is classically computed according to the
formula :
.. math::
z = arctanh(r)
For **r = 1**, the Fisher transform is not defined, typically on the diagonal
of connectivity matrices. Then we fill diagonal value with np.nan values.
"""
# Discarding diagonal which is one for correlation, and partial correlation, not defined in Z-Fisher transformation
vectorize_array = sym_matrix_to_vec(symmetric = symmetric_array, discard_diagonal=False)
# Apply Fisher transform, i.e the bijection of hyperbolic tangent:
fisher_vectorize_array = np.arctanh(vectorize_array)
# Reconstruct the symmetric matrix:
fisher_transform_array = vec_to_sym_matrix(vec = fisher_vectorize_array, diagonal=None)
# Number of dimension of fisher transform array
fisher_array_ndim = fisher_transform_array.ndim
# if ndim = 2, put NaN in the diagonal:
if fisher_array_ndim == 2:
np.fill_diagonal(a = fisher_transform_array, val = np.nan)
# if ndim > 2, we consider fisher_transform_array as ndimensional array with shape (..., n_features, n_features),
# we put nan in the diagonal of each array, along the first dimension
elif fisher_array_ndim > 2:
for i in range(fisher_transform_array.shape[0]):
np.fill_diagonal(a = fisher_transform_array[i,:,:], val = np.nan)
return fisher_transform_array
def stacked_connectivity_matrices(subjects_connectivity_matrices, kinds):
"""Stacked the connectivity matrices for each group and for each kinds.
If a masked array exist, i.e a 'masked_array' key in each subjects dictionnary, we
stacked them too.
Parameters
----------
subjects_connectivity_matrices : dict
A multi-levels dictionnary organised as follow :
- The first keys levels is the different groupes in the study.
- The second keys levels is the subjects IDs
- The third levels is the different kind matrices
for each subjects, a 'discarded_rois' key for the
discarded rois array index, a 'masked_array' key containing
the array of Boolean of True for the discarded_rois index, and False
elsewhere.
kinds : list
List of kinds you are interrested in.
Returns
-------
ouput : dict
A dictionnary with two keys : kinds and masked_array. The values
is respectively the stacked matrices for one kind in a ndimensional
array of shape (..., numbers of regions, numbers of regions), and the
ndimensional boolean mask array of the same shape (..., numbers of regions,
numbers of regions).
"""
#Dictionnary which will contain the stack of connectivity matrices for each groups and kinds.
stacked_connectivity_dictionnary = dict.fromkeys(subjects_connectivity_matrices)
for groupe in subjects_connectivity_matrices.keys():
#Dictionnary initialisation with all kinds as entry
stacked_connectivity_dictionnary[groupe] = dict.fromkeys(kinds)
#subjects list for the groupe
subjects_list = subjects_connectivity_matrices[groupe].keys()
for kind in kinds:
#We stack the matrices for the current kind
kind_groupe_stacked_matrices = [subjects_connectivity_matrices[groupe][subject][kind] for subject in subjects_list]
#We detect if the keys named 'masked_array' existe to create a numpy masked array strucutre.
kind_masked_array = [ subjects_connectivity_matrices[groupe][subject]['masked_array'] for subject in subjects_list if 'masked_array' in subjects_connectivity_matrices[groupe][subject].keys() ]
#We fill a dictionnary with kind connectivity as keys, and stacked connectivity matrices, with masked array if they exist as values
stacked_connectivity_dictionnary[groupe][kind] = np.array(kind_groupe_stacked_matrices)
stacked_connectivity_dictionnary[groupe]['masked_array'] = np.array(kind_masked_array)
return stacked_connectivity_dictionnary
|
ebdb0f8a1d2b401fd301dc71f20ed08638f96fdf | jpmarinm/CX_challenges | /Weekly_Challenge_Week04_jomarinm.py | 3,001 | 4.21875 | 4 | tasksList = []
print("Let's add all the tasks you need to do before your trip:")
print("After done with all task enter an X to exit")
def tasks():
exit1=''
while exit1 != 'X':
task = input('Enter Task >>> ')
task = task.capitalize()
if task == 'X' or task == 'x':
exit1 = task
elif task != 'X' or 'x':
tasksList.append(task)
return(tasksList)
def reviewTasks():
review = input('Want to review your taks... Enter Y for yes, N for No >>> ')
review = review.capitalize()
if review == 'Y':
for t in range(len(tasksList)):
print('Task',t+1,': ',tasksList[t])
def addNewTasK():
exit2 = True
while exit2:
addTask = input('Need to add a new task... Enter Y for yes, N for No >>> ')
addTask = addTask.capitalize()
if addTask == 'N':
exit2 = False
elif addTask == 'Y':
position = int(input('In which position you will enter the new task (Enter a number from 1 to {} >>> '.format(len(tasksList)+1)))
newTask = input('Enter new Task >>> ')
tasksList.insert(position-1,newTask)
return(tasksList)
def completedTasks():
exit3 = True
while exit3:
taskCompleted = input('Have completed any task... Enter Y for yes, N for No >>> ')
taskCompleted = taskCompleted.capitalize()
if taskCompleted == 'N':
exit3 = False
elif taskCompleted == 'Y':
position = int(input('Which task has been completed (Enter a number from 1 to {} >>> '.format(len(tasksList))))
tasksList.remove(tasksList[position-1])
tasks()
reviewTasks()
addNewTasK()
reviewTasks()
completedTasks()
reviewTasks()
print('let\'s keep save your party\'s passport information:')
passportInfo = {}
partyNum = int(input('How many members in your party >>> '))
for n in range(partyNum):
passportName = input('Enter name in passport >>> ')
passportNum = input('Enter number in passport >>> ')
passportInfo[passportName]=passportNum
print('Displaying passport information')
print('Party Members',partyNum)
for name in passportInfo:
print('Passport Name:',name,'Passport number:',passportInfo[name])
countriesVisited = set()
numCountries = int(input('How many countries have you visited >>> '))
for c in range(numCountries):
country = input('Add country {}: '.format(c+1))
country = country.capitalize()
countriesVisited.add(country)
#print(countriesVisited)
friendsCountry = set()
numCountriesF = int(input('How many countries have your friend visited >>> '))
for c in range(numCountriesF):
countryF = input('Add country {}: '.format(c+1))
countryF = countryF.capitalize()
friendsCountry.add(countryF)
#print(friendsCountry)
MissingCountries = friendsCountry.difference(countriesVisited)
print('The countries you have not visited, that your friend have visited are:')
for country in MissingCountries:
print(country,end=' ')
|
8823b05a096e28c4b1017fefa421aaa89961c938 | JasonOnes/LaunchCode | /eng2pir.py | 1,891 | 4.0625 | 4 | from test import testEqual
def translate(text):
eng2pir = { "sir" : "matey",
"hotel" : "fleabag inn",
"student" : "swabbie",
"boy" : "matey",
"madam" : "proud beauty",
"professor" : "foul blaggart",
"restaurant" : "galley",
"your" : "yer",
"excuse" : "arr",
"students" : "swabbies",
"are" : "be",
"lawyer" : "foul blaggart",
"the" : "th’",
"restroom" : "head",
"my" : "me",
"hello" : "avast",
"is" : "be",
"man" : "matey"}
text = text.split()
pirate_speak = ""
for word in text:
if not word[-1].isalpha():
pirate_speak += eng2pir.get(word[:-1], word) + word[-1]+ " "
else:
pirate_speak += eng2pir.get(word, word) + " "
pirate_speak = pirate_speak[:-1]
#print(pirate_speak)
return pirate_speak
text = "hello my man, please excuse your professor to the restroom!"
testEqual(translate(text), "avast me matey, please arr yer foul blaggart to th' head!")
#print(translate("Get theee out of this restaurant dumb students"))
print(len(translate("hello my man, please excuse your professor to the restroom!")))
print(len(translate(text)))
print(len("avast me matey, please arr yer foul blaggart to th' head!"))
print(type(translate(text)))
print(type("avast me matey, please arr yer foul blaggart to th' head!"))
a = list("avast me matey, please arr yer foul blaggart to th' head!")
b = list(translate(text))
x = [i for i in a if i not in b]
y = [i for i in b if i not in a]
print(x)
print(y)
print(translate(text))
print(translate(text).find("'"))
print("avast me matey, please arr yer foul blaggart to th' head!")
print("avast me matey, please arr yer foul blaggart to th' head!".find("'"))
print(ord(b[50]))
print(ord(a[50])) |
d017f076b12a044eee0720a1e10e457607548c44 | wsjhk/Python_Advance | /Python_Advance/chapter12/yield_from_test.py | 1,886 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/12/14 20:50
# @Author : huangjie
# @File : yield_from_test.py
# python3.3新加了yield from语法
from itertools import chain
my_list = [1, 2, 3]
my_dict = {
"tom": "http://www.baidu.com",
"tom1": "http://www.qq.com",
}
# yield from iterable
# def g1(iterable):
# yield iterable
#
# def g2(iterable):
# yield from iterable
#
# for value in g1(range(10)):
# print(value)
#
# for value in g2(range(10)):
# print(value)
def my_chain(*args, **kwargs):
for my_iterable in args:
yield from my_iterable
# for value in my_iterable:
# yield value
for value in my_chain(my_list, my_dict, range(5, 10)):
print(value)
# 1.main 调用方g1(委托生成器) gen 子生成器
# 2. yield from 会在调用方与子生成器之间建立一个双向通道
final_result = {}
def sales_sum(pro_name):
total = 0
nums = []
while True:
x = yield
print(pro_name + "销量:", x)
if not x:
break
total += x
nums.append(x)
return total, nums
def middle(key):
while True:
final_result[key] = yield from sales_sum(key) # yield from 建立了sales_num和main的双向通道
print(key + "销量统计完成!!!")
def main():
data_sets = {
"tom牌面膜": [1200, 1500, 3000],
"tom牌手机": [28, 55, 98, 108],
"tom牌大衣": [280, 560, 778, 70],
}
for key, data_set in data_sets.items():
print("start key:", key)
m = middle(key)
m.send(None) # 预激middle协程
for value in data_set:
m.send(value) # 给协程传递每一组值
m.send(None)
print("final_result:", final_result)
if __name__ == "__main__":
main()
|
3d7a7a98b4e9e5e6d10961018cdc3f7422a665ec | ablondal/comp-prog | /Practice/String_Matching/Dom_Pat_Test_Case.py | 293 | 3.609375 | 4 | print(150)
for i in range(150):
print(chr(ord('a')+i%26)*35 + chr(ord('a')+i//26)*35)
print('c'*int(5e5)+'b'*int(5e5))
# print(150)
# for i in range(150):
# print(chr(i%26)*35 + chr(i//10)*35)
# print('b'*int(1e6))
# for i in range(150):
# print(chr(i%26)*70)
# print('c'*int(1e6))
print(0) |
c558d10dc5c4805b27fad965c90f54e033813765 | elenatheresa/CSCI-160 | /listex.py | 300 | 3.90625 | 4 | #declaration for a list
values = []
values.append(10)
values.append(8)
values.append(7)
values.append(9)
values.append(6)
values.insert(0,3)
print(values)
print("first value",values[0])
print("last value",values[-1])
print('values/n')
for index in range(0, len(values)):
print(values[index])
|
aba15a3dca90b3eac80009e6f75bbec1228828fb | FazleRabbbiferdaus172/Codeforces_Atcoder_Lightoj_Spoj | /hackerrank_Array_Manipulation.py | 1,298 | 3.59375 | 4 | import math
import os
import random
import re
import sys
#
# Complete the 'arrayManipulation' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
# 1. INTEGER n
# 2. 2D_INTEGER_ARRAY queries
#
def arrayManipulation(n, queries):
# Write your code here
arr = [0]*n
print("len", len(arr))
for q in queries:
i, j, k = map(int, q)
# print(i-1,j-1,k)
#print("test", arr[i-1], arr[j-1], arr[j-1] - k)
arr[i-1] += k
if j < n:
arr[j] -= k
add = 0
mx = -1
for i in range(n):
arr[i] += add
add = arr[i]
if mx < arr[i]:
mx = arr[i]
#test_arr = [0]*n
# for q in queries:
# i,j,k = map(int, q)
# for x in range(i-1,j):
# test_arr[x] += k
# print(*arr)
# print(*test_arr)
return mx
if __name__ == '__main__':
fptr = open('output.txt', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)
fptr.write(str(result) + '\n')
fptr.close()
|
1b5ed1f947ad2ffd7a7f6d5f063747bdaa79441f | kevbradwick/algorithms | /algorithms/union_find.py | 1,731 | 4.625 | 5 | from typing import List
class UnionFind:
"""
Union-Find data structure.
This data structure is used to find connected components in a graph. An example can be
checking if two people are connected in a social network. It works by representing the
graph as a tree. Each node in the tree is a connected component. Two nodes are deemed
connected if they have the same root. The root of a node is the node that is not a
child of any other node.
For example;
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -> has no connections
[0, 3, 2, 3, 4, 5, 6, 7, 8, 9] -> 1 and 3 are connected
[0, 3, 2, 7, 4, 5, 6, 7, 8, 9] -> 1, 3 and 7 are connected
Tests for this data structure can be found in tests/test_union_find.py
"""
def __init__(self, size: int) -> None:
"""
Initialize a UnionFind data structure with size elements.
"""
# the index is initialized with the id of each element
self.index: List[int] = list(range(size))
def union(self, a: int, b: int) -> None:
"""
Union two elements.
This will make (a) a child of (b). The structure then represents a tree.
"""
self.index[a] = self.index[b]
def root(self, a: int) -> int:
"""
Find the root of an element.
"""
node = a
node_id = self.index[node]
while node != node_id:
node = node_id
node_id = self.index[node]
return node
def connected(self, a: int, b: int) -> bool:
"""
Check if two elements are connected.
Given that the index is a tree, we will need to follow the tree to the root.
"""
return self.root(a) == self.root(b)
|
d7bf2e2619a70f446b867f3260e1d046fce71e60 | johnjoonhwan/Python-Programs | /OddOrEven.py | 825 | 4.375 | 4 |
def oddOrEven():
'''
prompts user for an integer
determines whether integer is odd or even, and outputs appropriate response
'''
# method 1: assume user enters an int. Otherwise throw exception.
# num = int(input("Enter a number: "))
# method 2: does not assume type. Repeatedly queries user for valid arg if
# not supplied.
# additional specification: print a different message if divisible by 4
num = input("Enter an integer: ")
# raw_input accepts input as string. input reads as expression
while type(num) != int:
num = input("Please enter a valid integer")
if num % 4 == 0:
print "fun fact - %d is divisible by 4!" % num
if num % 2 == 0:
print "%d is an even number." % num
else:
print "%d is an odd number." % num
|
601c6eaadb4457e5ac94819bf93bc8744f9858f7 | doddydad/python-for-the-absolute-beginner-3rd-ed | /Chapter 7/Read it.py | 1,118 | 4.1875 | 4 | #Read it
# shows extracting from files
print("Opening and closing the file")
text_file = open("read it.txt", "r")
text_file.close()
print("\nReading characters from a file\n")
text_file = open("read it.txt", "r")
print(text_file.read(1))
print(text_file.read(5))
text_file.close()
print("\nReading entire file at once")
text_file = open("read it.txt", "r")
print(text_file.read())
text_file.close()
#if this finishes a line, next command will go to next line
print("\nReading characters from a line")
text_file = open("read it.txt", "r")
print(text_file.readline(1))
print(text_file.readline(5))
text_file.close()
print("\nReading one line at a time")
text_file = open("read it.txt", "r")
print(text_file.readline())
print(text_file.readline())
print(text_file.readline())
text_file.close()
print("\nSome shit with lists")
text_file = open("read it.txt", "r")
lines = text_file.readlines()
print(lines)
print(len(lines))
for line in lines:
print(line)
text_file.close()
print("\nLoops I guess")
text_file = open("read it.txt", "r")
for line in text_file:
print(line)
text_file.close()
input()
|
9ad34d9ab6113207454790d6370f23427fd28112 | rcaracheo/codemotion_scraping_the_web | /BeautifulSoup/google_translate.py | 1,098 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
import sys
#Example input to enter : en (= english)
convert_from = raw_input("Language to Convert from : ")
#Example input to enter : hi (= hindi), fr (= french), de (= German)
convert_to = raw_input("Language to Convert to : ")
#Example input to enter : Hello World
text_to_convert = raw_input("Text to Convert : ")
#A url cannot have spaces as parameters, so we replace all the spaces with '+'
text_to_convert = text_to_convert.replace(' ', '+')
#Passing the parameters to service
url = 'http://translate.google.com/?sl=%s&tl=%s&text=%s' % (convert_from, convert_to, text_to_convert)
#Get the content
data = requests.get(url).content
#For unicode support use this.
soup = BeautifulSoup(data, "lxml")
#Getting the result which is in div gt-res-content and inside that its in span result_box's text. Use Firebug to check this.
div_content = soup.find('div', {'id' : 'gt-res-content'})
converted_text = div_content.find('span', {'id':'result_box'}).text
print "Converted Text : " + converted_text
|
a54cf186deccad46a22147e12645cf1bafd7ec7c | FelixLC/lifenet | /lifenet/train.py | 1,267 | 3.953125 | 4 | """
Here's a function that can train a neural net
"""
from lifenet.data import BatchIterator
from lifenet.loss import MSE, Loss
from lifenet.nn import NeuralNet
from lifenet.optim import SGD, Optimizer
from lifenet.tensor import Tensor
def train(net: NeuralNet,
inputs: Tensor,
targets: Tensor,
num_epochs: int = 5000,
iterator: BatchIterator = BatchIterator(),
loss: Loss = MSE(),
optimizer: Optimizer = SGD()) -> None:
"""
A training function is just n loop on our data with:
- prediction step
- loss calculation
- gradient backpropagation
- parameter update
Each loop, called an epoch means that our net has seen our entire dataset.
We usually loop many times over the data to let the model learn the right amount
of knowledge.
"""
for epoch in range(num_epochs):
epoch_loss = 0.0
for batch in iterator(inputs, targets):
predicted = net.forward(batch.inputs)
epoch_loss += loss.loss(predicted, batch.targets)
grad = loss.grad(predicted, batch.targets)
net.backward(grad)
optimizer.step(net)
if epoch % 10 == 0:
print(f"Epoch {epoch} - Loss {epoch_loss}")
|
c8544b3de1eb0f9641af143b52a2bee4568fe42d | Dbl4/hw-geekbrains | /Основы python/homework_free.py | 2,739 | 4.0625 | 4 | #1
def func(arg_1, arg_2):
try:
return arg_1 // arg_2
except ZeroDivisionError:
return 'Деление на 0'
except Exception:
return 'Неизвестная ошибка'
number_one = int(input('Введите первое число: '))
number_two = int(input('Введите второе число: '))
print(func(number_one, number_two))
#2
def my_person(name, first_name, year, city, email, phone):
print(name, first_name, year, city, email, phone)
my_person( name = input('введите имя: '), first_name = input('введите фамилию: '), year = input('введите год рождения: '), city = input('введите город: '), email = input('введите email: '), phone = input('введите телефон: '))
# 3
def my_func(arg_1, arg_2, arg_3):
result = [arg_1 + arg_2, arg_1 + arg_3, arg_2 + arg_3]
return max(result)
number_one = int(input('Введите первое число: '))
number_two = int(input('Введите второе число: '))
number_three = int(input('Введите третье число: '))
print(my_func(number_one, number_two, number_three))
#4
#4.1
def my_func(x,y):
return float(x ** y)
number_one = float(input('Введите целое положительное число: '))
number_two = int(input('Введите целое отрицательное число: '))
print(my_func(number_one, number_two))
#4.2
def my_func(x,y):
while y < 0:
y += 1
return 1 / x
number_one = float(input('Введите целое положительное число: '))
number_two = int(input('Введите целое отрицательное число: '))
print(my_func(number_one, number_two))
#5
def my_func():
sum_numbers = 0
while True:
numbers = input('Введите числа через пробел: ').split()
if numbers != ['*']:
if '*' in numbers:
symvol = numbers.index('*')
for i in range(symvol):
numbers[i] = int(numbers[i])
sum_numbers += int(numbers[i])
print(f'Сумма: {sum_numbers}')
print('Конец программы')
break
else:
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
sum_numbers += sum(numbers)
print(f'Сумма: {sum_numbers}')
else:
print('Конец программы')
break
try:
my_func()
except ValueError:
print('Вы ввели что-то не то')
#6
def int_func():
new_text = []
text = input('Введите строку: ').split()
for word in text:
word = word.capitalize()
new_text.append(word)
new_text = ' '.join(new_text)
return new_text
print(int_func()) |
3afdf21e784bc4474005670824d2f2e9df84eb31 | ThisseasX/PythonTest | /ClassExcercises/ArrowSolution.py | 926 | 3.796875 | 4 | def repeat_string(count, string):
result = ""
for i in range(count):
result += string
return result
def left_arrow(row, width):
if row < width:
stars = row + 1
else:
stars = width * 2 + 1 - row
return repeat_string(width + 1 - stars, " ") + repeat_string(stars, "*")
def right_arrow(row, width):
if row < width:
stars = row + 1
else:
stars = width * 2 + 1 - row
return repeat_string(stars, '*') + repeat_string(width + 1 - stars, " ")
def shaft(row, height, length):
if (row > height * 0.25) and (row < height * 0.75):
string = repeat_string(length, "*")
else:
string = repeat_string(length, " ")
return string
def arrow(width, length):
for row in range(width * 2 + 1):
print(left_arrow(row, width) +
shaft(row, width * 2, length) +
right_arrow(row, width))
arrow(11, 45)
|
075201492c9ed59a063600389faaf44048aaa95c | rajeshboda/practise | /collections/append_insert.py | 202 | 3.828125 | 4 | empty_list =[]
empty_list.append("1")
empty_list.append("2")
for it in empty_list:
print(it)
empty_list.insert(0,0)
empty_list.insert(15,43)
print(".......")
for it in empty_list:
print(it) |
977eb2f6dfcdfd3727c245c9483bb51fc747bf2a | hisyamuddin-jamirun/PythonConcepts | /operators.py | 3,635 | 4.71875 | 5 | # Python Operators
firstVariable = 35
secondVariable = 24
thirdVariable = 41
fourthVariable = 32
fifthVariable = 32
sixthVariable = 25
# Arithmetic Operators (used with numeric values to perform common mathematical operations)
print(firstVariable + secondVariable) # Addition Operator
print(firstVariable - secondVariable) # Subtraction Operator
print(firstVariable * secondVariable) # Multiplication Operator
print(firstVariable / secondVariable) # Division Operator
print(firstVariable % secondVariable) # Modulus Operator
print(
firstVariable // secondVariable) # Floor Division Operator(results in whole number adjusted to the left in the number line)
print(3 ** 2) # Exponent Operator (3 to the power 2)
print("**********************************************************")
# Assignment Operators (used to assign values to variables)
thirdVariable = fourthVariable
thirdVariable += 2
print(thirdVariable)
thirdVariable -= 4
print(thirdVariable)
thirdVariable *= 3
print(thirdVariable)
thirdVariable /= 2
print(thirdVariable)
thirdVariable %= 5
print(thirdVariable)
thirdVariable //= 3
print(thirdVariable)
thirdVariable **= 4
print(thirdVariable)
# Multiple assignment (The variables firstVariable and secondVariable simultaneously get the new values 2 and 3)
firstVariable, secondVariable = 2, 3
print(firstVariable)
print(secondVariable)
# We can switch variable values using multiple assignment
firstVariable, secondVariable = secondVariable, firstVariable
print(firstVariable)
print(secondVariable)
print("**********************************************************")
# Comparison Operators (used to compare two values)
print(fourthVariable == fifthVariable)
print(fifthVariable != sixthVariable)
print(sixthVariable > fifthVariable)
print(sixthVariable < fifthVariable)
print(sixthVariable >= fifthVariable)
print(sixthVariable <= fifthVariable)
print("**********************************************************")
# Logical Operators (and, or, not) (used to combine conditional statements)
print(firstVariable == 35 and secondVariable == 24)
print(firstVariable == 35 or secondVariable == 21)
print(not firstVariable == 14)
print("**********************************************************")
# Identity Operators (is, is not) (used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location)
print(fifthVariable is sixthVariable)
print(fifthVariable is not sixthVariable)
fifthVariable = sixthVariable
print(fifthVariable is sixthVariable)
print("**********************************************************")
# Membership Operators (in, not in) (used to test if a sequence is presented in an object)
mySampleString = "Hello John Doe"
print("Hello" in mySampleString)
print("ll" in mySampleString)
print("Sam" not in mySampleString)
print("John" not in mySampleString)
print("**********************************************************")
# Bitwise Operators (performs operations on numbers at the bit level)
print(firstVariable & secondVariable) # Sets each bit to 1 if both bits are 1
print(firstVariable | secondVariable) # Sets each bit to 1 if one of two bits is 1
print(firstVariable ^ secondVariable) # Sets each bit to 1 if only one of two bits is 1
print(~secondVariable) # Inverts all the bits
print(
firstVariable << secondVariable) # Shift left by pushing zeros in from the right and let the leftmost bits fall off
print(
firstVariable >> secondVariable) # Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
print("**********************************************************")
|
4521cab01ef960394391eba1599e7a366af212b4 | ColdMacaroni/mystery-calculator | /mystery_calculator.py | 5,088 | 4.375 | 4 | ##
# mystery_calculator.py
# Dago
# 2021-04-15
def generate_numbers(start, numbers, group=1, skip_amount=0):
"""
Generates numbers according to the parameters.
Starting number tells what the starting number of the sequence
will be
Numbers determines how many numbers it will have
Group is how many consecutive nums before there is a skip
skip amount is the numbers to skip between each group
numbers and group must > 0
"""
nums = []
base = start
# Handling in case the numbers arent perfectibly divisible
iterations = numbers // group
leftover = numbers % group
# In each iteration "group" numbers will be added to the list,
# So to get "numbers" numbers we need to divide them.
# The base at first is the start number, the actual num starts
# counting up from it.
# After each group is added, the skip amount is added to the base
# to create the difference between each group.
for actual_num in range(iterations):
for group_num in range(group):
nums.append(base + actual_num + group_num)
base += skip_amount
# Check if it has been assigned
# This is a safety measure because in rare cases (e.g. start = 0,
# numbers = 1) the previous loop will be skipped, leaving
# actual_num unnassigned
if 'actual_num' not in locals():
actual_num = start
# This is basically the same loop that is nested in the previous
# one except with leftover < group
for leftover_num in range(leftover):
nums.append(base + actual_num + leftover)
return nums
def mystery_numbers():
"""
Returns the numbers necessary to get the mystery calculator to work
"""
# The patterns necessary to generate the numbers
# Format:
# - start
# - numbers needed
# - step
# - skip after this many numbers (default = 1)
# - amount to skip (default = 0))
patterns = [[1, 32, 1, 1],
[1, 32, 8, 9],
[2, 32, 2, 3],
[16, 32, 16, 9],
[4, 32, 4, 5],
[32, 32, 1, 0]]
numbers = []
for pattern in patterns:
numbers.append(generate_numbers(pattern[0],
pattern[1],
pattern[2],
pattern[3]))
return numbers
def make_sections(ls, size, spaces=None):
"""
splits list with sections of determined size
fills in with spaces if keyword is given
"""
if size < 0:
raise ValueError('Cannot be negative')
new_list = []
# Remove from list
while len(ls) >= size:
new_list.append(ls[:size])
del ls[:size]
# Check if there are any leftovers
if len(ls):
if spaces is not None:
# Add amount of spaces needed to fulfill size
for i in range(size - len(ls)):
ls.append(spaces)
# Add leftovers
new_list.append(ls)
return new_list
def make_size(string, size, char=" "):
"""
Adds chars to the start of a string to make it the specific length
"""
length = len(string)
# Add starting chars
new_string = char * (size - length)
# Rest of string
new_string += string
return new_string
def recursive_func(ls, func, argument=None):
"""
Applies a function recursively to the list provided, has support for
multidimensional lists
has support for a single argument
"""
# In case the given argument isnt a list
if type(ls) != list:
if argument is None:
return func(ls)
else:
return func(ls, argument)
new_list = []
for item in ls:
# If the item is also a list run this same function on it
if type(item) == list:
nested_list = []
for i in item:
if argument is None:
nested_list.append(recursive_func(i, func))
else:
nested_list.append(recursive_func(i, func, argument))
new_list.append(nested_list)
else:
if argument is None:
new_list.append(func(item))
else:
new_list.append(func(item, argument))
return new_list
def make_table(ls, columns):
"""
Displays a table with given columns
No support for 2d lists
"""
sectioned = make_sections(ls, columns, spaces=" ")
rows = []
# Turn into strings
for row in sectioned:
rows.append(' '.join(row))
table = "\n".join(rows)
return table
def main():
print("Mystery calculator :0")
for numbers in mystery_numbers():
# Blank Line
print()
# Make them all into strings
string_numbers = recursive_func(numbers, str)
# Make them all same size
same_size = recursive_func(string_numbers, make_size, 2)
# Display table
print(make_table(same_size, 8))
if __name__ == "__main__":
main()
|
5f2c900f55bdd3167694d80a9cd0e8bf9e0d3063 | asiShefer/aaa | /dataLoader.py | 12,058 | 3.5625 | 4 | from dataclasses import dataclass
from typing import List
from collections import defaultdict
import dataclasses
import pandas as pd
import numpy as np
@dataclass(order=True)
class utter:
'''
This dataclass represents an utterance.
It contains the following fields:
- time: Float. The utterance timestep
- conv_idx: Int. The utterace's conversation file id (the conversation should be in conv_idx.txt)
- utter_id: Int. The number of the utterance in the conversation (e.g, 1'st/2'nd utterance in the conversation)
- speaker: String. Who is the speaker (e.g, "agent"/"costumer"/"unknown speaker")
- text: String. The text spoken in this utterance
- labels: List of dictionaries. Each dictionary is {'label':String, 'text':String (the labeled span)}
- prev_utter_text/labels/speaker: Lists containing the text/labels/speakers of the
prev_utters_num (see DataLoader) previous utterances.
Note that the list is ordered by closeness to this utterance,
that is, the first item is the utter_id-1 utterance, the next is utter_id-2
and so on
- post_utter_text/labels/speaker: Lists containing the text/labels/speakers of the
post_utters_num (see DataLoader) utterances that come after this one.
'''
time: float=None
conv_idx: int=None
utter_id: int=None
speaker: str=None
text: str=None
labels: List=dataclasses.field(default_factory=list)
prev_utter_text: List=dataclasses.field(default_factory=list)
post_utter_text: List=dataclasses.field(default_factory=list)
prev_utter_labels: List=dataclasses.field(default_factory=list)
post_utter_labels: List=dataclasses.field(default_factory=list)
prev_utter_speaker: List=dataclasses.field(default_factory=list)
post_utter_speaker: List=dataclasses.field(default_factory=list)
class DataLoader(object):
def __init__(self, annotation_file, labels_column_name,
conv_idx_column_name,
text_column_name,
conv_dir,
prev_utters_num=0, post_utters_num=0,
sheet_names=None, Asi=True):
'''
@args:
- annotation_file: String. The path to the Excel file holding the labeled data
- labels_column_name/conv_idx_column_name/text_column_name: What are the columns name in annotation_file
- conv_dir: String. Path to the conversations directory.
- prev_utters_num/post_utters_num: Int. Number of previous/post utterances that each utter object should hold.
- sheet_names: String or List of strings. The sheet name/s in annotation_file we should use.
'''
self.annotation_file=annotation_file
self.labels_column_name=labels_column_name
self.conv_idx_column_name=conv_idx_column_name
self.text_column_name=text_column_name
self.conv_dir=conv_dir
self.sheet_names=sheet_names
self.prev_utters_num=prev_utters_num
self.post_utters_num=post_utters_num
self.convDict, self.bad_conv_idx, self.labels, self.conv2labeledText = self.dataloader()
self.label2utter = self.get_label2utter()
def get_labels(self):
return self.labels
def get_convDict(self):
return self.convDict
def get_labeled_convID(self):
'''
Returns a dictionary s.t for each conversation we have a list of all (and only) labeled utterances
'''
return {conv_id:self.get_conv(conv_id) for conv_id, conv in self.convDict.items() if len(self.get_conv(conv_id))>0}
def get_label2utter(self):
'''
label2utter: Dictionary where label2utter[label] = List containing only utterances with spans labeled with "label"
'''
label2utter = {label:[] for label in self.labels}
for utter_list in self.convDict.values():
for utter in utter_list:
if len(utter.labels)!=0:
labels_set=set()
for item in utter.labels:
label = item["label"]
if label not in labels_set:
label2utter[label].append(utter)
labels_set.add(label)
return label2utter
def get_conv(self, conv_id):
'''
Return utterances, from conversation conv_id, that contain labeled spans
'''
return [item for item in self.convDict[conv_id] if len(item.labels)>0]
def load_excel_file(self):
df_list = []
if type(self.sheet_names)==str:
df = pd.read_excel(self.annotation_file, sheet_name=self.sheet_name)
df_list.append(df)
elif type(self.sheet_names)==list:
for sheet_name in self.sheet_names:
df = pd.read_excel(self.annotation_file, sheet_name=sheet_name)
df_list.append(df)
elif self.sheet_names is None:
df = pd.read_excel(self.annotation_file)
df_list.append(df)
labels = list(set(item.lower() for df in df_list for item in df[self.labels_column_name] if item is not np.nan))
return df_list, labels
def get_file_path(self, conv_idx, max_num_of_digits=3):
'''
get the conversation number as an int and return the file name (string)
e.g, 1->001, 10->010, 100->100
'''
conv_int_as_string = str(int(conv_idx))
num_of_digits = len(conv_int_as_string)
return ''.join(['0' for _ in range(max_num_of_digits-num_of_digits)])+conv_int_as_string
def get_conv2labeledText(self, df_list):
'''
preprocessing step for get_conv_labeled_data
@args:
df_list: List of dataframes (one df for each Excel tab that represent one tagger)
returns:
Dict. Each conversation points to a list of the labeled spans.
conv2labeledText[conversation number]: [{label, text, count}, ...]
where count will be used to count the number of times the text was found in the conversation
(see get_conv_labeled_data) to help us find bugs (long texts tet get duplicated in the same
conversation for no reason)
'''
conv2labeledText = defaultdict(list)
conv_idx_set = set() # for testing
for df_count, df in enumerate(df_list):
conv_idx_set_tmp = set()
for index, row in df[df[self.labels_column_name].notna()].iterrows():
if type(row[self.text_column_name])!=str:
continue
conv_idx = int(row[self.conv_idx_column_name])
# conv_idx_set contains data from other Excel's tabs (taggers). We want to insure that the same
# conversation doesn't appear twice in the data
assert conv_idx not in conv_idx_set, f"df_count: {df_count}, conv_idx: {conv_idx}, conv_idx_set: {conv_idx_set}, conv_idx_set_tmp:{conv_idx_set_tmp}"
conv_idx_set_tmp.add(conv_idx)
if row[self.labels_column_name].lower() not in ["action response", "no data", "noted"]:
conv2labeledText[conv_idx].append({'label':row[self.labels_column_name].lower(),
'text':row[self.text_column_name].strip(),
'count':0})
conv_idx_set = conv_idx_set.union(conv_idx_set_tmp)
return conv2labeledText
def get_conv_labeled_data(self, conv_idx, conv, conv2labeledText):
'''
Takes conv list which contains the text in conersasion conv_idx in the following froms:
[Speaker Time (of utterance 1, i.e, "Agent 0:12"), text (of utterance 1), ...,
Speaker time (of utterance i), text (of utterance i), ...]
and turns it into a list of utter objects.
params:
conv_idx: int
conversation id
conv: List of strings.
The text segments (utterances) in conv_idx conversation.
Should look like
[Speaker Time (of utterance 1, i.e, "Agent 0:12"), text (of utterance 1), ..., Speaker time (of utterance i), text (of utterance i), ...]
conv2labeledText:dict.
see get_conv2labeledText
returns:
utters_list: a list of utter dataclasses for conv
'''
utters_list = []
itr_utter = utter()
utter_id=0
for text_seg_num, text_seg in enumerate(conv):
utters_num = len(utters_list)
if itr_utter.speaker is None:
# itr_utter.speaker is None if this is the first time this utterance is seen
# This means that text_seg should be - Speaker Time
for i in range(self.prev_utters_num):
if utters_num>i:
itr_utter.prev_utter_text.append(utters_list[utters_num-1-i].text)
itr_utter.prev_utter_labels.append(utters_list[utters_num-1-i].labels)
itr_utter.prev_utter_speaker.append(utters_list[utters_num-1-i].speaker)
splits = text_seg.split()
if splits[0].lower()=="prospect":
splits[0] = 'customer'
if splits[0].lower()=="'agnet'":
splits[0] = 'agent'
if itr_utter.conv_idx is not None or itr_utter.time is not None or splits[0].lower() not in ['customer', 'agent', 'agnet', 'prospect', 'unknown']:
return -1
utter_id+=1
itr_utter.utter_id=utter_id
itr_utter.speaker = ' '.join(splits[:-1]).strip()
itr_utter.time = float(splits[-1].replace(':', '.'))
itr_utter.conv_idx = conv_idx
else:
# If we're here, we've already dealt with the utterance's speaker and time and now
# we're dealing with its text
itr_utter.text=text_seg
for i in range(self.post_utters_num):
if utters_num>i:
utters_list[utters_num-1-i].post_utter_text.append(text_seg)
utters_list[utters_num-1-i].post_utter_speaker.append(itr_utter.speaker)
for item in conv2labeledText[conv_idx]:
if item['text'].lower() in text_seg.lower():
if item['count']!=0:# and len(item['text'].split())>7:
# We conversations that have cutterances with count>0, that is,
# the text in this conversation is duplicated, and the duplicated text is
# has more than 7 words
return -2
itr_utter.labels.append({'label':item['label'], 'text':item['text']})
item['count']+=1
for i in range(self.post_utters_num):
if utters_num>i:
utters_list[utters_num-1-i].post_utter_labels.append(itr_utter.labels)
utters_list.append(itr_utter)
itr_utter = utter()
if conv_idx!=1:
for item in conv2labeledText[conv_idx]:
if item['count']==0:
# If the text were not processed at all
return -3
return utters_list
def dataloader(self):
'''
Read the data and process it.
@returns:
convDict: Dictionary: convDict[conv_idx] = list of the conversation utter objects
bad_conv_idx: List of ints. conv_idx of problematic conversations (get_conv_labeled_data returns
an int < 0)
labels: lList of all labels
conv2labeledText: see get_conv2labeledText
'''
df_list, labels = self.load_excel_file()
conv2labeledText = self.get_conv2labeledText(df_list)
convDict = {}
bad_conv_idx = []
labeled_conv_idx = conv2labeledText.keys()
for fpath in self.conv_dir.iterdir():
conv_idx = int(fpath.name.split('.')[0].split()[0])
if conv_idx not in labeled_conv_idx:
# If the conversation has no labeled spans
continue
with open(fpath, 'r') as f:
conv_text = [item.strip() for item in f.read().split('\n') if item.strip()!='']
utters_list=self.get_conv_labeled_data(conv_idx, conv_text, conv2labeledText)
if type(utters_list)==int:
# For testing
bad_conv_idx.append([conv_idx, utters_list])
else:
convDict[conv_idx]=utters_list
conv_num = len(convDict)
utters_num = sum([len(conv) for conv in convDict.values()])
labeled_utters_num = sum([sum([1 for uttr in conv if len(uttr.labels)>0]) for conv in convDict.values()])
labeled_uttr_ratio_per_conv_mean = np.mean(
[sum([1 for uttr in conv if len(uttr.labels)>0])/len(conv) for conv in convDict.values()])
print("Utterances nummber:", utters_num)
print(f"Labeled utterances nummber: {labeled_utters_num}")
print("Conversations number:", conv_num)
print(f"Average number of utterances in a conversations: {utters_num/conv_num:.2f}")
print()
print(f"{100*labeled_utters_num/utters_num:0.2f}% of the utterances are labeled")
print(f"{100*labeled_uttr_ratio_per_conv_mean:0.2f}% of the utterances in an average conversation are labeled")
return convDict, bad_conv_idx, labels, conv2labeledText
|
1161ff5d595a8ce219aec7e246cc90eef20d121b | yuanxuanjie/test | /基础服务/基础/格式化输出.py | 422 | 4.09375 | 4 | """
name=input('name:')
job=input('job')
ap=input('axl')
info = '''
------------------info or {name}
name:{name}
job:{job}
ap:{ap}
'''.format(name=name,
job=job,
ap=ap)
print(info)
"""
t = '窝气'
print(t.encode('utf-8'))
print(t.encode('utf-8').decode('utf-8'))
a = [0,1,2,3]
for i,f in enumerate(a):
print(i,f)
print(a.index(1))
ak = {
a:'wo',b:'ta',c:'ni'
}
if ak in a:
print(ak) |
1d6efcb2b7a9fa50c5f861a30009c5e99e34c8b4 | PaytonZ/IC-Practica1 | /node.py | 920 | 3.921875 | 4 | # -*- coding: utf-8 -
'''
Juan Luis Pérez Valbuena
Ingeniería del Conocimiento - Práctica 1 - Algoritmo A*
'''
import math
''' Clase Nodo :
x : posicion x del nodo
y : posicion y del nodo
forbidden : indica si esta prohibido el paso o no
penality : indica el nivel de penalización por el paso por este nodo
'''
class Node(object):
def __init__(self,x,y,forbidden,penalty):
self.x = x
self.y = y
self.forbidden = forbidden
self.penalty = penalty
def euclidean_distance(self,nodo):
return float(math.sqrt(pow(self.x-nodo.x,2)+pow(self.y-nodo.y,2)))
def __str__(self):
return "({0},{1})".format(self.x,self.y) + " Forbiden %r penalty: %f" % (self.forbidden , self.penalty)
def __unicode__(self):
return self.__str__()
def __repr__(self):
return self.__str__()
def __eq__(self,other):
return self.x == other.x and self.y == other.y
def __ne__(self,other):
return self.x != other.x or self.y != other.y
|
60bad25ebf333aeaf459683b862513749e726158 | vinayakushakola/ShellScript | /8.User Registration/UserRegistrationGUI.py | 1,990 | 3.625 | 4 | from tkinter import *
import re
def startChecking():
name=name1.get()
phnum=phnum1.get()
email=email1.get()
password=password1.get()
namePattern="^[A-Z]{1}[a-z]{2,}$"
emailPattern="^([a-zA-Z]{3,}([.|_|+|-]?[a-zA-Z0-9]+)?[@][a-zA-Z0-9]+[.][a-zA-Z]{2,3}([.]?[a-zA-Z]{2,3})?)$"
phonePattern="^([0-9]{1,3}[ ][1-9]{1}[0-9]{9})$"
passPattern="^[a-zA-Z0-9]{8,}$"
if re.match(namePattern, name):
print("name is Successfully Registered")
else:
print("Invalid")
if re.match(phnum, phonePattern):
print("Phone number is Successfully Registered")
else:
print("Invalid")
if re.match(email, emailPattern):
print("email is Successfully Registered")
else:
print("Invalid")
if re.match(password, passPattern):
print("password is Successfully Registered")
else:
print("Invalid")
root=Tk()
root.title("User Registration")
root.geometry("500x300")
name1=StringVar()
phnum1=StringVar()
email1=StringVar()
password1=StringVar()
Label(root, text="User registration", font="helvetica 30").grid(row=0, columnspan=2)
Label(root, text="Name", font="helvetica 20").grid(row=1, column=0)
Entry(root, textvariable=name1, font="helvetica 20").grid(row=1, column=1)
Label(root, text="Phone Number", font="helvetica 20").grid(row=2, column=0)
Entry(root, textvariable=phnum1, font="helvetica 20").grid(row=2, column=1)
Label(root, text="Email", font="helvetica 20").grid(row=3, column=0)
Entry(root, textvariable=email1, font="helvetica 20").grid(row=3, column=1)
Label(root, text="Password", font="helvetica 20").grid(row=4, column=0)
Entry(root, textvariable=password1, font="helvetica 20").grid(row=4, column=1)
Button(root, text="Submit", font="helvetica 15", width=10, command=startChecking).grid(row=5, column=1)
root.mainloop()
|
01693f037e76c82e9200e68ecfd94f4d1b273fdf | SteveGachanja/linuxlab | /tech notes/Python refresher notes 2022.py | 1,870 | 4.40625 | 4 | #####Python
Python Basics
Python Lists
- Subsetting Lists
- Slicing and Dicing
- Manipulating Lists
- Explicit and reference-based list copies
- Functions , a piece of reusable code, aim at solving a particular task
- Methods - functions that belong to objects
- In Python everything is an object , and depending on the type, every object has associated methods
- Packages - A directory of Python scripts (the scripts/modules specify functions, methods and types)
- e.g. Numpy, Matplotlib, scikit-learn
from scipy.linalg import inv as my_inv --- import the function inv(), which is in the linalg subpackage of the scipy package.
- NumPy - Numeric Python (calculations over entire arrays)
- import numpy as np
Data Visualizations
- import matplotlib.pyplot as plt
Numpy Boolean Operators
- bmi[np.logical_and(bmi > 21 , bmi < 22)]
Accessing data in dataframes
cars.loc['IN', 'cars_per_cap']
cars.iloc[3, 0]
cars.loc[['IN', 'RU'], 'cars_per_cap']
cars.iloc[[3, 4], 0]
cars.loc[['IN', 'RU'], ['cars_per_cap', 'country']]
cars.iloc[[3, 4], [0, 1]]
Loops:
- for var in seq:
expression
- Example
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
for index,y in enumerate(areas) :
print("room" + str(index) + ":" + str(y))
Iterate over a dictionary
- for key, val in my_dict.items(): -- dictionaries use a method to iterate
Iterate over a Numpy arrays
- for val in np.nditer(my_array): -- numpy arrays use a function to iterate
Iterate over a Pandas Dataframe
- for val, row in data.iterrows():
- Example
for lab, row in cars.iterrows() :
print(lab +": "+ str(row['cars_per_cap']))
for i, row in cars.iterrows() :
cars.loc[i,"COUNTRY"] = row["country"].upper()
# Use .apply(str.upper)
cars["COUNTRY"] = cars["country"].apply(str.upper)
|
11681c08ba5606778c4e9005563ee222a7ed2741 | Talos-Martin/LearnTheHardWay | /Python3/exercise12/ex12.py | 1,011 | 3.953125 | 4 |
#This is a slightly modified exercise 11. I already did input("stuff") in there
print("what's the weight of a swallow?") #removing end statement makes input read from new line, not same line
weight=input()
print("European or African? How old??", end=' '); #end='' removes space. space between sentence and input can also be achieved by placing extra space after question mark, before closing quote
age=input()
print("Does the size of the bird matter??", height=input()) #This does not work. Breaks.
print(f"""So here we have a swallow with a weight of {weight},
an age of {age},
and a height of {height}""")
#input list(2 variables here)
#input function called with descriptive string
#split with no argument, to separate by space
age, eight = input("Age and weight please. Separate by space. No Lies!").split()
print("Age is", age, "and weight is", weight);
#int number = input"Gimme a number") #doesn't work
number = int(input("Gimme a number! "))
print("Square is: ", number*number)
|
6b9ae7de47d4da2e34c307d24ef2b7a62048ff3f | raajatk/PythonCodingPractice | /list_sublist.py | 453 | 4.125 | 4 | """Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
and makes a new list of only the first and last elements of the given list.
For practice, write this code inside a function."""
def fetch_sublist(list):
new_list = [list[0],list[-1]]
return new_list
print("Please input the list of numbers separated by commas(,)")
list = [int(i) for i in input().split(',')]
sub_list = fetch_sublist(list)
print(sub_list)
|
c71b24a24e29700754a26646bac7a89a45a4bcfc | Haoxiaoling/MachineLearningProject | /project1.py | 11,437 | 3.515625 | 4 | #!/usr/bin/env python3
import pandas as pd
import numpy as np
def read_data():
data = pd.read_csv('DataTraining.csv', delim_whitespace = False)
# miss = data.dropna(axis = 1)
# miss.info()
#################################
#
# full = data.dropna(subset = data.columns.values[:-3])
# # data = data.diff()
# # print(data.isnull())
#
#
#
# ###nan is the rows which miss some data and nan already remove the rows which miss two or two more items.
# idx1 = data.index[:]
# idx2 = full.index[:]
# nan = data.loc[idx1.difference(idx2)]
# nan = nan.dropna(thresh = 20, subset = data.columns.values[:-3])
#
# for column in ['schooling', 'day_of_week']:
# missing = missing_columns(nan, column)
# # print('Logistic Regression: ', sum(abs(y_test == y_predict))/y_predict.shape[0])
# missing_column = data_retrieve(full.drop([column, 'id', 'profit', 'responded'],axis = 1), full[column].values, missing.drop([column, 'id', 'profit', 'responded'], axis = 1))
# missing[column] = missing_column
# full = pd.concat([full, missing], axis = 0)
#
#
# ######Recover custAge via linear Regression
# from sklearn.model_selection import train_test_split
# size = full.shape[0]
# missing_age = missing_columns(nan, 'custAge')
# x, _ = dummy_standardarize(pd.concat([full.drop(['custAge','id', 'profit', 'responded'], axis =1 ), missing_age.drop(['custAge','id', 'profit', 'responded'], axis =1 )]), [13,14,15,16])
# full_x = x[:size, :]
# x_pre = x[size:, :]
# from sklearn.linear_model import Lasso
#
# regr = Lasso(alpha = 0.1)
#
# regr.fit(full_x, full['custAge'])
#
# age_pre = regr.predict(x_pre)
#
# missing_age['custAge'] = age_pre
#
# full = pd.concat([full, missing_age], axis = 0)
#
#
# #####Get profit and responded
# profit = full['profit'].values
# responded = 1 * (full['responded'].values == 'yes')
# #print(sum(responded))
# full = full.drop(['id', 'profit', 'responded'], axis = 1)
# #dummy and standardarization
# normalized_data, scaler = dummy_standardarize(full, [0, 14, 15, 16, 17])
# sklearn process data
data.info()
p = data['profit'].values
r = 1 * (data['responded'].values == 'yes')
#print(sum(responded))
data = data.drop(['id', 'profit', 'responded'], axis = 1)
values = {'custAge': 0, 'schooling': 'no', 'day_of_week': 'weekend'}
fill = data.fillna(value = values)
fill.info()
from sklearn.preprocessing import LabelBinarizer, StandardScaler
x = None
estimator = []
for column in fill.columns.values:
if fill[column].dtype == object:
le = LabelBinarizer()
# print(fill[column])
le.fit(fill[column].values.reshape(-1, 1))
encode_data = le.transform(fill[column].values.reshape(-1, 1))
if x is None:
x = encode_data
else:
x = np.c_[x, encode_data]
estimator.append(le)
else:
scaler = StandardScaler()
scaler.fit(fill[column].values.reshape(-1, 1))
encode_data = scaler.transform(fill[column].values.reshape(-1, 1))
if x is None:
x = encode_data
else:
x = np.c_[x, encode_data]
estimator.append(scaler)
return x, r, p, estimator, fill.columns
def missing_columns(data, columns):
non_missing = data.dropna(subset = [columns])
idx1 = data.index[:]
idx2 = non_missing.index[:]
missing = data.loc[idx1.difference(idx2)]
return missing
def dummy_standardarize(data, index, scaler = None):
from sklearn.preprocessing import StandardScaler
#print(data.values.shape)
#print(list(np.delete(data.columns,[14, 15, 16, 17] )))
dummied_data = pd.get_dummies(data, columns=list(np.delete(data.columns,index )) )
if scaler == None:
scaler = StandardScaler()
scaler.fit(dummied_data[list(dummied_data.columns.values)[:5]])
normalized_data = np.c_[scaler.transform(dummied_data[list(dummied_data.columns.values)[:5]]), dummied_data.drop(list(dummied_data.columns.values)[:5], axis = 1).values ]
return normalized_data, scaler
def data_retrieve(x_train, y_train, x):
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=2)
size = x_train.shape[0]
x, scaler = dummy_standardarize(pd.concat([x_train, x]), [0, 13, 14, 15, 16])
x_train = x[:size,:]
x = x[size:, :]
neigh.fit(x_train, y_train)
y = neigh.predict(x)
# from sklearn.model_selection import train_test_split
#
# x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size = 0.2)
#
# neigh.fit(x_train, y_train)
#
# y = neigh.predict(x_test)
#
# print(sum(abs(y_test == y))/y.shape[0])
return y
def data_viz(data):
import matplotlib.pyplot as plt
columns = list(data.columns)
for tag in columns[:-2]:
attr = getattr(data, tag)
responded_yes = attr[data.responded == 'yes'].value_counts()
responded_no = attr[data.responded == 'no'].value_counts()
df=pd.DataFrame({u'Yes':responded_yes, u'No':responded_no})
df.plot(kind='barh', stacked=True)
plt.title(tag)
plt.ylabel(tag)
plt.xlabel(u"responded")
plt.show()
if __name__ == '__main__':
import random
[data_x, y, r, estimator, labels] = read_data()
data_size = data_x.shape[0]
positive_size = int(sum(y))
negative_size = data_size - positive_size
#Feature selection: VarianceThreshold
# from sklearn.feature_selection import VarianceThreshold
# selector = VarianceThreshold(threshold=5e-4)
# x = selector.fit_transform(data_x)
# # print(selector.variances_)
# # print(x.shape)
##########No feature selection
x = data_x
#Split data
k = 500
index_n = random.sample(range(0, negative_size), positive_size)
index_p = random.sample(range(negative_size, data_size) , positive_size)
index = index_n + index_p
#split data as train and test
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)
#Classifier: LogisticRegression Part
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(class_weight = 'balanced', penalty='l1')
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('Logistic Regression: ', sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: SVM part
from sklearn.svm import SVC
classifier = SVC(class_weight = 'balanced')
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('SVM: ',sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: LDA part
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
classifier = LinearDiscriminantAnalysis(solver='lsqr')
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print(sum(y_test==1))
print(sum(y_test==0))
print('LDA: ',sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: LDA part
# from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
#
# classifier = QuadraticDiscriminantAnalysis()
# classifier.fit(x_train, y_train)
#
# y_predict = classifier.predict(x_test)
# print(sum(abs(y_test - y_predict))/len(y_predict))
# print(y_test)
# print(y_predict)
#Classifier: Randomforest
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier()
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('Random Forest: ', sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: Adaboost
from sklearn.ensemble import AdaBoostClassifier
classifier = AdaBoostClassifier(n_estimators=40)
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('Adaboost: ', sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: Naive Bayes
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('Naive Bayes: ', sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: Gradient boosting
from sklearn.ensemble import GradientBoostingClassifier
classifier = GradientBoostingClassifier()
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('Gradient boosting: ', sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: GP classifier
from sklearn.gaussian_process import GaussianProcessClassifier
classifier = GaussianProcessClassifier()
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('Gaussian Process: ', sum(abs(y_test - y_predict))/len(y_predict))
#Classifier: MLP classifier
from sklearn.neural_network import MLPClassifier
classifier = MLPClassifier(hidden_layer_sizes=(20,), early_stopping=True, alpha=1)
classifier.fit(x_train, y_train)
y_predict = classifier.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('MLP: ', sum(abs(y_test - y_predict))/len(y_predict))
###KNN part
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=2)
neigh.fit(x_train, y_train)
y_predict = neigh.predict(x_test)
print(sum(y_predict - y_test == -1)/(sum(y_test ==1 )))
print(sum(y_predict - y_test == 1)/(sum(y_test ==0 )))
print('KNN: ', sum(abs(y_test - y_predict))/len(y_predict))
print(x.shape)
####test data part
data_pre = pd.read_csv('DataPredict.csv', delim_whitespace = False, header = None)
data_pre.columns = labels
values = {'custAge': 0, 'schooling': 'no', 'day_of_week': 'weekend'}
data_pre = data_pre.fillna(value = values)
data_pre.columns = range(0, labels.values.shape[0])
x = None
for i in data_pre.columns:
x_predict = estimator[i].transform(data_pre[i].values.reshape(-1, 1))
if x is None:
x = x_predict
else:
x = np.c_[x, x_predict]
print(x.shape)
|
c2ed6fd34fd1c23f9f6c08dfeb45c1d596ed0474 | kwahome/python-escapade | /balanced-brackets/input/sample.py | 547 | 4.03125 | 4 | import sys
def main(n):
n= int(n)
fibonacci_series = [0,1]
for i in range(1,n-1):
next_fibonacci_no = fibonacci_series[(len(fibonacci_series)-1)]+fibonacci_series[(len(fibonacci_series)-2)]
fibonacci_series.append(next_fibonacci_no)
print fibonacci_series
if __name__ == "__main__":
try:
sys.exit(main(sys.argv[1]))
except Exception:
print "An error has occured"
print "To run this program, the number of Fibonacci numbers to be generated should be passed as a parameter"
print "For instance, python weather fibonacci.py 5" |
e1bf77a5a3d56fb532de55d97ab3a1e3b9b88131 | DeepeshKashyup/DataStructures-Algos | /Python/DijkstraShortestPath.py | 1,387 | 3.578125 | 4 | from collections import defaultdict
class graph:
def __init__(self,v):
self.V=v
self.graph = defaultdict(dict)
self.q = []
self.dist = [float('inf')]*self.V
self.path = [[] for _ in range(v)]
def enqueue(self,item):
self.q.append(item)
def dequeue(self):
return self.q.pop(0)
def addEdge(self,tail,head,length):
self.graph[tail][head] = length
def DijkstraSP(self,s):
visited= [False]*self.V
visited[s]=True
self.dist[s]= 0
self.path[s].append(s)
self.enqueue(s)
while not self.q == []:
u = self.dequeue()
for w in self.graph[u]:
#print 'u:',u,'\tw:',w
if(self.dist[w] > self.dist[u]+self.graph[u][w]):
self.dist[w] = self.dist[u]+self.graph[u][w]
self.path[w]=[]
for x in self.path[u]:
self.path[w].append(x)
self.path[w].append(w)
#print dist
#print self.path
self.enqueue(w)
visited[w]= True
##
## print self.dist
## print self.path
g = graph(4)
g.addEdge(0,1,1)
g.addEdge(0,2,4)
g.addEdge(1,2,2)
g.addEdge(1,3,6)
g.addEdge(2,3,3)
print g.graph
g.DijkstraSP(0)
print g.dist
print g.path
|
218e3fcbf9078bc731b05c98b17f05463a0e078b | jamesfallon99/CA318 | /week1/permutations_and_backtracking.py | 1,243 | 3.875 | 4 | #
# Back tracking version
#
# Helps to have variables with global scope.
#
total = 0
letters = [] # This list will be updated by the recursive backtracking function (DFS)
def permutation(pos, next_letter, remaining_letters):
global letters
global total
letters[pos] = next_letter # update the letters array
if len(remaining_letters) == 0: # no more letters => reached the end
print("".join(letters), total) # ... => found a new permutation
# update the total
total += 1
else:
# So, try each of the remaining letters in the next position
for letter in remaining_letters:
permutation(pos+1, letter, remaining_letters.replace(letter, ""))
# When we are finished the recursive call, we revert to previous state
letters[pos] = ' ' # actually doesn't matter in this case, because it will be overwritten when going forward.
def main():
global letters
# Try a word
word = 'jcdhfebiag'
letters = ['-'] * len(word)
for letter in word:
remaining_letters = word.replace(letter, "") # find the remaining letters
permutation(0, letter, remaining_letters) # let our function know which letters remain.
main() |
9ce603442c0e558866d52e0e00577dfbeea144f9 | biosx32/python_PIL_and_BMP | /gui.py | 437 | 3.890625 | 4 | import tkinter
from tkinter import Button
def toggle(btn):
if btn['fg'] != "black":
print(btn['fg'])
btn.configure(bg="red")
else:
btn.configure(bg="blue")
window = tkinter.Tk()
window.resizable(width=False, height=False)
window.minsize(width= 1000, height = 500)
a = None
a = Button (window, width=40, height = 20, fg="white", command=toggle(a))
a.place(x=20, y=20)
window.mainloop()
|
9889724ee39f3f308ef0e7356729fb4ed73ae0c9 | hanhan1280/mips241 | /test/big/generate-single-op.py | 1,942 | 3.578125 | 4 | #!/usr/bin/env python3
import fileinput
import struct
import sys
import signal
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
def get_skel(s):
"""Get a tuple representing an instrution skeleton.
Args:
s: String of chars in {0, 1, x} of the skeleton
Returns:
Tuple (before, length, after), where
- before is the number before the mask
- length is the length of x's in the mask
- after is the number after the mask
"""
i = 0
# get number before x's
before = 0
while i < len(s):
if s[i] != 'x':
assert s[i] == '0' or s[i] == '1'
before += before
before += int(s[i])
else:
break
i += 1
# get number of x's
xlen = 0
while i < len(s):
if s[i] == 'x':
xlen += 1
else:
break
i += 1
# get number of 0s after x's
zerolen = 0
while i < len(s):
if s[i] == '0':
zerolen += 1
else:
break
i += 1
# get number afer x's
after = 0
while i < len(s):
assert s[i] == '0' or s[i] == '1'
after += after
after += int(s[i])
i += 1
return (before, xlen, zerolen, after)
def gen_from_skel(skel):
"""
Iterator for all possible instructions, given a skeleton.
See get_skel(s).
Args:
skel: skel, from get_skel
Yields:
A next possible instruction in machine code, as a word.
"""
(before, xlen, zerolen, after) = skel
increment = 1 << (after.bit_length() + zerolen)
result = (before << (xlen + zerolen + after.bit_length())) + after
for i in range(1 << xlen):
yield result
result += increment
for line in fileinput.input():
line = line.strip()
for instruction in gen_from_skel(get_skel(line)):
sys.stdout.buffer.write(struct.pack('>I', instruction))
|
da5920501d67aa601cc5aa7ea97234f154c694cc | Katherine916/suye | /three/test3.py | 453 | 4.15625 | 4 | friend = ["Katherine","Lily","Demon"]
print(friend)
print(friend[2]+" can't join")
friend[2] = "steven"
print(friend)
print("I find a big desk")
friend.insert(0,"Helln")
friend.insert(4,"Jack")
friend.insert(5,"Seamon")
print(friend)
print("----------------------------")
# 为什么pop 删除到数组为2 就不删除了
for friends in friend:
pop_frinend = friend.pop()
print(friend)
del friend[2]
del friend[1]
del friend[0]
print(friend) |
ed262efa29cc07de64cecb4004f4c92f0d75de1d | jamesbting/COMP-400-Research-Project | /filtering/src/loader.py | 1,624 | 3.546875 | 4 | import csv
def load_data(file_name, team_dictionary):
print("Loading data into the program")
dataset = {}
with open(file_name,'r') as f:
reader = csv.reader(f, delimiter = ',')
i = 0
for row in reader:
add_data(dataset, row)
i += 1
print(i, 'data points loaded')
f.close()
print("Done loading data.")
with open(team_dictionary, 'w') as f:
f.write(str(dataset))
f.close()
return dataset
#build the dataset
def add_data(dataset, row):
if(len(row) != 11):
raise ValueError
blue_team = tuple(row[0:5])
red_team = tuple(row[5:10])
blue_team_victory = True if int(row[10]) == 1 else False
#check if blue team is already in the dictionary
if blue_team not in dataset:
dataset[blue_team] = [1 if blue_team_victory else 0, 1]
else:
#update blue team
dataset[blue_team] = [dataset[blue_team][0] + 1 if blue_team_victory else dataset[blue_team][0], dataset[blue_team][1] + 1]
if red_team not in dataset:
dataset[red_team] = [1 if blue_team_victory else 0, 1]
else:
#update red team
dataset[red_team] = [dataset[red_team][0] + 1 if not blue_team_victory else dataset[red_team][0], dataset[red_team][1] + 1]
def load_win_rate(win_rate_file):
with open(win_rate_file, 'r') as f:
content = f.readlines()
return [int(line) for line in content]
def list_to_string(row):
res = ""
row.sort()
for element in row:
res += (str(element) + ',')
return res[0:len(res)-1]
# load_win_rate("data/win_rate.txt") |
86493efb5e7f53931f6e32a4261c900ba51d1c4d | Inazuma110/atcoder | /cpp/icpcmogi2019/c/main.py | 648 | 3.640625 | 4 | import sys
def f(x, y):
if x == 0 and y >= 3 and y % 2 == 1:
return y + 1
if x % 2 == 0 and y % 2 == 0:
return x + y
else:
return x + y + 1
def solve(a, b):
a = abs(a)
b = abs(b)
if a > b:
a, b = b, a
if (a == 1 and b == 1) or (a == 0 and b == 1) or (a == 1 and b == 0):
return 1
else:
f(a, b)
def main():
# try:
# while True:
# solve(*map(int, input().split()))
# except:
# pass
for i in range(10):
for j in range(10):
res = solve(i, j)
print(f'{res}\t', end='')
print()
main()
|
81bdad8df62fe85e7c571ac0ec9a2dccddb4e0ab | seraaaayeo/Cloud-AI-SKinfosec | /week2/day3/argument.py | 1,243 | 4.1875 | 4 | # Argument and Parameter
def func1(param1, param2):
'''
func1에는 매개변수 param1, param2가 전달받는다.
매개변수: 함수가 정의되는 내용에 포함(Variable)
'''
print(f"parameter1: {param1}, parameter2: {param2}")
'''
func1에 "AA"와 "B"라는 값을 전달하며 함수를 호출한다.
인자: 함수에 전달하는 값(Value)
'''
func1("AA", "B") #parameter1: AA, parameter2: B
# 인자의 전달방식 - Call by Value & Call by Reference
def call_by_value(param1:int)->None:
param1 +=1
print(f"callb by value: {param1}")
def call_by_ref(param2:list)->None:
param2[0]+=1
print(f"call by ref: {param2}")
val1 = 3
val2 = [3]
print(f"ori val1:{val1}") #3
call_by_value(val1) #4
print(f"val1 after func:{val1}") #3
print("--------")
print(f"ori val2:{val2}") #[3]
call_by_ref(val2) #[4]
print(f"val2 after func:{val2}") #[4]
'''
call by value: 함수로 인자가 전달될 때 동일한 값을 가진 객체를 복사하여 전달.
= val1이 전달된 것이 아니라 val1과 동이란 값을 가진 객체가 전달됨.
call by reference: 함수로 인자가 전달될 때 실제로 인자가 가진 참조 값을 전달.
= 실제로 인자 객체를 그대로 전달.
'''
|
8377ab4ac3e7e7a8ef696046e220cfffbc4f000f | Roshni-jha/ifelse | /percentage.py | 323 | 3.875 | 4 | var=input("enter the subject")
num=var/100*100
if var>=90:
print("grade A")
elif var>=80:
print("grade B")
elif var>=70:
print("grade C")
elif var>=60:
print("grade D")
elif var>=50:
print("grade E")
elif var>=40:
print("grade F")
elif var<=40:
print("grade G")
else:
print("nothing")
|
7b30f5fbb0230f1cd17a7ce5c6c9345aed1c2f5b | AwakenedMachine/lcthw | /ex6.py | 1,067 | 4.46875 | 4 | types_of_people = 10 #this sets the number of people though it also sets up the punchline since 10 is 2 in binary
x = f"there are {types_of_people} types of people."
#the following is setting the variable binary so that it reads "binary"
binary = "binary"
#the following is setting the variable do_not so that it reads the contraction: "don't"
do_not = "don't"
#the following is setting the variable as a function string which inserts two variables, binary and do_not
y = f"Those who know {binary} and those who {do_not}."
#this is printing the variable x
print(x)
#this is printing the variable y
print(y)
print(f"I said: {x}") #since the strings were made into variables, they could be repeated without retyping
print(f"I also said: '{y}'")
#the following variable allows for a word to be inserted in multiple places and can be changed later
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
w = "This is the left side of..."
e = "a string with a right side."
print(w + e) |
0681096fc27021a2c31bb1ff52b22bb182670506 | andres-aguilar/PyGame | /1_introduction/rectangles.py | 761 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import pygame
pygame.init()
width = 400
height = 500
surface = pygame.display.set_mode( (width, height) )
pygame.display.set_caption('Colors')
# RBG
red = pygame.Color(115, 38, 80)
white = pygame.Color(255, 255, 255)
green = pygame.Color(0, 200, 0)
rect = pygame.Rect(100, 150, 120, 60)
rect.center = ( width//2, height//2 )
# También se pueden definir rectangulos por medio de una tupla
rect2 = (100, 100, 80, 40)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
surface.fill(white)
pygame.draw.rect(surface, red, rect)
pygame.draw.rect(surface, green, rect2)
pygame.display.update() |
56698a65ee690dba02064fbc0d9222d9a4ec23b6 | RoyTimes/ProjectEuler | /44.py | 483 | 3.65625 | 4 | import math
import os,sys
import time
begin = time.time()
if __name__ == "__main__":
#main >>
solved = False
getlist = set()
i = 0
while solved != True:
i += 1
get = int (i * (3 * i - 1) / 2)
getlist.add(get)
for num in getlist:
if get - num in getlist and get - num * 2 in getlist:
print (abs(num - (get - num)))
solved = True
#main <<
end = time.time()
print (end - begin)
|
420cd83d986f4b6632c0faef00fefdf6962bf080 | khritova-kate/introductionML-exercises | /1-titanic.py | 1,442 | 3.515625 | 4 | import pandas
from collections import Counter
data = pandas.read_csv('titanic.csv', index_col = 'PassengerId')
pandas.DataFrame(data)
# Количство мужчин и женщин
print ( '1. ' , data['Sex'].value_counts(), '\n')
# Процентное отношение выживших
print ( '2. ' , round (100 * data['Survived'].value_counts().loc[1] / len(data) , 2), '\n')
# Доля пассажиров первого класса среди всех пассажиров
print ( '3. ' , round (100 * data['Pclass'].value_counts().loc[1] / len(data) , 2), '\n')
# Среднее и медиана возраста
print('4. ', round( data['Age'].mean(), 2) )
print(' ', round( data['Age'].median(), 2) , '\n')
# Корелляция Пирсона между признаками SibSp и Parch
print ( '5. ', round( data['SibSp'].corr(data['Parch']), 2), '\n')
# Самое популярное женское имя (всего 314 женщин)
name = data.sort_values(by = ['Sex'])['Name'].tolist()
name[:10]
name = name[0:314]
for i in range(len(name)):
a = name[i].find('Miss.')
if (a != -1):
name[i] = name[i][a:].split()[1]
else:
b = name[i].find('(')
if (b != -1):
name[i] = name[i][b+1:].split()[0]
name[i] = name[i].replace(')',"")
else:
name[i] = ""
print ( '6. ', Counter(name).most_common(1)[0], '\n')
|
4536c0d2350d543b8cb7420bf6a49bb001e2ac6b | fearonviel/naloga_8 | /pretvornik.py | 433 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
print("Dobrodošli. Ta program pretvori kilometre v milje.")
while True:
vneseni_km = float(raw_input("Vnesite število kilometrov: "))
milje = vneseni_km * 0.621371
print(str(vneseni_km) + " km je " + str(milje) + " milj(e).")
nov_vnos = raw_input("Želite pretvoriti novo število kilometrov? (Da/ne): ").lower()
if nov_vnos == "ne":
break
print("END") |
cfa4fc4872b8c08e9e1c5be1731398e3a2639358 | 180847/I2P | /Chocolate Machine Demo.py | 993 | 3.90625 | 4 | Price_Chocolate= float(16.90)
print("Price of Chocolate is"),(Price_Chocolate)
payed=input("Please Enter Amount of Coins")
print("you payed"),(payed)
if payed > Price_Chocolate:
change= payed-Price_Chocolate
print("Your Change is"),(payed-Price_Chocolate)
if payed < Price_Chocolate:
print("That is not enough you asshole")
if change > 0:
print("your change is:")
while change > 50:
change = change - 50
print("50+")
while change > 20:
change = change - 20
print("20+")
while change > 10:
change = change - 10
print("10+")
while change > 5.0:
change = change - 5.0
print("5+")
while change > 2.0:
change = change - 2.0
print("2+")
while change > 1.0:
change = change - 1.0
print("1+")
while change > 0.5:
change = change - 0.5
print("0.5+")
while change > 0.2:
change = change - 0.2
print("0.2+")
while change >= 0.1:
change = change - 0.1
print("0.1+")
while change >= 0.01:
change = change - 0.01
|
00e7fe742bc941030bf0ce505e99f82a68c98c1c | developervarinder/PythonCodingExercise | /fiblist.py | 158 | 3.53125 | 4 | def fib1(n):
result = []
a,b = 0, 1
while a<n:
result.append(a)
a,b =b,a+b
return result
f1 = fib1(100)
print(f1) |
54c3aabc7386b7248eb375090b3c9e09c0f74679 | kevrocks67/Music-Automation-MPD | /createRotation.py | 837 | 3.546875 | 4 | import os
user = input("Name of user in home folder of music: ")
musicDir = "/home/"+user+"/Music"
print("Music Directory set to: "+musicDir)
rotFileName = input("What would you like to call the rotation file?: ")
rotFile = open(rotFileName,"w")
rotFile.close()
for genre in os.listdir(musicDir):
print(genre)
def addGenre():
toAdd = input("Pick a genre to add to rotation: ")
numToAdd = input("How many of this genre to add?: ")
with open(rotFileName,'a') as r:
r.write((toAdd+'\n')*int(numToAdd))
print("Added {0} of genre: {1} to rotation".
format(numToAdd, toAdd))
while True:
response = input("Add genre?(y/n)")
if response.lower() == 'y':
addGenre()
else:
break
print("Rotation file {0} created".format(rotFile))
|
efb6ec6d64e222f5e2b63fd0084ffa0412f8d9c0 | ceto2016/python | /assignment/2/for/for_assignment_4.py | 87 | 3.96875 | 4 | num = input("Enter any number : ")
count = 0
for i in num:
count += 1
print(count)
|
b9e1ef72e358c63bcdfed9e5e5dd1c004088788a | kyleetaan/git-pythonmasterclass | /src/basics/functionser.py | 1,267 | 3.609375 | 4 | #! python 3
# def center_text(*args, sep = " ", end = "\n", flush = False):
# text = ""
# for arg in args:
# text += str(arg) + sep
# left_margin = (80 - len(text)) // 2
# print(" " * left_margin, text, end=end, flush=flush)
# center_text("hatdog", "footlong", 2, 3, 4, "spam", sep = ", ")
# center_text("spam", "bacon", 2, 3, 4, "spam", sep = ", ")
# center_text("hatdog", "footlong", 2, 3, 4, "spam", sep = ", ")
import tkinter
def parabola(page, size):
for x in range(size):
y = x * x / size
plot(page, x, y)
plot(page, -x, y)
def draw_axes(page):
page.update()
x_origin = page.winfo_width() / 2
y_origin = page.winfo_height() / 2
page.configure(scrollregion = (-x_origin, -y_origin, x_origin, y_origin))
page.create_line(-x_origin, 0, x_origin, 0, fill = "black")
page.create_line(0, -y_origin, 0, y_origin, fill = "black")
def plot(page, x, y):
page.create_line(x, -y, x + 1, -y + 1, fill = "red")
main_window = tkinter.Tk()
main_window.title("Parabola")
main_window.geometry("640x480")
canvas = tkinter.Canvas(main_window, width = 640, height = 480)
canvas.grid(row = 0, column = 0)
draw_axes(canvas)
parabola(canvas, 100)
parabola(canvas, 200)
main_window.mainloop() |
1dcaacc2e454e14c5c5bc1fba3a3374296d741b8 | Dhan-shri/function | /sum_of_limit.py | 367 | 3.828125 | 4 | #Ek function likhiye jo ki ek limit naam ka parameter lega aur 0 se limit
# tak ke beech ke number jo ki 3 aur 5 ke multiples hain unka sum print karega.jaisa ki niche dikhaya gya hai.
def komal(limit):
i=0
sum=0
while i<=limit:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print(sum)
num=int(input("enter a number"))
komal(num)
|
f3cece87ddc8c3da8687b552a08435abfebefe92 | ishuratha/Python- | /pos or neg.py/nk integers.py | 114 | 4.0625 | 4 | x=(int(raw_input))
sum=0
if(x<=0):
print("Enter a positive number"):
for i in range(0,x):
sum=sum+i
print(sum)
|
3709c05a17298124f050590de30f6d3696098255 | enatielly/studying-python | /learn-reading.py | 1,406 | 3.953125 | 4 | #Read the example1.txt
example1 = 'example1.txt'
file1 = open(example1,'r')
#print the Example1.txt
file1.name
#print the mode of file, either 'r' or 'w'
file1.mode
#Read the file
FileContent = file1.read()
FileContent
# Print the file with '\n' as a new line
print(FileContent)
#Type of file content
type(FileContent)
#Close file after finish
file1.close()
#open file using with
with open(example1,'r') as file1:
FileContent = file1.read()
print(FileContent)
# Verify if the file is closed
file1.closed
#See the content of file
print(FileContent)
#Read first four characters
with open(example1,'r') as file1:
print(file1.read(4))
#REad certain amount of characters
with open(example1,'r') as file1:
print(file1.read(4))
print(file1.read(4))
print(file1.read(7))
print(file1.read(15))
#read one line
with open(example1,'r') as file1:
print('first line:' + file1.readline())
with open(example1, "r") as file1:
print(file1.readline(20)) # does not read past the end of line
print(file1.read(20)) # Returns the next 20 chars
#Iterate through the lines
with open(example1, 'r') as file1:
i=0;
for line in file1:
print('Interaction', str(i), ':', line)
i=i+1
#Read all lines and save as a list
with open(example1, 'r') as file1:
FileasList = file1.readlines()
FileasList[0]
FileasList[2]
|
979b2467b2eb8f8e9f7e4d2a148ef207791e70c0 | bitnot/hackerrank-solutions | /master/data-structures/stacks/balanced-brackets/solution.py | 425 | 4 | 4 | match = {'(':')','[':']','{':'}'}
def is_matched(expression):
stack = []
for c in expression:
if c in match:
stack.append(c)
elif len(stack) > 0 and match[stack[-1]] == c:
stack.pop()
else:
return False
return stack == []
t = int(input().strip())
for a0 in range(t):
expression = input().strip()
print("YES" if is_matched(expression) else "NO") |
4d468d8a75ad5ffbcc537a0d280325e3d026db5f | LiquidDuck/Stained-Glass | /main.py | 7,427 | 4.125 | 4 |
"""
This set of code (until the next multi-line comment) defines functions for drawing shapes.
"""
x= 200
#This variable controls the x-coordinate of the colored shapes.
y= 200
#This variable controls the y-coordinate of the colored shapes.
def outline():
#This function makes an black outline. This outline is the black parts of the art. (Otherise the "frame")
color("black")
#The color is changed to black so it matches with the art.
pensize(7)
#Tracy's path width is changed to an "7" to create the bold visual effect as seen in the art.
for i in range(2):
#This loop creates part of the outline
forward(220)
left(90)
forward(20)
left(90)
left(90)
forward(180)
right(90)
forward(220)
right(90)
forward(180)
backward(180)
right(90)
forward(60)
left(110)
forward(165)
right(180)
forward(165)
left(70)
forward(60)
left(126.5)
forward(200)
right(127.5)
forward(160)
right(64)
forward(72)
right(107.5)
forward(127.4)
left(120.5)
forward(105)
left(100)
forward(136)
left(139)
forward(150)
left(115.5)
forward(105)
right(213)
def positioning(x_coordinate, y_coordinate):
#This funtion with certain parameters controls the starting position of one set of colored shapes.
setposition(x_coordinate, y_coordinate)
def colored_shapes():
#This function creates one set of colored shapes (red, purple, blue, yellow, green, and orange shapes.
pensize(1)
#The pensize is changed to one for more accuracy
red_shape()
#Calls out the function "red_shape" and draws the red shape
purple_shape()
#Calls out the function "purple_shape" and draws the purple shape
blue_shape()
#Calls out the function "blue_shape" and draws the blue shape
yellow_shape()
#Calls out the function "yellow_shape" and draws the yellow shape
green_shape()
#Calls out the function "green_shape" and draws the green shape
orange_shape()
#Calls out the function "orange_shape" and draws the orange shape
def red_shape():
#This function creates one of the four red shapes.
color("red")
#The color is changed to red for the red shape.
begin_fill()
#Tracy can now fill in shapes with color.
forward(60)
left(110)
forward(165)
right(180)
end_fill()
#Tracy stops the fill and fills in shapes with color.
def purple_shape():
#This function creates one of the four purple shapes.
color("purple")
#The color is changed to purple for the purple shape.
begin_fill()
#Tracy can now fill in shapes with color.
forward(165)
left(70)
forward(60)
left(126.5)
forward(200)
right(127.5)
end_fill()
#Tracy stops the fill and fills in shapes with color.
def blue_shape():
#This function creates one of the four blue shapes.
color("blue")
#The color is changed to blue for the blue shape.
begin_fill()
#Tracy can now fill in shapes with color.
forward(160)
right(64)
forward(72)
right(107.5)
forward(127.4)
left(120.5)
end_fill()
#Tracy stops the fill and fills in shapes with color.
def yellow_shape():
#This function creates one of the four yellow shapes.
color("yellow")
#The color is changed to yellow for the yellow shape.
begin_fill()
#Tracy can now fill in shapes with color.
forward(105)
left(100)
forward(136)
left(139)
forward(150)
end_fill()
#Tracy stops the fill and fills in shapes with color.
left(115.5)
forward(105)
left(106)
def green_shape():
#This function creates one of the four green shapes.
color("green")
#The color is changed to green for the green shape.
begin_fill()
#Tracy can now fill in shapes with color.
forward(140)
right(139)
forward(95)
right(90)
forward(85)
end_fill()
#Tracy stops the fill and fills in shapes with color.
backward(85)
right(90)
forward(100)
def orange_shape():
#This function creates one of the four orange shapes.
color("orange")
#The color is changed to orange for the green shape.
begin_fill()
#Tracy can now fill in shapes with color.
left(100)
forward(28)
right(75)
forward(70)
right(114)
forward(56)
right(90)
forward(60)
end_fill()
#Tracy stops the fill and fills in shapes with color.
penup()
#For positioning purposes, Tracy now cannot create an visible path
backward(80)
right(90)
pendown()
#Now that Tracy is properly positioned, Tracy can now create an visible path
"""
This set of code (until the next multi-line comment) asks the user for the program speed and controls the program speed.
"""
program_speed=input("How fast do you want the art to be drawn? (slow, medium, or fast): ")
#sets the variable, "program_speed", to an input value. This value controls the speed of the art drawn. Also prompts the user with the messsage "How fast do you want the art to be drawn? (slow, medium, or fast): "
if program_speed=="slow":
#If the user types "slow" then the program speed is 3/11 of it's maximum potential.
speed(3)
elif program_speed=="medium":
#If the user types "medium" then the program speed is 6/11 of it's maximum potential.
speed(6)
else:
#If the user types anything else then the program speed is 11/11 of it's maximum potential.
speed(0)
"""
This set of code (until the next multi-line comment) creates an 20x20 pixel filled-in black square in the center.
"""
penup()
#For positioning purposes, Tracy cannot draw an visible path
forward(20)
left(90)
pendown()
#Tracy now can draw because she is in an correct position
begin_fill()
#Tracy now has the ability to fill in shapes with color.
forward(20)
left(90)
for i in range(4):
#This loop repeats four times for the four sides.
forward(40)
left(90)
forward(40)
left(180)
end_fill()
#Tracy fills in shapes with color then loses her ability to do so.
"""
This set of code (until the next multi-line comment) draws everything except of the starting center square. It calls out numerous functions for positioning and drawing.
"""
for i in range(4):
#This loop repeats 4 times for the 4 panels in the art. It draws the colored shapes and outlines while positioning for the next plane.
penup()
positioning(x, y)
#Calls out the parameter function "positioning(x, y)" to position into drawing the colored shapes.
if x==200:
#This if-else statement changes the x values to approximetly the exact values needed in each iteration of the loop.
x=200.001
else:
x=-200
if y==200:
#This if-else statement changes the x values to approximetly the exact values needed in each iteration of the loop.
y=-200
elif y==-200:
y=-200.001
else:
y=200.001
left(180)
pendown()
#Tracy can now draw
colored_shapes()
#Calls out the function "colored_shapes" to make the colored shapes
outline()
#Calls out the function "outline" to draw an outline
penup()
#Tracy now cannot draw for positioning purposes.
forward(193)
right(90)
forward(55)
left(90)
setposition(0,0)
#Tracy goes to the pitch-black center (0,0) so that she does not "show up" visually on the final product. |
324c0898de3710e13f11b5440830650a78ba83b9 | manishbhatt94/game-of-codes | /gfg/trees/insert_search_bst.py | 1,332 | 4.09375 | 4 | class TreeNode:
def __init__(self, key):
self.val = key
self.left = self.right = None
def insert(root, data):
"""Inserts a new node with `data` as the key in the BST."""
if root is None:
return TreeNode(data)
if data < root.val:
root.left = insert(root.left, data)
elif data > root.val:
root.right = insert(root.right, data)
return root
def search(root, data):
"""Searches for a node with `data` as key in the BST.
Returns the node if found, None otherwise.
"""
if root is None or root.val == data:
return root
if data < root.val:
return search(root.left, data)
return search(root.right, data)
def inorder(root):
"""Prints inorder traversal of binary tree (recursively)."""
if root is None:
return
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
def main():
keys = [100, 20, 500, 30, 25, 10]
root = None
for key in keys:
root = insert(root, key)
inorder(root)
print()
t = int(input("Enter number of searches: "))
for i in range(t):
key = int(input("Enter key to be searched: "))
if search(root, key):
print(key, "found")
else:
print(key, "not found")
if __name__ == "__main__":
main()
|
b9a1ec86a7d0b511619543c79b332d289ec0fb58 | nsossamon/100daysofcode | /Day2/Project2-1.py | 551 | 4 | 4 | # First Pass - Input a two digit number and output the two digits added together
# Number input as a string, digit variables created from subscripting, new digit variables type casted to integers
number = input("Type a two digit number: ")
digit_one = number[0]
digit_two = number[1]
digit_one_new = int(digit_one)
digit_two_new = int(digit_two)
print(digit_one_new+digit_two_new)
# Instructor Solution:
number = input("Type a two digit number: ")
digit_one = number[0]
digit_two = number[1]
result = int(digit_one) + int(digit_two)
print(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.