blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6dae0009db5c974725c375f8b4e427a2fbe0e2a5 | duderman/geek_brains | /python/1/1.py | 209 | 3.796875 | 4 | a = ""
b = 1
str_input = input("SUP?: ")
print("str_input is: ", str_input)
try:
int_input = int(input("SUP(int)?: "))
except ValueError:
print("Not a number")
else:
print("int_input is :", int_input)
|
897b853b0b3b93fba2309d87f994f3c722ad029d | ekateryna-rodina/problem-solving | /pow.py | 545 | 4.25 | 4 | # This problem was asked by Google.
# Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.
# Do this faster than the naive method of repeated multiplication.
# For example, pow(2, 10) should return 1024.
def pow(number, power):
if power == 1:
return number
if power == 0:
return 1
result = pow(number, int(power/2))
if power % 2 == 0:
return result * result
else:
return number * result * result
print(pow(2, 10)) |
a5abda2fc996ee6bdb50cb905d7d435bd6516335 | rajlath/rkl_codes | /LeetCodeContests/others/forest1.py | 1,144 | 3.875 | 4 | '''
Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Input: answers = [10, 10, 10]
Output: 11
Input: answers = []
Output: 0
Note:
answers will have length at most 1000.
Each answers[i] will be an integer in the range [0, 999].
'''
from collections import Counter
class Solution:
def numRabbits(n):
"""
:type answers: List[int]
:rtype: int
"""
cnts = set()
population = 0
for i in answers:
if i == 0 :
population += 1
else:
if i in cnts:continue
else:
cnts.add(i)
population += i+1
return population
sol = Solution()
print(sol.numRabbits([1,0,1,0,1]))
|
004d76fee20f60d48d0f03601ade498bc2d9c73d | mehdislymnv/PragmatechFoundationProject | /HackerRank/python-arithmetic-operators.py | 161 | 3.53125 | 4 | a=int(input())
b=int(input())
t=a+b
c=a-b
v=a*b
print(t)
print(c )
print(v )
""" https://www.hackerrank.com/challenges/python-arithmetic-operators/problem """ |
65cdb4eb3a39bead0049fa93465fe1033cdfcb3d | schatfield/Convert-Student-Object-to-a-String | /convert.py | 3,854 | 4.1875 | 4 | # Use the __str__ and __repr__ magic methods on your class to specify what an object's string representation should be. It's just like the toString() method in JavaScript.
# If you print a Student object. The output would look something like below.
# mike = Student()
# mike.first_name = "Mike"
# mike.last_name = "Ellis"
# mike.age = 35
# mike.cohort_number = 39
# print(mike)
# <__main__.Student object at 0x107133f60>
# But if you specify exactly what string should be returned from __str__ or __repr__, that will print out instead. If you implement the following method on your class...
# class Student:
# def __str__(self):
# return f"{self.full_name}"
# then the output will change
# print(mike)
# Mike Ellis
# Change your class so that any objects created from it will be rerpesented as strings in the following format.
# Mike Ellis is 35 years old and is in cohort 39
class Student:
def __str__(self):
return f'{self.full_name} is {self.age} and is in cohort {self.cohort_number}'
# def first_name is a function that can be accessed as a property because of the @decorater
@property
def first_name(self):
try:
return self.__first_name
# .__first_name is private: it's only available for changing inside this class
except AttributeError:
return ""
@first_name.setter
def first_name(self, first_name):
if type(first_name) is str:
# we are enforcing type rules here. checking for the type- it should be a string here.
self.__first_name = first_name
else:
raise TypeError('Please provide first name as a string. NO NUMBERS ALLOWED I HATE MATH')
@property
def last_name(self):
try:
return self.__last_name
# .__first_name is private: it's only available for changing inside this class
except AttributeError:
return ""
@last_name.setter
def last_name(self, last_name):
if type(last_name) is str:
# we are enforcing type rules here. checking for the type- it should be a string here.
self.__last_name = last_name
else:
raise TypeError('Please provide last name as a string. NO NUMBERS ALLOWED I HATE MATH')
@property
def age(self):
try:
return self.__age
# .__first_name is private: it's only available for changing inside this class
except AttributeError:
return 0
@age.setter
def age(self, age):
if type(age) is int:
# we are enforcing type rules here. checking for the type- it should be a string here.
self.__age = age
else:
raise TypeError('Please provide age as a number. BUT I STILL HATE MATH')
@property
def cohort_number(self):
try:
return self.__cohort_number
# .__first_name is private: it's only available for changing inside this class
except AttributeError:
return 0
@cohort_number.setter
def cohort_number(self, cohort_number):
if type(cohort_number) is int:
# we are enforcing type rules here. checking for the type- it should be a string here.
self.__cohort_number = cohort_number
else:
raise TypeError('Please provide cohort # as a number. BUT I STILL HATE MATH')
@property
def full_name(self):
return f'{self.__first_name} {self.__last_name}'
# this is only one instance,, you just changed the name form shawna eddy
student = Student()
student.first_name = "Shawna"
student.last_name = "Honkey"
print(student.full_name)
student.first_name = "Eddy"
student.last_name = "Not a Honkey"
print(student.full_name)
student.age = 213
print(student.age)
student.cohort_number = 98
print(student.cohort_number)
print(student)
|
9556d69914a7503fa2573289827d7da0a8a6c2d3 | MashuAjmera/Algorithms | /lcs.py | 879 | 3.625 | 4 | # Problem: Longest Common Subsequence
# Author: Mashu Ajmera
# Algorithm: Dynamic Programming
# Leetcode: https://leetcode.com/problems/longest-common-subsequence/submissions/
# GFG: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
class Solution:
def longestCommonSubsequence(self,a,b):
la=len(a)
lb=len(b)
dp=[[0 for i in range(lb+1)] for j in range(la+1)]
print(dp[0])
for i in range(1,la+1):
for j in range(1,lb+1):
if i==0 or j==0:
dp[i][j]=0
elif a[i-1]==b[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i][j-1],dp[i-1][j])
# print(dp[i])
return dp[la][lb]
if __name__=="__main__":
a="GXTXAYB"
b="AGGTAB"
s=Solution()
print(s.longestCommonSubsequence(a,b))
|
8c4202185d9cd80693b4aa5e516e3a3f9858deeb | chavp/MyPython | /ThinkPython/string.py | 309 | 3.78125 | 4 | fruit = 'banana'
print(len(fruit))
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
# slice
print(fruit[:3])
print(fruit[3:])
import string
import random
rans = [random.random() for x in range(10)]
print(rans)
t = [x for x in range(10)]
print(random.choice(t)) |
7747f18cbd2cca9675e8e5cd4e88d66e42f6e4d5 | QIAOZHIBAO0104/My-Leetcode-Records | /1800. Maximum Ascending Subarray Sum.py | 837 | 4.03125 | 4 | '''
https://leetcode.com/problems/maximum-ascending-subarray-sum/
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.
Example 1:
Input: nums = [10,20,30,5,10,50]
Output: 65
Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
'''
'''
Time:O(n)
Space:O(1)
'''
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
res = 0
for i in range(len(nums)):
if i==0 or nums[i-1] >= nums[i]:
cur = 0
cur += nums[i]
res = max(cur, res)
return res
|
9f68a1d5e77682aa4b7247f8c0cca60ecf620244 | BAFurtado/Python4ABMIpea2020 | /classes/class_da_turma.py | 1,479 | 4.4375 | 4 | """ Exemplo de uma class construída coletivamente
"""
class Aluno:
def __init__(self, name):
self.name = name
self.disciplinas = list()
self.email = ''
class Turma:
def __init__(self, name='Python4ABMIpea'):
self.name = name
self.students = list()
def add_student(self, name):
self.students.append(name)
def remove_student(self, name):
self.students.remove(name)
def count_std(self):
return len(self.students)
def list_std(self):
for each in self.students:
print(each)
def __repr__(self):
return '{} tem {} alunos'.format(self.name, self.count_std())
if __name__ == '__main__':
t1 = Turma()
print(type(t1))
print(t1)
t1.add_student('Sirley')
t1.add_student('Paulo Sávio')
t1.add_student('Paulo Martins')
t1.add_student('Godoy')
t1.add_student('William')
t1.add_student('Alan')
t1.add_student('Diego')
t1.add_student('Bruno')
t1.add_student('Douglas')
t1.add_student('Kadidja')
t1.add_student('Marcio')
print(t1)
t1.list_std()
t1.add_student('Bernardo')
t1.remove_student('Bernardo')
t2 = Turma('Econometria')
for aluno in t1.students:
t2.add_student(aluno)
t2.remove_student('Sirley')
t2.remove_student('William')
t2.remove_student('Alan')
print(t2)
t2.list_std()
b = Aluno('Bernardo')
t3 = Turma('100daysofwebPython')
t3.add_student(b)
|
60e26bdfb2f94f1f0df94c7a85ac9c1c81d7cdc4 | zubuxx/University_programming | /List_1/Vector.py | 6,301 | 4.28125 | 4 | # -*- coding: utf-8 -*-
u"""Klasa przechowująca wektor j"""
import random
import math
class Vector():
"""
Class used to represent Vector
...
Attributes
----------
size : int
size of vector(default 3)
numbers : list
vector respresented as a list ex. [x,y,z]
"""
def __init__(self, size=3, numbers=[]):
"""
Parameters:
----------
param size: int
size(dimension) of vector(default 3)
param numbers: list
vector represnted as a list (not required)
"""
self.size = size
self.numbers = numbers
def generate_numbers(self):
"""Generates random parameters of vector
Parameters:
----------
"""
for i in range(self.size-len(self.numbers)):
self.numbers.append(random.randint(-100,100))
def load_vector(self, ls):
"""Loads parameters of vector as a list
Parameters:
----------
param ls: list
List with paramters of vector
"""
try:
if type(ls) == list and len(ls)==self.size:
self.numbers = ls
if len(ls)>self.size:
raise ValueError
if type(ls) != list:
raise NameError("Type of argument is wrong")
except ValueError:
raise ValueError("Incorrect size of lists")
def add_elements(self, list1, list2):
"""Returns list of adding two lists
Parameters:
----------
param list1: list1
The first list to add
param list2L list2
The second list to add
"""
list3 = []
for i in range(len(list1)):
list3.append(list1[i] + list2[i])
return list3
def radd_elements(self, list1, list2):
"""Returns list of substrating two lists
Parameters:
----------
param list1: list1
The first list to add
param list2L list2
The second list to add
"""
list3 = []
for i in range(len(list1)):
list3.append(list1[i] - list2[i])
return list3
def __add__(self, other):
"""Adds two vectors to each other
Parameters:
----------
param other: class Vector object
The second vector to add
"""
try:
if self.size != other.size:
raise ValueError
summed_numbers = self.add_elements(list1=self.numbers, list2=other.numbers)
return Vector(size=len(self.numbers), numbers=summed_numbers)
except ValueError:
raise ValueError ("Size of both list are not equal!")
def __sub__(self, other):
"""Substracts two vectors to each other
Parameters:
----------
param other: class Vector object
The second vector to add
"""
try:
if self.size != other.size:
raise ValueError
summed_numbers = self.radd_elements(list1=self.numbers, list2=other.numbers)
return Vector(size=len(self.numbers), numbers=summed_numbers)
except ValueError:
raise ValueError ("Size of both list are not equal!")
def scale_vector(self, scalar):
"""Multiplies a vector by a number.
Parameters:
----------
param scalar: float
Scalar of a vector
"""
self.numbers = [x * scalar for x in self.numbers]
return Vector(size=len(self.numbers), numbers=self.numbers)
def length(self):
"""Returns length of the vector
Parameters:
----------
"""
square_values = [x**2 for x in self.numbers]
return math.sqrt(sum(square_values))
def sum_of_elements(self):
"""Returns sum of paramters
Parameters:
----------
"""
return sum(self.numbers)
def scalar_multiplying(self, second_vector):
"""Returns a vector that is a product of scalar_multiplying of two vectors
Parameters:
----------
param second_vector: class Vector object
The second Vector of scalar multiplying
"""
try:
if self.size != second_vector.size:
raise ValueError
z = []
for i in range(self.size):
z.append(self.numbers[i]* second_vector.numbers[i])
return Vector(size=self.size, numbers=z)
except ValueError:
raise ValueError ("Size error")
def __str__(self):
"""Returns a string representation of Vector
Parameters:
----------
"""
return f"Vector: {tuple(self.numbers)}\nSize of Vector:{self.size} "
def __getitem__(self, item):
"""Allow to access parameters of a vector as a list
Parameters:
----------
"""
return self.numbers[item]
def __contains__(self, item):
"""Allow to check if there is a paramter with command in.
Parameters:
----------
param item: double
"""
if item in self.numbers:
return True
else:
return False
if __name__ == "__main__":
#Testing package
x = Vector(3, [1,1,1])
y = Vector(3, [1,2,3])
print(x+y)
help(Vector.generate_numbers)
print(1 in x)
|
993aad02c5ac7639ff0a135699968e150a9c02cc | Gramosa/Importacao_teste | /plano_cartesiano/point.py | 2,426 | 4.0625 | 4 | from .functions import *
def check_value(value):
"""
Check if a value is numeric
"""
try:
value / 2
except:
raise Exception('The value need be numeric')
class Point():#Just a 2D point, A(x, y)
"""
This class simulates 2D points, type A(x, y)
There are two atributes:
- x: is a float or integer number, this is the first coordinate for points
- y: is a float or integer number, this is the second coordinate for points
"""
def __init__(self, pos_x, pos_y):
self.x = pos_x
self.y = pos_y
def get_x(self):
"""
Return the x value
"""
return self.x
def get_y(self):
"""
Return the y value
"""
return self.y
def set_x(self, new_x):
"""
Set the value of x for a new numeric value
"""
check_value(new_x)
self.x = new_x
def set_y(self, new_y):
"""
Set the value of y for a new numeric value
"""
check_value(new_y)
self.y = new_y
def is_in_func(self, function):
"""
Parameters
__________
function: is an object from Function class in the archive functions.py
Return True if the point is in function, a point is created using the self
value of x in the function, so if the y value of this new point is the same
of the self point. then these points are the same and return True. else return
False
"""
tester = function.get_point(self.get_x())
if tester.get_y() == self.get_y():
return True
else:
return False
def get_location(self):
"""
Only a visual way to see the coordinates
"""
return f'x={self.get_x()}, y={self.get_y()}'
def get_location_array(self):
"""
Get the coordinates in a list
"""
loc = [self.get_x(), self.get_y()]
return loc
def distance_points(point1, point2):
"""
return a float number, that show the distance between two point in a cartesian plan
using the Pythagorean theorem
"""
delta_x = abs(point1.get_x() - point2.get_x())
delta_y = abs(point1.get_y() - point2.get_y())
dist = (delta_x ** 2 + delta_y ** 2) ** (1/2)
return dist
|
e3daa24bfd640e01fb7401bd949968cedd4a9b9a | johnromanishin/Python | /Old Python Programs/ps54.py | 1,302 | 4.0625 | 4 | # Problem set 2
# Name: John Romanishin
# Collabortors: R Tharu
# Time: 6:00
# Enumerate possible answers starting at 1 McNugget
# For each possible answer n,
# Check if there exists x, y, and z such that 6x+9y+20z = n
# (this can be done by looking at all feasible combinations of x, y, and z)
# If not, n is a possible answer, save n
# When you have found six consecutive values of n that have solutions,
# the last answer that was saved is the correct answer
#
# Problem 3.
#
# Write an iterative program that finds the largest number of McNuggets it is not possible to buy.
#
# Hint: Your program should follow the outline above.
# 20 McNuggets. So, for example, it is possible to buy 15 McNuggets
# (with one package of 6 and one package of 9), but not 16 McNuggetsn
# x = 0
# y = 0
# z = 0
def ispossible(n):
for x in range(0,n):
for y in range(0,n):
for z in range(0,n):
if 6*x + 9*y + 20*z == n:
return True
return False
# above is the definition of a checking function
count = 0
a = True
n = 1
while count < 6:
test = ispossible(n)
if test == True:
count = count+1
elif test == False:
count = 0
n = n+1
print "largest number of McNuggets it is not possible to buy =",(n-7)
|
d1f28bd8346d9591ef93265ad9b03b73ddf3b3b9 | pvinod480/msit | /set6.py | 3,861 | 3.671875 | 4 | class Players:
def __init__(self):
self.players ={}
try:
fobj = open("players.txt","r")
for line in fobj:
fields = line.split()
name = fields[0]
players = fields[1:]
for player in players:
self.addElement(name,player)
except:
pass
def addElement(self,name,player):
if name in self.players:
if player not in self.players[name]:
self.players[name].append(player)
else:
self.players[name] = [player]
def removePlayer(self,name,player):
if name in self.players:
if player in self.players[name]:
self.players[name].remove(player)
def save(self):
fobj = open("players.txt","w")
for name in self.players:
fobj.write(name+" ")
for player in self.players[name]:
fobj.write(player+" ")
fobj.write("\n")
fobj.close()
def show(self):
for name in self.players:
print(name,end = " ")
for player in self.players[name]:
print(player,end=" ")
print()
def mostPopularPlayer(self):
populars = {}
finals = []
for players in self.players.values():
for name in players:
if name in populars:
populars[name] = populars[name]+1
else:
populars[name] = 1
for name,count in populars.items():
finals.append((count,name))
finals.sort()
return finals[-1][-1]
def __bool__(self):
if len(self.players) == 0:
return False
else:
return True
def __eq__(self,obj):
if self.players == obj.players:
return True
else:
return False
def __setitem__(self,name,player):
if name in self.players:
if player not in self.players[name]:
self.players[name].append(player)
else:
self.players[name] = [player]
def __getitem__(self,name):
return self.players[name]
def __add__(self,obj):
self.addElement(*obj)
return Players(self)
p1= Players()
p1.show()
#print(dir(p1))
'''if p1:
print("True")
else:
print("false")'''
p2= Players()
p2.show()
'''p1["jade"]='amber'
p1["jade"] = "ravi"
print(p1["jade"])'''
#p1.show()
'''p2.players.clear()
print(p1.players)
print()
print(p2.players)
if p2:
print("True")
else:
print("False")'''
'''if p1==p2:
print("Equal")
else:
print("Not Equal")'''
print(p1+p2)
'''p1.addElement("raj","ambrose")
p1.addElement("milton","dravid")
p1.addElement("chirag","steve")
p1.addElement("veena","panting")
p1.addElement("jane","steve")
p1.addElement("raj","steve")
p1.addElement("sam","mark")
p1.addElement("sam","panting")
p1.addElement("sam","steve")
p1.addElement("sam","chris")
p1.addElement("raj","dravid")
p1.addElement("sam","richards")
p1.addElement("jane","ambrose")
p1.addElement("karthik","virat")
p1.removePlayer("sam","steve")'''
#p1.show()
#p1.save()
#print("Most popular player is "+p1.mostPopularPlayer())
'''
r={}
for name in self.players:
for player in self.players[name]:
if name in r:
if player not in r[name]:
r[name].append(player)
else:
r[name] = [player]
for name in obj.players:
for player in self.players[name]:
if name in r:
if player not in r[name]:
r[name].append(player)
else:
r[name] = [player]
'''
|
09245803e096e4b461a699f99f3b4a2a4b667ab7 | dylanlee101/leetcode | /code_week21_914_920/sum_of_leaves.py | 896 | 4 | 4 | '''
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
isLeafNode = lambda node: not node.left and not node.right
def dfs(node):
ans = 0
if node.left:
ans += node.left.val if isLeafNode(node.left) else dfs(node.left)
if node.right and not isLeafNode(node.right):
ans += dfs(node.right)
return ans
return dfs(root) if root else 0 |
5cd79ad9eac30ead789f5bbbd9205ba3169a53c9 | ngzhian/codeinsert | /grablines.py | 995 | 3.890625 | 4 | import sys
def grab(filename, start, end=None):
"""Returns a lines `start` to `end` of a file
Line numbers are 1-based and end is inclusive
If end is None, return just one line
"""
start = int(start)
end = start if end is None else int(end)
with open(filename) as f:
lines = []
f_iter = iter(f)
# since start is 1-based, we don't want to lose any lines in the file
# e.g. start is 1, we shouldn't call next at all
for skip in range(start - 1):
next(f_iter)
for skip in range(end - start + 1): # end is inclusive so add 1
lines.append(next(f_iter))
return lines
if __name__ == '__main__':
if len(sys.argv) < 3:
sys.exit('Usage: %s <filename> <start> [end]' % sys.argv[0])
if len(sys.argv) == 3:
lines = grab(sys.argv[1], sys.argv[2])
elif len(sys.argv) > 3:
lines = grab(sys.argv[1], sys.argv[2], sys.argv[3])
if (lines):
print(lines)
|
72105d7e79a9a77595ef64127ca9253d82598ee3 | liuqun5050/myScript | /计算1到100的偶数和.py | 133 | 3.609375 | 4 | # 计算1到100之间偶数之间的和
i = 2
result = 0
while i <= 100:
result += i
i += 2
print("总和为:%d" %result)
|
dadc119f98306971563a56e5ea3ca7479b65f31b | AntoineAugusti/katas | /prologin/2014/15_balloons.py | 715 | 3.625 | 4 | # http://www.prologin.org/training/challenge/demi2014/balloons
from sys import stdin
data = [int(x) for x in stdin.readline().split()]
nbBalloons = data[0]
nbCustomers = data[1]
# Get data for balloons
balloons = []
for i in range(nbBalloons):
balloons.append([int(x) for x in stdin.readline().split()])
# Get data from customers
customers = []
for i in range(nbCustomers):
customers.append([int(x) for x in stdin.readline().split()])
money = 0
for customer in customers:
for balloon in balloons:
# If the balloon meets the customer's need
if customer[0] <= balloon[0] and balloon[0] <= customer[1]:
# Buy it
money += balloon[1]
# Remove it from the pool
balloons.remove(balloon)
print money |
36b2fdd3b6b7ac296aa304cbef1518cff18eef43 | Jschnore/hort503 | /assignment2/ex8.py | 383 | 3.546875 | 4 | formatter = "{} {} {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"I got something",
"to type cuz",
"This python thing takes",
"me some time"
))
|
7b3f65b63548856ae574fba472666ba580c44e35 | ztony123/codeHouse | /yl_python_code/python_code/A_Python 总文件/继承/一个小题目.py | 410 | 3.953125 | 4 | class Parent(object):
x = 1
class Son1(Parent):
pass
class Son2(Parent):
pass
print(Parent.x, Son1.x, Son2.x) # Son1.x Son2.x 是去找父类的参数
Son1.x = 2
print(Parent.x, Son1.x, Son2.x) # Son1.x = 2 是给Son1添加了一个参数 Son2.x 是去找父类的参数
Parent.x = 3
print(Parent.x, Son1.x, Son2.x) # x 先会去找本身是否有这个参数 没有再去父类里面找 |
a5d7de3a132d7119ee8682384c55f22ad4f90792 | lxconfig/UbuntuCode_bak | /algorithm/leetcode/backtracking/07-组合总和Ⅱ.py | 2,215 | 3.703125 | 4 |
"""
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
"""
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
"""减法思维
"""
size, res, path = len(candidates), [], []
candidates.sort()
def dfs(candidates, begin, target, res, path):
# 终止条件
if target == 0:
res.append(path[:])
return
for i in range(begin, size):
if candidates[i] > target:
break
if i > begin and candidates[i] == candidates[i - 1]:
continue
path.append(candidates[i])
dfs(candidates, i+1, target - candidates[i], res, path)
path.pop()
dfs(candidates, 0, target, res, path)
return res
def combinationSum2_1(self, candidates: List[int], target: int) -> List[List[int]]:
"""加法思维
"""
size, count, res, path = len(candidates), 0, [], []
candidates.sort()
def dfs(candidates, begin, count, res, path):
if count == target:
res.append(path[:])
return
for i in range(begin, size):
if candidates[i] > target:
break
if candidates[i] + count > target:
continue
if i > begin and candidates[i] == candidates[i - 1]:
continue
# 做选择
path.append(candidates[i])
# 回溯
dfs(candidates, i+1, sum(path), res, path)
# 撤销
count -= candidates[i]
path.pop()
dfs(candidates, 0, count, res, path)
return res
if __name__ == "__main__":
s = Solution()
candidates, target = [10,1,2,7,6,1,5], 8
print(s.combinationSum2(candidates, target)) |
373a729fb9666bb0cf8d2afadf2ab146a96dfc9c | brauliotegui/SPICED | /Week_08/poker_player.py | 1,058 | 3.75 | 4 | class Player:
'''
The class Player is a blueprint for a poker player.
Parameter
-------
name: Name of the player
stack_size: Amount of chips the player currently has
'''
buy_in = 1000
limit = 100
def __init__(self, name, maximum_bet):
self.name = name
self.__maximum_bet = maximum_bet
self.stack_size = self.buy_in
self.current_bet = 0
def raise_bet(self):
self.current_bet += self.__maximum_bet
self.stack_size -= self.__maximum_bet
return self.current_bet
def get_stack_size(self):
print(self.stack_size)
def vocalize_max_bet(self):
return f'The maximum I am allowed to bet is {self.__maximum_bet}'
@classmethod
def increase_limit(cls, increase):
cls.limit = cls.limit + increase
@staticmethod
def conversion_to_dollar():
return 'One chip is worth 3 dollars'
def __repr__(self):
return f'Player {self.name} is betting {self.current_bet} and his stack size is {self.stack_size}'
|
c026eff9cb3d493306e82edd56770341818ae9fb | Isko00/ICT | /task1/24.py | 329 | 4.09375 | 4 | import math
seconds = 0
print("Enter number of days: ")
seconds += int(input()) * 24 * 60 * 60
print("Enter number of hours: ")
seconds += int(input()) * 60 * 60
print("Enter number of minutes: ")
seconds += int(input()) * 60
print("Enter number of seconds: ")
seconds += int(input())
print("Time: " + str(seconds) + " seconds") |
3a7f57dabaf19c9e58aac77c99dff694d2ebd673 | zby981207/PythonDemon | /Chapter2/2-3.py | 193 | 3.8125 | 4 | char = input("Your customized character: ")
print(char, char, '', sep=char)
print(char, sep='')
print(char, char, '', sep=char)
print(char, ' ', char, sep='')
print(char, char, '', sep=char)
|
f4de0c91b3e7224e3dd634c8362ddae6b55a6f02 | yoongyoonge/python_100Q | /code/2. data_graph/026.py | 395 | 3.5625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
# 예제 025에서 저장한 CSV 파일을 불러와서 데이터프레임으로 변환
df = pd.read_csv('./code/data/bok_statistics_CD_2.csv', header=0, index_col=0)
print(df.head())
print('\n')
# 막대 그래프 그리기
df.plot(kind='bar')
plt.show()
df['CD_rate'].plot(kind='bar')
plt.show()
df['change'].plot(kind='bar')
plt.show() |
e4ce29954355e352818c31f9605e7a25fa648a2f | dianedef/P3-Aidez-MacGyver | /models/player.py | 2,233 | 4.03125 | 4 | """This module defines classes and functions related to the hero in the game."""
from copy import copy
from models.position import Position
class Player:
"""This class represents the player's sprite on the screen."""
def __init__(self, pseudo, bag, position, jeu):
"""This function initialize a player with a name, an empty bag and a
position."""
self.pseudo = pseudo
self.bag = bag
self.position = position
self.jeu = jeu
def move(self, direction):
"""The function sees if the direction chosen by the player is valid,
moves the player to it if so and checks if he is on the exit position,
or reverse to the previous position otherwise."""
prev_position = copy(self.position)
self.position.update(direction)
if self.position in self.jeu.labyrinth.paths:
self.exit()
else:
self.position = prev_position
self.catch_item()
print(self.position)
def catch_item(self):
"""This function verifies if there is an object on the position of the
player, changes its status and position if so, and deletes it from the
objects list."""
if self.position.xy in self.jeu.labyrinth.item_positions:
print("Well done, you got " + str(self.bag) + " object(s).")
self.bag += 1
self.jeu.labyrinth.item_positions[self.position.xy].status = "catched"
self.jeu.labyrinth.item_positions[self.position.xy].position = Position(
self.bag, 15)
del self.jeu.labyrinth.item_positions[self.position.xy]
def exit(self):
"""This function verifies if the player is at the end of the labyrinth
and if its bag is full, so that the game is lost or won."""
if self.position == self.jeu.labyrinth.end:
if self.bag == 3:
print(
"Well done, you managed to put the keeper asleep and get out of the maze ! You won !")
self.jeu.running = False
else:
print("Oops, there was still objects to catch... You lost !")
self.jeu.running = False
else:
pass
|
86e8e74f7ac8460e1753a480fa853012ffb21915 | cyxy7757/PythonDemo | /FirstPython.py | 2,684 | 4.09375 | 4 | # msg = 'Hello world python'
# print(msg)
s = set([1,2,3,4,4,5])
print(s)
# 定义一个求绝对值的函数,当入参错误时,给出提示。
# def my_abs(x):
# if not isinstance(x,(int, float)):
# raise TypeError("类型错啦,只能整数或者浮点数"")
# if x >= 0:
# return x
# else:
# return -x
# print(my_abs(-5))
# print(my_abs('a'))
# 默认参数
def enroll(name, gender, age = 8, city = 'Beijing'):
print('name:',name)
print('gender:',gender)
print('age:',age)
print('city:',city)
# print(enroll('lili','girl'))
# print(enroll('dick','boy',9,'henbei'))
print(enroll('jack','boy', city='henbei'))
# 定义默认参数要牢记一点:默认参数必须指向不变对象!
# def add_end(l=None):
# if l is None:
# l = []
# l.append('End')
# return l
# 可变参数
# def calc(*numbers):
# sum = 0
# for number in numbers:
# sum = sum + number*number
# return sum
# # print(calc())
# # print(calc(1,2,3,4))
# # *nums表示把nums这个list的所有元素作为可变参数传进去
# nums = [4,5,6,7]
# print(calc(*nums))
# 关键字参数
# 关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict
def person(name, age, **kw):
print('name:',name,'age:',age,'others:',kw)
#print(person('Michael',20))
# print(person('Bob',22,city = 'Beijing'))
# person('Adam', 45, gender='M', job='Engineer')
#extra = {'city':'Beijing', 'job':"English"}
#print(person("Jack",24,city = extra["city"], Job = extra["job"]))
# 简化写法
# **extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra
#print(person("Jack",24,**extra))
# 命名关键字参数
# 检查是否有city和job参数
# def person(name, age, **kw):
# if "city" in kw:
# pass
# if 'job' in kw:
# pass
# print('name:', name, 'age:', age, 'other:', kw)
# 如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和job作为关键字参数
# def person(name, age, *, city, job):
# print(name, age, city, job)
# print(person('Jack', 24,city = 'shenzhen',job = 'coder'))
# 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
# def person(name, age, *args, city, job):
# print(name, age, args, city, job)
# 递归函数
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print(fact(5))
|
ddcbf35e6d58d77a53a04f2245c30be101785d59 | Brandsma/LangTechFinal | /Question_Classifier.py | 2,030 | 3.515625 | 4 | # Find the Root
# Look at Dependencies of Root
# Find {'nsubj', 'dobj', 'prep', 'attr', 'ccomp'} (Question words can also be attributes)
# With those dependencies find the subject and object
# What's type of the question
#Does root have a nsubj:
# NO:
# list/show/print/ hwatadffaheve
# YES:
# iS 'is' the root the first word in the snetences?
#YES: yes/no
#NO:
# Do you find "how many" "how much"
# YES:
#Count question
# NO:
# Do you find "which" "who" "what" "How" etc.
#YES:
#Which question
#NO:
# Did you find the dep acomp("How big is china?")
#YES:
# How big question (How far above sea level)
#NO:
# Handle Special cases (could you give me the population of the Netherlands?)
# Otherwise raise error
from enum import Enum
class QuestionTypes(Enum):
whichQuestion = 1
countQuestion = 2
listQuestion = 3
YesNoQuestion = 4
HowBigQuestion = 5
def isCountQuestion(question):
question = question.lower()
return question.find("how many") != -1 or question.find("how much") != -1
def isWhichQuestion(question):
question = question.lower()
return question.find("which") != -1 or question.find("who") != -1 or \
question.find("what") != -1 or (question.find("how") != -1 and question.find("big") == -1)
# How large
def findRoot(doc):
for token in doc:
if token.dep_ == 'ROOT':
return token
def hasDependency(token, dep):
for child in token.children:
if child.dep_ == dep:
return True
return False
def classifyQuestion(question, parsedQuestion):
root = findRoot(parsedQuestion)
if not hasDependency(root, "nsubj"):
return QuestionTypes.listQuestion
elif root == parsedQuestion[0]:
return QuestionTypes.YesNoQuestion
elif isCountQuestion(question):
return QuestionTypes.countQuestion
elif isWhichQuestion(question):
return QuestionTypes.whichQuestion
elif hasDependency(root, "acomp"):
return QuestionTypes.HowBigQuestion
else:
raise ValueError
|
99aa7a3e58453f93a35c4376425077865e66652c | paolobarto/Sudoku_Solver | /square.py | 1,910 | 3.6875 | 4 | import numpy as np
from board import Board
from squareVal import findSquareVal,possibleValue
import importlib
class Square(Board):
def __init__(self,x,y):
self.x=x
self.y=y
super().__init__()
self.value=self.array[x][y]
#This will be used to grab the array at each column, row, and box.
self.row=(self.array[x])
self.column=([row[y] for row in self.array])
box=Box(self.x,self.y)
self.box=(box.boxy)
#^this is used to contain the entire array of the row,col,box
self.possibleRow=possibleValue(self.row)
self.possibleColumn=possibleValue(self.column)
self.possibleBox=possibleValue(self.box)
#^this is used to contain the values of the possible values in each area
def setVal(self,val):
self.value=val
self.array[self.x][self.y]=val
def printRow(self):
print(self.row)
def printColumn(self):
print(self.column)
def printBox(self):
print(self.box)
def returnValue(self):
return self.value
def findValidNumbers(self):
one=set(self.possibleRow)
two=set(self.possibleColumn)
three=set(self.possibleBox)
one=(one.intersection(two)).intersection(three)
return list(one)
def validToInt(self):
temp=self.findValidNumbers()
temp=map(str,temp)
temp=''.join(temp)
temp=int(temp)
self.setVal(temp)
#Added Class in Assingment 4, Although could be completed with direct logic, this allows for me
#to make more complicated code in the future
class Box(Board):
def __init__(self,x,y):
super().__init__()
self.box=findSquareVal(x,y,self.array)
def _get_box(self):
return self.box
boxy=property(_get_box) |
8975625122e93a50b8cd5280db961055c4ed5967 | Armindo123/prog1 | /avaliacao/avaliacao2/avaliacao2ex2.py | 812 | 4.3125 | 4 | #ordenar 3 valores do maior para o menor
valor1 = float(input("Valor 1: "))
valor2 = float(input("Valor 2: "))
valor3 = float(input("Valor 3: "))
if valor1 == valor2 or valor1 == valor3 or valor2 == valor3:
print("Introduza valores diferentes")
elif valor1 > valor2 and valor2 > valor3:
print("{} > {} > {}".format(valor1, valor2, valor3))
elif valor1 > valor2 and valor3 > valor2:
print("{} > {} > {}".format(valor1, valor3, valor2))
elif valor2 > valor3 and valor1 > valor3:
print("{} > {} > {}".format(valor2, valor1, valor3))
elif valor2 > valor3 and valor3 > valor1:
print("{} > {} > {}".format(valor2, valor3, valor1))
elif valor3 > valor1 and valor1 > valor2:
print("{} > {} > {}".format(valor3, valor1, valor2))
else:
print("{} > {} > {}".format(valor3, valor2, valor1))
|
cb1f4faf899e13a265df0ccf58fb50356cfb68c2 | Cat9Yuko/python- | /Python14字符串格式化.py | 695 | 3.96875 | 4 | #coding:utf-8
#字符串连接
str1='good'
str2='bye'
print str1+str2
#字符串和字符串变量连接
print 'vert'+str1
print str1+'and'+str2
#字符串和数字连接
#不能直接把字符串和数字直接相加
#用str()把数字转换成字符串
print 'My age is'+str(18)
#或
num =18
print 'My age is '+str(num)
#%对字符串进行格式化
#输出时,%d会被%后面的值替换
#%d只能替换整数,格式化小数用%f,想保留两位小数在f前加条件:%.2f
#%s可以替换一段字符串
num=18
print 'My age is %d' %num
print 'Price is %.3f' %4.99
name='Crossin'
print '%s is a good teacher.'%name
print 'Today is %s.' %'Friday' |
79ce1e0713b2f86a92c57db171d4ca7f19e3cb9f | frankShih/TimeSeriesVectorization | /vectorization/rdp.py | 2,913 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
The Ramer-Douglas-Peucker algorithm roughly ported from the pseudo-code provided
by http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
"""
from math import sqrt
def distance(a, b):
return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def point_line_distance(point, start, end):
if (start == end):
return distance(point, start)
else:
n = abs(
(end[0] - start[0]) * (start[1] - point[1]) - (start[0] - point[0]) * (end[1] - start[1])
)
d = sqrt(
(end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2
)
return n / d
def rdp(points, epsilon):
"""
Reduces a series of points to a simplified version that loses detail, but
maintains the general shape of the series.
"""
dmax = 0.0
index = 0
for i in range(1, len(points) - 1):
d = point_line_distance(points[i], points[0], points[-1])
if d > dmax:
index = i
dmax = d
if dmax >= epsilon:
results = rdp(points[:index+1], epsilon)[:-1] + rdp(points[index:], epsilon)
else:
results = [points[0], points[-1]]
return results
if __name__ == "__main__":
import matplotlib.pyplot as plt
import numpy as np
import os
import rdp
def angle(dir):
"""
Returns the angles between vectors.
Parameters:
dir is a 2D-array of shape (N,M) representing N vectors in M-dimensional space.
The return value is a 1D-array of values of shape (N-1,), with each value
between 0 and pi.
0 implies the vectors point in the same direction
pi/2 implies the vectors are orthogonal
pi implies the vectors point in opposite directions
"""
dir2 = dir[1:]
dir1 = dir[:-1]
return np.arccos((dir1*dir2).sum(axis=1)/(
np.sqrt((dir1**2).sum(axis=1)*(dir2**2).sum(axis=1))))
tolerance = 70
min_angle = np.pi*0.22
filename = os.path.expanduser('/media/shih/新增磁碟區/ZiWen_packup/drivers/drivers/1/1.csv')
points = np.genfromtxt(filename).T
print(len(points))
x, y = points.T
# Use the Ramer-Douglas-Peucker algorithm to simplify the path
# http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
# Python implementation: https://github.com/sebleier/RDP/
simplified = np.array(rdp.rdp(points.tolist(), tolerance))
print(len(simplified))
sx, sy = simplified.T
# compute the direction vectors on the simplified curve
directions = np.diff(simplified, axis=0)
theta = angle(directions)
# Select the index of the points with the greatest theta
# Large theta is associated with greatest change in direction.
idx = np.where(theta>min_angle)[0]+1
fig = plt.figure()
ax =fig.add_subplot(111)
ax.plot(x, y, 'b-', label='original path')
ax.plot(sx, sy, 'g--', label='simplified path')
ax.plot(sx[idx], sy[idx], 'ro', markersize = 10, label='turning points')
ax.invert_yaxis()
plt.legend(loc='best')
plt.show()
|
5742096d50a153f525f4cc12a2e6bd2e38f360e6 | SKosztolanyi/Python-exercises | /48_Reading a text file and averageing the converted number.py | 611 | 4.03125 | 4 | # Use the file name mbox-short.txt as the file name
# In this assignment I work with another .txt file and I want to extract a number as a float from every line that starts with:
# Then I calculate the average of all the numbers I gained.
# I only print the final value
fname = raw_input("Enter file name: ")
fh = open(fname)
num=0
total=0
avg=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
elif line.startswith("X-DSPAM-Confidence:"):
pos=line.find(":")
num+=1
total += float(line[pos+1: ])
avg=total/num
print "Average spam confidence: " + str(avg) |
1da643ba961aed5094988005c912387da6f29e4f | kktn/DeepLearning | /chap3/activation_function.py | 1,477 | 3.578125 | 4 | import numpy as np
import matplotlib.pylab as plt
def step_function(x):
return np.array(x > 0, dtype=np.int)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def relu(x):
return np.maximum(0, x)
def identity_function(x):
return x
def neuron():
# initial layer -> first layer
X = np.array([1.0, 0.5])
W1 = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
B1 = np.array([0.1, 0.2, 0.3])
print("X.shape is {0}".format(X.shape))
print("W1.shape is {0}".format(W1.shape))
print("B1.shape is {0}".format(B1.shape))
A1 = np.dot(X, W1) + B1
print("A1 is {0}".format(A1))
Z1 = sigmoid(A1)
print("Z1 is {0}".format(Z1))
# first layer -> second layer
W2 = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])
B2 = np.array([0.1, 0.2])
A2 = np.dot(Z1, W2) + B2
Z2 = sigmoid(A2)
print("Z2 is {0}".format(Z2))
# second layer -> output layer
W3 = np.array([[0.1, 0.3], [0.2, 0.4]])
B3 = np.array([0.1, 0.2])
A3 = np.dot(Z2, W3) + B3
Y = identity_function(A3)
print("Result: {0}".format(Y))
def softmax(a):
exp_a = np.exp(a)
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
# Step function
# x = np.arange(-5.0, 5.0, 0.1)
# y = step_function(x)
# plt.plot(x, y)
# plt.ylim(-0.1, 1.1)
# plt.show()
# Sigmoid function
# x = np.arange(-5.0, 5.0, 0.1)
# y = sigmoid(x)
# plt.plot(x, y)
# plt.ylim(-0.1, 1.1)
# plt.show()
# ReLU function
# print(relu(1))
neuron() |
a15fe0a35fec9be762616a6b42ec42750294a144 | Fedalto/n-puzzle | /solver.py | 4,324 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tabuleiro, sys
from heuristica import cebola,manhattan
from nodo import Nodo, movimento
class Solver (object):
def __init__(self, n=3, tabini=None,heuristica=cebola):
self.heuristica = heuristica(n)
self.lista_pesos = []
self.n = n
self.hash_tab = {}
self.hash_nodos = {}
# Se usuário não forçou um tabuleiro inicial, cria um aleatório
if not tabini:
tabini = tabuleiro.random_tab(self.n)
else:
tabini = tabuleiro.Tabuleiro(tabini)
# Calcula peso do primeiro tabuleiro
peso = self.heuristica.calcula(tabini)
# Adiciona o tabuleiro na lista de hashs
self.hash_tab[hash(str(tabini.get_tab()))] = 0
# Cria um nodo
nodoini = Nodo(tabini, None, peso, None, 0)
# Adiciona nodo a lista de nodos
self.adiciona_nodo(nodoini)
def adiciona_nodo(self, nodo):
""" Cada item da lista possui [peso,nodo] """
#self.lista_nodos.append([nodo.peso,nodo])
if self.hash_nodos.has_key(nodo.peso):
self.hash_nodos[nodo.peso].append(nodo)
else:
self.hash_nodos[nodo.peso] = [nodo]
if nodo.peso not in self.lista_pesos:
self.lista_pesos.append(nodo.peso)
self.ordena_lista_pesos()
#self.insere_ordenado(nodo.peso)
def insere_ordenado(self,peso):
for i, v in enumerate(self.lista_nodos):
if peso <= v:
self.lista_nodos.insert(i,peso)
break
else:
self.lista_nodos.append(peso)
def ordena_lista_pesos(self):
self.lista_pesos.sort()
def _cmp_nodos(self,x,y):
return x[0]-y[0]
def prox_nodo (self):
idx = self.lista_pesos[0]
todosnodos = self.hash_nodos[idx]
if len(todosnodos) == 1: del self.lista_pesos[0]
return todosnodos.pop(0)
def gera_filhos (self, nodo):
# -> faz copias dos nodos
# -> aplica os movimentos as nodos (right, left,
# up, down)
# -> Recalcula o peso do nodo.
# -> Insere filhos na lista
for nome_mov, mov in movimento.items():
if not nodo.tab.swap_test(mov):
continue
else:
novo_tab = nodo.tab.copy()
novo_tab.swap(mov)
htab = hash(str(novo_tab.get_tab()))
if htab in self.hash_tab and self.hash_tab[htab] < nodo.altura+1:
continue
self.hash_tab[htab] = nodo.altura+1 # Altura do pai +1
# Jogada INVERTIDA
# Tudo e' relativo ao observador
jogada = {'ondetava': novo_tab.zero_pos,
'ondefoi' : nodo.tab.zero_pos }
if self.heuristica.__name__ == "cebola":
incaltura = nodo.tab.n/2
else:
incaltura = 1
delta = self.heuristica.calcula(novo_tab, nodo.peso, jogada)
novo_nodo = Nodo(novo_tab, nodo, (nodo.peso + delta)+incaltura,
nome_mov, nodo.altura+incaltura)
self.adiciona_nodo(novo_nodo)
def magic (self):
""" You want some magic??? Resolve tudo... """
nodo = self.prox_nodo()
while self.heuristica.terminou(nodo):
self.gera_filhos(nodo)
nodo = self.prox_nodo()
print self.print_solucao(nodo)
return self.get_solucao(nodo)
def get_solucao(self,nodo):
solution = []
while nodo.pai:
solution.append(nodo)
nodo = nodo.pai
solution.append(nodo)
solution.reverse()
return (len(solution),solution)
def print_solucao (self, nodo):
###
#
# Aki faz tratamento de subida dos nodos, empilhamento dos movimentos
# e impressao do resultado, alem do cafe.
print "Construindo solução..."
solution = []
while nodo.pai:
solution.append(nodo)
nodo = nodo.pai
solution.append(nodo)
solution.reverse()
print '\nSOLUCAO\n'
for step in solution:
print step.tab
print
print "Número de movimentos necessários =",len(solution)
|
4dd2f4c4ca8c46552db11f3120834f348c342278 | lanjar17/Python-Project | /Chapter 5/Latihan 1/Latihan 1_2.py | 613 | 3.875 | 4 | # program hitung syarat kelulusan
# input nilai
BahasaIndonesia = int(input('Nilai Bahasa Indonesia :'))
Matematika = int(input('Nilai Matematika :'))
IPA = int(input('Nilai IPA :'))
if(BahasaIndonesia < 0 or BahasaIndonesia > 100):
print('Maaf input ada yang tidak valid')
elif(Matematika < 0 or Matematika > 100):
print('Maaf input ada yang tidak valid')
elif(IPA < 0 or IPA > 100):
print('Maaf input ada yang tidak valid')
# Status Kelulusan
elif(BahasaIndonesia > 60 and Matematika > 70 and IPA >60):
print('Status Kelulusan : LULUS')
else:
print('Status Kelulusan : TIDAK LULUS')
|
bc625f7de2e191283a64b02eb9c26f6013cb0ebc | ayoubabounakif/edX-Python | /count_input_character.py | 156 | 3.734375 | 4 | def count_char(string, char):
count = 0
for x in string.lower():
if x == char.lower():
count = count + 1
return count
|
a21234ea6a5b6d77ff6fff28fb7b9fe7defe50f9 | grbalmeida/hello-python | /useful-modules/csv/main.py | 1,468 | 3.84375 | 4 | import csv
import sys
argv = sys.argv
def print_customers():
with open('./customers.csv', 'r') as file:
data = csv.reader(file)
next(data)
for customer in data:
name, lastname, email, phone = customer
print(f'Name: {name}')
print(f'Lastname: {lastname}')
print(f'Email: {email}')
print(f'Phone: {phone}')
print()
def dict_reader():
with open('./customers.csv', 'r') as file:
data = csv.DictReader(file)
for customer in data:
print(f"Name: {customer['Name']}")
print(f"Lastname: {customer['Lastname']}")
print(f"Email: {customer['Email']}")
print(f"Phone: {customer['Phone']}")
print()
def new_file():
with open('./customers.csv', 'r') as file:
data = [customer for customer in csv.DictReader(file)]
with open('./new-customers.csv', 'w') as file:
write = csv.writer(
file,
delimiter=',',
quotechar='"',
quoting=csv.QUOTE_ALL
)
keys = data[0].keys()
keys = list(keys)
write.writerow(
[
keys[0],
keys[1],
keys[2],
keys[3]
]
)
for customer in data:
write.writerow(
[
customer['Name'],
customer['Lastname'],
customer['Email'],
customer['Phone']
]
)
if '-print_customers' in argv:
print_customers()
if '-dict_reader' in argv:
dict_reader()
if '-new_file' in argv:
new_file()
|
941fb86b32b13a5da17f970859e0fde3d9a3ebee | Khachatur86/FredBaptisteUdemy | /checkio/long_repeat.py | 616 | 3.640625 | 4 | def long_repeat(line):
count = 1
max_count = 0
for index in range(len(line) - 1):
if line[index] == line[index + 1]:
count += 1
if count > max_count:
max_count = count
if line[index] != line[index + 1]:
count = 1
return max_count
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert long_repeat('sdsffffse') == 4, "First"
assert long_repeat('ddvvrwwwrggg') == 3, "Second"
assert long_repeat('abababaab') == 2, "Third"
assert long_repeat('') == 0, "Empty"
|
ff1a3175751aa93dce84c249bfb1f077cf13f822 | supragya1107/monopoly | /monopoly_game.py | 26,252 | 3.765625 | 4 | """Ever played MONOPOLY?
This is a short code written for the game.
Game asks for the number of players in the beginning.
You should choose more than one player.
MADE BY-SUPRAGYA UPADHYAY :)
"""
###############################################################################
class Player:
money=15.000 #starting money
def __init__(self,string):
self.name=string
#self.avatar=avatar
self.properties={"Brown":[0],"LightBlue":[0],"Magenta":[0],"Orange":[0],
"Red":[0],"Yellow":[0],"Green":[0],"Blue":[0],"Services":[0]}
self.plist=[]
bankrupt=False
position=0
in_jail=False
###############################################################################
no_of_players=0
players=[] #list that contains objects of the class Player
###############################################################################
Place ={0 :"GO!!", #These are the loacations on the board.
1 :"Bhubhaneshwar", #There are 40 in total.
2 :"Patna", #
3 :"Ranchi", #They are in groups of 3.
4 :"Income Tax", #
5 :"Air transport", #Groups are BROWN,LIGHTBLUE,MAGENTA,ORANGE,RED,YELLOW,GREEN,BLUE
6 :"Shimla", #
7 :"Lucknow", #If you own all 3 of a single colour the rent on each site doubles.
8 :"Chance", #
9 :"Jodhpur", #Also you become eligible to build hotel on any of those sites.
10:"JAIL(Just Visiting)", #
11:"Bhopal", #rent on a service will be proportional to number of services owned.
12:"Gas services", #
13:"Gandhinagar", #You get +$2.000 for completing round across te board.
14:"Allahbad", #
15:"Railway services", #You can mortgage any of your site for 90% of its cost but to unmortgage you need to pay full of its price again.
16:"Varanasi", #
17:"Pune", #
18:"Chance", #
19:"Kanpur", #
20:"FREE PARKING", #
21:"Chandigarh", #
22:"Chance", #
23:"Ghaziabad", #
24:"Jaipur", #
25:"Telecom services", #
26:"Ahmedabad",
27:"Udaipur",
28:"Electricity services",
29:"Indore",
30:"GO TO JAIL!!",
31:"Kolkata",
32:"Chennai",
33:"Chance",
34:"Hyderabad",
35:"Railway services",
36:"Chance",
37:"Mumbai",
38:"Banglore",
39:"Delhi",}
###############################################################################
status={"GO!!" :["can't buy"], #first is status, then price, rent, rent after hotel, price of hotel
"Chance" :["can't buy"],
"Income Tax" :["can't buy"],
"Patna" :["not bought",0.600,0.150,0.450,0.800], #
"Bhubhaneshwar" :["not bought",0.600,0.150,0.450,0.800], # brown
"Ranchi" :["not bought",0.650,0.200,0.500,1.000], #
"Air transport" :["not bought",2.000,0.250], #
"Electricity services" :["not bought",2.000,0.250], #
"Railway services" :["not bought",2.000,0.250], #
"Water services" :["not bought",2.000,0.250], # services
"Gas services" :["not bought",2.000,0.250], #
"Telecom services" :["not bought",2.000,0.250], #
"Shimla" :["not bought",1.000,0.300,0.800,1.200], #
"Lucknow" :["not bought",1.000,0.300,0.800,1.200], # light blue
"Jodhpur" :["not bought",1.200,0.350,0.900,1.500], #
"JAIL(Just Visiting)" :["can't buy"],
"Bhopal" :["not bought",1.400,0.450,1.200,1.800], #
"Gandhinagar" :["not bought",1.400,0.450,1.200,1.800], # magenta
"Allahbad" :["not bought",1.600,0.550,1.300,2.000], #
"Varanasi" :["not bought",1.800,0.600,1.500,2.500], #
"Pune" :["not bought",1.800,0.600,1.500,2.500], # orange
"Kanpur" :["not bought",2.000,0.700,1.700,3.000], #
"FREE PARKING" :["can't buy"],
"Chandigarh" :["not bought",2.200,0.800,2.000,3.500], #
"Ghaziabad" :["not bought",2.200,0.800,2.000,3.500], # red
"Jaipur" :["not bought",2.400,0.900,2.200,4.000], #
"Ahmedabad" :["not bought",2.600,1.100,2.400,4.500], #
"Udaipur" :["not bought",2.600,1.100,2.400,4.500], # yellow
"Indore" :["not bought",2.800,1.200,2.600,5.000], #
"GO TO JAIL!!" :["can't buy"],
"Kolkata" :["not bought",3.000,1.400,2.800,5.500], #
"Chennai" :["not bought",3.000,1.400,2.800,5.500], # green
"Hyderabad" :["not bought",3.200,1.500,3.000,6.000], #
"Banglore" :["not bought",3.500,1.600,3.200,6.500], #
"Mumbai" :["not bought",3.500,1.600,3.200,6.500], # blue
"Delhi" :["not bought",4.000,1.800,3.500,7.000] #
}
###############################################################################
"""You will receive 90% of money of the property you mortgage.
But you won't be able to charge rent from the property"""
def mortgage(i):
available=[]
for site in players[i].plist:
if status[site][0]!="mortgaged":
available.append(site)
print("Your unmortgaged properties are",",".join(available))
site=input("Enter the property you want to mortgage : ")
if (site.capitalize() in players[i].plist) and (status[site.capitalize()][0]=="bought"):
status[site.capitalize()][0]="mortgaged"
players[i].money+=(status[site.capitalize()][1]) * (0.9)
print("Your property",site,"has been mortgaged succesfully")
elif (site.capitalize() in players[i].plist)and (status[site.capitalize()][0]=="hotel"):
print("You have a hotel on this site. First sell the hotel then mortgage")
ask=input("Sell the hotel? ")
if ask in "yesYES":
players[i].money+=status[site.capitalize()][4] * (0.9)
status[site.capitalize()][0]="set"
elif (site.capitalize() in players[i].plist) and (status[site.capitalize()][0]=="set"):
status[site.capitalize()][0]="mortgaged"
players[i].money+=(status[site.capitalize()][1]) * (0.9)
print("Your property",site,"has been mortgaged succesfully")
elif (site.capitalize() in players[i].plist) and (status[site.capitalize()][0]=="mortgaged"):
print("This property of yours has already been mortgaged")
else:
print("Mentioned site not in your property\nPlease enter a valid site")
print("Updated balance : $%.3f"%players[i].money)
print()
###############################################################################
"""If you are in jail you can pay $1.000 to get out or try to roll doubles. """
def jail(i):
from random import randint
print("You are in jail currently")
print("Roll doubles or pay $1.000 to get out")
ask=input("Enter your choice(\"pay\" or \"roll\" : ")
if ask.lower() in "roll":
die1=randint(1,6)
die2=randint(1,6)
print("Dice rolled and the numbers are",die1,die2)
if die1==die2:
print("You are now released from jail")
players[i].in_jail=False
players[i].position+=die1+die2
action(players[i].position,i)
else:
print("Wait for another chance")
elif ask.lower() in "pay":
if players[i].money>=0.500:
players[i].money-=0.500
print("Roll the dice")
input()
die1=randint(1,6)
die2=randint(1,6)
print("Dice rolled and the numbers are",die1,die2)
players[i].position+=die1+die2
if players[i].position>39:
players[i].position-=40
players[i].money+=2.000
if players[i].position!=0:
print("You recieved $2.000 for passing GO!!")
print("\nDice rolled and numbers are",die1,die2,end="")
input()
action(players[i].position,i)
else:
print("You do not have enough money to pay!!")
print("Mortgage your property or roll for the doubles")
answer=input("Enter your choice : ")
if answer in "mortgage":
mortgage(i)
jail(i)
elif answer in "roll":
die1=randint(1,6)
die2=randint(1,6)
print("Dice rolled and the numbers are",die1,die2)
if die1==die2:
print("You are now released from jail")
players[i].in_jail=False
players[i].position+=die1+die2
action(players[i].position,i)
else:
print("Wait for another chance")
###############################################################################
"""You can build hotel on a site if you have the complete set of it.
Hotels will increase the amount of rent charged on a site."""
def hotel(i):
sites=[]
for site in players[i].plist:
if status[site][0]=="set":
sites.append(site)
if sites:
print("You can build hotel on ",",".join(sites))
site=input("Enter the site you wish to build hotel on ")
if site in sites:
if players[i].money>=status[site][4]:
status[site][0]="hotel"
players[i].money-=status[site][4]
print("Successfully built a hotel on",site)
else:
print("You do not have enough money to build a hotel on this site")
else:
print("You can't build hotel on any of your properties")
###############################################################################
"""To unmortgage a site you must pay exaclty the amount as paid while buying the site.
Rent will again be charged."""
def unmortgage(i):
sites=[]
for site in players[i].plist:
if status[site][0]=="mortgaged":
sites.append(site)
if sites:
print("Mortgaged sites: ",",".join(sites))
a=input("Enter the property you want to unmortgage: ")
b=a.capitalize()
if b in sites:
if players[i].money>=status[b][1]:
print("Property unmortgaged successfully")
players[i].money-=status[b][1]
print("Updated balance : $"+"%.3f"%players[i].money)
status[b][0]="bought"
else:
print("You do not have enough money to unmortgage")
else:
print("Entered site not in your properties")
else:
print("You have no mortgaged sites.")
###############################################################################
def chance(i):
from random import randint
print("Roll the dice again!! press Enter")
input()
die1=randint(1,6)
die2=randint(1,6)
print("Dice rolled and the numbers obtained are :",die1,die2)
input()
total=die1+die2
if total==2:
print("Beauty contest won worth $2.500")
players[i].money+=2.500
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==3:
print("Profit in business worth $1.500")
players[i].money+=1.500
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==4:
print("Fire in factories. Loss of $2.000")
players[i].money-=2.000
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==5:
print("Advance to Delhi")
players[i].position=39
action(39,i)
elif total==6:
print("Income Tax return $1.000")
players[i].money+=1.00
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==7:
print("GO TO JAIL!!")
players[i].position=10
players[i].in_jail=True
elif total==8:
print("Maintenance fee. For each hotel pay $1.000")
for prop in players[i].plist:
if status[prop][0]=="hotel":
players[i].money-=1.000
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==9:
print("Pay each player $0.500")
for player in players:
if player!=players[i]:
player.money+=0.500
players[i].money-=0.500
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==10:
print("Recieve from each player $0.500")
for player in players:
if player!=players[i]:
player.money-=0.500
players[i].money+=0.500
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==11:
print("Investment Loss of $2.000")
players[i].money-=2.00
print("Updated Balance : $"+"%.3f"%players[i].money)
elif total==12:
print("Investment Profit of $3.000")
players[i].money+=3.00
print("Updated Balance : $"+"%.3f"%players[i].money)
###############################################################################
def action(k,i):
print("\nYou have reached",Place[players[i].position])
if(status[Place[k]][0]=="not bought"):
if players[i].money>=status[Place[k]][1]:
confirm=input("This place is unsold yet. Do you wish to buy it?(if you press enter it is \"Yes\")")
if confirm in "yesYES":
status[Place[k]][0]="bought"
players[i].money-=status[Place[k]][1]
if k==1 or k==2 or k==3:
players[i].properties["Brown"][0]+=1
players[i].properties["Brown"].append(Place[k])
players[i].plist.append(Place[k])
elif k==6 or k==7 or k==9:
players[i].properties["LightBlue"][0]+=1
players[i].properties["LightBlue"].append(Place[k])
players[i].plist.append(Place[k])
elif k==11 or k==13 or k==14:
players[i].properties["Magenta"][0]+=1
players[i].properties["Magenta"].append(Place[k])
players[i].plist.append(Place[k])
elif k==16 or k==17 or k==19:
players[i].properties["Orange"][0]+=1
players[i].properties["Orange"].append(Place[k])
players[i].plist.append(Place[k])
elif k==21 or k==23 or k==24:
players[i].properties["Red"][0]+=1
players[i].properties["Red"].append(Place[k])
players[i].plist.append(Place[k])
elif k==26 or k==27 or k==29:
players[i].properties["Yellow"][0]+=1
players[i].properties["Yellow"].append(Place[k])
players[i].plist.append(Place[k])
elif k==31 or k==32 or k==34:
players[i].properties["Green"][0]+=1
players[i].properties["Green"].append(Place[k])
players[i].plist.append(Place[k])
elif k==37 or k==38 or k==39:
players[i].properties["Blue"][0]+=1
players[i].properties["Blue"].append(Place[k])
players[i].plist.append(Place[k])
elif k==5 or k==12 or k==15 or k==25 or k==28 or k==35:
players[i].properties["Services"][0]+=1
players[i].properties["Services"].append(Place[k])
players[i].plist.append(Place[k])
print("\nYou have successfully bought",Place[k],"for $","%.3f"%status[Place[k]][1])
print("\nYour updated balance is $"+"%.3f"%players[i].money)
print("Your properties contain :",",".join(players[i].plist))
else:
print("You will pass by")
elif status[Place[k]][0]=="bought":
for player in players:
if player.plist.count(Place[k])==1 and player!=players[i]:
if k==5 or k==12 or k==15 or k==25 or k==28 or k==35:
rent=(status[Place[k]][2])*(player.properties["Services"][0]) #rent = rent on one service * no of services bought
print(players[i].name,"should pay $","%.3f"%rent,"as rent to",player.name)
player.money+=rent
players[i].money-=rent
print("Updated balance :\n",player.name,": $"+"%.3f"%player.money,"\n",players[i].name,": $"+"%.3f"%players[i].money)
else:
rent=(status[Place[k]][2]) #rent = rent as specified on the card
print(players[i].name,"should pay $",rent,"as rent to",player.name)
player.money+=rent
players[i].money-=rent
print("Updated balance :\n",player.name,": $","%.3f"%player.money,"\n",players[i].name,": $"+"%.3f"%players[i].money)
elif status[Place[k]][0]=="set":
for player in players:
if player.plist.count(Place[k])==1 and player!=players[i]:
print("Player",player.name,"has completed the set of these properties. Rent charged will be twice.")
rent=(status[Place[k]][2])*2 #rent = twice as specified on the card
print(players[i].name,"should pay $","%.3f"%rent,"as rent to",player.name)
player.money+=rent
players[i].money-=rent
print("Updated balance :\n",player.name,": $"+"%.3f"%player.money,"\n",players[i].name,": $"+"%.3f"%players[i].money)
elif status[Place[k]][0]=="hotel":
for player in players:
if player.plist.count(Place[k])==1 and player!=players[i]:
print("Player",player.name,"has a hotel on this property.")
rent=status[Place[k]][3] #rent = as specified for a hotel
print(players[i].name,"should pay","%.3f"%rent,"as rent to",player.name)
player.money+=rent
players[i].money-=rent
print("Updated balance :\n",player.name,": $"+"%.3f"%player.money,"\n",players[i].name,": $"+"%.3f"%players[i].money)
elif status[Place[k]][0]=="can't buy":
if Place[k]=="Chance":
chance(i)
elif Place[k]=="Income Tax":
print("You will be charged $2.000 as Income tax")
players[i].money-=2.000
print("Updated balance: $"+"%.3f"%players[i].money)
elif Place[k]=="GO TO JAIL!!":
print("You have to go to jail")
players[i].position=10
players[i].in_jail=True
elif Place[k]=="FREE PARKING":
print("You are awarded $3.000 for reaching FREE PARKING")
players[i].money+=3.000
print("Updated balance : $"+"%.3f"%players[i].money)
elif Place[k]=="GO!!":
print("You recieved twice the passing money for landing on GO!!")
players[i].money+=4.000
print("Updated balance : $"+"%.3f"%players[i].money)
for key in players[i].properties.keys():
sets=[]
if players[i].properties[key][0]==3:
sets.append(key)
status[players[i].properties[key][1]][0]="set"
status[players[i].properties[key][2]][0]="set"
status[players[i].properties[key][3]][0]="set"
if sets:
print("You have the set of "+",".join(sets))
###############################################################################
def turn(i):
from random import randint
global no_of_players
print("\n\t\t\t\tCHANCE OF PLAYER",players[i].name)
if not players[i].in_jail and not players[i].bankrupt:
a=input("Press Enter to roll the dice")
if a.lower().startswith("go"): #cheats for the game XD
b=a.split(" ") #write go and number of place you want to go eg. "go 1" will take you to bhuvaneshwar
players[i].position=int(b[1])
action(players[i].position,i)
elif a.lower().startswith("money"):
b=a.split(" ")
players[i].money+=int(b[1])
else:
die1=randint(1,6)
die2=randint(1,6)
players[i].position+=(die1+die2)
if players[i].position>39:
players[i].position-=40
players[i].money+=2.000
if players[i].position!=0:
print("You recieved $2.000 for passing GO!!")
print("\nDice rolled and numbers are",die1,die2,end="")
input()
action(players[i].position,i)
elif players[i].in_jail:
players[i].position=10
jail(i)
if players[i].money<0:
print("You are out of money")
p=0 #a count of worth of properties owned by player(i)
for site in players[i].plist:
if status[site][0]=="hotel":
p+=status[site][1]+status[site][4]
elif status[site][0]=="bought" or status[site][0]=="set":
p+=status[site][1]
if players[i].money+(p*0.9)<0:
print("You do not have enough properties to clear your debt. You are now bankrupt.")
players[i].bankrupt=True
for site in players[i].plist:
status[site][0]="not bought"
players.remove(players[i])
no_of_players-=1
return i-1
else:
while players[i].money<0:
mortgage(i)
j="o"
while j not in "4. finish turn":
print("\n1.Build hotel\n2.Mortgage\n3.Unmortgage\n4.Finish Turn")
j=input("Enter your choice : ")
if not j:
j="o"
continue
elif j.lower() in "1. build hotel":
hotel(i)
elif j.lower() in "2. mortgage":
mortgage(i)
elif j.lower() in "3. unmortgage":
unmortgage(i)
return i
###############################################################################
def game():
global no_of_players
try:
no_of_players=int(input("Enter the number of players : "))
except ValueError:
print("No integer obtained!!retry.")
game()
else:
if no_of_players<=1:
print("Try again with more players")
game()
j=0
while j<no_of_players:
n=input("Enter the player name : ")
if not n:
print("Can't leave blank")
else:
players.append(Player(n))
j+=1
i=0
while True:
if len(players)==1:
print("Winner is :",players[0].name)
exit()
i=turn(i)
i+=1
if i>=no_of_players:
i=0
if __name__=="__main__":
game()
|
94393011973525b51044bde6d694bb925a81e49b | shukad333/leet-python | /dynamicprogramming/MaxSumCombinationFromTwoArrays.py | 1,120 | 3.890625 | 4 | """
Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both the arrays such that no two elements have the same index and no two consecutive numbers can be selected from a single array. Find the maximum sum possible of above-chosen numbers.
Examples:
Input : arr1[] = {9, 3, 5, 7, 3}, arr2[] = {5, 8, 1, 4, 5}
Output : 29
Select first, third and fivth element from the first array.
Select the second and fourth element from the second array.
Input : arr1[] = {1, 2, 9}, arr2[] = {10, 1, 1}
Output : 19
Select last element from the first array and first element from the second array.
"""
class Solution:
def maxSum(self,arr1,arr2):
n = len(arr1)
dp = [[0]*2 for i in range(n)]
for i in range(0,n):
if i==0:
dp[i][0] = arr1[i]
dp[i][1] = arr2[i]
continue
dp[i][0] = max(dp[i-1][0],dp[i-1][1]+arr1[i])
dp[i][1] = max(dp[i-1][1],dp[i-1][0]+arr2[i])
return max(dp[n-1][0],dp[n-1][1])
sol = Solution()
print(sol.maxSum([9, 3, 5, 7, 3],[5, 8, 1, 4, 5]))
|
1c7181d7d8c7a89e6e37a4f650894048ddd64047 | evgenylahav/exercism_python | /matrix/testing.py | 225 | 3.53125 | 4 | class A:
def __init__(self, number):
self.n = number
a = A(1)
b = A(1)
print(id(a) == id(b)) # False
L1 = [1, 2, 3]
L2 = [1, 2, 3]
print(id(L1) == id(L2)) # False
c = 1
d = 1
print(id(c) == id(d)) # True |
b5bb25579949bdbb1d9ed352c5726d01e54c3238 | Burnin9Bear/PythonCode | /20181214Day1/counter.py | 494 | 3.765625 | 4 | num1 = int(input("请输入第一个数字"))
num2 = int(input("请输入第二个数字"))
num3 = int(input("请输入第三个数字"))
sum = num1 + num2 +num3
if sum >100000:
print("您输入的三个数的和忒大了")
elif sum >10000:
print("您输入的三个数的和挺大")
elif sum >1000:
print("您输入的三个数的和有点大")
elif sum >100:
print("您输入的三个数的和不算大")
elif sum <=100:
print("您输入的三个数的和忒小了") |
1656931eabcdb86412f5bd5f991ded6ed622cff0 | boppanaravisastry/Examples-of-python-programs | /feet-inches.py | 268 | 4.4375 | 4 | #Unit conversion
#Convert units from feet to inches.
feet = float(input('# of feet?'))
print (feet, "feet is:\t", feet*12.0, "inches")
#Convert units from inches to feet.
inches = float(input('# of inches?'))
print (inches, "inches is:\t", inches/12.0, "feet")
|
34a2318b42d5f2bb3425644cf4b116e50511f90f | itsanshulverma/du-cs-undergrad-course | /Semester3/PythonSEC/Practicals/_04/ques_4.py | 298 | 4.21875 | 4 | # Input
num = int(input("Enter a number greater than or equal to 10: "))
if num >= 10: #Check if num satisfies condtn.
_set = set() #Create empty set
while num != 0:
_set.add(num%10)
num = int(num/10)
print("Set: ", _set)
else:
print("Oops! Number is less than 10") |
c161866326941efac9f2424ca5a3127a7b531e44 | gmg0829/pythonLearninng | /basic/listDemo.py | 1,060 | 3.828125 | 4 | hello = (1, 2, 3)
li = [1, "2", [3, 'a'], (1, 3), hello]
li.append("pytaya")
li.insert(0,'balabala')
li.pop()
li.pop(0)
li.remove('2')
#访问元素
print(li[3],li[-2])
#切片访问
#格式: list_name[begin:end:step]begin 表示起始位置(默认为0),end 表示结束位置(默认为最后一个元素),step 表示步长(默认为1)
print(li[0:2],li[:2])
print(li[0:3:2])
#嵌套访问
print(li[-2][1])
#删除元素
del li[3]
print(li)
#操作符
# + 用于合并列表
# * 用于重复列表元素
# in 用于判断元素是否存在于列表中
# for ... in ... 用于遍历列表元素
a=[1,2,3]+[4,5,6]
print(a)
print(a*2)
print(7 in a)
for k in a:
print(k)
#len(list) 列表元素个数 max(list) 列表元素中的最大值 min(list) 列表元素中的最小值 list(seq) 将元组转换为列表
#https://mp.weixin.qq.com/s?__biz=MjM5ODE1NDYyMA==&mid=2653387604&idx=1&sn=3dbac8356f723f31e927cd3382d33a19&chksm=bd1cc3478a6b4a517dcf7ef86aeeb327be64104c60ad2d5c2438208cb0a32161e3779684a421&mpshare=1&scene=1&srcid=0912pOM35RxmK8SrPLwvPn5Q#rd
|
8472fb6598e09c17f02ccad8059b64f916de565f | ganhan999/ForLeetcode | /中等55. 跳跃游戏.py | 1,703 | 4.28125 | 4 | """
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
"""
"""
如果某一个作为 起跳点 的格子可以跳跃的距离是 3,那么表示后面 3 个格子都可以作为 起跳点。
可以对每一个能作为 起跳点 的格子都尝试跳一次,把能跳到最远的距离 不断更新。
如果可以一直跳到最后,就成功了。
"""
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_distance = 1#至少为1
length = len(nums)
index = 0
while index+1 <= max_distance:#因为索引肯定要少1的
max_distance = max(max_distance, nums[index] + index+1)
if max_distance >= length:
return True
else:
index += 1
return True if index >= length else False
"""
同上
贪心算法
刷新每次最长距离
"""
#大神做法2
class Solution:
def canJump(self, nums: List[int]) -> bool:
n, rightmost = len(nums), 1
for i in range(n):
if i+1 <= rightmost:
rightmost = max(rightmost, i +1 + nums[i])
if rightmost >= n :
return True
return False
|
67924b9236d42dc2dbc21e6d5297a9255ff93f90 | tmurray19/BSc-Archives | /Python/Past Assignments/CS211/gaussian.py | 5,436 | 4.21875 | 4 | #student I.D: 15315901
"""A class for Gaussian integers
A Gaussing integer is a complex number of the form a+bi where a and b are integers"""
"""write the code for the class Gaussian which models Gaussian integers. Your code should have:
1. A constructor so that we can create objects of the class Gaussian as follows:
z = Gaussian(4, -2)
The arguments to the constructor should be converted to ints using the int function.
2. A string representation using the __str__ method.
3. Methods __eq__ and __neq___ for equality testing.
4. Methods for doing arithmetic on Gaussian integers, in particular The following methods should be implemented:
5. __add__ and __radd__ for addition.
6. __sub__ and __rsub__ for subtraction.
7. __mul__ and __rmul__ for multiplication.
8. For division, we cannot expect the quotient of two Gaussian integers to be a new Gaussian integer, so we will have to implement the methods __floordiv__ (for ‘integer’ division) and __mod__ for remainder.
For each of the arithmetic operations, one argument is allowed to be an int. The ‘integer’ division is defined in the following way:
if z = a + bi and w = c + di, then we can form the quotient in the complex numbers:
z/w = (a + bi) / (c + di) = ((a + bi)(c − di)) /(c^2 + d^2) = (ac + bd)/(c^2 + d^2) + ((ad − bc)/ (c^2 + d^2)) i
Now we let the ‘integer’ quotient of z and w be q = m+ni, where m is the closest
integer to (ac+bd)/(c^2 +d^2) and n is the closest integer to
(ad−bc)/(c^2+d^2)
Then we can define the remainder by as r = z − q*w."""
class Gaussian:
"""A class for modeling gaussian integers"""
def __init__(self, a, b):
"""initialises the two values for the gaussian integer"""
self.a=int(a)
self.b=int(b)
def __str__(self):
"""for representing the gaussian integer as a string"""
if self.a>=0 and self.b>=0:
return("{}+{}i".format(self.a, self.b))
if self.a>0 and self.b<0:
return("{}{}i".format(self.a, self.b))
if self.a<0 and self.b>0:
return("{}+{}i".format(self.a, self.b))
if self.a<0 and self.b<0:
return("{}{}i".format(self.a, self.b))
def __eq__(self, other):
"""for testing if two gaussian integers are the same"""
return self.a == other.a and self.b == other.b
def __add__(self, other):
"""[a+bi]+[c+di]=[a+c,bi+di]"""
if type(other) == int or type(other) == float:
other = Gaussian(other,other)
l = self.a + other.a
r = self.b + other.b
return Gaussian(l,r)
def __radd__(self, other):
if type(other) == int or type(other) == float:
other = Gaussian(other,other)
return other.__add__(self)
def __sub__(self, other):
"""[a+bi]-[c+di]=[a-c,bi-di]"""
if type(other)==int or type(other)==float:
other=Gaussian(other, other)
l=self.a - other.a
r=self.b - other.b
return Gaussian(l,r)
def __rsub__(self, other):
if type(other) == int or type(other) == float:
other = Gaussian(other, other)
return other.__sub__(self)
def __mul__(self, other):
"""[a+bi]*[c+di]=[((a*c)-(b*d))+((a*d)+(b*d))]"""
if type(other)==int or type(other)==float:
other=Gaussian(other, other)
l=((self.a * other.a)-(self.b*other.b))
r=((self.a*other.b)+(self.b*other.a))
return Gaussian(l,r)
def __rmul__(self, other):
if type(other)==int or type(other)==float:
other=Gaussian(other,other)
return other.__mul__(self)
def __floordiv__(self, other):
"""
if
z = a + bi
and
w = c + di
then we can form the quotient in the complex numbers:
z/w = (a + bi) / (c + di) = ((a + bi)(c − di)) /(c^2 + d^2) = (ac + bd)/(c^2 + d^2) + ((ad − bc)/ (c^2 + d^2))i
Now we let the ‘integer’ quotient of z and w be q = m+ni, where m is the closest
integer to (ac+bd)/(c^2 +d^2) and n is the closest integer to (ad−bc)/(c^2+d^2)
Then we can define the remainder by as r = z − q*w.
"""
if type(other)==int or type(other)==float:
other=Gaussian(other,other)
l=((self.a*other.a)+(self.b*other.b))/((other.a**2)+(other.b**2))
r=((self.a*other.b)-(self.b*other.a))/((other.a**2)+(other.b**2))
m=int(l)
n=int(r)
Gaussian.q=Gaussian(m,n)
return Gaussian.q
def __mod__(self, other):
"""for finding the remainder for division
r= z - q*w, z=a+bi, q=m+ni, w=c+di"""
if type(other)==int or type(other)==float:
other=Gaussian(other, other)
return self - (Gaussian.q * other)
def test_equality():
assert Gaussian.__eq__(Gaussian(1,1),Gaussian(3,5))==False
def test_addition():
assert Gaussian.__add__(Gaussian(1,1),Gaussian(3,5)) == Gaussian(4,6)
def test_subtraction():
assert Gaussian.__sub__(Gaussian(1,1),Gaussian(3,5)) == Gaussian(-2,-4)
def test_multiplication():
assert Gaussian.__mul__(Gaussian(1,1),Gaussian(3,5)) == Gaussian(-2,8)
def test_floordivision():
assert Gaussian.__floordiv__(Gaussian(1,1),Gaussian(3,5)) == Gaussian(0,0)
def test_mod():
assert Gaussian.__mod__(Gaussian(1,1),Gaussian(3,5)) == Gaussian(1,1)
first = Gaussian(1,1)
second = Gaussian(3,5)
print(first,",", second)
print("{} == {} = {}".format(first, second, first==second))
print("{} + {} = {}".format(first,second,first+second))
print("{} - {} = {}".format(first,second, first-second))
print("{} * {} = {}".format(first, second, first*second))
print("{} // {} = {}".format(first, second, first//second))
print("{} % {} = {}".format(first, second, first%second))
test_equality()
test_addition()
test_subtraction()
test_multiplication()
test_floordivision()
test_mod()
|
8c0377b70b902e6e61351869a4378b4c2c50a3a7 | TheKillerAboy/programming-olympiad | /Python_Solutions/CodeForces/#579/Remove_the_Substring_(easy_version).py | 636 | 3.546875 | 4 | def get_all_lefts(word,substring):
if len(substring) == 0:
yield ((len(word),word),)
else:
if substring[0] not in word:
yield (-1,)
else:
for i in range(len(word)):
if word[i] == substring[0]:
for sub_sequance in get_all_lefts(word[i+1:],substring[1:]):
yield ((i,word[:i]),*sub_sequance)
if __name__ == '__main__':
word = input('')
substring = input('')
maxNum = 0
for lefts in map(list,get_all_lefts(word,substring)):
if -1 in lefts:
continue
print(lefts)
print(maxNum) |
12860fa37b1ec617847a69f89b332f65d5ebad8e | sylvain-01/Python_Games | /rock_paper_scissors/rock_paper_scissors.py | 3,610 | 4.15625 | 4 | import tkinter
from tkinter import *
from random import randint
# initialize window where game will be played
root = tkinter.Tk()
root.geometry("1500x300")
root.title("Rock, Paper, Scissors")
root.config(bg="white smoke")
# Define top label name
label_top = tkinter.Label(root, text="Rock, Paper, Scissors Game: select your choice below with your mouse ")
label_top.grid(row=0, columnspan=6)
label_top.config(font="aerial 20 italic", bg="light green", bd=10, padx=270)
# variables
Result = StringVar()
player_number = IntVar()
# Function to play game and show result
def show_message(user_pick, comp_pick):
if user_pick == 1 and comp_pick == 1:
Result.set("Draw,you both selected Rock")
elif user_pick == 2 and comp_pick == 2:
Result.set("Draw,you both selected Paper")
elif user_pick == 3 and comp_pick == 3:
Result.set("Draw,you both selected Scissors")
elif user_pick == 1 and comp_pick == 2:
Result.set("You Lost! Comp picked paper, you chose rock. Paper beats rock!")
elif user_pick == 1 and comp_pick == 3:
Result.set("You Win! You chose rock, comp picked scissors. Rock beats scissors!")
elif user_pick == 2 and comp_pick == 1:
Result.set("You Win! You chose paper, comp picked rock. Paper beats rock!")
elif user_pick == 2 and comp_pick == 3:
Result.set("You Lost! Comp picked scissors, you chose paper. Scissors beats paper!")
elif user_pick == 3 and comp_pick == 1:
Result.set("You Lost! Comp picked rock, you chose scissors. Rock beats scissors!")
elif user_pick == 3 and comp_pick == 2:
Result.set("You Win! You chose scissors, Comp picked paper. Scissors beats paper!")
# Define entry label to show results
entry_label_top = tkinter.Label(root, textvariable=Result)
entry_label_top.grid(row=2, columnspan=6)
entry_label_top.config(font="roman 25 bold", fg="indian red", bd=25)
# Definition for computer choice
def comp():
comp_pick = randint(1, 3)
return comp_pick
# functions for user to make choice via pressing the button
def rock_clicked():
user_pick = 1
comp_pick = randint(1, 3)
show_message(user_pick, comp_pick)
def paper_clicked():
user_pick = 2
comp_pick = randint(1, 3)
show_message(user_pick, comp_pick)
def scissors_clicked():
user_pick = 3
comp_pick = randint(1, 3)
show_message(user_pick, comp_pick)
# Functions for reset and close
def reset():
player_number.set("")
Result.set("")
def close():
root.destroy()
# Define rock / paper / scissors / buttons
button_rock = tkinter.Button(root, text="Rock", command=lambda: rock_clicked())
button_rock.grid(row=1, column=0)
button_rock.config(font="aerial 20 bold", bg="dim grey", padx=30, pady=10, bd=10)
button_paper = tkinter.Button(root, text="Paper", command=lambda: paper_clicked())
button_paper.grid(row=1, column=2)
button_paper.config(font="aerial 20 bold", bg="cyan", padx=30, pady=10, bd=10)
button_scissors = tkinter.Button(root, text="Scissors", command=lambda: scissors_clicked())
button_scissors.grid(row=1, column=4)
button_scissors.config(font="aerial 20 bold", bg="gold", padx=30, pady=10, bd=10)
# Define reset and close button
reset_button = tkinter.Button(root, text="Reset", command=reset)
reset_button.grid(row=3, column=1, sticky=W)
reset_button.config(font="aerial 15 bold", bg="sandy brown", padx=30, pady=10, bd=10)
close_button = tkinter.Button(root, text="Close", command=close)
close_button.grid(row=3, column=3, sticky=E)
close_button.config(font="aerial 15 bold", bg="red", padx=30, pady=10, bd=10)
root.mainloop()
|
1d2caa0d9d87f80e40b3c5644c0854e94886e0c0 | mathvolcano/leetcode | /1268_suggestedProducts.py | 2,352 | 3.609375 | 4 | """
1268. Search Suggestions System
https://leetcode.com/problems/search-suggestions-system/
"""
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
# Binary search
# [1] Sort the products lexicographically
# [2] For each prefix of searchWord Perform a binary search on each prefix
# to find a match
# [3] Once a match is found then backtrack to the left until no match is found.
# [4] Check that the next 3 products have matches and append to results
# Time complexity is O(p log p + len(searchWord) * log(p)) = O(max(p, len(searchWord)) log p)
# Space complexity is O(searchWord * max(len(p)))
def prefix_suggestion(products, prefix):
l, r, found = 0, len(products) - 1, -1
while l <= r:
m = (l + r) // 2
m_word = products[m]
if m_word.startswith(prefix):
found = m
break
elif m_word[:len(prefix)] > prefix:
r = m - 1
else: # m_word[:len_prefix] < prefix
l = m + 1
if found < 0:
return []
else:
while found > 0 and products[found-1].startswith(prefix):
found -= 1
res = [products[found]]
for i in range(1,3):
if found + i < len(products) and products[found+i].startswith(prefix):
res.append(products[found+i])
return res
products.sort()
res = []
for i in range(len(searchWord)):
res.append(prefix_suggestion(products, searchWord[:i+1]))
return res
# Brute Force
# Sort the products lexicographically
# Iterate through each prefix of the searchword and match with top 3 products
# O(p*s) time and O(s*max(len(p))) space
# products.sort()
# res = []
# for i in range(1, len(searchWord)+1):
# prefix = searchWord[:i]
# matches = []
# for p in products:
# if p[:i] == prefix:
# matches.append(p)
# if len(matches) == 3:
# break
# res.append(matches)
# return res
|
a5c6cbd1ffd539881de0dfd87a5b254b0a7ab5ee | alexnsadler/Fundamentals-of-Computing-Specialization | /AT/AT Part 2/Project 3/week_3_app.py | 6,209 | 3.984375 | 4 | """Project 3 application (student written)."""
import random
import timeit
import alg_cluster
import alg_project3_solution as des
import matplotlib.pyplot as plt
def gen_random_clusters(num_clusters):
"""Return a list of randomly generated points in the corners of a square.
Input: num_clusters is the number of desired random clusters
Output: List of tuples that have possible values of (+/- 1, +/- 1)
"""
cluster_list = []
point_values = (-1, 1)
for idx in range(num_clusters):
h_cord = random.choice(point_values)
v_cord = random.choice(point_values)
cluster = alg_cluster.Cluster(set(), h_cord, v_cord, 0, 0)
cluster_list.append(cluster)
return cluster_list
def running_times(num_clusters, function):
"""Return a list of running times for num_clusters for a given function.
Input: num_clusters is the number of clusters, and function is either
fast_closest_pair or slow_closest_pair from alg_project3_solution
Output: list of running times
"""
times_list = []
for num_cluster in range(2, num_clusters):
cluster_lst = gen_random_clusters(num_cluster)
start_time = timeit.default_timer()
function(cluster_lst)
stop_time = timeit.default_timer()
elapsed_time = stop_time - start_time
times_list.append(elapsed_time)
return times_list
def compute_distortion(cluster_list, data_url):
"""Compute the distorition of a cluster_list.
Uses cluster_error from alg_cluster to compute the error of each cluster
(the sum of the sequares of distances from each county in the cluster to
the cluster's center, weighted by each county's population)
Input: cluster_list is a list of clusters
Output: the distortion of a cluster_list
"""
# Change argument for load_data_table depending on cluster_list input
data_table = des.load_data(data_url)
distortion = 0
for cluster in cluster_list:
distortion += cluster.cluster_error(data_table)
return distortion
def clustering_distortion(data_url, cluster_method):
"""Return a list of distortions.
Input: a data_url for information on cancer data and either clustering
method of des.kmeans_clustering or des.hierarchical_clustering
Output: a list of distortions for a range of iterations for
kmeans_clustering
"""
cluster_list = des.cluster_lst(data_url)
distortions_list = []
if cluster_method == des.kmeans_clustering:
for num_clstr in range(6, 21):
kmeans_clusters = des.kmeans_clustering(cluster_list, num_clstr, 5)
distortions_list.append(compute_distortion(kmeans_clusters, data_url))
elif cluster_method == des.hierarchical_clustering:
init_hierachical_clusters = des.hierarchical_clustering(cluster_list, 20)
distortions_list.append(compute_distortion(init_hierachical_clusters, data_url))
for num_clstr in range(19, 5, -1):
hierachical_clusters = des.hierarchical_clustering(init_hierachical_clusters, num_clstr)
distortions_list.append(compute_distortion(hierachical_clusters, data_url))
distortions_list.reverse()
else:
return "Invalid cluster_method"
return distortions_list
###############################################################################
# Application answers
def question_one():
"""Generate graph of running time of pair functions for 200 clusters."""
q1_x_vals = range(2, 200)
slow_vals = running_times(200, des.slow_closest_pair)
fast_vals = running_times(200, des.fast_closest_pair)
fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.title('Running Time of Pair Functions for 200 Clusters in Desktop Python')
plt.xlabel('Number of Clusters')
plt.ylabel('Running Time in Seconds')
ax1.plot(q1_x_vals, slow_vals, label="slow_closest_pair")
ax1.plot(q1_x_vals, fast_vals, label="fast_closest_pair")
ax1.legend(loc='upper right')
plt.show()
# Answers for questions 2, 3, 5, and 6 are in alg_project3_viz
def question_seven():
"""Return the distortion for kmeans and hierarchical clusters."""
q7_data_url = des.DATA_111_URL # change url depending on desired data table
q7_clst = des.cluster_lst(q7_data_url)
q7_kmeans_clusters = des.kmeans_clustering(q7_clst, 9, 5)
q7_hierarchical_clusters = des.hierarchical_clustering(q7_clst, 9)
kmeans_dist = compute_distortion(q7_kmeans_clusters, q7_data_url)
hierarchical_dist = compute_distortion(q7_hierarchical_clusters, q7_data_url)
return "hierarchical distortion =", hierarchical_dist, "kmeans distortion =", kmeans_dist
def question_ten():
"""Generate graph for distortions vsn umber of clusters."""
kmeans_dist_111 = clustering_distortion(des.DATA_111_URL,
des.kmeans_clustering)
kmeans_dist_290 = clustering_distortion(des.DATA_290_URL,
des.kmeans_clustering)
kmeans_dist_896 = clustering_distortion(des.DATA_896_URL,
des.kmeans_clustering)
hierarchical_dist_111 = clustering_distortion(des.DATA_111_URL,
des.hierarchical_clustering)
hierarchical_dist_290 = clustering_distortion(des.DATA_290_URL,
des.hierarchical_clustering)
hierarchical_dist_896 = clustering_distortion(des.DATA_896_URL,
des.hierarchical_clustering)
q2_x_vals = range(6, 21)
# change the below values for desired graph/ number of points
kmeans_vals = kmeans_dist_896
hierarchical_vals = hierarchical_dist_896
num_points = 896
fig = plt.figure()
ax2 = fig.add_subplot(111)
plt.title('Disortions vs Number of Clusters for ' + str(num_points) + ' points')
plt.xlabel('Number of Clusters')
plt.ylabel('Distortions * 10^11')
ax2.plot(q2_x_vals, kmeans_vals, label="kmeans_clustering")
ax2.plot(q2_x_vals, hierarchical_vals, label="hierarchical_clustering")
ax2.legend(loc='upper right')
plt.show()
|
724c807d4567215be0de9f657b28dbbcc476848c | duvu/my-filter5 | /testpandas.py | 885 | 3.78125 | 4 | import pandas as pd
df = pd.DataFrame({'Age': [20, 21, 22, 24, 32, 38, 39],
'Color': ['Blue', 'Green', 'Red', 'White', 'Gray', 'Black',
'Red'],
'Food': ['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese',
'Melon', 'Beans'],
'Height': [165, 70, 120, 80, 180, 172, 150],
'Score': [4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
},
index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean',
'Christina', 'Cornelia'])
# print("\n -- loc -- \n")
# df.loc[df['Age'] < 40, 'Test'] = 1
#
# print(df)
#
# # print("\n -- iloc -- \n")
# # print(df.iloc[(df['Age'] < 30).values, [1, 3]])
print(df['Age'].shift(-1))
print(df['Age'] < df['Age'].shift(-1)) |
0aac905b298bd04987437fc02a5f1fcd9621000d | afs2015/SmallPythonProjects | /FunPythonProjects/FizzBuzzSolution.py | 317 | 4.09375 | 4 | #!/usr/bin/python
# Author: Andrew Selzer
# Purpose: Sample FizzBuzz solution. Counts from 1-100 and prints Fizz if number is divisible by 3, Buzz if number is divisible by 5
for num in range(1,101):
msg = ''
if num % 3 == 0:
msg += 'Fizz'
if num % 5 == 0:
msg += 'Buzz'
print (msg or num)
|
5d19e5be06bde6d6e4ae9badb4e38e3a9af7472e | EtoKazuki/python_calendar | /calendar.py | 6,426 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import datetime
import sqlite3
# 今日の日付データを代入
today = datetime.date.today()
# 空のリストを作成
day = []
month = []
year = []
# 今日の年、月、日、を代入
today_year = int(today.year)
today_month = int(today.month)
today_day = int(today.day)
# DBに接続する
conn = sqlite3.connect("zemi.db")
cur = conn.cursor()
# 5年分のリストを追加
for i in range(1, 32):
day.append("")
for i in range(1, 13):
hoge = day[:]
month.append(hoge)
for i in range(1, 5):
hoge = month[:]
year.append(hoge)
# DBにあるデータをリストに入れる
cur.execute("select * from calendar")
for row in cur:
db_day = row[0]
db_day_split = db_day.split("-")
db_year = int(db_day_split[0])
db_month = int(db_day_split[1])-1
db_day = int(db_day_split[2])-1
db_title = row[1]
db_place = row[2]
db_time = row[3]
db_content = row[4]
db_event = {
"タイトル": db_title,
"場所": db_place,
"時間": db_time,
"詳細内容": db_content
}
db_year = db_year - today_year
if len(year[db_year][db_month][db_day]) != 0:
year[db_year][db_month][db_day].append(db_event)
else:
year[db_year][db_month][db_day] = [db_event]
cur.close()
while True:
# 日付を入力してもらう
while True:
try:
time = str(input("日付を入力してください (入力例:2017-12-26) :"))
hoge = time.split("-")
# 入力してもらった日付データを分割
select_year = int(hoge[0])
select_month = int(hoge[1])-1
select_day = int(hoge[2])-1
break
except ValueError:
print("入力例に従って入力してください")
print()
# 入力してもらった年と現在の年の差を出す
diff_year = select_year-today_year
if year[diff_year][select_month][select_day] == ""\
or not year[diff_year][select_month][select_day]:
# 予定を入力してもらう
print()
print("予定を入力してください")
title = input("タイトル :")
place = input("場所 :")
event_time = input("時間 :")
event_detile = input("詳細内容 :")
# 予定を辞書型にする
event = {
"タイトル": title,
"場所": place,
"時間": event_time,
"詳細内容": event_detile
}
# 選択した日に何も予定がなければイベントを追加する
year[diff_year][select_month][select_day] = [event]
choice_day = year[diff_year][select_month][select_day]
print()
print("予定を追加しました。")
print("タイトル:", choice_day[0]["タイトル"])
print("場所:", choice_day[0]["場所"])
print("時間:", choice_day[0]["時間"])
print("詳細内容:", choice_day[0]["詳細内容"])
day_data = (time, title, place, event_time, event_detile)
conn.execute("insert into calendar values(?, ?, ?, ?, ?)", day_data)
conn.commit()
# 予定が一つでも入っていた場合は選択肢を出す
else:
print("0:予定を見る 1:予定を追加する 2:予定を削除する")
select_number = int(input("上記の数字から選択してください :"))
while True:
if select_number == 0:
for i in range(len(year[diff_year][select_month][select_day])):
choice_day = year[diff_year][select_month][select_day][i]
print(i)
print("タイトル:", choice_day["タイトル"])
print("場所:", choice_day["場所"])
print("時間:", choice_day["時間"])
print("詳細内容:", choice_day["詳細内容"])
break
elif select_number == 1:
print("予定を入力してください")
title = input("タイトル:")
place = input("場所:")
event_time = input("時間:")
event_detile = input("詳細内容:")
event = {
"タイトル": title,
"場所": place,
"時間": event_time,
"詳細内容": event_detile
}
year[diff_year][select_month][select_day].append(event)
day_data = (time, title, place, event_time, event_detile)
conn.execute("insert into calendar values\
(?, ?, ?, ?, ?)", day_data)
conn.commit()
break
elif select_number == 2:
print("どの予定を削除しますか?")
# 現在ある予定を表示する
for i in range(len(year[diff_year][select_month][select_day])):
choice_day = year[diff_year][select_month][select_day]
print(i)
print("タイトル:", choice_day[i]["タイトル"])
print("場所:", choice_day[i]["場所"])
print("時間:", choice_day[i]["時間"])
print("詳細内容:", choice_day[i]["詳細内容"])
# 削除したい予定の番号を入力してもらう
while True:
try:
drop_index = int(input("削除したい予定の番号を入力してください :"))
del_title = (time, choice_day[drop_index]["タイトル"])
del choice_day[drop_index]
conn.execute("delete from calendar where\
day = ? and title = ?", del_title)
conn.commit()
break
except ValueError:
print("表示されている番号から選んでください")
break
else:
print("上記の数字以外を選ばないでください")
conti_end = str(input("0:続けますか? 1:終了しますか? :"))
if conti_end != "0":
print("終了します")
conn.close()
break
|
695b26becb587b0975df0b088e81f00c63340a0c | luckybooooy/test | /biji.py | 6,793 | 3.9375 | 4 | (代码换行,实际不换行)
# total='appalPrice'\
# +'bananaPrice'\
# +'pearPrice'
# print(total)
#
# appalPrice=1; bananaPrice=2; pearPrice=3
# a=(appalPrice+bananaPrice+pearPrice)
# print(a)
#
# import keyword
# print(keyword.iskeyword('admin'))
#
# print(keyword.kwlist)
#
# x = 4
# y = x
# print(x,id(x))
# print(y,id(y))
# x = 5
# print(x,id(x))
# print(y,id(y))
#
# a = [1,2,'hello'] #列表
# a = {'name':'123','age':18} #字典
#
# print(int(3.14)) #非四舍五入
# print(int(0.2)) #浮点数转换成整数类型
#
# print(int(True))
# print(int(False))
# print(bool(1))
# print(bool(2))
# print(bool(5))
# print(bool(5.5))
# print(bo('helloworld'))
# # print(bool('')) #无值是显示False
# print(bool(' ')) #空格也算值
#
# a = "Apple's unit price is 9 yuan"
# # 0123456789
# print(a[22]) #第22位
# print(a[-6])
# print(a[13:18]) #13位到18位
# print(a[1:100]) #截取1至100位
# print(a[:100]) #从头开始截取
#
# 拼接
# print('456'+'123')
# print('456''123')
# print('456','123')
# print('456'+'123'*4)
#
# #修改
# a = "Apple's unit price is 9 yuan"
# #将9改为6,切片法
# b = a[0:22]
# c = a[23:28]
# print(b+'6'+c)
#
# a = 'Apple\'s unit price is 9 yuan'
# b =(a[22])
# print(type(b))
# b = int(b)
# print(b)
#
# print('1'=='2')
# print('2'>'1')
# print('a'<'b')
# print('b'<'a')
#
# print(ord('a')) #将字母转换成ASCII字符
# print(ord('b'))
# print(chr(97)) #将ASCII字符转换成对应的字母
# print(chr(98))
#
# print(bin(a)) #bin函数用来将十进制书转换成二进制数
#
# print(a and b) #顺序查找false的值,找到则输出false,如果没有找到,则输出最后一个值
#
# List = [1,2,3,4,[5,6],'123']
# print(1 in List) #判断元素1是否存在于字典List中
#
# r = input('r=')
# r = int(r)
# c = 2*3.14*r
# print('周长=',c)
#
# s = r**2*3.14
# print('面积=',s)
#
# s = input('s=')
# s = int(s)
# r = (s/3.14)**0.5
# l = 2*s/r
# print('半径=',r)
# print('周长=',l)
#
# print(round((s/3.14)**0.5))
# print(round((2*s/r))
#
#
# x = int(input('请输入第一个数字:'))
# y = int(input('请输入第二个数字:'))
# z = int(input('请输入第三个数字:'))
# m = 3
# u = (x+y+z)/m
# u = int(u)
# print('均值=',u)
# f = (((x-u)**2+(y-u)**2+(z-u)**2)/m)
# f = int(f)
# print('方差=',f)
# b = f**(1/2)
# b = int(b)
# print('标准差=',b)
#
# x = float(input('请输入第一个数字:'))
# y = float(input('请输入第二个数字:'))
# z = float(input('请输入第三个数字:'))
# m = 3
# u = (x+y+z)/m
# u = float(u)
# print('均值 =',u)
# f = (((x-u)**2+(y-u)**2+(z-u)**2)/m)
# f = float(f)
# print('方差 =',f)
# b = f**(1/2)
# b = float(b)
# print('标准差 =',b)
#
# ccc = [1,2,[1,2,3],4,5,6]
# print(ccc[0:4:2]) #1为步长,隔0取数。如果2为步长,隔1取数
# print(ccc[5:0:-1]) #倒过来
#
# a = [110,'dog','cat',120, 'apple']
# print(a)
# (a.insert(2,[]))
# (a.remove('apple'))
# a[0]=a[0]*10
# a[4]=a[4]*10
# print(a)
#
# a = [110,'dog','cat',120, 'apple']
# print(a.index(120)) #查询120在列表的那个位置
#
# #copy
# a = [1,2,3]
# b = a.copy()
# print(a,id(a)) #a,b地址不相同
# print(b,id(b))
#
# # 不可变数据类型(数值,字符串,元组)
# a = 1
# b = a
# print(a,id(a)) #a,b地址相同
# print(b,id(b))
# # 可变数据类型(列表)
# a = [1,2,3]
# b = a
# a[2] = 300
# print(a,id(a)) #a,b地址不相同
# print(b,id(b))
#
# #copy
# a = [1,2,3]
# b = a.copy()
# c = a[:]
# d = list(a)
# print(a,id(a))
# print(b,id(b))
# print(c,id(c))
# print(d,id(d))
# #b,c,d地址都不同于a
#
#
# a = [1,2,3,4,5,6,2,2,2]
# print(a.count(2)) #查询2在list(a)中出现了几次
#
# a = [1,2,3,4,5,6,2,2,2]
# a.sort() #排序,默认从小到大(False)
# print(a)
# a.sort(reverse= True) #True代表降序
# print(a)
# a.sort(reverse= False) #False代表升序
# print(a)
#
# a = [1,2,3,4,5,6,2,2,2]
# print(sorted(a)) #已改变
# print(a) #但a本身没有改变
#
# a = [1,2,3,4,5,6,2,2,2]
# print(a)
# a.reverse() #将列表倒过来
# print(a)
#
# a = ['123',1,2,3]
# print(len(a)) #数a中有几个元素
#
# a = (1,2,3)
# b = tuple([1,2,3]) #将list(a)转换成tuple(a),元组的创建,元组不可改变
# print(a)
# print(b)
# print(a[0:2]) #可切片
#
# a = (1,2,3)
# A,B,C = a #a与A对应
# print(A)
#
#
# a = {'x':1,'y':2,'z':3}
# print('x' in a)
# print('e' in a)
#
# print(a.get('x'))
# print(a.get('y'))
#
# print(a.get('x',3)) #存在输出存在的值x,不存在输出3
# print(a.get('j',4)) #存在输出存在的值j,不存在输出4
#
# a['新增'] = 5
# print(a)
#
# #拼接
# a = {'x':1,'y':2,'z':3}
# b = {'q':4,'w':5,'e':6}
# a.update(b)
# print(a)
#
# a = {'x':1,'y':2,'z':3}
# b = {'x':4,'y':5,'z':6}
# a.update(b) #重复的会被后者取代
# print(a)
#
# a = {'x':1,'y':2,'z':3}
# del a['x']
# print(a)
# a.pop('y')
# print(a)
# a.clear() #清空字典
# print(a)
#
# #修改
# a = {'x':1,'y':2,'z':3}
# a['x'] = 4
# print(a)
#
# b = a.keys() #获取全部键
# print(b)
# c = a.values() #获取全部值
# print(c)
# d = a.items() #获取全部内容
# print(d)
#
#
# p68
# a = {'Math':96,'English':86,'Chinese':95.5,'Biology':86,'Physics':None}
# b = {'History':88}
# a.update(b)
# print(a)
# del a['Physics']
# print(a)
# a['Chinese'] = round(a['Chinese'])
# print(a)
# print(a.get('Math'))
#
# a = set([4,5,3,1,2])
# print(a)
# b = frozenset([4,5,3,1,2])
# print(b)
#
# a = {1,2,3,4,5}
# b = {4,5,6,7,8}
# # 并集
# print(a | b)
# print(a.union(b))
# #交集
# print(a & b)
# #差集
# print(a - b)
# print(b - a)
# print(a.difference(b))
# print(b.difference(a))
# #异或
# # a | b 去掉 a & b
# print(a ^ b)
# print(a.symmetric_difference(b))
# # <= in 子集
# print(b <= a) #子集
# print(b < a) #真子集
# #超集
# print(a >= b) #超集
# print(a > b) #真超集
#
# a = {1,2,3,4,5}
# a.add(7) #新增元素
# print(a)
#
# a.pop() #删除元素
# print(a)
#
# a = ['apple','pear','watermelon','prach']
# b = ['pear','banana','orange','peach','grape']
# c = set(a)
# d = set(b)
# print(c | d)
# print(c & d)
# print(c - d)
#
# print('请选择需要进行操作的对应数字')
# print('查询汉堡类菜单请输入:1')
# print('查询小食类菜单请输入:2')
# print('查询饮料类菜单请输入:3')
# print('若不查询请输入:0')
# x = int(input('请输入数字:'))
# a = ('香辣鸡腿堡','劲脆鸡腿堡','奥尔良烤鸡腿堡','半鸡半虾堡')
# b = ('薯条','黄金鸡块','香甜栗米棒')
# c = ('可口可乐','九珍果汁','经典咖啡')
# d = ('感谢你的使用')
# if x == 1:
# print(a)
# if x == 2:
# print(b)
# if x == 3:
# print(c)
# if x == 0:
# print(d)
#
# import random (该函数可以取一个随机数字给变量)
# b=random.randint(0,10)
|
a27f1eac3eb43cadc43e7227c019015ddcad55d8 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/prkgyu001/question2.py | 345 | 4.125 | 4 | def counting(p):
if len(p) == 1:
return 0
elif len(p) == 2:
if p[0] == p[1]:
return 1
else:
return 0
elif p[0] == p[1]:
return 1 + counting(p[2:])
else:
return counting(p[1:])
string = input("Enter a message:\n")
print("Number of pairs: "+ str(counting(string)))
|
9bf79b5c13b467d4086e084d51bb842f225be03a | TarasKravchuk/human_calc | /main.py | 1,847 | 3.546875 | 4 | import inflect
p = inflect.engine()
action_list = ["*", "+", "/", "-"]
action_dict = {"+": "plus",
"*": "multiplication",
"/": "division",
"-": "minus"}
def calc (validator_result):
arg1 = validator_result[0]
action = validator_result[1]
arg2 = validator_result[2]
if action == action_list[0]:
result = arg1 * arg2
elif action == action_list[1]:
result = arg1 + arg2
elif action == action_list[2]:
result = arg1/arg2
elif action == action_list[3]:
result = arg1 - arg2
final_result = p.number_to_words(arg1)+ " " + action_dict.get(action) + " " + p.number_to_words(arg2) + " equally" + \
" " + p.number_to_words(result)
return final_result
def inputer ():
arg1 = input("please input first argument, it should be integer ")
action = input('please input your action it can be "*" or "+" or "/" or "-" ')
arg2 = input("please input second argument, it should be int or integer ")
return [arg1, action, arg2]
def space_killer (inputer_list):
space_killer_list = []
for arg in inputer_list:
arg = arg.replace(' ', '')
space_killer_list.append(arg)
return space_killer_list
def validator (space_killer_list):
try:
arg1 = int(space_killer_list[0])
except ValueError:
print(f"Invalid input {space_killer_list[0]}, please try again ")
return None
try:
arg2 = int(space_killer_list[2])
except ValueError:
print(f"Invalid input {space_killer_list[2]}, please try again ")
return None
if not space_killer_list[1] in action_list:
print(f"Invalid input {space_killer_list[1]}, please try again ")
return None
else:
action = space_killer_list[1]
return [arg1, action, arg2]
|
771ad6545112a09cdd4507ac1340479ddc721871 | alisatsar/itstep | /Python/Lessons/string/str.split.py | 259 | 3.671875 | 4 | a = "Ivan Aleksandrovich Petrov"
print(a.split()[-1]) #[-1] означает вывести последнее слово
#Petrov
print(a.split("a" [-1])) #[-1] означает максимальное количество разбиений
#['Iv', 'n Aleks', 'ndrovich Petrov']
|
92195f98dbcaaba97329f6f622faaa6203dc6d22 | visw2290/Scripts-Practice | /Scripts-Sublime/emailvalid.py | 548 | 3.734375 | 4 |
class EmaVer:
email_list=[]
def ema(self,email):
self.email = email
if '@' in self.email:
if self.email not in EmaVer.email_list:
EmaVer.email_list.append(email)
else:
return 'Email ID already exists'
else:
return 'Enter a valid email address'
em1 = EmaVer()
print(em1.ema('visw@gmail.com'))
print(em1.ema('visw@gmail.com'))
print(em1.ema('oiu@hjk.com'))
print(em1.ema('lkkll'))
print(em1.email_list)
em2 = EmaVer()
print(em2.ema('viswa@gmail.com'))
print(em2.ema('viswa@gmail.com'))
print(em2.ema('oiuk@hjk.com'))
print(em2.ema('lkkll'))
print(em2.email_list)
|
9513f780d3a55860d0c78b71b667081e9cae859c | camwebby/ANN-Builder | /ANNClassFinal.py | 5,169 | 4.0625 | 4 | import numpy as np
from matplotlib import pyplot as plt
###test data####
trainFeatures1 = np.array( [[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1],
[0,0,0]] )
trainLabels1 = np.array([[0,1,1,0,0]]).T
### end of test data###
##Example network with 3 layers, the first having 6 neurons, second having 2, third having 3:
layersAndWeights = np.array([[6],[2],[3]])
##neurons and weights form: [[x],[y],[z]],
##where dimesions of array show how many layers and value in each
##shows the weights per layer
##One can have as many layers as one desires, e.g. [[x]] for one layer, or [[],[],[],[],[],[],[],........[]]
##defining the class
class ANN():
##one can specify the following parameters when creating the network:
def __init__(self, trainFeatures, trainLabels, dimensions, activation, iterations):
self.trainFeatures = trainFeatures
self.trainLabels = trainLabels
self.dimensions = dimensions
self.activation = activation
self.iterations = int(iterations)
def initialiseWeights(self):
np.random.seed(1)
self.weights = []
#creating the first weight
trainFeatColumns = int(self.trainFeatures.shape[1])
firstLayerSynapses = int(self.dimensions[0])
self.weights.append(2*np.random.random((trainFeatColumns,firstLayerSynapses)) - 1)
#creating middle weights
for count,synapses in enumerate(self.dimensions):
if count < len(self.dimensions) - 1:
x = int(self.dimensions[count])
y = int(self.dimensions[count+1])
self.weights.append(2*np.random.random((x,y)) - 1)
else:
break
#creating the last neuron to output(s) weight(s)
trainLabelColumns = int(self.trainLabels.shape[1])
lastWeight = self.weights[len(self.weights)-1].shape
self.weights.append(2*np.random.random((lastWeight[1],trainLabelColumns)) - 1)
def activationFunc(self, func, x, deriv=False):
if func == "tanh":
if deriv == True:
return 1/np.cosh(x**2)
return np.tanh(x)
elif func== "sigmoid":
if deriv == True:
return np.exp(-x)/((1+np.exp(-x))**2)
return 1/(1+np.exp(-x))
else:
print("mistyped or unknown activation function. try 'sigmoid' or 'tanh'")
def forwardProp(self):
X = self.trainFeatures
self.zn = [X]
self.an = [X]
for count,weigh in enumerate(self.weights):
dotProd = np.dot(self.zn[count], self.weights[count])
self.zn.append(self.activationFunc(self.activation, dotProd))
self.an.append(dotProd)
def getError(self):
return self.trainLabels - self.zn[len(self.zn) - 1]
def backProp(self):
error = self.getError()
self.deltas = []
self.pderivatives = []
#finding partial derivative of error with respect to the last weight(s)
deltan = np.multiply(-(error), self.activationFunc(self.activation, self.an[len(self.an) - 1], True))
dEdwn = np.dot(self.zn[len(self.zn) - 2].T, deltan)
self.deltas.append(deltan)
self.pderivatives.append(dEdwn)
#finding the partial derivative(s) of error with respect to the remenaining weight(s)
for count, idk in enumerate(self.zn):
if count < len(self.zn)-2:
self.deltas.append(np.dot(self.deltas[count], self.weights[len(self.weights) - (count+1)].T)*self.activationFunc(self.activation, self.an[len(self.an) - (count+2)] , True))
self.pderivatives.append( np.dot( self.zn[len(self.zn) - (count+3)].T, self.deltas[count+1]))
else:
break
def updateWeights(self):
for count, (diff, weigh) in enumerate(zip(self.pderivatives, self.weights)):
self.weights[count] -= self.pderivatives[len(self.pderivatives)-(count+1)]
def run(self, printError=False, costGraph=False):
self.averageCost = []
self.interval = []
self.initialiseWeights()
for iter in range(self.iterations):
self.forwardProp()
self.getError()
self.backProp()
self.updateWeights()
if costGraph==True:
if iter % int(self.iterations*0.01) == 0:
self.averageCost.append(abs(np.mean(self.getError())))
self.interval.append(iter)
if printError == True:
print(self.getError())
if costGraph==True:
plt.plot(self.interval, self.averageCost)
plt.show()
if __name__ == "__main__":
neuralNet1 = ANN(trainFeatures=trainFeatures1, trainLabels=trainLabels1, dimensions=layersAndWeights, activation="sigmoid", iterations=2000)
neuralNet1.run(printError=True,costGraph=True)
|
9ec405356ba0c2a4915dc884845653af0aa73f72 | Prakharpatni/Functions | /To Find Numbers Divisible by Another Number.py | 173 | 3.546875 | 4 | value=25
list= [25,65,15,75,62,84,100,150,163]
def check(num):
for i in list:
if(i%value==0):
print(i)
else:
print("")
|
b6e46a4799656a48c31fcb0357f8a387f007a628 | wenxinjie/leetcode | /backtracking/python/leetcode39_Combination_Sum.py | 1,154 | 3.546875 | 4 | # Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
# The same repeated number may be chosen from candidates unlimited number of times.
# Note:
# All numbers (including target) will be positive integers.
# The solution set must not contain duplicate combinations.
# Example 1:
# Input: candidates = [2,3,6,7], target = 7,
# A solution set is:
# [
# [7],
# [2,2,3]
# ]
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
self.helper(res,[],candidates,target,0)
return res
def helper(self,res,cur,candidates,target,index):
if target < 0: return
if target == 0: res.append(cur+[])
for i in range(index,len(candidates)):
cur.append(candidates[i])
self.helper(res,cur,candidates,target-candidates[i],i)
cur.pop()
# Time: kO(k^n)
# Space: O(n)
# Difficulty: medium |
9a7ec6941bc2d0467bd0e58a630afca31e39f779 | imcmurray/digitalSignageDev | /add_new_slide.py | 3,943 | 3.5 | 4 | """
Shows basic usage of the Slides API. Prints the number of slides and elments in
a presentation.
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# Setup the Slides API
IMG_FILE = 'leaves-fallen-leaves-HD-Wallpapers.jpg' # use your own!
TMPLFILE = 'title slide template' # use your own!
SCOPES = (
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/presentations',
)
#SCOPES = 'https://www.googleapis.com/auth/presentations.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
slides_service = build('slides', 'v1', http=creds.authorize(Http()))
drive_service = build('drive', 'v3', http=creds.authorize(Http()))
# Call the Slides API
PRESENTATION_ID = '1CuDcEYKxvJGF1dWQrjnhW3GrPWB6bQxe0cTauKRXWa4'
presentation = slides_service.presentations().get(presentationId=PRESENTATION_ID).execute()
slides = presentation.get('slides')
print ('The presentation contains {} slides:'.format(len(slides)))
for i, slide in enumerate(slides):
print('- Slide #{} contains {} elements.'.format(i + 1,
len(slide.get('pageElements'))))
print ('** Adding another Slide to the deck **')
page_id = 'iantestingf'
element_id = 'ian1234felem'
pt350 = {
'magnitude': 350,
'unit': 'PT'
}
pt150 = {
'magnitude': 150,
'unit': 'PT'
}
pt100 = {
'magnitude': 100,
'unit': 'PT'
}
pt50 = {
'magnitude': 50,
'unit': 'PT'
}
# Add a slide at index 1 using the predefined 'TITLE_AND_TWO_COLUMNS' layout and
# the ID page_id.
requests = [
{
'createSlide': {
'objectId': page_id,
'insertionIndex': '1',
'slideLayoutReference': {
'predefinedLayout': 'BLANK'
}
}
},
{
'createShape': {
'objectId': element_id,
'shapeType': 'TEXT_BOX',
'elementProperties': {
'pageObjectId': page_id,
'size': {
'height': pt50,
'width': pt150
},
'transform': {
'scaleX': 1,
'scaleY': 1,
'translateX': 20,
'translateY': 20,
'unit': 'PT'
}
}
}
},
# Insert text into the box, using the supplied element ID.
{
'insertText': {
'objectId': element_id,
'insertionIndex': 0,
'text': 'Hello World! New Box with Text Inserted!'
}
},
{
'updateTextStyle': {
'objectId': element_id,
'style': {
'fontFamily': 'Times New Roman',
'fontSize': {
'magnitude': 8,
'unit': 'PT'
},
'foregroundColor': {
'opaqueColor': {
'rgbColor': {
'blue': 1.0,
'green': 0.0,
'red': 0.0
}
}
}
},
'fields': 'foregroundColor,fontFamily,fontSize'
}
}
]
# If you wish to populate the slide with elements, add element create requests here,
# using the page_id.
# Execute the request.
body = {
'requests': requests
}
response = slides_service.presentations().batchUpdate(presentationId=PRESENTATION_ID,
body=body).execute()
create_slide_response = response.get('replies')[0].get('createSlide')
print('Created slide with ID: {0}'.format(create_slide_response.get('objectId')))
print('DONE')
|
e2d4b02cee90684f7980cbdbd4a1910ac92a772f | YYKyeko/Basic-Python-Codes-For-Beginners | /rockpaper31.py | 1,020 | 4.125 | 4 | print("*****rock*****")
print("*****paper*****")
print("*****scissors*****")
from random import randint
player = input("write your choice player: ").lower()
rand_num = randint(0, 2)
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
print(f"Computer plays: {computer}")
if player and computer:
if player == "rock":
if computer == "scissors":
print("player wins!!!")
if computer == "paper":
print("computer wins!!!")
if player == "paper":
if computer == "rock":
print("player wins!!!")
if computer == "scissors":
print("computer wins!!!")
if player == "scissors":
if computer == "rock":
print("computer wins!!!")
if computer == "paper":
print("player wins!!!")
if player == computer:
print("it is a tie!")
else:
print("please enter a valid move!")
else:
print("I said write something!!!")
|
1b60ebc3f76147477c08162922b14686947d8d48 | Inflearn-everyday/study | /dahyun/gcd and lcm.py | 128 | 3.609375 | 4 | from math import gcd
a,b = map(int, input().split())
def lcm(a,b):
return a*b // gcd(a,b)
print(gcd(a,b))
print(lcm(a,b))
|
2734d34005255811f134cea5035f874775ba7c1f | krrish94/learn_tensorflow | /lstm_repetition_detection increased_freq.py | 8,245 | 3.6875 | 4 | # Tutorial from: https://jasdeep06.github.io/posts/Understanding-LSTM-in-Tensorflow-MNIST/
import numpy as np
import tensorflow as tf
from tensorflow.contrib import rnn
# Seed RNG
rng_seed = 12345
np.random.seed(rng_seed)
tf.set_random_seed(rng_seed)
# Declare constants
# LSTM is unrolled through 10 time steps
seq_len = 10
# Number of hidden LSTM units
num_units = 10
# Size of each input
n_input = 1
# Learning rate
learning_rate = 0.0001
# Beta (for ADAM)
beta = 0.9
# Momentum
momentum = 0.099
# Number of classes
n_classes = 2
# Batch size
batch_size = 10
# Train/Test split
train_split = 0.8
# Number of epochs
num_epochs = 6
# Flag to check if loss has been stepped down
stepFlag = False
# Class weights (for 0->no-repetition vs 1->repetition)
class_weights = tf.constant([0.1, 0.9])
# class_weights = np.ones((batch_size * seq_len,n_classes))
# class_weights[:,0] = 0.1*class_weights[:,0]
# class_weights[:,1] = 0.1*class_weights[:,1]
# class_weights_tensor = tf.constant(class_weights, dtype = tf.float32)
# Synthesize data
num_tokens = 10
dataset_size = 20000
data = np.zeros((dataset_size, seq_len))
# label = np.zeros((dataset_size, seq_len, n_classes))
label = np.concatenate((np.ones((dataset_size, seq_len, 1)), np.zeros((dataset_size, seq_len, 1))), \
axis = -1)
print(label.shape)
for i in range(dataset_size):
# Generate a random permutation of all tokens.
# Throw in a random translation of all tokens.
tmp = np.random.permutation(num_tokens) #+ np.random.randint(50)
coin_filp = np.random.randint(0,2)
if coin_filp == 0 or coin_filp == 1:
# Add a repetition
# Index of number to repeat
tmpIdx_src = np.random.randint(len(tmp))
# Where to repeat that number
tmpIdx_dst = np.random.randint(len(tmp))
while tmpIdx_dst == tmpIdx_src:
tmpIdx_dst = np.random.randint(len(tmp))
tmp[tmpIdx_dst] = tmp[tmpIdx_src]
# label[i,tmpIdx_src,1] = 1.0
if tmpIdx_src > tmpIdx_dst:
tmpvar = tmpIdx_dst
tmpIdx_dst = tmpIdx_src
tmpIdx_src = tmpvar
label[i,tmpIdx_dst,0] = 0.0
label[i,tmpIdx_dst,1] = 1.0
label[i,tmpIdx_src,0] = 1.0
label[i,tmpIdx_src,1] = 0.0
data[i,:] = tmp
# print(data[i,:])
# print(label[i,:])
# More variable definitions
num_iters = int(np.floor(dataset_size / batch_size))
train_iters = int(train_split * num_iters)
test_iters = num_iters - train_iters
# Define placeholders
# Outputs
out_weights = tf.Variable(tf.random_normal([num_units, n_classes]))
# out_bias = tf.Variable(tf.random_normal([n_classes]))
out_bias = tf.Variable(tf.constant(5.0, shape = [n_classes]))
# Inputs
x = tf.placeholder("float", [None, seq_len, n_input])
y = tf.placeholder("float", [None, seq_len, n_classes])
# Reshape x from shape [batch_size, seq_len, n_input] to
# 'seq_len' number of [batch_size, n_input] tensors
input = tf.unstack(x, seq_len, axis = 1)
# Define network
lstm_layer = rnn.BasicLSTMCell(num_units, forget_bias = 1)
outputs, _ = rnn.static_rnn(lstm_layer, input, dtype = tf.float32)
outputs = tf.transpose(outputs, [1,0,2])
# Reshape outputs to batch_size * seq_len x num_units
# outputs_reshaped = tf.reshape(outputs, [batch_size * seq_len, num_units])
outputs_reshaped = tf.reshape(outputs, [-1, num_units])
prediction = tf.matmul(outputs_reshaped, out_weights) + out_bias
weighted_prediction = tf.multiply(prediction, class_weights)
# Loss function
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = weighted_prediction, labels = y))
# loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = prediction, labels = y))
# Optimization
# opt = tf.train.AdamOptimizer(learning_rate = learning_rate, beta1 = beta).minimize(loss)
opt = tf.train.MomentumOptimizer(learning_rate = learning_rate, momentum = momentum).minimize(loss)
# Model evaluation
# correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
# accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
soft = tf.nn.softmax(prediction)
# # Set the idx of the max location to 1 and the other label to 0
# hard = tf.where(tf.equal(tf.reduce_max(soft, axis = 1, keep_dims = True), soft), \
# tf.constant(1.0, shape = soft.shape), \
# tf.constant(0.0, shape = soft.shape))
# Init variables
init = tf.global_variables_initializer()
# Run session
with tf.Session() as sess:
sess.run(init)
epoch = 0
while epoch < num_epochs:
shuffledOrder = np.random.permutation(dataset_size)
# if epoch > 7 and not stepFlag:
# learning_rate = learning_rate / 10
# stepFlag = True
iter = 0
while iter < train_iters:
# # batch_x, batch_y = mnist.train.next_batch(batch_size = batch_size)
# # batch_x = batch_x.reshape((batch_size, seq_len, n_input))
# startIdx = (iter-1)*batch_size
# endIdx = iter*batch_size
# batch_x = data[startIdx:endIdx,:]
# batch_x = np.expand_dims(batch_x, -1)
# # print(batch_x, batch_x.shape)
# batch_y = label[startIdx:endIdx,:,:]
# # print(batch_y, batch_y.shape)
# # batch_y = np.reshape(batch_y, (batch_size * seq_len,-1))
curIterInds = shuffledOrder[iter*batch_size:(iter+1)*batch_size]
batch_x = data[curIterInds,:]
batch_x = np.expand_dims(batch_x, -1)
batch_y = label[curIterInds,:,:]
net_out = sess.run([outputs, outputs_reshaped, prediction, loss, opt], \
feed_dict = {x: batch_x, y: batch_y})
# print('Pred:', net_out[2], net_out[2].shape)
# print('Soft:', net_out[5])
# print('Label:', batch_y, batch_y.shape)
if iter % 10 == 0:
# acc = sess.run(accuracy, feed_dict = {x: batch_x, y: batch_y})
# los = sess.run(loss, feed_dict = {x:batch_x, y: batch_y})
# print('Iter: ', iter, 'Acc: ', acc, 'Loss: ', los)
# Non-Repeat Accuracy
tmp_out = np.transpose(batch_y, [1,0,2])
tmp_out = np.reshape(batch_y, (batch_size*seq_len, n_classes))
print('Epoch: ', epoch, 'Loss:', np.sum(np.abs(net_out[2] - tmp_out)))
iter += 1
while iter < train_iters + test_iters:
# batch_x, batch_y = mnist.train.next_batch(batch_size = batch_size)
# batch_x = batch_x.reshape((batch_size, seq_len, n_input))
startIdx = iter*batch_size
endIdx = (iter+1)*batch_size
batch_x = data[startIdx:endIdx,:]
batch_x = np.expand_dims(batch_x, -1)
# print(batch_x, batch_x.shape)
batch_y = label[startIdx:endIdx,:,:]
# print(batch_y, batch_y.shape)
# batch_y = np.reshape(batch_y, (batch_size * seq_len,-1))
net_out = sess.run([prediction], feed_dict = {x: batch_x, y: batch_y})
# print('Pred:', net_out[2], net_out[2].shape)
# print('Soft:', net_out[5])
# print('Label:', batch_y, batch_y.shape)
if iter % 10 == 0:
# acc = sess.run(accuracy, feed_dict = {x: batch_x, y: batch_y})
# los = sess.run(loss, feed_dict = {x:batch_x, y: batch_y})
# print('Iter: ', iter, 'Acc: ', acc, 'Loss: ', los)
# Non-Repeat Accuracy
tmp_out = np.transpose(batch_y, [1,0,2])
tmp_out = np.reshape(batch_y, (batch_size*seq_len, n_classes))
print('Epoch: ', epoch, 'Test Loss:', np.sum(np.abs(net_out[0] - tmp_out)))
iter += 1
epoch += 1
# Number of repetitions detected
iter = train_iters
while iter < train_iters + test_iters:
startIdx = iter*batch_size
endIdx = (iter+1)*batch_size
batch_x = data[startIdx:endIdx,:]
batch_x = np.expand_dims(batch_x, -1)
batch_y = label[startIdx:endIdx,:,:]
net_out = sess.run([prediction], feed_dict = {x: batch_x, y: batch_y})
if iter % 10 == 0:
tmp_out = np.transpose(batch_y, [1,0,2])
tmp_out = np.reshape(batch_y, (batch_size*seq_len, n_classes))
print('Final Test Loss:', np.sum(np.abs(net_out[0] - tmp_out)))
# net_out_hard = np.where(np.equal(np.maximum.reduce(net_out[0], axis = 0), net_out[0]), \
# np.ones(net_out[0].shape), np.zeros(net_out[0].shape))
net_out_hard = np.where(np.equal(np.matlib.repmat(np.maximum.reduce(net_out[0], axis = 1), 2, 1).T, \
net_out[0]), np.ones(net_out[0].shape), np.zeros(net_out[0].shape))
for k in range(batch_size):
print(net_out_hard[k*batch_size:(k+1)*batch_size].T)
print(tmp_out[k*batch_size:(k+1)*batch_size].T)
# print(net_out_hard[10:20], net_out_hard.shape)
# print(tmp_out[10:20], tmp_out.shape)
print('Acc: ', np.mean(np.abs(np.ones(net_out_hard.shape) - np.abs(net_out_hard - tmp_out))))
# break
iter += 1
|
810a047c69fa09415cc784b40f2de82009a7acc2 | Simeontues/Test | /main_consult.py | 186 | 3.515625 | 4 | from calculate import calculate
days = int(input("How many days did you worked: "))
salary = 0
bonus = 0
full = 0
salary = days*200
bonus = calculate(days)
full = salary + bonus |
926b1528a810324638c190fe92577528e5858d06 | harshjohar/CS50_intro | /ProblemSet6/mario/less/mario.py | 611 | 4.1875 | 4 | while True:
n = int(input("Height: "))
if n >= 1 and n <= 8:
break
for i in range(n):
print(" " * (n- i - 1), end = "")
print("#" * (i + 1))
#two things not working
#Run your program as python mario.py and wait for a prompt for input. Type in foo and press enter. Your program should reject this input as invalid, as by re-prompting the user to type in another number.
#Run your program as python mario.py and wait for a prompt for input. Do not type anything, and press enter. Your program should reject this input as invalid, as by re-prompting the user to type in another number. |
d8c006020a59928e2e46d810798f2c5435764073 | njdevengine/python-the-hardway | /nuts.py | 275 | 3.515625 | 4 | def nuts():
print "What are your favorite nuts?"
print "Third favorite nut?"
C = raw_input("> ")
print "Second favorite nut?"
B = raw_input ("> ")
print "What is your ultimate nut?"
A = raw_input("> ")
print "So your favorite nuts are: %r, %r, %r" %(A, B, C)
nuts() |
2ba8908397d5453276717d624b481c7b7a0faed6 | pdelro/IS211_Assignment6 | /conversions_refactored.py | 1,874 | 4.25 | 4 |
def convert(fromUnit, toUnit, value):
"""
Convert
"""
if fromUnit == toUnit:
return value
elif fromUnit == "C" and toUnit == "K":
# do Celsius to Kelvin
value = value + 273.15
return value
elif fromUnit == "C" and toUnit == "F":
# do Celsius to Fahrenheit
value = value * 9/5 + 32
return value
elif fromUnit == "K" and toUnit == "C":
# do Kelvin to Celsius
value = value - 273.15
return value
elif fromUnit == "K" and toUnit == "F":
# do Kelvin to Farenheit
value = value * 9/5 - 459.67
return value
elif fromUnit == "F" and toUnit == "K":
# do Farenheit to Kelvin
value = (value + 459.67) * 5/9
return value
elif fromUnit == "F" and toUnit == "C":
# do Farenheit to Celsius
value = (value - 32) * 5/9
return value
elif fromUnit == "m" and toUnit == "yd":
# do meters to yards conversion
value = value * 1.094
return value
elif fromUnit == "m" and toUnit == "mi":
# do meters to miles conversion
value = value * 0.000621
return value
elif fromUnit == "yd" and toUnit == "m":
# do yards to meters conversion
value = value / 1.094
return value
elif fromUnit == "yd" and toUnit == "mi":
# do yards to miles conversion
value = value / 1760
return value
elif fromUnit == "mi" and toUnit == "m":
# do miles to meters conversion
value = value * 1609.34
return value
elif fromUnit == "mi" and toUnit == "yd":
# do miles to yards conversion
value = value * 1760
return value
else:
raise ConversionNotPossible("Incompatible units. Conversion is not possible.")
class ConversionNotPossible(Exception):
pass
|
1a964f608285f1822d8a94412338f22bb8a7a7d2 | klamb95/flask_homework | /solution/tests/calculator_test.py | 544 | 3.625 | 4 | import unittest
from modules.calculator import *
class TestCalculator(unittest.TestCase):
def test_add_3_and_2_returns_5(self):
result = add(2,3)
self.assertEqual(5, result)
def test_subtract_2_from_3_returns_1(self):
result = subtract(3,2)
self.assertEqual(1, result)
def test_multiply_3_and_2_returns_6(self):
result = multiply(3,2)
self.assertEqual(6, result)
def test_divide_3_by_2_returns_1_5(self):
result = divide(3,2)
self.assertEqual(1.5, result)
|
075fe0d96f70ca6f24a7f03a9c7a2bac51cfb2bc | RomanAdriel/AlgoUnoDemo | /RomanD/ejercicios_rpl/estructuras_basicas/ej_5_triangulos.py | 1,275 | 4.3125 | 4 | """Escribir un programa que solicite el ingreso del valor de los 3 lados de un triángulo. Luego, debe imprimir por
pantalla si el triángulo es equilátero (3 lados iguales), escaleno (3 lados distintos) o isósceles (2 lados iguales).
Ejemplos:
Ingrese la longitud del primer lado del triangulo: 10
Ingrese la longitud del segundo lado del triangulo: 10
Ingrese la longitud del tercer lado del triangulo: 10
Es equilatero
Ingrese la longitud del primer lado del triangulo: 10
Ingrese la longitud del segundo lado del triangulo: 15
Ingrese la longitud del tercer lado del triangulo: 20
Es escaleno
Ingrese la longitud del primer lado del triangulo: 10
Ingrese la longitud del segundo lado del triangulo: 5
Ingrese la longitud del tercer lado del triangulo: 10
Es isosceles"""
lado_uno = int(input("Ingrese la longitud del primer lado del triangulo: "))
lado_dos = int(input("Ingrese la longitud del segundo lado del triangulo: "))
lado_tres = int(input("Ingrese la longitud del tercer lado del triangulo: "))
if lado_uno == lado_dos and lado_dos == lado_tres:
print("Es equilatero")
elif lado_uno == lado_dos or lado_uno == lado_tres or lado_dos == lado_tres:
print("Es isosceles")
else:
print("Es escaleno") |
777eb1e60defc984e10cc82432df4331a516e029 | Da1anna/Data-Structed-and-Algorithm_python | /基础知识/贪心算法/经典例题.py | 4,989 | 3.71875 | 4 | '''
1.[分数背包问题] 可以用贪心求最优解
有一个背包,背包容量是M=150。有7个物品,物品可以分割成任意大小。
要求尽可能让装入背包中的物品总价值最大,但不能超过总容量。
物品 A B C D E F G
重量 35 30 60 50 40 10 25
价值 10 40 30 50 35 40 30
'''
class goods():
def __init__(self,id,weight,value):
self.id = id
self.w = weight
self.v = value
def __str__(self):
return str(self.id) + ' w:'+ str(self.w) + ' v:' + str(self.v)
def greedy_for_bag(cap:int,some_goods:list):
#对物品列表按重量价值比由高到低排序
some_goods.sort(key=lambda goods:- (goods.v/goods.w))
# print('排序后:',end='')
# for i in some_goods:
# print(i,end=' | ')
res = []
i = 0
for item in some_goods:
if cap < item.w:
break
res.append(item)
i += 1
cap -= item.w
if len(res) != len(some_goods) and cap != 0:
res.append(goods(some_goods[i].id,cap,cap/some_goods[i].w*some_goods[i].v))
#输出结果
# print()
print('结果集:',end='')
for i in res:
print(i,end=' | ')
return res
some_goods = [goods('A',35,10),goods('B',30,40),goods('C',60,30),goods('D',50,50)]
# greedy_for_bag(100,some_goods)
# a = goods('A',35,10)
# print(a) #打印单个class:goods可以
# print(some_goods) #不能打印一个装有goods的列表?????
'''
2.[0-1背包问题] 用贪心不能求求最优解,可用动态规划求解
物品不可分割,其它同分数背包问题
'''
'''
3.[均分纸牌]
有N堆纸牌,编号分别为1,2,…,n。每堆上有若干张,但纸牌总数必为n的倍数.
可以在任一堆上取若干张纸牌,然后移动。
移牌的规则为:在编号为1上取的纸牌,只能移到编号为2的堆上;在编号为n的堆上取的纸牌,只能移到编号为n-1的堆上;
其他堆上取的纸牌,可以移到相邻左边或右边的堆上。现在要求找出一种移动方法,用最少的移动次数使每堆上纸牌数都一样多。
例如:n=4,4堆纸牌分别为:① 9 ② 8 ③ 17 ④ 6
移动三次可以达到目的:从③取4张牌放到④ 再从③区3张放到②然后从②去1张放到①。
输入输出样例:4
9 8 17 6
输出:3
注:感觉跟贪心算法不算很有关系
'''
def junfen_cards(lst:list) -> int:
k = sum(lst)//len(lst)
n = 0
for i in range(len(lst)-1):
need = k - lst[i]
if need != 0:
lst[i] = k
lst[i+1] = lst[i+1] - need
n += 1
return n
# res = junfen_cards([0,0,5,0,0])
# print(res)
'''
4.[找零钱问题]
假设只有 1 分、 2 分、5分、 1 角、二角、 五角、 1元的硬币
求1.84元最少找几个硬币?
注:这个零钱问题可以用贪心求解,因为零钱数额很 “标致”
'''
def find_change(lst:list,change):
# n = 0 #只计算个数
lst_n = [0 for _ in lst] #列举找了哪些硬币
while change != 0:
if change >= lst[-1]:
change = round(change - lst[-1],2) #限制数字的位数,因为浮点数计算不精确
# n += 1
lst_n[lst.index(lst[-1])] += 1
else:
lst.pop()
return lst_n
lst= [0.01,0.02,0.05,0.1,0.2,0.5,1]
change = 1.85
# res = find_change(lst,change)
# print(res)
#
'''
5.[求最大子数组之和]
问题:给定一个整数数组(数组元素有负有正),求其连续子数组之和的最大值。
'''
'''
6.[汽车加油问题]
一辆汽车加满油后可行驶n公里。旅途中有若干个加油站。设计一个有效算法,
指出应在哪些加油站停靠加油,使沿途加油次数最少。
对于给定的n(n <= 5000)和k(k <= 1000)个加油站位置,编程计算最少加油次数。
'''
'''
7.[救生艇]
第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最对容纳2个人
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
示例 1:
输入:people = [1,2], limit = 3
输出:1
解释:1 艘船载 (1, 2)
示例 2:
输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
示例 3:
输入:people = [3,5,3,4], limit = 5
输出:4
解释:4 艘船分别载 (3), (3), (4), (5)
提示:
1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000
'''
def jiushengting(people:list, limit:int) -> int:
one_ship = []
res = []
i,j = 0,len(people) - 1
people.sort()
while i <= j:
one_ship.append(people[j]) #people[j]怎么都是要装的
if people[i] + people[j] <= limit:
one_ship.append(people[i])
i += 1
j -= 1
res.append(one_ship)
one_ship = [] #没循环一次,一定走一艘船
print(res)
return len(res)
# print(jiushengting([5,1,2,4],6)) |
2d19baa307d5e388879d800005b387dbe33bc3a1 | chimnanishankar4/Logic-Building | /Day-7/3.py | 534 | 4.5 | 4 | '''
3.Define a class named Shape and its subclass Square. The Square class
has an init function which takes a length as argument.
Both classes have a area function which can print the
area of the shape where Shape's area is 0 by default.
'''
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square:
def __init__(self,l):
super().__init__()
self.length=l
def area(self):
return self.length*self.length
s=Square(3)
print("The area of square:",s.area())
|
6c2819c58815c0f59d038678ba69b534e618b8b3 | twood1/LeetCode | /Medium/MinSquares.py | 1,263 | 3.609375 | 4 | # Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...)
# which sum to n.
# Input: n = 12
# Output: 3
# Explanation: 12 = 4 + 4 + 4.
import math
class Solution(object):
def numSquares(self, n):
if n == 0:
return 0
# edge case, exit immediately if n is a perfect square
squares = sorted(set([int(math.pow(i, 2)) for i in range(1, int((math.sqrt(n))) + 1)]))
if n in squares:
return 1
# the worst case is just 1*n. Initialize our array to start with this.
opt = [i for i in range(0,n+1)]
for i in range(2, len(opt)):
currentMin = opt[i]
# for candidateNum in range(1, int(math.sqrt(n)) + 1):
# currentSquare = int(math.pow(candidateNum, 2))
for currentSquare in squares:
if currentSquare > i:
break
if (i - currentSquare) >= 0:
if opt[i - currentSquare] + 1 < currentMin:
currentMin = opt[i - currentSquare] + 1
if currentMin == 1:
break
opt[i] = currentMin
return opt[n]
sol = Solution()
print(sol.numSquares(41)) |
79685422b90ada7beae46f96dc4fa550d05fed2f | longjiazhen/learn-python-the-hard-way | /ex3.py | 605 | 4.125 | 4 | #coding:utf-8
print "I will now count my chikens:"
print "Hens",25+30/6 #30
print "Roosters",100-25*3%4 #100-75%4=100-3=97
print "Now I will count the eggs:"
print 3+2+1-5+4%2-1/4+6 #1+0+0+6=7
print "Is it true that 3+2<5-7?"
print 3+2<5-7 #False
print "What is 3+2?",3+2 #5
print "What is 5-7?",5-7 #-2
print "Oh,that's why is False"
print "How about some more"
print "Is it greater?",5>-2 #True
print "Is it greater or equal?",5>=-2 #True
print "Is it less or equal?",5<=-2 #False
print "20/3",20/3 #6
print "20.0/3",20.0/3 #6.6667
print "20/3.0",20/3.0 #6.6667
print "20.0/3.0",20.0/3.0 #6.6667
|
9f90a33051d8fefceb44e2b385131d37e33edf59 | Oleksandr015/NIX_edu_solutions | /task_6/sixth_task.py | 849 | 3.671875 | 4 | '''Дан список из словарей:
list_ = [
{'name': 'Alex', 'age': 25},
{'name': 'Oleg', 'age': 23},
{'name': 'Anna', 'age': 32},
{'name': 'Igor', 'age': 50},
{'name': 'Anton', 'age': 17},
]
Отфильтруйте его так, чтобы в нём остались только люди, имена которых начинаются с буквы "А", и возраст между 18 и 30 годами включительно.
В итоговом результате должен быть такой список:
[{'name': 'Alex', 'age': 25}]'''
list_ = [
{'name': 'Alex', 'age': 25},
{'name': 'Oleg', 'age': 23},
{'name': 'Anna', 'age': 32},
{'name': 'Igor', 'age': 50},
{'name': 'Anton', 'age': 17},
]
print([x for x in list_ if x['name'][0] == 'A' and x['age'] in range(18, 31)])
|
03dd980579e284402dd3e6ba61a743466d98a8f6 | rajeshberwal/dsalib | /dsalib/Array/search.py | 523 | 4.28125 | 4 | def search(arr: list, elem: object) -> int or None:
"""Uses Linear Search for searching the given element.
It will returns index for given element if element is present in the list.
Args:
arr (list): list of elements
elem (object): element that we want to search
Returns:
int or None: if element is present in the list then will return index of that element otherwise return None
"""
for i in range(len(arr)):
if arr[i] == elem:
return i
return None |
08e9c46a6df3483f5aafae545761e8ea60af5443 | Vasiliy1982/repo24122020 | /praktika_urok5_2.py | 254 | 4.03125 | 4 | # практическое задание 2
число = int(input("Введите число:"))
число_крат7 = число % 7
if число_крат7 > 0:
print(число, "не кратно 7")
print(число, "кратно 7")
|
3b54a3a3f215a76b2d159b88791d52519a50349d | dragonsarebest/Portfolio | /Code/3October2020.py | 1,192 | 3.640625 | 4 | class Solution:
def isValid(self, s):
openBraces = {'(' : 0, '[' : 0, '{' : 0}
closedBraces = {')' : 0, ']' : 0, '}' : 0}
stack = []
for i in range(0, len(s)):
brace = s[i]
if(brace in openBraces.keys()):
openBraces[brace] += 1
stack.append(brace)
if(brace in closedBraces.keys()):
closedBraces[brace] += 1
lastOpen = stack.pop()
#if the last open bracket isnt the same type - return false
if((lastOpen == '[' and brace != ']' or lastOpen == '(' and brace != ')' or lastOpen == '{' and brace != '}')):
return False
#if the number of open & closed brackets dont match
#then its invalid.
if(len(stack) != 0):
return False
return True
# Test Program
s = "()(){(())"
# should return False
print(Solution().isValid(s))
s = ""
# should return True
print(Solution().isValid(s))
s = "([{}])()"
# should return True
print(Solution().isValid(s))
|
a535b027889670afb1febbbd036ed2c8ca44bf16 | iamanx17/dslearn | /linkedlist/printati.py | 234 | 3.625 | 4 | from linkedlist import takeinput, printdata
def printati(head,i):
count=0
while count<i:
head=head.next
count+=1
return head.data
head=takeinput()
printdata(head)
i=int(input())
print(printati(head, i))
|
ec5420107350ed227750c052240564cfe91c20fb | petitepirate/interviewQuestions | /q0109.py | 835 | 4.125 | 4 | # This problem was asked by Cisco.
# Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped,
# the 3rd and 4th bit should be swapped, and so on.
# For example, 10101010 should be 01010101. 11100010 should be 11010001.
# Bonus: Can you do this in one line?
#___________________________________________________________________________________________________
# Solution
# We can do this by applying a bitmask over all the even bits, and another one over all the odd bits.
# Then we shift the even bitmask right by one and the odd bitmask left by one.
def swap_bits(x):
EVEN = 0b10101010
ODD = 0b01010101
return (x & EVEN) >> 1 | (x & ODD) << 1
# In one line, that would be:
def swap_bits(x):
return (x & 0b10101010) >> 1 | (x & 0b01010101) << 1
|
9207750aa057675633d9c18fb7b1ea8ad5c3f007 | CGodiksen/ritmo-discord | /ritmo.py | 9,609 | 3.859375 | 4 | """A simple discord bot named Ritmo. Ritmo is a music bot that has expanded functionality through spotify integration.
The discord bot is implemented using a class based design with the "discord.Client" superclass from the
"discord" python package.
"""
import json
import discord
import os
import youtube
from song_queue import SongQueue
from player import Player
from spotify_playlist import SpotifyPlaylist
class Ritmo(discord.Client):
"""
Class representing a discord bot object. The function "on_message" from the super class
"discord.Clint" is overwritten to implement the functionality of the available commands.
"""
def __init__(self, **options):
self.song_queue = SongQueue()
super().__init__(**options)
self.player = None
async def on_ready(self):
"""Displaying information about the bot and setting the activity when it is ready to run."""
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
# Setting the activity to "listening to !help" to make it easier for people to learn how Ritmo works.
activity = discord.Activity(name='!help', type=discord.ActivityType.listening)
await client.change_presence(activity=activity)
async def on_message(self, message):
"""
This method is called every time a message is sent and if the message contains
a command then that command is executed via another class method.
"""
# Ignore if the message is from the bot itself.
if message.author == self.user:
return
if message.content == "!hi":
await message.channel.send("Hi!")
if message.content.startswith("!play"):
await self.play(message)
if message.content.startswith("!stop"):
if self.player is not None:
await self.stop(message)
if message.content.startswith("!pause"):
if self.player is not None:
self.player.pause()
if message.content.startswith("!resume"):
if self.player is not None:
self.player.resume()
if message.content.startswith("!skip"):
if self.player is not None:
self.player.skip()
if message.content.startswith("!shuffle"):
self.song_queue.shuffle()
if message.content.startswith("!queue"):
await message.channel.send(str(self.song_queue))
if message.content.startswith("!np"):
await self.player.now_playing(message)
if message.content.startswith("!create playlist"):
SpotifyPlaylist(message.content[17:], message.guild.id)
await message.add_reaction("\N{THUMBS UP SIGN}")
if message.content.startswith("!delete playlist"):
await self.delete_playlist(message)
if message.content.startswith("!list playlists"):
await self.display_playlists(message)
if message.content.startswith("!info"):
await self.display_playlist_info(message)
if message.content.startswith("!tracklist"):
await self.display_tracklist(message)
if message.content.startswith("!help"):
await self.display_help(message)
async def play(self, message):
"""
Adds the request to the queue and starts playing songs from the queue. If the request is the name of a saved
playlist then we put every song from that playlist in the queue. Creates a player if there is none.
"""
# Creating a player if there currently is none.
if self.player is None:
voice_channel = message.author.voice.channel
self.player = await Player.create(voice_channel, self.user, self.song_queue)
# Getting the playlist names for the specific server by finding the filenames and removing ".pickle".
playlist_names = [playlist_name[:-7] for playlist_name in os.listdir("playlists/" + str(message.guild.id))]
# If the content following "!play" is the name of a saved playlist then we push every song from the playlist.
if message.content[6:] in playlist_names:
playlist = await SpotifyPlaylist.load_playlist(message.content[6:], message.guild.id, message.channel)
for song in playlist.tracklist:
self.song_queue.push_song(song)
else:
# Appending the requested song to the song queue.
self.song_queue.push_song(youtube.get_video_title_url(message.content[6:]))
self.player.play()
async def stop(self, message):
"""Stops the audio and disconnects the bot from the voice channel."""
await self.player.stop(message)
self.player = None
@staticmethod
async def delete_playlist(message):
try:
os.remove("playlists/" + str(message.guild.id) + "/" + message.content[17:] + ".pickle")
await message.add_reaction("\N{THUMBS UP SIGN}")
except FileNotFoundError:
await message.channel.send("```There is no playlist with that name.```")
@staticmethod
async def display_tracklist(message):
"""
Displays the tracklist of a playlist by sending 25 songs at a time. We are limited to 25 songs due to the
character limit on discord messages.
"""
playlist = await SpotifyPlaylist.load_playlist(message.content[11:], message.guild.id, message.channel)
counter = 0
while counter < len(playlist.tracklist):
# Encapsulating the string representation in "```" to put the text in a code block in discord.
playlist_str = "```"
playlist_str += playlist.get_tracklist_str(counter, counter + 25)
# Completing the code block encapsulation.
playlist_str += "```"
await message.channel.send(playlist_str)
counter += 25
@staticmethod
async def display_playlists(message):
"""Displays the currently available playlists for the server."""
# Encapsulating the string representation in "```" to put the text in a code block in discord.
playlists_str = "```"
# Getting the playlist names for the specific server by finding the filenames and removing ".pickle".
playlist_names = [playlist_name[:-7] for playlist_name in os.listdir("playlists/" + str(message.guild.id))]
# If the server has no playlists then we inform the user of that.
if not playlist_names:
await message.channel.send("```This server has no playlists.```")
return
for counter, playlist_name in enumerate(playlist_names):
playlist = await SpotifyPlaylist.load_playlist(playlist_name, message.guild.id, message.channel)
playlists_str += str(counter + 1) + ". " + playlist.get_info_str(verbose=False) + "\n"
# Completing the code block encapsulation.
playlists_str += "```"
await message.channel.send(playlists_str)
@staticmethod
async def display_playlist_info(message):
"""Displays full information about a playlist."""
# Encapsulating the string representation in "```" to put the text in a code block in discord.
info_str = "```"
playlist = await SpotifyPlaylist.load_playlist(message.content[6:], message.guild.id, message.channel)
info_str += playlist.get_info_str()
# Completing the code block encapsulation.
info_str += "```"
await message.channel.send(info_str)
@staticmethod
async def display_help(message):
"""Displays a help message that lists the available commands with accompanying explanations."""
# Encapsulating the string representation in "```" to put the text in a code block in discord.
help_str = "```"
help_str += "!play *Song or Playlist* - Joins your voice channel and plays the song or playlist that " \
"you requested.\n\n"
help_str += "!stop - Stops the music and leaves the voice channel.\n\n"
help_str += "!pause - Pauses the music.\n\n"
help_str += "!resume - Resumes the music.\n\n"
help_str += "!skip - Skips the current song and continues to the next song in the queue.\n\n"
help_str += "!shuffle - Shuffles the song queue.\n\n"
help_str += "!queue - Displays the song queue.\n\n"
help_str += "!np - Displays the currently playing song.\n\n"
help_str += "!create playlist *Spotify playlist URI* - Creates a new playlist containing the songs from the" \
" given spotify playlist URI. To get the playlist URI, right-click a playlist on spotify -> Share" \
" -> Copy spotify URI.\n\n"
help_str += "!delete playlist *Playlist name* - Deletes the playlist with the given name.\n\n"
help_str += "!list playlists - Displays the list of available playlists.\n\n"
help_str += "!info *Playlist name* - Displays information about the playlist with the given name.\n\n"
help_str += "!tracklist *Playlist name* - Displays the tracklist of the playlist with the given name.\n\n"
# Completing the code block encapsulation.
help_str += "```"
await message.channel.send(help_str)
if __name__ == '__main__':
client = Ritmo()
# Pulling the token from the config file and using it to set up the bot.
with open("config.json", "r") as config:
config_dict = json.load(config)
client.run(config_dict["token"])
|
229e12c93432d1c66259be470b52ccc25d55aa13 | RedPandaDev/Problemsolving-in-python | /week_7/tasks.py | 1,708 | 3.65625 | 4 | ######### 1 #########
# def counting(i):
# print(i)
# i -= 1
# if i == 0: return
# counting(i)
def counting(i):
print(i)
i *=2
if i > 1024: return
counting(i)
######## 3 #########
def printList(a):
while len(a) > 0:
print(a.pop(0))
#### Doesn't print twice as 'pop' removes the items from the list
######## 4 ########
#import csv
# with open('facup.csv') as csvfile:
# rdr = csv.reader(csvfile)
# for row in rdr:
# print(row[0] + " last won in " + row[1])
# print(type(row[1])) ### year is entered as string so integer operations would not work
# year = int(row[1])
# if year % 2 == 0:
# print(True)
# else:
# print(False)
######## 5 ########
import csv
def winners():
with open('MultipleTourWinners.csv') as csvfile:
rdr = csv.reader(csvfile)
for row in rdr:
if row[1] == "FRA":
print(row[0] + ", "+ row[2])
####### 6 ########
def iterate():
for n in range(0,101,2):
print(n)
####### 7 #######
def enu_winners():
with open('MultipleTourWinners.csv') as csvfile:
rdr = csv.reader(csvfile)
for i, wins in enumerate(rdr):
if int(wins[2]) >= 3:
print(i, "with", wins[2], "wins.")
######## 8 ######
def mark():
mark = int(input("Enter mark: "))
if mark <= 50 or mark > 60:
# Mark can't be both lower than 50 and higher than 60,
# 'and' changed to 'or' - semantic
# Mark is taken as string but used as int - runtime
print("Result is 2:2")
# Print the first 10 square numbers
for n in range (1,11): # range can't be from higher to lower, swaped places - semantic
print(n * n)
def f(n):
if n == 1 or n == 2: #### n = 1, needs == instead - syntax
return 1
else: ##### Mising double colon - syntax
return f(n-1) + f(n-2) |
0d4199f051426d2ce7dce78d222e5e668a34146b | cahilld/stream2 | /day2/hello.py | 384 | 3.765625 | 4 | def addition(x,y):
return(x+y)
print (addition("hello ","world"))
def size(z):
if z>10:
return("BIG")
else:
return("small")
print(size(12))
def aresame(a,b):
return(a==b)
print(aresame(5,5))
def shape(o,p):
if o>p:
return ("Bigger")
if o<p:
return ("Smaller")
else:
return ("Same")
print (shape(2,2)) |
742b833db84d32bbdab561391c60299c8c4abd8e | marioDonaire/GPS | /main.py | 699 | 3.9375 | 4 | #!/usr/bin/python3
from Problema import Problema
from Solucionador import Solucionador
def main():
switch = {0:"Anchura", 1:"Costo uniforme", 2:"Profundidad simple", 3:"Profundidad iterativa", 4:"Profundidad acotada",5:"Voraz",6:"A*"}
json = input("Inserte el nombre del json: ")
problema = Problema(str(f"json/{json}.json"))
num = input("Que estrategia quieres usar?\n0.Anchura\n1.Costo Uniforme\n2.Profundidas simple\n3.Profundidad iterativa\n4.Profundidad recursiva\n5.Voraz\n6.A*\n")
estrategia =switch.get(int(num))
num = input("Profundidad maxima:")
Solucionador(problema, estrategia, int(num))
print("Solucion creada")
if __name__ =='__main__':
main() |
bc7495af31fcab4d4570f142256db81f85b562dc | tragicmj/python | /basics/guessNumber.py | 178 | 3.90625 | 4 | chances = 3
while chances != 0:
chances -= 1
x = int(input("Guess Number: "))
if(x == 9):
print("You Won!")
break
else:
print("Sorry You Failed")
|
3a81b3e088b0c749eb40ec065ea7cf97409a46d4 | HazelIP/pands-problem-sheet | /plottask.py | 854 | 4 | 4 | # The program displays a plot of the functions,
# f(x)=x, g(x)=x2 and h(x)=x3 in the range [0, 4] on the one set of axes.
# author: Ka Ling Ip
import numpy as np
import matplotlib.pyplot as plt
f = np.array ([0,1,2,3,4]) #f(x) in range [0,4]
g = f * f #g(x) = f squared
h = f * f * f # h(x) = f cubed
# create a plot showing the 3 functions, with lines of different colors ref[8.1]
plt.plot (f,'r', linewidth = '3', label = 'f(x)') #f(x) in red line
plt.plot (g,'b', linewidth = '3', label = 'g(x)') #g(x) in blue line
plt.plot (h,'y', linewidth = '3', label = 'h(x)') #h(x) in yellow line
plt.title("Functions f(x), g(x), h(x)") # ref[8.2]
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.legend(loc="upper left")
plt.show()
#ref[8.1]: https://www.w3schools.com/python/matplotlib_line.asp
#ref[8.2]: https://www.w3schools.com/python/matplotlib_labels.asp |
4525a8c47f22e40b601035a67a71be9d569c46f3 | naveenkommineni/Week3 | /Flipcoin.py | 373 | 3.546875 | 4 | #Flip coin prob
lst=['H','T']
import random
heads=0
tails=0
for i in range(22):
n=random.choice(lst)
if n=='H':
heads+=1
else:
tails+=1
print('Number of heads:',heads)
print('Number of tails:',tails)
poh=(heads/i)*100
pot=(tails/i)*100
print('probability percentage of heads:',poh)
print('probability percentage of tails:',pot)
|
d902168c25d9690ebf8f71463c39c4b55f73b0a1 | DivyanshMangla/Games | /Frosthack/Main.py | 1,134 | 3.90625 | 4 | while(True):
print("Welcome to the Main Menu")
print("Please type the code of the game that you want to play")
print("Tic Tac Toe: code = 1")
print("Guessing Game: code = 2")
print("IPL Quiz: code = 3")
print("To Exit the Game code = 4")
n=int(input())
if(n==1):
print("Welcome to Tic Tac Toe")
import TicTacToe
exec(open('TicTacToe.py').read())
continue
elif(n==2):
print("Welcome to the guessing game")
import GuessingGame
exec(open('GuessingGame.py').read())
continue
elif(n==3):
print("Welcome to IPL Quiz")
import QuizzingGame
exec(open('QuizzingGame.py').read())
continue
elif(n==4):
print("Do you want to exit the Game?? (y/n)")
n1=input()
if(n1=="y"):
print("Thank You for playing the small Games")
print("We Hope You get well Soon")
break
else:
continue
else:
print("Wrong code!!!!!")
print("Please Try Again")
|
4910bee05a89799c324016e3a382f79622a3e7ab | RizkiAsmoro/python | /Arithmetic.py | 1,163 | 3.84375 | 4 | '''
Basic Arithmetic base on input
'''
val_a = float(input ('Input value for a ='))
val_b = float(input ('Input value for b ='))
val_c = float(input ('Input value for c ='))
# addition
add_result = val_a + val_b
print (val_a,"+",val_b,"=",add_result)
# subtraction
subtract_result = val_a - val_b
print (val_a,"-",val_b,"=",subtract_result)
# multiplication
multipy_result = val_a * val_b
print (val_a,"*",val_b,"=",multipy_result)
# division
div_result = val_a / val_b
print (val_a,"/",val_b,"=",div_result)
# Eksponent
eks_result = val_a ** val_b
print (val_a,"Eksponent",val_b,"=",eks_result)
# Modulus / remainder of the division
mod_result = val_a % val_b
print (val_a,"modulus",val_b,"=",mod_result)
# Floor division / rounding off the division
fd_result = val_a // val_b
print (val_a,'floor division',val_b,'=',fd_result)
# Precedence (priority)
'''
order of priority
1. ()
2. Eksponen **
3. multiplication, pdivision, modulus, floor division
4. addition & subtraction
'''
preced = val_a ** val_b * val_c + val_a / val_b - val_b % val_c // val_a
print (val_a,'**',val_b,'*',val_c,'+',val_a,'/',val_b,'-',val_b,'%',val_c,'//',val_a,'=',preced)
|
04458ea403b678e03cf12496bfe87565549dd4f3 | AnXnA05/python_practic | /0816_cal_area_n_perimeter.py | 159 | 3.71875 | 4 | r = float(input('请输入圆形对半径 = '))
pi = 3.1415926
area = pi*r*r
perimeter = pi*r*2
print(f'圆形的周长是{perimeter:.2f},面积是{area:.2f}') |
a478365a6230f550e731faebe1810a8246c57f87 | broadinstitute/catch | /catch/utils/dynamic_load.py | 1,298 | 3.921875 | 4 | """Functions for dynamically loading modules and functions.
"""
import importlib
import os
__author__ = 'Hayden Metsky <hayden@mit.edu>'
def load_module_from_path(path):
"""Load Python module in the given path.
Args:
path: path to .py file
Returns:
Python module (before returning, this also executes
the module)
"""
path = os.path.abspath(path)
# Use the filename (without extension) as the module name
_, filename = os.path.split(path)
module_name, _ = os.path.splitext(filename)
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
# Execute the module
spec.loader.exec_module(module)
return module
def load_function_from_path(path, fn_name):
"""Load Python function in a module at the given path.
Args:
path: path to .py file
fn_name: name of function in the module
Returns:
Python function
Raises:
Exception if the module at path does not contain a function
with name fn_name
"""
module = load_module_from_path(path)
if not hasattr(module, fn_name):
raise Exception(("Module at %s does not contain function %s" %
(path, fn_name)))
return getattr(module, fn_name)
|
dce5e5778fe60d42eae643428e7691284ac93186 | wileyzhao/Algorithms-Specialization | /course1_codes/selection_sort.py | 565 | 3.703125 | 4 | import random
'''
selection sort:'
n*n - n
O(n*n)
12 41 4 7 99 45 34 6 31 8 90 54
4 41 12 7
'''
def main():
for i in range(20):
x = random.randint(1,100)
print(x, end=' ')
print()
arrStr = input('Please input a list of numbers:')
arr = arrStr.split(' ')
arr = list(map(int,arr))
arrR = selection_sort(arr)
print(arrR)
def selection_sort(arr):
for i in range(len(arr)):
k = arr[i]
for j in range(i+1,len(arr)):
if k > arr[j]:
temp = k
k = arr[j]
arr[j] = temp
j+=1
arr[i] = k
return arr
if __name__ == '__main__':
main() |
05a4cb563cbd2989458b3e81d9729a4d4c827480 | liazylee/python | /my_py_notes_万物皆对象/面向对象(万物皆对象)/深拷贝与浅拷贝/copy_deepcopy_可变对象.py | 588 | 3.765625 | 4 | # coding = utf-8
'''
@author = super_fazai
@File : copy_deepcopy_可变对象.py
@Time : 2017/8/3 20:32
@connect : superonesfazai@gmail.com
'''
# 对可变对象的拷贝
from copy import copy,deepcopy
a = [1,2,3]
b = a
c = copy(b)
d = deepcopy(a)
a.append(4)
print(id(a) == id(b)) # ---> True
print(id(a) == id(c)) # ---> False
print(id(a) == id(d)) # ---> False
print('')
from copy import copy,deepcopy
a = [1,2,3]
b = a
c = copy(b)
d = deepcopy(a)
a = [1,2,3,4,5]
print(id(a) == id(b)) # ---> False
print(id(a) == id(c)) # ---> False
print(id(a) == id(d)) # ---> False |
fa8fd86b85a8476cb05a1bd9b8936436ac43c3e3 | q798010412/untitled2 | /6.22/判断环链.py | 472 | 3.953125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
def is_circle(head):
pre=head
cur=head
while cur and cur.next:
pre=pre.next
cur=cur.next.next
if pre==cur:
return True
return False
if __name__ == '__main__':
h=Node(0)
a=Node(1)
b=Node(2)
c=Node(3)
d=Node(4)
e=Node(5)
h.next=a
a.next=b
b.next=c
c.next=e
e.next=b
print(is_circle(h))
|
4efc011e4f332adc51537757db6f0775249422c2 | mariaperezdeayalas/Shark-Attacks-Pandas-Project- | /SRC/cleaning_functions.py | 1,524 | 3.6875 | 4 |
# First I create a dictionary indicating which moment of the day represent each hour
# horarios = {'Night': ['00', '01', '02', '03', '04', '05', '20', '21', '22', '23'], 'Morning': ['06', '07', '08', '09', '10', '11'], 'Afternoon': ['12', '13', '14', '15', '16'], 'Evening': ['17', '18', '19']}
# Then I create the function so I can replace the hour by a specific moment of the day
def cambia_hora(x):
horarios = {'Night': ['00', '01', '02', '03', '04', '05', '20', '21', '22', '23'], 'Morning': ['06', '07', '08', '09', '10', '11'], 'Afternoon': ['12', '13', '14', '15', '16'], 'Evening': ['17', '18', '19']}
for key, values in horarios.items():
if x[0:2] in values:
return key
return x
# Now, for my hypotheses #3 I need to use the regex function to simplify the column of Activities. This way I can identify in a simple way if surfing is actually the activity ending the most in fatality
import re
def cambia_activity(x):
dicc_activities = {
'Surfing': '.*urf.*|.*addl.*|.*oard.*|.*Board.*|.*surf.*|.+Surf.*',
'Swimming': '.*wi.*|.*mmi.*|.*bath.*|.*ading.*|.*swim.*',
'Fishing': '.*shin.*|.*fish.*|.*Fish.*',
'Diving': '.*spear.*|.*div.*|.*photo.*|.*subm.*|.*merged.*|.*norkel.*|.*scuba.*',
'Boating': '.*kay.*|.*yak.*|.*banana.*|.*sail.*|.*atch.*|.*anoing.*',
'Feeding': '.*feed.*|.*food.*'
}
for key, values in dicc_activities.items():
if re.match(values, x):
return key
return 'Other'
|
c9d69e5a3da06416b4bc94dc274c2d8b53995ead | iota-cohort-dc/Daniel-Perez | /Python/Python_Fun/string&list.py | 89 | 3.859375 | 4 | str= "if monkeys like bananas, then i must be a monkey"
print string&list.find("monkey")
|
7e51c52c6e5630dae99ebfc82526721c00f6248b | BlakeBeyond/python-onsite | /week_02/09_functions/03_dog.py | 613 | 4.21875 | 4 | '''
Write a program with the following three functions:
- bark - this function should not take in any arguments and should print the string "bark bark"
- eat - takes in parameters food_item and amount and prints out "The dog ate <amount> of <food_item>
- sleep - calls the python sleep method to sleep the program for 5 seconds.
'''
import time
def sleep():
time.sleep(5)
flag = True
while flag:
for i in range(1, 11):
print("bark bark")
i += i
if i == 10:
flag = False
def eat(food_item, amount):
print("Dog ate", amount, "of", food_item)
|
7ebe0d95378b5ced041aec74033f033a87e83946 | JFluo2011/leetcode | /leetcode/strings/003_longest_substring_without_repeating_characters.py | 1,474 | 3.515625 | 4 | class Solution:
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
# return self.o_2n(s)
return self.o_n(s)
def o_2n(self, s):
# worst case: O(2n)
i, j, length = 0, 0, 0
seen = set()
while j < len(s):
if s[j] not in seen:
seen.add(s[j])
j += 1
else:
length = max((j - i), length)
seen.remove(s[i])
i += 1
else:
length = max((j - i), length)
return length
def o_n(self, s):
# O(n)
# i: 字串起点 j:字串终点
i, j, length = 0, 0, 0
# 存储每个字符的value: index+1
dct = {}
while j < len(s):
if s[j] in dct.keys():
# 取出字串最大起始位置
i = max(dct[s[j]], i)
# 初始化/更新字符s[j]的value: index+1
dct[s[j]] = j + 1
j += 1
# 计算无重复字串长度
length = max((j - i), length)
return length
def main():
args = [
'',
'abba',
'abcdef',
'abcabcbb',
'aaabb',
'bbbbb',
'pwwkew',
'pwxawkew',
'wpbwxakwjw',
]
solution = Solution()
for arg in args:
print(solution.length_of_longest_substring(arg))
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.