blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
50826a332fbbbe9f3cae4ab168bda200dd8184e6 | libo-sober/LearnPython | /day13/datetime_demo.py | 1,905 | 4.25 | 4 | """
datetime:日期时间模块
封装了一些和日期时间相关的类
date
time
datetime
timedelta
"""
import datetime
# # date类:
# d = datetime.date(2010, 10, 10)
# print(d) # 2010-10-10
# # 获取date对象的各个属性
# print(d.year, d.month, d.day) # 2010 10 10
#
#
# # time类:
# t = datetime.time(10, 48, 59)
# print(t) # 10:48:59
# print(t.hour, t.minute, t.second) # 10 48 59
#
#
# # datetime
# dt = datetime.datetime(2010, 11, 11, 11, 11, 11)
# print(dt) # 2010-11-11 11:11:11
# # datetime中的类,主要是用于数学计算的。
# # timedelta:时间变化量。
# # class datetime.timedelta(days=0, seconds=0, microseconds=0,
# # milliseconds=0, minutes=0, hours=0, weeks=0)
# td = datetime.timedelta(days=1)
# print(td) # 1 day, 0:00:00
# # 参与数学运算
# # 创建时间对象
# # date, datetime, timedelta 不能和time对象进行运算
# d = datetime.datetime(2010, 10, 10)
# res = d + td
# print(res) # 2010-10-11 00:00:00
# # 时间变化量的计算是否会产生进位?会的。
# t = datetime.datetime(2010, 10, 10, 10, 10, 59)
# td = datetime.timedelta(seconds=3)
# res = t + td
# print(res) # 2010-10-10 10:11:02
# # 练习:计算某一年的二月份有多少天?
# # 普通的算法:根据年份计算是否是闰年,是。29天,否,28天。
# # 用datetime模块
# # 首先创建出指定年份的3月1号,然后让它往前再走一天。
# year = int(input('输入年份:'))
# # 创建指定年份的date对象
# d = datetime.date(year, 3, 1)
# # 创建一天的时间段
# td = datetime.timedelta(days=1)
# res = d - td
# print(res.day)
# 和是时间段进行运算的结果 类型???与另一个操作数保持一致。如果没有秒则不显示不会报错。
d = datetime.date(2010, 10, 10) # 与这个类型保持一致
td = datetime.timedelta(days=1)
res = d - td
print(type(res)) # <class 'datetime.date'>
|
96c5e935ffd34aa174b4bfd7bb35a35b3a44c463 | balloonio/algorithms | /lintcode/dynamic_programming/515_paint_house.py | 889 | 3.6875 | 4 | class Solution:
"""
@param costs: n x 3 cost matrix
@return: An integer, the minimum cost to paint all houses
"""
def minCost(self, costs):
# write your code here
if not costs:
return 0
n = len(costs)
COLORS = 3
# f[i][j] - the lowest cost to build the first i houses under the condition that last house is j colored
f = [[0] * COLORS for i in range(n + 1)]
# cost to build first 0 houses is 0
for i in range(COLORS):
f[0][i] = 0
# paint from first 1 house to first n houses
for i in range(1, n + 1):
for j in range(COLORS):
f[i][j] = math.inf
for k in range(COLORS):
f[i][j] = min(f[i - 1][k], f[i][j]) if j != k else f[i][j]
f[i][j] += costs[i - 1][j]
return min(f[-1])
|
f84abb747a2072f84153e756bbcb1011c4767b0b | GekkouRoid/PycharmProject | /dicetest.py | 440 | 3.734375 | 4 | # Exercise of 9-14
import random
class Dice:
def __init__(self, sides=6):
self.sides = sides
def roll_dice(self):
x = random.randint(1, self.sides)
# print(x)
return x
dice1 = Dice()
dice1.roll_dice()
dice2 = Dice(10)
seq2 = []
for i in range(10):
seq2.append(dice2.roll_dice())
print(seq2)
dice3 = Dice(20)
seq3 = []
for i in range(10):
seq3.append(dice3.roll_dice())
print(seq3)
|
c6214cfbdfd8b68ecb99f7c3b8efab9942bf6014 | AbnerZhu/notebook | /00StudyNote/00Technology/01Program-Language/04Python/workspace/chinahoop/decorator/deco1.py | 266 | 3.546875 | 4 | #!/usr/bin/env python
# coding:utf-8
# 计算平方和
def square_sum(a, b):
print("input: ", a, b)
return a ** 2 + b ** 2
# 计算平方差
def square_diff(a, b):
print("input: ", a, b)
return a ** 2 - b ** 2
print(square_sum(3, 4))
print(square_diff(3, 4)) |
671fc9412ba99d2c5352fed409be5e54eeeec78d | c-nino-a/UP-ACM-entries | /A.riceofskywalker.py | 523 | 3.59375 | 4 | #!/usr/bin/env pypy
import timeit
def main():
r=int(input())
w=int(input())
standard=1/3
actual=r/w
# if(actual!=standard):
# if(actual>standard):
# print("WE NEED MORE WATER.")
# else:
# print("WE NEED MORE RICE.")
# else:
# print("THE RICE IS RIGHT!")
res= "THE RICE IS RIGHT!" if actual==standard else "WE NEED MORE WATER" if actual>standard else "WE NEED MORE RICE"
print(res)
if __name__=="__main__":
main() |
d394d68e203a5dafc2cdbff28951abaca27d3ae3 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/53_4.py | 3,251 | 4.3125 | 4 | Python – Sort dictionary by Tuple Key Product
Given dictionary with tuple keys, sort dictionary items by tuple product of
keys.
> **Input** : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
> **Output** : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
> **Explanation** : 6 < 18 < 32 < 40, key products hence retains order.
>
> **Input** : test_dict = {(20, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
> **Output** : {(6, 3) : 9, (8, 4): 10, (10, 4): 12, (20, 3) : 3, }
> **Explanation** : 18 < 32 < 40 < 60, key products hence adjusts order.
**Method #1 : Using dictionary comprehension + lambda + sorted()**
This is one of the ways in which this task can be performed. In this, we
perform sort() using sorted() and lambda function is used to compute product
over which sort can be performed.
## Python3
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dictionary comprehension + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8,
4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dictionary comprehension reassigs dictionary by order
res = {key: test_dict[key] for key in sorted(test_dict.keys(),
key = lambda ele: ele[1] * ele[0])}
# printing result
print("The sorted dictionary : " + str(res))
---
__
__
**Output**
The original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (6, 4): 12, (5, 6): 3, (8, 4): 10}
**Method #2 : Using dict() + sorted() + lambda**
The combination of above functions can be used to solve this problem. In this,
similar method is used as above method. The only difference being items
arrangement done using dict() rather than dictionary comprehension after
computing keys ordering .
## Python3
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dict() + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8,
4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dict() used instead of dictionary comprehension for rearrangement
res = dict(sorted(test_dict.items(), key = lambda ele:
ele[0][1] * ele[0][0]))
# printing result
print("The sorted dictionary : " + str(res))
---
__
__
**Output**
The original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (6, 4): 12, (5, 6): 3, (8, 4): 10}
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
d4861013c871948c798b48b3841fc54cee42232d | matt-leach/strava-similarity | /utils.py | 864 | 3.578125 | 4 | import math
from constants import EARTH_RADIUS
def dist(p1, p2):
''' calculates distance from coordinates p1 and p2 '''
# both array lat, lng
dlat = p1[0] - p2[0]
dlon = p2[1] - p2[1]
a = math.sin(dlat / 2)**2 + math.cos(p1[0]) * math.cos(p2[0]) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = EARTH_RADIUS * c
return distance
def find_closest(point, path):
''' finds the shortest distance from a point to a path '''
return min([dist(p1, point) for p1 in path])
def gaussian(val1, val2, var):
''' gaussian similarity (1/ to get distance) '''
return 1. / math.exp(-(val1-val2)**2 / (2*var))
def variance(values):
''' calculates variance of some values '''
mean = sum(values) / len(values)
return sum((mean - value) ** 2 for value in values) / len(values)
|
41c96a267f3dc5709faca99ed059f0d3528d1110 | lihujun101/LeetCode | /Tree/L559_maximum-depth-of-n-ary-tree.py | 642 | 3.71875 | 4 | # Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return 0
# 不能这样写,children是个Node的列表[Node1,Node2]
# depth = self.maxDepth(root.children)
if not root.children:
return 1
return max(list(map(self.maxDepth,root.children))) + 1
if __name__ == '__main__':
node = Node(1, None)
s = Solution()
print(s.maxDepth(node))
|
98bce2338962dc243e8a4457b80f22214be087c9 | luisfmelo/hacker-rank-exercises | /hacker-rank/implementation/1-extra-long-factorials.py | 665 | 3.71875 | 4 | #!/bin/python3
def extra_long_factorial(n):
if n < 0 or type(n).__name__ != 'int':
raise ValueError('Not a valid input')
if n <= 1:
return n
return n * extra_long_factorial( n - 1)
def main():
n = int(input().strip())
res = extra_long_factorial(n)
print(res)
def test(n, expected_res):
actual_res = extra_long_factorial(n)
print('Good Code here' if actual_res == expected_res else 'Bad Code! Expected {}. Got {}'.format(expected_res,
actual_res))
main()
# test(4, 24)
# test(25, 15511210043330985984000000)
|
5c5f09bdd5fd2b0ba9673e88a577339d93166a7b | joshlaplante/TTA-Course-Work | /Python Drills/Python in a Day 2/part 3 - sqlite intro.py | 1,604 | 4.40625 | 4 | import sqlite3
#connect to database 'simpsons.db'
conn = sqlite3.connect('simpsons.db')
##Create table named simpson_info (commented out because table already created)
#conn.execute("CREATE TABLE SIMPSON_INFO( \
# ID INTEGER PRIMARY KEY AUTOINCREMENT, \
# NAME TEXT, \
# GENDER TEXT, \
# AGE INT, \
# OCCUPATION TEXT \
# );")
##Add bart simpson to table (commented out because already added)
#conn.execute("INSERT INTO SIMPSON_INFO \
# (NAME, GENDER, AGE, OCCUPATION) VALUES \
# ('Bart Simpson', 'Male', 10, 'Student')");
##Add homer simpson to table (commented out because already added)
#conn.execute("INSERT INTO SIMPSON_INFO \
# (NAME, GENDER, AGE, OCCUPATION) VALUES \
# ('Homer Simpson', 'Male', 40, 'Nuclear Plant')");
##Add lisa simpson to table (commented out because already added)
#conn.execute("INSERT INTO SIMPSON_INFO \
# (NAME, GENDER, AGE, OCCUPATION) VALUES \
# ('Lisa Simpson', 'Female', 8, 'Student')");
##Delete rows with ID=2 to remove duplicate bart simpson
##(commented out because already removed)
#conn.execute("DELETE from SIMPSON_INFO where ID=2")
#Make homer simpson age 41
conn.execute("UPDATE SIMPSON_INFO \
set AGE = 41 where NAME = 'Homer Simpson'")
#Save changes
conn.commit()
#Print number of changes to database
changes = conn.total_changes
print "Number of changes:", changes
#Get data from database (commented out because data already viewed)
cursor = conn.execute("SELECT * from SIMPSON_INFO")
#Get data from cursor
rows = cursor.fetchall()
print rows
##Delete the table (commented out to save table)
#conn.execute("DROP TABLE SIMPSON_INFO")
|
56f2340e198edc219f939be23421a0138a8a1dc9 | leemingee/CoolStuff | /NN/ecbm4040/features/pca.py | 1,166 | 3.75 | 4 | import time
import numpy as np
def pca_naive(X, K):
"""
PCA -- naive version
Inputs:
- X: (float) A numpy array of shape (N, D) where N is the number of samples,
D is the number of features
- K: (int) indicates the number of features you are going to keep after
dimensionality reduction
Returns a tuple of:
- P: (float) A numpy array of shape (K, D), representing the top K
principal components
- T: (float) A numpy vector of length K, showing the score of each
component vector
"""
###############################################
#TODO: Implement PCA by extracting eigenvector#
#You may need to sort the eigenvalues to get #
# the top K of them. #
###############################################
X -= X.mean(axis=0)
R = np.cov(X.T)
eigenvalues, eigenvector = np.linalg.eig(R)
P = eigenvector[:K]
T = eigenvalues/sum(eigenvalues)
T = T[:K]
###############################################
# End of your code #
###############################################
return (P, T)
|
7353865e0b1f731e1ddfb74462653a8708dd13a5 | aironm13/Python_Project_git | /Modules_learn/functools_Modules/functools_partial.py | 901 | 4.09375 | 4 | from functools import partial
def add(x, y):
return x + y
# 固定x形参
triple = partial(add, 3)
# 只用传入一个参数给y就可以
print(triple(4))
# # Python3.5
# # 源码:使用函数定义
#
# def partial(func, *args, **keywords):
# def newfunc(*fargs, **fkeywords): # 新的函数
# newkeywords = keywords.copy()
# newkeywords.update(fkeywords)
# return func(*(args + fargs), **newkeywords)
#
# newfunc.func = func
# newfunc.args = args
# newfunc.keywords = keywords
# return newfunc # 返回新的函数
#
#
# # Python3.6
# # 源码:使用类定义
#
# def __call__(*args, **keywords):
# if not args:
# raise TypeError("descriptor '__call__' of partial needs an argument")
#
#
# self, *args = args
# newkeywords = self.keywords.copy()
# newkeywords.update(keywords)
# return self.func(*self.args, *args, **newkeywords) |
4166e92b9d642049b3c01fd35a4b928c54cc1452 | b3296/py | /test/filter.py | 780 | 3.859375 | 4 | # -*- coding : utf-8 -*-
def _odd_iter():
n = 1
while True :
n = n+2
yield n
def _not_divisible(n):
return lambda x : x % n > 0
def primes(end = 100):
yield 2
it = _odd_iter()
flag = True
while flag:
n = next(it)
if n > end:
flag =False
yield n
it = filter(_not_divisible(n), it)
def divisible(num):
return lambda x : num % x == 0
def Rational(num):
def ans(x):
y = int(num /x)
return (x,y)
return ans
def checkNum(num):
if num in primes(num):
print('yes')
else:
print('no')
answerFilter = filter(divisible(num), range(2,num))
answer = map(Rational(num),answerFilter)
answerList = list(answer)
l = int((len(answerList)+1)/2)
answerList = answerList[:l]
for x,y in answerList:
print(x,'*',y,'=',num)
num = 6977
checkNum(num) |
64cf5ba928051f85af746404c8d39bbda954c75b | DJSiddharthVader/PycharmProjects | /PythonPractice/bulls.py | 1,530 | 4.15625 | 4 | '''
Randomly generate a 4-digit number.
Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the wrong place is a “bull.” Every time the
user makes a guess, tell them how many “cows” and “bulls” they have. Once the user
guesses the correct number, the game is over. Keep track of the number of guesses
the user makes throughout teh game and tell the user at the end.
Say the number generated by the computer is 1038. An example interaction could look
like this:
Enter a number:
>>> 1234
2 cows, 0 bulls
>>> 1256
1 cow, 1 bull
...
Until the user guesses the number.'''
import random as rd
q = rd.randrange(9)
w,e,r = 10, 10, 10
while w > 9 or w == q:
w = rd.randrange(9)
while e > 9 or e == q or e == w:
e = rd.randrange(9)
while r > 9 or r == q or r == w or r == e:
r = rd.randrange(9)
num = str(q) + str(w) +str(e) + str(r)
print(num)
cow = 0
bull = 0
i = 1
guess = str(input("Guess a number:"))
while guess != num:
i += 1
for y in guess:
if y in num:
if num.index(y) != guess.index(y):
bull += 1
x = 0
while x < 4:
if num[x] == guess[x]:
cow += 1
x += 1
print('bull:', bull, '\n', 'cow:', cow)
cow = 0
bull = 0
guess = str(input("Guess again:"))
else:
print(i, '\n', "you win!")
|
02917ff382ada4509f2d1116ce3ef09c338408ec | manishym/algorithms_in_python | /hotpotato.py | 446 | 3.640625 | 4 | #!/usr/local/bin/env python
from queue import Queue
def hotpotato(names, number):
q = Queue()
for name in names:
q.enqueue(name)
while q.size() > 1:
for i in range(number):
q.enqueue(q.dequeue())
print q.dequeue() + " is out"
return q.dequeue()
def main():
print hotpotato(["Manish", "Dashi", "Guru", "1t", "Mayura", "Raj", "Sapna"], 5) + " Wins"
if __name__ == '__main__':
main()
|
34d704d43497bfbd490b80e2003538ffc999e821 | BrichtaICS3U/assignment-2-logo-and-action-ahmedm88 | /logo.py | 1,984 | 4.25 | 4 | # ICS3U
# Assignment 2: Logo
# <Ahmed M>
# adapted from http://www.101computing.net/getting-started-with-pygame/
# Import the pygame library and initialise the game engine
import pygame
pygame.init()
# Define some colours
# Colours are defined using RGB values
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (240, 0, 0)
LBLUE = (157, 186, 232) #Light Blue, Background
# Set the screen size (please don't change this)
SCREENWIDTH = 852
SCREENHEIGHT = 480
# Open a new window
# The window is defined as (width, height), measured in pixels
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Ahmed M's Target Logo")
# This loop will continue until the user exits the game
carryOn = True
# The clock will be used to control how fast the screen updates
clock = pygame.time.Clock()
#---------Main Program Loop----------
while carryOn:
# --- Main event loop ---
for event in pygame.event.get(): # Player did something
if event.type == pygame.QUIT: # Player clicked close button
carryOn = False
# --- Game logic goes here
# There should be none for a static image
# --- Draw code goes here
# Clear the screen to white
screen.fill(LBLUE)
# Queue different shapes and lines to be drawn
#pygame.draw.ellipse(screen, RED, [50, 50, 300, 300], 0)
#pygame.draw.ellipse(screen, WHITE, [100, 100, 200, 200], 0)
#pygame.draw.ellipse(screen, RED, [150, 150, 100, 100], 0)
pygame.draw.ellipse(screen, RED, [0, 0, 400, 400], 0) #Large Red Outside Circle
pygame.draw.ellipse(screen, WHITE, [62.5, 62.5, 275, 275], 0) #Medium White Middle Circle
pygame.draw.ellipse(screen, RED, [125, 125, 150, 150], 0) #Small Red Central Circle
# Update the screen with queued shapes
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Once the main program loop is exited, stop the game engine
pygame.quit()
|
b3c9ef0e834c5da5c323556af1100aa074605a11 | amaner/Udacity-Data-Analysis | /readiness-test/fizzbuzz.py | 220 | 3.796875 | 4 | def fizzbuzz(intList):
fizzbuzz = []
for l in intList:
value = ''
if l%3 == 0:
value += "Fizz"
if l%5 == 0:
value += "Buzz"
if l%3 != 0 and l%5 != 0:
value = l
fizzbuzz.append(value)
return fizzbuzz |
b1a71b70ffe557491a5978d6bb77f867ace1c52e | TovenBae/study | /python/leetcode/easy/ClimbingStairs.py | 883 | 3.9375 | 4 | import unittest
# https://leetcode.com/problems/add-binary/
def climbStairs(n):
if (n == 1):
return 1
first = 1
second = 2
for i in range(2,n):
third = first + second
first = second
second = third
return second
class Test(unittest.TestCase):
def test(self):
n = 2
output = 2
self.assertEqual(output, climbStairs(n))
n = 3
output = 3
self.assertEqual(output, climbStairs(n))
n = 4
output = 5
self.assertEqual(output, climbStairs(n))
n = 5
output = 8
self.assertEqual(output, climbStairs(n))
n = 1
output = 1
self.assertEqual(output, climbStairs(n))
n = 44
output = 1134903170
self.assertEqual(output, climbStairs(n))
if __name__ == '__main__':
unittest.main()
|
2763e5877a8f922ce48ac09df89def174aa4aed8 | Sean-Xiao-x/new1 | /variable.py | 1,070 | 4 | 4 | #message = 'hello world!'
#print(message)
#name = 'adA lovelace'
##.title ()
#print(name.title())
##.upper()
#print(name.upper())
##.lower()
#print(name.lower())
#first_name = 'ada'
#last_name = 'lovelace'
#space = ' '
#full_name = first_name+space+last_name
#print(full_name)
#print('hello,'+full_name.title()+'!')
#print('python')
##\t is tab
#print('\tpython')
##\n is newline
#print('hi,\n\nthis is a message from sean!\n\nBR/Sean')
#language = ' python '
#print(language)
##.rstrip() is right strip
#print(language.rstrip())
#language = language.rstrip()
#print(language)
##.strip()
#print(language.strip())
##.lstrip() is left strip
#language = language.lstrip()
#print(language)
##when use quote should be very careful
#message = "12'33"
#print(message)
#message = "123'456'"
#print(message)
#message = '123"456"'
#print(message)
#age = 23
##str() tells python to represent non-string values as strings
#message = 'happy '+str(age)+'rd birthday'
#print(message)
##use division in python2 should add 0 after integer
#a = 3/2
#print(a)
#b = 3.0/2
#print(b)
|
b89fe8800a88ae73c81c89c55e0a3632b8b3771e | gitter-badger/python_me | /hackrankoj/collections/word_order.py | 789 | 4.03125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
'''
Task
You are given words. Some words may repeat. For each word, output its number of occurrences.
The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Sample Input
4
bcdef
abcdefg
bcde
bcdef
Sample Output
3
2 1 1
'''
from collections import OrderedDict
od = OrderedDict()
for _ in range(int(raw_input())):
item = raw_input().strip()
od[item]=od.get(item,0)+1
print len(od)
print ' '.join([str(value) for value in od.itervalues()])
'''
牛人用继承!!
'''
from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
pass
d = OrderedCounter(input() for _ in range(int(input())))
print(len(d))
print(*d.values())
|
fa4ac3366e303994b5dcad76bc4c3c07da095619 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/9bc5667f-1abb-4364-9145-30b147188c1a__cb2_5_4_exm_1.py | 246 | 3.78125 | 4 | def _sorted_keys(container, keys, reverse):
''' return list of 'keys' sorted by corresponding values in 'container' '''
aux = [ (container[k], k) for k in keys ]
aux.sort()
if reverse: aux.reverse()
return [k for v, k in aux]
|
b05db3b68db5cc7d8ae59c01d334b1411322ac8b | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/shrdan007/question2.py | 322 | 3.53125 | 4 | # Text reformatting
# Danielle Sher
import textwrap
x = input("Enter the input filename:\n")
y = input("Enter the output filename:\n")
z = eval(input("Enter the line width:\n"))
a = open(x, "r")
b = a.read()
lst = textwrap.wrap(b, width = z)
string = "\n".join(lst)
c = open(y, "w")
c.write(string)
a.close()
c.close()
|
ae14bf8c680189652b961a7eaba69e049e1e5a9c | crisortiz92/MicroEconomic-Theory-Programs | /Econ_programs/monopolies.py | 1,209 | 4.09375 | 4 | ## Monopolies
from sympy import *
x1, x2, y, z, p = symbols('x1 x2 y z p')
def monopoly():
cost = sympify(input("Enter the cost function c(y): "))
average_cost = simplify((cost/y)) #computes average cost
marginal_cost = diff(cost,y) #computes marginal cost
print("Average Cost, Ac(y)=",average_cost,'\n')
print("Marginal Cost, MC(y)=",marginal_cost,'\n')
demand = sympify(input("Enter the demand function D(p): \n"))
price = solve(Eq(demand, y),p)[0] #computes the price function p(y) by inversing the demand function
print("Inverse: p(y)=",simplify(price),'\n')
revenue = price*y
marginal_revenue = diff(revenue, y)
print("Revenue p(y)*y=",revenue,'\n')
print("Marginal Revenue MR(y)=",marginal_revenue,'\n')
Ym = solve(Eq(marginal_revenue,marginal_cost),y)[0]
Pm = solve(Eq(demand,Ym),p)[0]
print('Ym=',Ym,'\n')
print("Pm=",Pm,'\n')
profit = revenue-cost
total_profit = profit.subs(y,Ym)
print("profit=",profit,'\n')
print("Profit : ", total_profit,'\n')
Yc = solve(Eq(price,marginal_cost),y)[0]
Pc = solve(Eq(demand,Yc),p)[0]
print("Optimal output and price, if market competitive instead of Monopoly: ")
print("Yc=",Yc)
print("Pc=",Pc,'\n')
print()
monopoly() |
1cb82527279ebb8b48a6abc6286138459e914a6f | TheoRobin76/Data_Engineering22 | /DataEngineering22/OOP.py | 4,523 | 4.03125 | 4 | # # class Dog:
# # # Class attribute
# # species = "Canis familiaris"
# #
# # # Instance attributes
# # def __init__(self, name, age, cuteness_factor):
# # self.name = name
# # self.age = age
# # self.cuteness_factor = cuteness_factor
# #
# # # Instance method
# # def __str__(self):
# # return (f"{self.name} is {self.age} years old with a cuteness factor of {self.cuteness_factor}")
#
#
# #
# # # Instantiating
# # Myles = Dog("Myles", 9, 4)
# # Oscar = Dog("Oscar", 2, 1000)
# #
# # print(Myles)
#
# #
# # class Dog:
# #
# # animal_kind = "Dolphin" # class_variable
# #
# # def bark(self): # method
# # return "woof"
# #
# # Myles = Dog()
# # Oscar = Dog()
# #
# # print(type(Myles))
# # print(type(Oscar))
# # print(Myles.animal_kind)
# # print(Oscar.animal_kind)
# #
# # Oscar.animal_kind = "Big Dog"
# # print(Myles.animal_kind)
# # print(Oscar.animal_kind)
# # print(Myles.bark())
# # print(Oscar.bark())
#
#
# # class Dog:
# #
# # def __init__(self, name, colour):
# # self.animal_kind = "canine"
# # self.name = name
# # self.colour = colour
# # self.bark()
# #
# #
# # def bark(self): # method
# # return "woof"
# #
# # Amy = Dog("Amy", "Golden")
# # print(Amy.name)
# # print(Amy.colour)
# #
# class Car:
# def __init__(self, max_speed, fuel_econ, max_fuel):
# self.wheels = 4
# self.speed = 0
# self.max_speed = max_speed
# self.fuel_econ = fuel_econ
# self.max_fuel = max_fuel
# self.fuel_level = 10
#
# def Accelerate(self, speed_increase):
# print("Vroom Vroom")
# if self.speed + speed_increase > self.max_speed:
# self.speed = self.max_speed
# else:
# self.speed += speed_increase
#
# def Deccelerate(self, speed_decrease):
# print("Cat in the road!")
# if self.speed - speed_decrease > 0:
# self.speed -= speed_decrease
# else:
# self.speed = 0
#
# def FillTank(self, amount_filled):
# print("Please refuel, I don't want to break down again")
# if self.fuel_level + amount_filled > self.max_fuel:
# self.fuel_level = self.max_fuel
# else:
# self.fuel_level += self.fuel_level
#
#
# lambo = Car(250, 10, 80)
# fiat500 = Car(110, 40, 35)
#
# lambo.Accelerate(300)
# print(lambo.speed)
#
# fiat500.Accelerate(300)
# print(fiat500.speed)
#
# lambo.Deccelerate(200)
# print(lambo.speed)
# #
# def century(year):
# return math.ceil(year/100)
#
# print(century(1980))
# def reverse_seq(n):
# reverse = list(range(1, n+1))
# return reverse[::-1]
#
# print(reverse_seq(5))
# class Car:
# wheels = 4
# def __init__(self, max_speed, mileage, model, colour):
# self.max_speed = max_speed
# self.mileage = mileage # miles per gallon
# self.model = model
# self.colour = colour
# self.fuel_tank_size = 12 # gallons of fuel
# self.fuel_level = 0
# self.speed = 0
# def description(self):
# print(f"This car is a {self.colour} {self.model} with a maximum speed of {self.max_speed} mph")
# def fuel_up(self):
# self.fuel_level = self.fuel_tank_size
# print("Fuel tank is now full.")
# def drive(self):
# print(f"The {self.model} is now driving")
# def refuel(self):
# print("Fuel is currently £5 a gallon.")
# new_level = int(input("How many gallons would you like to refuel? "))
# while self.fuel_tank_size - self.fuel_level <= new_level:
# print(f"Exceeded capacity, please enter an amount lower than {self.fuel_tank_size - self.fuel_level}.")
# new_level = int(input("How many gallons would you like to refuel? "))
# else:
# self.fuel_level += new_level
# print(f"This is going to cost £{5*new_level}")
# def distance_to_travel(self): # max distance a car can travel with amount of fuel
# print(f"The maximum distance you can travel is {self.mileage * self.fuel_level}")
# def acceleration(self, speed_increase):
# if self.speed + speed_increase > self.max_speed:
# self.speed = self.max_speed
# print(self.speed)
# else:
# self.speed += speed_increase
# print(self.speed)
#
# Ford = Car(120, 40, "Fiesta", "Red")
# def reverse_seq(n):
# reverse = list(range(1, n+1))
# return reverse[::-1]
|
1e15625e38c33569f7dd075723f30962fda50e21 | AbhishekVasudevMahendrakar/ECE-3year-Code-Challenge | /BHARGAVI4AL17EC061.py | 543 | 3.765625 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
count=0
while count<3:
user_name=input("Enter the username: ")
password =input("Enter the password:")
if user_name =="Micheal" and password =="e3$WT89x":
print("You have successfully logged in")
else:
count+=1
print("Invalid username and passwor")
if count==3:
print("Account Locked")
|
d618c107faa4bb7712b3222fb762b8c3041cc140 | a-toro/Prueba_Tecnica | /Prueba1.py | 5,042 | 4.0625 | 4 | """ Enunciado
Construya un objeto que reciba un arreglo o una matriz de dimensión N el cual contiene
números de tipo entero.
a. o.dimension -> Devuelve el número entero que define la dimensión del arreglo o
matriz en su mayor profundidad.
b. o.straight -> Devuelve true o false según el siguiente criterio: -True: Si el arreglo o
matriz contiene la misma cantidad de elementos en cada una de sus dimensiones
(Matriz uniforme). -False: Caso contrario.
c. o.compute -> Devuelve el número entero resultado de la
"""
# Crear un objeto de clase que reciba una matriz de N
class MyMatrix():
def __init__(self, matrix):
self.matrix = matrix
self.suma = 0
self.profundidad_matrix = 0
self.vector_straight = []
self.valores_unicos = []
# Los siguientes métodos se definen con funciones de recursividad.
# Definir método compute
def compute(self):
# Recorre la matriz por cada uno de sus elemento
for elemento in self.matrix:
# Evalua si elemento es una lista
if isinstance(elemento, list):
# Si es una lista, asigan el elemento a la matrix y se vuelve a llamar a la misma dunción
self.matrix = elemento
self.compute()
else:
# Si no es una lista, se acumula el valor de cada uno de sus elementos
self.suma += elemento
return self.suma
# Definir método dimension
# Retorna en nivel de profundidad de una matriz
def dimension(self):
# Recorre la matríz por cada uno de sus elementos
for elemento in self.matrix:
# Evalua si el elemento es un número entero
if isinstance(elemento, int):
# Suma 1 punto y termina el ciclo
self.profundidad_matrix += 1
break
# Evalua si el elemento es una liosta
if isinstance(elemento, list):
# Suma 1 punto
self.profundidad_matrix += 1
# Actualiza la matríz
self.matrix = elemento
# Se llama así misma
self.dimension()
# Retorna el valor de la profundidad de la matríz
return self.profundidad_matrix
return self.profundidad_matrix
# Definir método straingt
def straight(self):
# Recorre la matriz por cada uno de sus elemento
for elemento in self.matrix:
# Evalua si los elementos dentro de la matriz
# Si es verdadero almacena el la longitud de la lista en el vector_straight
if isinstance(elemento, int):
self.vector_straight.append(len(self.matrix))
else:
# De lo contrario se actualiza el valor de la self.matrix
# Se vuelve a llamar la misma función
self.matrix = elemento
self.straight()
# Recorre los valores almacenado en el vector_straight en el paso anterior
for x in self.vector_straight:
# Evalua si el elemento x se encuentra en el vector valores_unicos
# Si no esta lo agrega.
if x not in self.valores_unicos:
self.valores_unicos.append(x)
# Evalua la longitud del vector valores_unicos
# Si es mayor a uno significa que dentro de la matriz hay un elemento con diferetes dimensión por lo que devuelkve False
if len(self.valores_unicos)==1:
return True
else:
return False
# Ejemplos de prueba
w = [[[[[1]]]]]
a = [1,2]
b = [[1,2],[2,4]]
c = [[1,2],[2,4],[2,4]]
d = [[[3,4],[6,5]]]
e = [[[1, 2, 3]], [[5, 6, 7],[5, 4, 3]], [[3, 5, 6], [4, 8, 3], [2, 3]]]
f = [[[1, 2, 3], [2, 3, 4]], [[5, 6, 7], [5, 4, 3]], [[3, 5, 6], [4, 8, 3]]]
# Resultados
print("Compute: ",MyMatrix(w).compute())
print("Dimension: ",MyMatrix(w).dimension())
print("Straight: ", MyMatrix(w).straight())
print("---------------------------------------------")
print("Compute: ",MyMatrix(a).compute())
print("Dimension: ",MyMatrix(a).dimension())
print("Straight: ", MyMatrix(a).straight())
print("---------------------------------------------")
print("Compute: ",MyMatrix(b).compute())
print("Dimension: ",MyMatrix(b).dimension())
print("Straight: ", MyMatrix(c).straight())
print("---------------------------------------------")
print("Compute: ",MyMatrix(d).compute())
print("Dimension: ",MyMatrix(d).dimension())
print("Straight: ", MyMatrix(d).straight())
print("---------------------------------------------")
print("Compute: ",MyMatrix(e).compute())
print("Dimension: ",MyMatrix(e).dimension())
print("Straight: ", MyMatrix(e).straight())
print("---------------------------------------------")
print("Compute: ",MyMatrix(f).compute())
print("Dimension: ",MyMatrix(f).dimension())
print("Straight: ", MyMatrix(f).straight()) |
05ab88e763ea514aaa7f4a1532962ab335e9bd02 | jonathabsilva/ProgISD20202 | /Jonatha/Aula 03/Programas da aula e Exercícios/Exercicio02.py | 490 | 3.828125 | 4 | # EXERCÍCIO 02 - Índice de massa corporal (IMC) - Recebendo dados
print('Programa usado para calcular o indice de massa corporal.')
peso = float(input('Informe seu peso: '))
altura = float(input('Informe sua altura: '))
print(type(peso))
imc = peso/(altura ** 2)
print('Muito abaixo do peso', imc < 17)
print('Abaixo do peso normal', 17 <= imc < 18.5)
print('Dentro do peso normal', 18.5 <= imc < 25)
print('Acima do peso normal', 25 <= imc < 30)
print('Muito acima do peso', imc > 30)
|
242c4c2d7c81d637010ba93b332b0e2d512b9966 | anixshi/CS-111-Python-PSETS | /ps01/debugNumsBuggy.py | 1,038 | 3.6875 | 4 | # *** DO NOT EDIT THIS FILE! ***
# Bud Lojack's buggy debugNumsBuggy.py for CS111 PS01 Task 1
# Tests involving an integer
intNum = raw_input('Enter a nonnegative integer intNum: ')
print('The integer you entered is intNum')
print 'Three times intNum is', intNum * 3
print intNum, 'concatenated copies of X is', intNum+'X'
print 'The integer remainder of', intNum, 'divided by 3 is', + int(intNum)%3
print 'The integer quotient of', intNum, 'divided by 3 is', int(intNum/3)
print 'The floating point quotient of', intNum,\
'divided by 3 is', float(int(intNum)/3)
print 'The number of digits in', intNum, 'is', len(int(intNum))
# Tests involving an floating point number
floatNum = raw_input('Enter a floating point number floatNum: ')
'floatNum is ' + floatNum
print(floatNum + ' rounded to two places is ' + round(float(floatNum),2))
print floatNum, 'truncated to an integer is', int(floatNum)
print floatNum, 'rounded to an integer is', round(floatNum)
print 'The maximum of', intNum, 'and', floatNum, 'is', max(intNum, floatNum)
|
8f2f945034b5c69c20707ce87b947b5db6c587e1 | DanaAbbadi/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/quick_sort/quick_sort_basic.py | 983 | 4.25 | 4 |
def partition(arr,low,high):
"""
This function takes last element as the pivot, places
the pivot element at its correct position where elements on the left
are smaller, and all elemnts on the right are larger.
"""
i = ( low-1 )
pivot = arr[high]
for j in range(low , high):
if arr[j] < pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quickSort(arr,low,high):
"""
The main function that implements QuickSort
Arguments:
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index
"""
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
if __name__ == "__main__":
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr,0,n-1)
print (arr) |
0c32182782bd0f48275e3f88c1d775a0df4aa421 | takapdayon/atcoder | /abc/AtCoderBeginnerContest069/B.py | 178 | 3.625 | 4 | def i18n(s):
count = (len(s) - 2)
return str(s[0]) + str(count) + str(s[-1])
def main():
s = str(input())
print(i18n(s))
if __name__ == '__main__':
main() |
8589758e33f6e4d5ed69313ce753724c65aafa95 | chenxi0329/HassleFree | /frequency_sort.py | 664 | 3.75 | 4 | import Queue
# import Queue, q = Queue.PriorityQueue()
# q.put((a tuple)) q.qsize() q.get()
class Solution:
def frequencysrot(self, lst):
dict = {}
q = Queue.PriorityQueue()
for str in lst:
if str in dict:
dict[str] += 1
else:
dict[str] = 1
for key,value in dict.iteritems():
#use tuple here
#Priority queue will sort first parameter
q.put((value,key))
for i in xrange(q.qsize()):
print q.get()
if __name__ == '__main__':
lst = ['33','33','33','33','444','444','1']
Solution().frequencysrot(lst) |
ac87cc0a11ace244bb35ef729f9015d312f485d2 | ClaudenirFreitas/learning-python | /exercises/ex006.py | 131 | 3.78125 | 4 | input_number = input('Number: ')
number = int(input_number)
print(f"Number: {number}. {number * 2}. {number * 3}. {number ** 2} ")
|
30c94a09e177201634aae76e5c7e032dea9f9865 | AP-Skill-Development-Corporation/PythonWorkshop-PaceCollege-Batch-3 | /strings.py | 1,579 | 4.375 | 4 | # Strings
"""
-->Collection of charatcter is called string
--->Group of chararcters is called a string
-->in python string representation is '' or "" or """"""
---> In python string immutable
---> in python string is indexed value based
--->string supports slicing operator--->':'
"""
#a=''' '''
#print(type(a))
'''
a="welcome to python"
print(a)
# concatination of string
b='workshop'
c=a+b
print(c) # a+= 'hello'
# getting values
print(a[0])
print(a[1])
# forwardindex and backword index
# forwardindex
print(a[0])
print(a[5])
# backword index
s="welcome to python"
print(s[-1])
print(s[-5])
# slicing operation-->:
name='python programming'
#print(name[:])
#print(name[0:6])
#print(name[4:6])
#print(name[::-1])
#print(name[0:17:2])
#print(name[6:7])
print(name[0:])
'''
# String Methods 3 ways
# by using datatype--->str
#print(dir(str))
#n=''
#print(dir(n))
#m='hello'
#print(dir(m))
p=' welcome to apssdc '
#print(p.capitalize())
#print(p.casefold())
#print(p.swapcase())
#print(p.count('S'))
#print(p.index('z'))
#print(p.find('x'))
#print(p.center(20,'*'))
#print('My name is {0} & i am from {1}'.format('abc','xyz'))
#print(p.upper())
#print(p.lower())
#print(p.title())
#print(p.isupper())
#print(p.islower())
#print(p.startswith('w'))
#print(p.endswith('c'))
#print(p.istitle())
q='<--'
#print(q.join(p))
#print(p.isdigit())
#print(p.isalpha())
#print(p.isalnum())
#print('python\tprogtamming\tworkshop'.expandtabs())
'''split,
spltlines,
strip,
lstrip,
rstrip'''
#print(p.split())
#print(p.strip())
print(p.lstrip())
print(p.rstrip())
|
5b0ce9a43a1c6e2cd2b51b2ac03ee4854dc3389d | alexwang19930101/PythonBase | /基础类型/while和for遍历列表.py | 142 | 3.65625 | 4 | #-*- coding:utf-8 -*-
nums = [10,11,12,13,14,15]
'''
i = 0
while i<len(nums):
print nums[i];
i+=1
'''
for num in nums:
print num |
677df796c8ea53676715c640b7b0c262a12b1f61 | thom145/exercism | /python/acronym/acronym.py | 365 | 4.125 | 4 | import re
def abbreviate(words):
"""
:param words: the word you want the abbreviation of
:return: returns the abbreviate as a string
"""
list_abbreviate = re.split("[, \-!?:]+", words) # split on all given chars
abbreviate = [word[0].upper() for word in list_abbreviate] # take the first letter of each word
return ''.join(abbreviate)
|
9721ce443d54ed1ccf38d56cb88a218972b4d474 | xenron/sandbox-github-clone | /qiwsir/algorithm/int_divide.py | 417 | 3.515625 | 4 | #! /usr/bin/env python
#encoding:utf-8
"""
将一个整数,分拆为若干整数的和。例如实现:
4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
"""
def divide(m,r,out):
if(r==0):
return True
m1=r
while m1>0:
if(m1<=m):
out.append(m1)
if(divide(m1,r-m1,out)):
print out
out.pop()
m1-=1
return False
n=6
out=[]
divide(n-1,n,out)
|
40a6322f8da33d83ddbdad53e54c9ad5d52d243a | saurabhv1/QuesAnsBot | /athenabot/athenabot/utils.py | 185 | 3.765625 | 4 | def is_number(string):
if '%' in string:
string = string.split('%')[0].strip()
try:
float(string)
return True
except ValueError:
return False |
e9a8b408b2c45417f5fc545b332a09a1ba701915 | yesitsreallyme/Robotics | /lab_code/lab10.py | 1,823 | 3.53125 | 4 | import lab10_map
import math
class Run:
def __init__(self, factory):
"""Constructor.
Args:
factory (factory.FactoryCreate)
"""
self.create = factory.create_create()
self.time = factory.create_time_helper()
self.servo = factory.create_servo()
self.sonar = factory.create_sonar()
#Add the IP-address of your computer here if you run on the robot
self.virtual_create = factory.create_virtual_create()
self.map = lab10_map.Map("lab10.map")
def run(self):
# This is an example on how to visualize the pose of our estimated position
# where our estimate is that the robot is at (x,y,z)=(0.5,0.5,0.1) with heading pi
self.virtual_create.set_pose((0.5, 0.5, 0.1), math.pi)
# This is an example on how to show particles
# the format is x,y,z,theta,x,y,z,theta,...
data = [0.5, 0.5, 0.1, math.pi/2, 1.5, 1, 0.1, 0]
self.virtual_create.set_point_cloud(data)
# This is an example on how to estimate the distance to a wall for the given
# map, assuming the robot is at (0, 0) and has heading math.pi
print(self.map.closest_distance((0.5,0.5), math.pi))
# This is an example on how to detect that a button was pressed in V-REP
while True:
b = self.virtual_create.get_last_button()
if b == self.virtual_create.Button.MoveForward:
print("Forward pressed!")
elif b == self.virtual_create.Button.TurnLeft:
print("Turn Left pressed!")
elif b == self.virtual_create.Button.TurnRight:
print("Turn Right pressed!")
elif b == self.virtual_create.Button.Sense:
print("Sense pressed!")
self.time.sleep(0.01)
|
c30dfd8de5ecd8153fdbcca2ec7183e74c92a1ab | claraj/web-autograder | /grading_module/example_assignments/example_python_assignment/lab_questions/Loop2fun.py | 2,015 | 4.21875 | 4 | """
NOTE Chapter 3 lab (Lab 6) & Homework assignments are redesigns of previous programs, to follow the new IPO structure.
Use the code from the Loop-2 program from last time
You will create functions called main(), inputNumbers(), processing(), and outputAnswer().
The old program and new program will have a similar feel when run:
- ask the user for a small number.
- Then, ask the user for a larger number.
Your program should display all the numbers in the range,
add up all the numbers in the range, and display the total.
So if your user enters 20 and 23, the program should display the
numbers in that range, and calculate 20+21+22+23 = 86.
Add exception handling in main() and test with bad inputs.
Add validations and your own touches.
"""
# TODO your code here.
def inputNumbers():
# Validation should go here?
# Check that data is an integer and the first number is smaller than the seconds.
while True:
try:
firstNum = int(input('Enter a small number: '))
secondNum = int(input(f'Enter another number that is larger than {firstNum}: '))
if firstNum > secondNum:
print('The second number should be larger than the first number.')
continue
return firstNum, secondNum
except ValueError:
print('Make sure you enter an integer number.')
def processing(n1, n2):
# math
total = 0
for n in range(n1, n2+1):
total += n
return total
def outputAnswer(total, n1, n2):
print(f'All the numbers in the range {n1} to {n2} are:')
for n in range(n1, n2+1):
print(n)
print(f'The total is {total}')
def main():
n1, n2 = inputNumbers()
total = processing(n1, n2)
outputAnswer(total, n1, n2)
# It is important that you call main in this way,
# or all the code will run when this is imported into
# the test file, including input statements, which
# will confuse the tests.
if __name__ == '__main__':
main()
|
4f760adb3f1077898fb24db99666b49f36e77bc5 | NasimKh/Frauenloop_intro_python | /week2/leap_year.py | 384 | 4.03125 | 4 | # leap year
def is_leap(year):
leap = False
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
|
2cd8043da45ae96602bc28770224003f7f656f10 | Datrisa/AulasPython | /calculos.py | 716 | 4.03125 | 4 | #calcular duas notas e ter a média
nome = input('Qual o seu nome? ')
n1 = float(input('Sua nota na Prova 1 foi: '))
n2 = float(input('Coloque também a nota da Prova 2: '))
m = (n1+n2)/2
print(f'{nome}, Sua média na matéria foi: {m}')
print('Muito bem!')
# *****************
#Dobro, Triplo e raiz quadrada
n=int(input('Digite um número: '))
d = n*2
t = n*3
rq = n**(1/2)
print(f'O dobro deste número é {d}, o triplo {t} e a raiz quadrada {rq}!')
print('Muito Obrigada, vc está me ajudando a testar :)')
# ****************
#antecessor e sucessor
n = int(input('Digite um número: '))
a = n - 1
s = n + 1
print(f'O antecessor desse número é {a} e o sucessor é {s}')
input('Pressione ENTER para Sair')
|
412f57ee6068181c06e301d01a3d6e5e8915b657 | Don-Burns/CMEECourseWork | /Week2/Code/scope.py | 2,643 | 4.375 | 4 | #!/usr/bin/env python3
""" A script looking at how global and local funtions are handled inside and outside functions."""
__author__ = 'Donal Burns (db319@ic.ac.uk)'
__version__ = '0.0.1'
#PART 1
_a_global = 10 # a global variable
if _a_global >= 5:
_b_global = _a_global + 5 # alsoa global variable
def a_function():
""" shows how locals variables work"""
_a_global = 5 # a local variable
if _a_global >= 5:
_b_global = _a_global + 5 # also a local variable
_a_local = 4
print("Inside the function, the value is ", _a_global)
print("Inside the function, the value is ", _b_global)
print("Inside the function, the value is ", _a_local)
return None
a_function()
print("Outside the function, the value is ", _a_global)
print("Outside the function, the value is ", _b_global)
# PART 2
_a_global = 10
print("Outside the function, the value is ", _a_global)
def a_function():
""" shows local vs global variables"""
global _a_global
_a_global = 5
_a_local = 4
print("Inside the function, the value is ", _a_global)
print("Inside the function, the value is ", _a_local)
return None
a_function()
print("Outside the function, the value is ", _a_global)
# PART 3
def a_function():
""" shows how assigning global variables works"""
_a_global = 10
def _a_function2():
""" demonstrates how the global variable is handled in a fucntion"""
global _a_global
_a_global = 5
_a_local = 4
print("Inside the function, the value of _a_global ", _a_global)
print("Inside the function, the value of _a_local", _a_local)
return None
a_function()
print("Outside the function, the value of _a_global now is ", _a_global)
#PART 4
def a_function():
""" more global testing"""
_a_global = 10
def _a_function2():
global _a_global
_a_global = 20
print("Before calling a_function, value of _a_global is ", _a_global)
return None
_a_function2()
print("After calling _a_function2, value of _a_global is ", _a_global)
a_function()
print("The value of a_global in main workspace / namespace is ", _a_global)
#PART 5
_a_global = 10
def a_function():
""" more global vs local """
def _a_function2():
""" even more global vs local"""
global _a_global
_a_global = 20
print("Before calling a_function, value of _a_global is ", _a_global)
_a_function2()
print("After calling _a_function2, value of _a_global is ", _a_global)
a_function()
print("The value of a_global in main workspace / namespace is ", _a_global)
|
bf55521618e904356413a4ba8c3619ff0100b9aa | matheusms/python-pro-mentorama | /seq_fibonacci/modulo2_fibonacci.py | 908 | 3.75 | 4 | #Crie um objeto que gere a seq de Fibonacci
import pytest
class Fibonacci:
def __init__(self, interacao):
self.anterior = 0
self.proximo = 1
self.interacao = interacao
def __iter__(self):
return self
def __next__(self):
if self.interacao == 0:
return
soma = self.anterior + self.proximo
assert soma > self.anterior
self.anterior = self.proximo
self.proximo = soma
self.interacao -= 1
return self.proximo
elementos = int(input("Insira qtd de elementos: "))
u = Fibonacci(elementos) #iniciando a class
seq = iter(u) #iterando
var=[] #variavel para salvar a sequencia
for k in range(elementos): #rodando o programa
var.append(next(u))
fibo = { k : v for k,v in enumerate(var)} #criando o dicionário por dict comprehension
print(fibo) #print da sequencia em forma de dicionário |
b8c23cbb93832c67d9b093160a46620a22f7f31d | MonikaLaur/SmartNinja | /Class8/Homework_8.3.py | 85 | 3.65625 | 4 | # Make a string lower case
string = "Today Is A BeautiFul DAY"
print string.lower() |
66af9839631b0d1f875ecee8ad07596f22a6b509 | MaayanLab/clustergrammer-web | /clustergrammer/upload_pages/clustergrammer_py_v112_vect_post_fix/__init__.py | 6,202 | 3.5 | 4 | # define a class for networks
class Network(object):
'''
Networks have two states:
1) the data state, where they are stored as a matrix and nodes
2) the viz state where they are stored as viz.links, viz.row_nodes, and
viz.col_nodes.
The goal is to start in a data-state and produce a viz-state of
the network that will be used as input to clustergram.js.
'''
def __init__(self):
from . import initialize_net
initialize_net.main(self)
def load_file(self, filename):
'''
load file to network, currently supporting only tsv
'''
from . import load_data
load_data.load_file(self, filename)
def load_tsv_to_net(self, file_buffer, filename=None):
'''
This will load a tsv matrix file buffer, this is exposed so that it will
be possible to load data without having to read from a file.
'''
from . import load_data
load_data.load_tsv_to_net(self, file_buffer, filename)
def load_vect_post_to_net(self, vect_post):
'''
load vector format to network
'''
print('\nLOAD VECT POST TO NET\n---------------------\n')
from . import load_vect_post
load_vect_post.main(self, vect_post)
def load_data_file_to_net(self, filename):
'''
load my .dat format (saved as json) for a network to a netowrk
'''
from . import load_data
inst_dat = self.load_json_to_dict(filename)
load_data.load_data_to_net(self, inst_dat)
def make_clust(self, dist_type='cosine', run_clustering=True,
dendro=True, views=['N_row_sum', 'N_row_var'],
linkage_type='average', sim_mat=False, filter_sim=0.1,
calc_cat_pval=False, run_enrichr=None):
'''
The main function run by the user to make their clustergram.
views is later referred to as requested_views.
'''
from . import make_clust_fun
make_clust_fun.make_clust(self, dist_type=dist_type, run_clustering=run_clustering,
dendro=dendro,
requested_views=views,
linkage_type=linkage_type,
sim_mat=sim_mat,
filter_sim=filter_sim,
calc_cat_pval=calc_cat_pval,
run_enrichr=run_enrichr)
def produce_view(self, requested_view=None):
'''
under development, will produce a single view on demand from .dat data
'''
print('\tproduce a single view of a matrix, will be used for get requests')
if requested_view != None:
print('requested_view')
print(requested_view)
def swap_nan_for_zero(self):
from copy import deepcopy
'''
Expose this to user for their optional use
'''
# self.dat['mat_orig'] = deepcopy(self.dat['mat'])
import numpy as np
self.dat['mat'][np.isnan(self.dat['mat'])] = 0
def df_to_dat(self, df):
'''
Convert from pandas dataframe to clustergrammers dat format
'''
from . import data_formats
data_formats.df_to_dat(self, df)
def dat_to_df(self):
'''
convert from clusergrammers dat format to pandas dataframe
'''
from . import data_formats
return data_formats.dat_to_df(self)
def export_net_json(self, net_type='viz', indent='no-indent'):
from . import export_data
return export_data.export_net_json(self, net_type, indent)
def write_json_to_file(self, net_type, filename, indent='no-indent'):
from . import export_data
export_data.write_json_to_file(self, net_type, filename, indent)
def write_matrix_to_tsv(self, filename=None, df=None):
from . import export_data
return export_data.write_matrix_to_tsv(self, filename, df)
def filter_sum(self, inst_rc, threshold, take_abs=True):
'''
Filter a network's rows or columns based on the sum across rows or columns
Works on the network object
'''
from . import run_filter
inst_df = self.dat_to_df()
if inst_rc == 'row':
inst_df = run_filter.df_filter_row_sum(inst_df, threshold, take_abs)
elif inst_rc == 'col':
inst_df = run_filter.df_filter_col_sum(inst_df, threshold, take_abs)
self.df_to_dat(inst_df)
def filter_N_top(self, inst_rc, N_top, rank_type='sum'):
'''
Filter a network's rows or cols based on sum/variance, and only keep the top
N
'''
from . import run_filter
inst_df = self.dat_to_df()
inst_df = run_filter.filter_N_top(inst_rc, inst_df, N_top, rank_type)
self.df_to_dat(inst_df)
def filter_threshold(self, inst_rc, threshold, num_occur=1):
'''
Filter a network's rows or cols based on num_occur values being above a
threshold (in absolute value)
'''
from . import run_filter
inst_df = self.dat_to_df()
inst_df = run_filter.filter_threshold(inst_df, inst_rc, threshold,
num_occur)
self.df_to_dat(inst_df)
def normalize(self, df=None, norm_type='zscore', axis='row', keep_orig=False):
'''
under development, normalize the network rows/cols using zscore
'''
from . import normalize_fun
normalize_fun.run_norm(self, df, norm_type, axis, keep_orig)
def Iframe_web_app(self, filename=None, width=1000, height=800):
from . import iframe_web_app
link = iframe_web_app.main(self, filename, width, height)
return link
def enrichr(self, req_type, gene_list=None, lib=None, list_id=None,
max_terms=None):
'''
under development, get enrichment results from Enrichr and add them to
clustergram
'''
from . import enrichr_functions as enr_fun
if req_type == 'post':
return enr_fun.post_request(gene_list)
if req_type == 'get':
return enr_fun.get_request(lib, list_id, max_terms)
# if req_type == ''
@staticmethod
def load_gmt(filename):
from . import load_data
return load_data.load_gmt(filename)
@staticmethod
def load_json_to_dict(filename):
from . import load_data
return load_data.load_json_to_dict(filename)
@staticmethod
def save_dict_to_json(inst_dict, filename, indent='no-indent'):
from . import export_data
export_data.save_dict_to_json(inst_dict, filename, indent)
|
4504eb1fc912373aa244e0d891b6ac199607387e | shakib0/BasicPattterns | /pattern6.py | 176 | 3.6875 | 4 | for r in range(5):
for c in range(r+1):
if c<1 :
print((5-r)*' ',r,end = '')
else:
print('',r,end = '')
print()
|
d48d59ba512d46f1da62d8ca9334959c9c0da9d5 | reud/AtCoderPython | /Python/ABC126B.py | 275 | 3.671875 | 4 | S=input()
mae=int(S[0]+S[1])
usiro=int(S[2]+S[3])
maeMM = True if 0< mae and mae<13 else False
usiroMM =True if 0< usiro and usiro<13 else False
if maeMM and usiroMM:
print('AMBIGUOUS')
elif maeMM:
print('MMYY')
elif usiroMM:
print('YYMM')
else:
print('NA') |
11fef3c419dd3102d413e27494bb47b18d81e4c1 | christinegithub/oop_cat | /cat.py | 1,694 | 4.46875 | 4 | # Create a class called Cat
class Cat:
# Every cat should have three attributes when they're created: name, preferred_food and meal_time
def __init__(self, name, preferred_food, meal_time):
self.name = name
self.preferred_food = preferred_food
self.meal_time = meal_time
# Create two instances of the Cat class in your file
# They should each have unique names, preferred foods and meal times
# Let's assume meal_time is an integer from 0 to 23 (representing the hour of the day in 24 hour time)
# Define a __str__() instance method.
def __str__(self):
return "{} likes to eat {} at around {}:00.".format(self.name, self.preferred_food, self.meal_time)
# Add an instance method called eats_at that returns the hour of the day with AM or PM that this cat eats.
# The return value should be something like "11 AM" or "3 PM"
# Make sure your method returns this string rather than printing it
def eats_at(self):
if self.meal_time < 12:
return "{}AM".format(self.meal_time)
elif self.meal_time == 12:
return "{}PM".format(self.meal_time)
else:
return "{}PM".format(self.meal_time - 12)
# Add another instance method called meow that returns a string of the cat telling you all about itself
# The return value should be something like "My name is Sparkles and I eat tuna at 11 AM"
# Call the meow method on each of the cats you instantiated in step 3
def meow(self):
return "My name is {} and I eat {} at {}.".format(self.name, self.preferred_food, self.eats_at())
cat_1 = Cat("Garfield", "tuna", 12)
cat_2 = Cat("Tom", "chicken", 18)
print(cat_1.meow())
print(cat_2.meow())
|
b1c51433733553cb528b4c3e1a4dfbf9ece3d694 | nv29arh/hw2 | /variables.py | 423 | 3.875 | 4 | country = 'Russia'
capital = 'Moscow'
rank = 1
print(country)
print(country, 'is', 'a', 'country')
print (capital, 'is', 'the', 'biggest', 'city', 'of', country)
print ('Cremlin', 'is', 'in', capital)
print ('Square', 'is', rank, 'place')
# str
country = 'Russia'
print (type(country))
#int
rank = 1
print (type(rank))
#float
population = 144.5
print (type(population))
#bool
is_country = True
print (type(is_country)) |
076d4bddfac1ee507fe0528a444729cb7be8c236 | ming-log/NetworkProgramming | /06 tcp客户端.py | 1,829 | 3.9375 | 4 | # !/usr/bin/python3
# -*- coding:utf-8 -*-
# author: Ming Luo
# time: 2020/9/3 11:40
# tcp客户端
# tcp客户端,并不是像之前一个段子一个顾客去吃饭,这个顾客要点菜,就问服务员咱们饭店有客户端么,
# 然后这个服务器非常客气的说道:先生 我们饭店不用客户端,我们直接送到您的餐桌上
# 如果,不学习网络的知识是不是说不定也会发生那样的笑话
# 所谓的服务器端:就是提供服务的一方,而客户端,就是需要被服务的一方
# tcp客户端构建流程
# tcp 的客户端要比服务器端简单很多,如果说服务器端是需要自己买手机、插手机卡、设置铃声、等待别人
# 打电话流程的话,那么客户端就只需要我们找一个电话亭,拿起电话拨打即可,流程要少很多
from socket import *
def main():
n = 1
while True:
# 创建socket
tcp_client_socket = socket(AF_INET, SOCK_STREAM)
# 目的信息
# server_ip = input("请输入服务器ip:")
server_ip = '127.0.0.1'
# try:
# server_port = int(input("请输入服务器端口:"))
# except Exception as e:
# print(e)
server_port = 7788
# 链接服务器
tcp_client_socket.connect((server_ip, server_port))
# 提示用户输入数据
# send_data = input("请输入要发送的数据:")
send_data = '数据条数:' + str(n)
tcp_client_socket.send(send_data.encode("gbk"))
n += 1
# 接收对方发送过来的数据,最大接收1024个字节
recv_data = tcp_client_socket.recv(1024)
print("接收到的数据为:", recv_data.decode("gbk"))
# 关闭套接字
tcp_client_socket.close()
if __name__ == '__main__':
main()
|
89462ac39995eb1d6d6a777ad50c6dc5a4fa3148 | newagequanta/MITx_6.00.1x | /Week 3/biggest.py | 643 | 4.03125 | 4 | def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
list_biggest = []
biggest_len = 0
for element in aDict:
if isinstance(aDict[element], (dict, list, tuple)):
current_len = len(aDict[element])
else:
current_len = 1
if current_len > biggest_len:
list_biggest = [element]
biggest_len = current_len
elif current_len == biggest_len:
list_biggest.append(element)
biggest_len = current_len
return list_biggest
|
d933cfea18035e77ed23a3eda38440abc84f87cf | AaronLack/C200 | /Assignment3/qc1.py | 1,152 | 3.53125 | 4 | #Consult At Office Hours, I am Cofused.
import math
def f(x):
return 3*(x**2) + 4*x + 2
x = -2/3 + math.sqrt(2)/3j
y = -2/3 - math.sqrt(2)/3j
print(f(x))
print(f(y))
###
import numpy as np
import math
import numpy as np
import matplotlib.pyplot as plt
def q(a,b,c): #figure out how to define x
discrimanent = (b**2-4*a*c)
if discrimanent < 0:
d = (math.sqrt((b**2-4*a*c)*-1))/(2*a)
print(d)
e = -b/(2*a)
print(e)
x = complex(e,d)
y = complex(-e,d)
print("Complex")
return(x,y)
else:
x = (-b - (math.sqrt(b**2-4*a*c)))/(2*a)
y = (-b + (math.sqrt(b**2-4*a*c)))/(2*a)
print("Not Complex")
return (x,y)
print(q(1,3,-4))
print(q(2,-4,-3))
print(q(9,12,4))
print(q(3,4,2))
x1,y1 = (q(1,-2,-4)) #x**2 -2*x -4
print(x1,y1)
f = lambda x: x**2 -2*x -4
print(f(x1), f(y1))
#Ploting
x = np.arange(-4.0, 5.0, 0.2)
plt.plot(x, x**2 - 2*x - 4, 'g--')
plt.plot(x, 3*x**2 + 4*x + 2, 'b--')
plt.plot([-4,4],[0,0], color='k', linestyle='-', linewidth=2)
plt.plot([x1,y1],[0,0], 'ro')
if __name__=="__main__":
plt.show()
|
07d2bf8acfe0301ec2e1dab36d2bdd39396197a1 | evshary/leetcode | /0137.Single_Number_II/solution.py | 439 | 3.53125 | 4 | from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hash_table = {}
for i in nums:
try:
hash_table[i] += 1
if hash_table[i] == 3:
del hash_table[i]
except:
hash_table[i] = 1
return list(hash_table)[0]
solution = Solution()
print("single number=", solution.singleNumber([2,2,3,2]))
|
1b65f24773f1f9b1d3dd71d2dbe7887b155d82fd | phlalx/algorithms | /leetcode/360.sort-transformed-array.py | 1,090 | 3.609375 | 4 | #
# @lc app=leetcode id=360 lang=python3
#
# [360] Sort Transformed Array
#
# https://leetcode.com/problems/sort-transformed-array/description/
#
# algorithms
# Medium (47.27%)
# Likes: 242
# Dislikes: 70
# Total Accepted: 29.1K
# Total Submissions: 61.5K
# Testcase Example: '[-4,-2,2,4]\n1\n3\n5'
#
# Given a sorted array of integers nums and integer values a, b and c. Apply a
# quadratic function of the form f(x) = ax^2 + bx + c to each element x in the
# array.
#
# The returned array must be in sorted order.
#
# Expected time complexity: O(n)
#
#
# Example 1:
#
#
# Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
# Output: [3,9,15,33]
#
#
#
# Example 2:
#
#
# Input: nums = [-4,-2,2,4], a = -1, b = 3, c = 5
# Output: [-23,-5,1,7]
#
#
#
#
class Solution:
def sortTransformedArray(self, nums: List[int], a: int, b: int, c: int) -> List[int]:
res = [ a * x ^ 2 + b * x + c for x in nums]
i = 0
while i + 1 < n and res[i] <= res[i+1]:
i += 1
# res is sorted on [:i]
# and reversed sorted on [i+1:]
|
b37ec6b5bacd45c435ac427a5af9e1a30137cb41 | euleoterio/Python | /input.py | 144 | 3.984375 | 4 | numero = input("Digite um numero: ")
print("O numero digitado eh:")
print(numero)
nome = input("Digite seu nome: ")
print("Bem vindo, " + nome) |
6dd61080292e46cdf29ff36a2c02b8f374a98fa1 | WinterBlue16/Coding_Test | /input/01_basic_input.py | 553 | 3.921875 | 4 | # 가장 보편적인 입력(input) 코드
# 문자열(str) 1개 입력
x = input()
print(x)
# 정수형(int) 1개 입력
n = int(input())
print(n)
# 실수형(float) 1개 입력
f = float(input())
print(f)
# 공백을 기준으로 다수 입력
# 문자열
x, y, z = input().split()
print(x, y, z)
# 정수형, 실수형
x, y, z = map(int, input().split())
# print(x, y, z)
x, y, z = map(float, input().split())
# print(x, y, z)
# 공백을 기준으로 다수 입력, 리스트화
data = list(map(int, input().split()))
print(data)
print(data[0]) |
bcedeba1696765d26b93fff57747eb1dcd3946d2 | hmgans/DataMiningHW | /AS01.py | 6,289 | 3.859375 | 4 | #This is the python file for AS01
from random import random
from random import randint
import numpy as np
import matplotlib.pyplot as plt
import time
#Part 1A
# n - int that is the max of the domain 1-n
def randomIntCollision(n):
trialNumber = 0;
dictionary = dict();
while(True):
trialNumber+=1;
randomInt = randint(1, n); #inclusive so if n = 3000, [1,3000]
if(dictionary.get(randomInt) == 1): #Collision detected
return trialNumber;
dictionary[randomInt] = 1;
#Part1B
# Creates an array with the number of random ints needed to be
# created for a collision for each trial.
# m - number of trials
# n - domain size
def randomCollisionsArr(m, n):
start = 0;
list =[] # list of
for x in range(start, m):
list.append(randomIntCollision(n));
return list;
#1B Creates a cummulative density plot for the randomCollisionsArr generated.
def createPlotFor1B(m, n):
# generate m collision trials
data = randomCollisionsArr(m, n);
# evaluate the histogram
values, base = np.histogram(data, bins=m);
#evaluate the cumulative
cumulative = np.cumsum(values);
# plot the cumulative function
X2 = np.sort(data);
F2 = np.array(range(m))/float(m);
#Label Graph
plt.title('Cumulative Distribution of Collisions');
plt.xlabel('Number of Trials Until Collision');
plt.ylabel('Percentage Hit');
plt.plot(X2, F2)
plt.show()
# This gives an average of the number of numbers generated to get a collision
# m - number of trials
# n - domain size
def empiricalEstimate1C(m, n):
data = randomCollisionsArr(m, n);
sum = 0;
for x in range(0, m):
sum += data[x];
return sum/m;
# This method gives the average time to calculate random collisions for varying m and n
# m - number of trials
# n - domain
def timingCollision(m, n):
timesToLoop=3;
startTime = time.time();
for x in range(0,timesToLoop):
randomCollisionsArr(m,n);
midpointTime = time.time();
#Run empty loop for accuracy
for x in range(0,timesToLoop):
pass;
stopTime = time.time();
# compute average time of timesToLoop
averageTime = ((midpointTime - startTime) - (stopTime-midpointTime))/timesToLoop;
return averageTime;
#This creates a graph for varying m in relation to time in seconds.
def graphingForVaryingM(m):
timingData = [];
nValues = [];
for n in range(250000, 1000001, 250000):
timingData.append(timingCollision(m,n));
nValues.append(n);
plt.title("M = "+str(m));
plt.xlabel("Value of N");
plt.ylabel("Time Until Colision in Seconds");
plt.plot(nValues, timingData);
plt.show()
################################################################################################
#COUPON COLLECTORS
#Part 2A
# n - int that is the max of the domain 1-n
def randomIntCollisionForAll(n):
trialNumber = 0;
dictionary = dict();
totalCollisions = 0;
for x in range(1,n):
dictionary[x] = False; # initialize to not visited
while(totalCollisions != n-1):
trialNumber+=1; #K
randomInt = randint(1, n); #inclusive so if n = 3000, [1,3000] Domain size of 3000
if(dictionary.get(randomInt) == False): # It has not been visited
dictionary[randomInt] = True; # Set to true to indicate it has been visited
totalCollisions += 1;
return trialNumber;
#Part2B
# Creates an array with the number of random ints needed to be
# created for a all numbers of the domain to experience a collision.
# m - number of trials
# n - domain size
def randomCollisionsArrForCouponCollectors(m, n):
start = 0;
list =[] # list of trial numbers
for x in range(start, m):
list.append(randomIntCollisionForAll(n));
return list;
#2B Creates a cummulative density plot for the randomCollisionsArr generated.
def createPlotFor2B(m, n):
# generate m collision trials
data = randomCollisionsArrForCouponCollectors(m, n);
# evaluate the histogram
values, base = np.histogram(data, bins=m);
#evaluate the cumulative
cumulative = np.cumsum(values);
# plot the cumulative function
X2 = np.sort(data);
F2 = np.array(range(m))/float(m);
#Label Graph
plt.title('Cumulative Distribution of Collisions');
plt.xlabel('Number of Trials Until All Slots Have a Collision');
plt.ylabel('Percentage Hit');
plt.plot(X2, F2)
plt.show()
# This gives an average of the number of numbers generated so all
# numbers in the domain havee a collision
# m - number of trials
# n - domain size
def empiricalEstimate2C(m, n):
data = randomCollisionsArrForCouponCollectors(m, n);
sum = 0;
for x in range(0, m):
sum += data[x];
return sum/m;
# This method gives the average time to calculate random collisions for varying m and n
# m - number of trials
# n - domain
def timingCollision2(m, n):
timesToLoop=1;
startTime = time.time();
for x in range(0,timesToLoop):
randomCollisionsArrForCouponCollectors(m,n);
midpointTime = time.time();
#Run empty loop for accuracy
for x in range(0,timesToLoop):
pass;
stopTime = time.time();
# compute average time of timesToLoop
averageTime = ((midpointTime - startTime) - (stopTime-midpointTime))/timesToLoop;
return averageTime;
#This creates a graph for varying m in relation to time in seconds.
def graphingForVaryingM2(m):
timingData = [];
nValues = [];
for n in range(1000, 10001, 1000):
timingData.append(timingCollision2(m,n));
nValues.append(n);
plt.title("M = "+str(m));
plt.xlabel("Value of N");
plt.ylabel("Time Until All N have a Colision in Seconds");
plt.plot(nValues, timingData);
plt.show()
#print(randomIntCollision(3000));
#createPlotFor1B(200, 3000);
#print(empiricalEstimate1C(200, 3000));
#Timing Section
#graphingForVaryingM(200);
#graphingForVaryingM(5000);
#graphingForVaryingM(10000);
################################################################################
#Next part
#print(randomIntCollisionForAll(200));
#print(empiricalEstimate2C(300, 200));
#Timing Section
#graphingForVaryingM2(300);
#graphingForVaryingM2(1000);
#graphingForVaryingM2(2000);
|
f5f20d2ceb28f0f4df70d2edc10283a0b87ab380 | Stitch-wk/learngit | /001.py | 603 | 3.765625 | 4 | # -*- coding: utf-8 -*-
#sorted函数排序方法
list1 = []
for i in range(5):
num1 = int (input('请输入整数:'))
list1.append(num1)
list2=sorted(list1)
print(list1)
print(list2)
input('press any key to...')
#增加了冒泡排序法
list3 = []
print ('请输入十个整数:')
for i in range(10):
print ('输入第%d个整数:'%i)
num2 = int input()
list3.append(num2)
print (list3)
for i in range(9):
for j in range(9 - i):
if list3[j] > list3[j+1]:
list3[j], list3[j + 1] = list3[j + 1], list3[j]
print (list3)
input ('press any key to...')
|
5225e7d2d72d4958e593f6c33ba79d872d7bb48a | helen5haha/pylee | /game/PascalsTriangle.py | 724 | 4.0625 | 4 | '''
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
def generate(numRows):
rows = []
if numRows <= 0:
return rows
if numRows >= 1:
rows.append([1])
if numRows >= 2:
rows.append([1,1])
if numRows >= 3:
need_rowsnum = numRows - 2
last_row = [1,1]
for i in range (0, need_rowsnum):
new_row = [1]
for j in range(1, len(last_row)):
new_row.append(last_row[j-1] + last_row[j])
new_row.append(1)
rows.append(new_row)
last_row = new_row
return rows
generate(5) |
7a679597672833f9c9332b3f7084a3f1d7d5d66e | FemkeAsma/afvinkopdrachten | /(7)miles-per-gallon.py | 197 | 3.84375 | 4 | miles_driven= input("Number of miles that have been driven: ")
gallons_gas= input("Number of gallons of gas that have been used: ")
MPG= int(miles_driven) / int(gallons_gas)
print("MPG:", MPG)
|
360629627ca569be476cc4fe08f48269e12a1c78 | alrijleh/chess | /bots/odd_bot/odd_bot.py | 1,834 | 3.9375 | 4 | from board import Board
from collections import defaultdict
import random
def look_for_moves_to_odd(pieces: list, board):
moves_to_make = []
for piece in pieces:
piece_moves = piece.get_moves(board)
for move in piece_moves:
if move.target[0] % 2 == 1:
moves_to_make.append(move)
if moves_to_make:
return random.choice(moves_to_make)
return None
def get_random_move(pieces: list, board):
moves_to_make = []
for piece in pieces:
moves_to_make.extend(piece.get_moves(board))
if moves_to_make:
return random.choice(moves_to_make)
return None
def odd_bot(board: Board, color):
pieces_by_column = defaultdict(list)
# sort pieces with available moves based on their current column
for piece in [piece for piece in board.get_pieces(color) if piece.get_moves(board)]:
pieces_by_column[board.get_location(piece)[0]].append(piece)
even_pieces = []
odd_pieces = []
# sort pieces based on whether they're on an odd or even column
for column, pieces in pieces_by_column.items():
if column % 2 == 1:
odd_pieces.extend(pieces)
else:
even_pieces.extend(pieces)
# look for an even column'd piece that can move to an odd column
# if we can't do that, look for an even column'd piece with a different move
# if we can't do that, look for an odd piece that can move to another odd position
# if we can't do that, move an odd piece to a gross even position
move = look_for_moves_to_odd(even_pieces, board)
if move is None:
move = get_random_move(even_pieces, board)
if move is None:
move = look_for_moves_to_odd(odd_pieces, board)
if move is None:
move = get_random_move(odd_pieces, board)
return move
|
b9393d851a29737a5f64c4f22567cf1b503cec1b | Antoine-Darfeuil/Python-Training | /Python Formation Exercices/library.py | 2,996 | 3.703125 | 4 | class Document():
def __init__(self, code, title):
self.code = code
self.title = title
def __str__(self):
return self.title
class Book(Document):
_compter = 0
def __init__(self, isbn, title, author, genre):
super().__init__(isbn, title)
self.author = author
self.genre = genre
Book._compter += 1
def __del__(self):
Book._compter -= 1
def __str__(self):
return "BOOK: {} [{}]".format(super().__str__(), self.author)
class Video(Document):
def __init__(self, code, title, real, length):
super().__init__(code, title)
self.real = real
self.length = length
def __str__(self):
return "VIDEO: {} [{}]".format(super().__str__(), self.real)
class Library():
def __init__(self):
self.books = {}
self._videos = {}
self.docs = {'books': self.books , 'videos': self._videos}
def addBook(self, *, isbn, title, author, genre):
if isbn not in self.books:
self.books[isbn] = set()
self.books[isbn].add(Book(isbn, title, author, genre))
def addVideo(self, *, code, title, real, length):
if code not in self._videos:
self._videos[code] = set()
self._videos[code].add(Video(code, title, real, length))
"""
def displayAll(self):
'''Display function => Bad design.'''
for isbn, books in self.collection.items():
for book in books:
print("{} : \t {}".format(isbn, book))
"""
def __str__(self):
out = '-'*50 + '\n'
for media, collection in self.docs.items():
for code, set_obj in collection.items():
for obj in set_obj:
out += "{} : \t {}\n".format(code, obj)
return out
def _getvideos(self):
for item in self:
if isinstance(item, Video):
yield item
def videos(self):
return self._getvideos()
def __iter__(self):
for media, collection in self.docs.items():
for code, set_item in collection.items():
for item in set_item:
yield item
def main():
lib = Library()
lib.addBook(isbn="ZO45", title="Germinal", author="Zola", genre="Novel")
lib.addBook(isbn="ZO45", title="Germinal", author="Zola", genre="Novel")
lib.addBook(isbn="PY67", title="Python for Dummies", author="Jean-Mi", genre="Education")
lib.addBook(isbn="CON57", title="1984", author="George Orwell", genre="Novel")
lib.addVideo(code="HAL50", title="2001", real="Kubick", length="120")
for vid in lib.videos():
print(vid)
print('-'*50)
for item in lib:
print(item)
print(lib)
return lib
if __name__ == '__main__':
lib = main()
|
9be4a2dfb8235be3e9b24e7e72ec398129357b59 | dbzahariev/Python-Basic | /pythonbasic/Basic/EXAM_1_dec_2018/solution/05_trekking_mania.py | 855 | 3.796875 | 4 | count_groups = int(input())
all_people = 0
count_musala = 0
count_montblanc = 0
count_kilimanjaro = 0
count_k2 = 0
count_everest = 0
for i in range(0, count_groups):
count_people = int(input())
all_people += count_people
if count_people <= 5:
count_musala += count_people
elif 6 <= count_people <= 12:
count_montblanc += count_people
elif 13 <= count_people <= 25:
count_kilimanjaro += count_people
elif 26 <= count_people <= 40:
count_k2 += count_people
elif count_people >= 41:
count_everest += count_people
print(f'{count_musala / all_people * 100:.2f}%')
print(f'{count_montblanc / all_people * 100:.2f}%')
print(f'{count_kilimanjaro / all_people * 100:.2f}%')
print(f'{count_k2 / all_people * 100:.2f}%')
print(f'{count_everest / all_people * 100:.2f}%')
|
9ff40c8b3707c1d92eedbb3a198c3cda5e505696 | davidrotari19/FinalProject | /Position.py | 1,152 | 3.5 | 4 | import math
from time import sleep
import gopigo3
robot = gopigo3.GoPiGo3()
from Firebase import add,retreive
#Comment one out when u are on that
MAC_ADRESS_LEADER="leaderraspber123a"
MAC_ADRESS_FOLLOWER=["follower2468","follower13579"]
Last_Left=0
Last_Right=0
x=0
y=0
WHEEL_CIRCUMFERENCE = 0.20892 # wheel circumference in meter
def get distance(x1,x2,y1,y2):
return (x1-x2)**2+(y1-y2)**2
def get_minimum(data):
min=10000
return min
def position():
#Get encoder values
Left=robot.get_motor_encoder(robot.MOTOR_LEFT)-Last_Left
Right=robot.get_motor_encoder(robot.MOTOR_RIGHT)-Last_Right
#Get distance from encoer
distance=min(Left,Right)*WHEEL_CIRCUMFERENCE
Last_Left=robot.get_motor_encoder(robot.MOTOR_LEFT)
Last_Right=robot.get_motor_encoder(robot.MOTOR_RIGHT)
#Save last values
#Get angle
angle=(Right-Left)%360
#Get distances
x=x+distance*math.cos(angle)
y=y+distance*math.sin(angle)
print("x: %.3f, y: %.3f" % (x, y)
while True:
position()
data={"x":str(x),"y":str(y)}
add("Put here the right macadress",data)
print(retreive())
sleep(0.2)
|
242919e1f1ede298157ff32f1d40c2f172070379 | baviamu/set8-10.py | /VOV.PY | 219 | 3.890625 | 4 | B = input(" ")
if B in ('a', 'e', 'i', 'o', 'u','A','E','I','O','U'):
print("%s vowel." % B)
elif B == 'y':
print("Sometimes letter y stand for vowel, sometimes stand for constant.")
else:
print("%s constant." % B)
|
35c01ea84977ba69cf47706f300c56e8eceb4539 | BartlomiejRasztabiga/PIPR | /lab6-zaliczenie1/zad1.py | 359 | 4.15625 | 4 | def get_indices_of_given_chars(text, chars_list):
result = []
for char in text:
if char not in chars_list:
result.append(-1)
else:
result.append(chars_list.index(char))
return result
sample_text = 'Ala ma kota'
sample_list = ['a', 'A', ' ', 'k']
print(get_indices_of_given_chars(sample_text, sample_list)) |
a43631f167aad81ca9b558e7081f3c53cb6f0658 | cailinanne/python_examples | /generators.py | 737 | 4.34375 | 4 | # Create a list, iterate around it (twice)
print "list"
my_list = [1, 2, 3]
for i in my_list :
print(i)
for i in my_list :
print(i)
# Create a list using a list comprehension, iterate around it (twice)
print "list comprehension"
my_list = [x*x for x in range(1,5)]
for i in my_list :
print(i)
for i in my_list :
print(i)
print "list comprehension with filter"
my_list = [x*x for x in range(1,5) if x % 2 == 0]
for i in my_list :
print(i)
# Now use a generator
# The iteration only works once because with generators the values are not stored in memory
# just used then discarded
print "generator"
my_generator = (x*x for x in range(4))
for i in my_generator :
print(i)
for i in my_generator :
print(i) |
6c21d272efa5d0cfda2fe74ae8948123fa884a5b | AngelSosaGonzalez/IntroduccionMachineLearning | /Machine Learning/IntroduccionML/Modulos/IntroPandas/IntroPandas_2.py | 5,452 | 4.25 | 4 | """ Introduccion a Pandas: este proyecto veremos sobre el modulo de Pandas, veremos sobre el manejo de datos
antes de comenzar veremos el concpeto de Pandas:
Pandas es una herramienta de manipulación de datos de alto nivel desarrollada por Wes McKinney.
Es construido con el paquete Numpy y su estructura de datos clave es llamada el DataFrame.
El DataFrame te permite almacenar y manipular datos tabulados en filas de observaciones y columnas de variables. """
""" NOTA: En cursos que te encuentre sobre NumPy o Pandas al momento de importar los modulos te encontraras
con la palabra reservada "as" esto es un alias, asi podemos invocar las funciones del modulo sin escribir todo el
nombre por el momento para entender mejor el modulo no le pondremos alias """
#Importaremos la libreria de Pandas y Numpy
import pandas
import numpy
#Crear una DataFrame basica
#Crearemos el arreglo de datos con NumPy (Si no te acuerdas como checa el archivo "IntroNumPy")
DataFrame = numpy.array([[11, 12],[13, 14]])
#En forma de arreglo guardaremos en una variable el nombre de las columnas
Columnas = ['Colum No.1', 'Colum No.2']
#De igual forma que las columnas pero ahora con las filas
Filas = ['Fila No.1', 'Fila No.2']
""" Vamos a imprimir en consola el DataFrame creado, aunque igual lo podemos guardar en una variable y luego imprimirla.
Ahora para explicar la funcion de DataFrame de Pandas describire los atributos que nesesitamos para crear un DataFrame:
- data = Los datos que estaran dentro de nuestra DataFrame
- index = Nombre de las filas
- columns = Nombre de las columnas """
#Ejemplo de una DataFrame
print(pandas.DataFrame(data = DataFrame, index = Filas, columns = Columnas ))
#Otra forma de crear una DataFrame
""" Esta forma creamos el arreglo de datos NumPy dentro de la funcion DataFrame de Pandas
a diferencia de la anterior las columnas y filas seran nombrasdas por numeros"""
DataFrame = pandas.DataFrame(numpy.array([[11, 12],[13, 14]]))
print(DataFrame)
#Series
#Crearemos una serie basica, la estructura de una serie en pandas es la misma a la de un JSON
SeriesBasica = pandas.Series({'Nombre':'Angel Sosa','Edad':'21','Ciudad':'Ecatepec'})
print(SeriesBasica)
#Funciones de Pandas
#Forma de nuestro DataFrame (el tamaño pues...)
#Creamos nuestra DataFrame, esto lo puedes verlo arriba de como se púeden crear
DataFrame = pandas.DataFrame(numpy.array([[11, 12],[13, 14]]))
#Con la funcion "shape" vamos a saber el tamaño de nuestro DataFrame
print('El tamaño de la DataFrame es: {}'.format(DataFrame.shape))
#Altura del DataFrame para esto usamos "len" funcio basica de Python y "Index" funcion de Pandas
print('La altura de nuestra DataFrame es: {}'.format(len(DataFrame.index)))
#Estadisticas de Pandas
#Descripcion
#Creamos nuestra DataFrame, esto lo puedes verlo arriba de como se púeden crear
DataFrame = pandas.DataFrame(numpy.array([[11, 12],[13, 14]]))
#Vamos a utilizar la funcion "describe" para crear estadisticas descriptivas
print('Estadisticas descriptiva')
print(DataFrame.describe())
#Descubrir la media del DataFrame usando la funcion "mean"
print('Media')
print(DataFrame.mean())
#Descubrir la correlacion del DataFrame
print('Correlacion')
print(DataFrame.corr())
#Contar los datos de nuestro DataFrame (conteo no suma)
print('Conteo de datos')
print(DataFrame.count())
#Valor mas alto de las columnas
print('El valor mas alto')
print(DataFrame.max())
#Valor mas bajo de las columnas
print('El valor mas bajo')
print(DataFrame.min())
#Mediana de nuestra DataFrame
print('Mediana de DataFrame')
print(DataFrame.median())
#Desviacion estandar
print('Desviacion estandar')
print(DataFrame.std())
#Seleccion
#Creamos nuestra DataFrame, esto lo puedes verlo arriba de como se púeden crear
DataFrame = pandas.DataFrame(numpy.array([[11, 12, 13],[13, 14, 15]]))
#Buscar las columnas de una DataFrame (para esto solo buscaremos por indice de la columna)
print('Los valores de la columna 0 es: ')
print(DataFrame[0])
#Buscaremos mas de una columna de nuestra DataFrame (Dato curioso: Podemos crear DataFrames de una DataFrame)
print('Los valores de la columna 0 y 2 es: ')
print(DataFrame[[0, 2]])
""" Buscar un valor con "iloc" tomado como referencia su posicion en fila y columna
el primer corchete pertenece a las filas y el segundo a las columnas"""
print('El valor de la fila 0 y columna 1 es: {}'.format(DataFrame.iloc[0][1]))
#Buscar los valores de una fila
print('El valor de la fila 0 es: ')
print(DataFrame.loc[0])
#Otra forma de realizar la busqueda de filas
print('El valor de la fila 0 es: ')
print(DataFrame.iloc[0, :])
#Importacion y exportacion de datos
#Abrir datos de un documento descargado (IMPORTANTE DEBE SER UN .csv)
DatosExport = pandas.read_csv('Datos\car.csv')
#Limpieza de datos
#Creamos nuestra DataFrame, esto lo puedes verlo arriba de como se púeden crear
DataFrame = pandas.DataFrame(numpy.array([[numpy.nan, 12, 13],[numpy.nan, 14, 15]]))
#Vamos a limpiar nuestro DataFrame con datos nulos
print(DataFrame.isnull())
#Suma de valores nulos en nuestro DataFrame usando la funcion "sum"
print('Suma de valores nulos')
print(DataFrame.isnull().sum())
#Eliminar las filas nulas o perdidas
print(DataFrame.dropna())
#Eliminar las columnas nulas o con datos perdidos
print(DataFrame.dropna(axis= 1))
#Remplazar los valores nulos o perdidos, dentro de la funcion introduciremos porque lo vamos a remplazar
#En este ejemplo fue por una x
print(DataFrame.fillna('x')) |
5f01dfb8ff7c33f5f004171ecef3d2383b4c0ba9 | igortereshchenko/amis_python | /km73/Mirniy_Nickolay/3/task4.py | 300 | 3.75 | 4 | N = int(input('Количество студентов : '))
K = int(input('Количество яблок : '))
apples = K//N
rest = K%N
if (N > 0) & (K>0) :
print('Количество яблок у студента : ' , apples, '\nОстаток яблок : ' , rest)
else :
print('Error')
|
8c07ee6325ab6c1dea782153338429c914e9bf64 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/clxqui001/question1.py | 702 | 4.03125 | 4 | """this program removes any duplicated string within a list while still keeping the orignal order
quincy cele
27 april 2014"""
#convert the input into a list and continuously add more strings into the list until the word "done" has been supplied. create an additional empty list.
strings=input("Enter strings (end with DONE):\n")
listed=[]
par=[]
if strings!="DONE":
listed.append(strings)
while strings!="DONE":
strings=input()
if strings!="DONE":
listed.append(strings)
#only add the one of any duplicate words into the additional list
for i in listed:
if i not in par:
par.append(i)
print()
print("Unique list:")
for i in par:
print(i) |
7a0d7870b83861dcec82ddec383c02f43a77ab55 | chathula777/mycode | /listmethods/day1challenge02.py | 565 | 3.921875 | 4 |
#!/usr/bin/env python3
import random
icecream = ["flavors", "salty"]
tlgclass = ["Adrian","Bikash","Chas","Chathula","Chris","Hongyi","Jauric","Joe L.","Joe V.","Josh","Justin","Karlo","Kerri-Leigh","Jason","Nicholas","Peng","Philippe","Pierre","Stephen","Yun"]
icecream.append(99)
print(icecream)
random_student = int(random.random() * len(tlgclass) )
select_student = input(f"Select a student between 0 and {len(tlgclass) -1}: ")
print(f"You had {icecream[2]} {icecream[0]} to pick from and {tlgclass[int(select_student)]} chose to be {icecream[1]}")
|
82da68d2b7f124dbc231ed4eabe4985f57a3e613 | sharmakajal0/codechef_problems | /EASY/LUCKY5.sol.py | 387 | 3.875 | 4 | #!/usr/bin/env python
'''Module for lucky 5'''
##
# Question URL: https://www.codechef.com/problems/LUCKY5
##
def unlucky_digits(str_value):
'''Function for Unlucky digits'''
count = 0
for i in str_value:
if i != '4' and i != '7':
count += 1
return count
T = int(input())
for _ in range(T):
N = input().strip()
print(unlucky_digits(N))
|
e0e4db55b09d9c1027e47cb49f09b42f0edbe131 | hyunjun/practice | /python/problem-O-of-n/peak_index_in_a_mountain_array.py | 878 | 3.5625 | 4 | # https://leetcode.com/problems/peak-index-in-a-mountain-array
# https://leetcode.com/problems/peak-index-in-a-mountain-array/solution
class Solution:
# 1.23%
def peakIndexInMountainArray(self, A):
peakIdx, maxVal = None, max(A)
for i, a in enumerate(A):
if maxVal == a:
peakIdx = i
break
for i in range(1, peakIdx + 1):
if A[i - 1] > A[i]:
return -1
for i in range(peakIdx, len(A) - 1):
if A[i] < A[i + 1]:
return -1
return peakIdx
s = Solution()
data = [([0, 1, 0], 1),
([0, 2, 1, 0], 1),
([2, 1, 0], 0),
([0, 1, 2, 3], 3),
]
for A, expected in data:
real = s.peakIndexInMountainArray(A)
print('{}, expected {}, real {}, result {}'.format(A, expected, real, expected == real))
|
68385143af943f8276bad9b81dd4e2584a01ac79 | James-Damewood/Leetcode_Solutions | /BinaryTreeLevelOrder.py | 1,038 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
queue = collections.deque()
queue.appendleft((root,0))
lvl_ord = []
depth = -1
while queue:
curr_node,curr_depth = queue.pop()
if curr_depth > depth:
lvl_ord.append([])
depth = curr_depth
lvl_ord[depth].append(curr_node.val)
if (curr_node.left != None):
queue.appendleft((curr_node.left,depth+1))
if (curr_node.right != None):
queue.appendleft((curr_node.right,depth+1))
return lvl_ord
|
2ce510956ce354a0f01725fd5647ea2b8d3230fd | Tarun-Sharma9168/Python-Programming-Tutorial | /gfgpy1.py | 251 | 4.0625 | 4 | '''
Author name : Tarun Sharma
Problem Statement:Python program to add two numbers
'''
num1=input("first number")
num2=input("second number")
result=float(num1)+float(num2)
print("the sum of {0} and {1} is {2}".format(num1,num2,result))
|
91d0e99762217d718ba256b5883c3d01d27c34a8 | domspad/hackerrank | /apple_disambiguation/which_apple.py | 1,613 | 4.3125 | 4 | #!/usr/bin/env python
"""
(Basic explanation)
"""
def whichApple(text) :
"""
Predicts whether text refers to apple - the fruit or Apple - the company.
Right now only based on last appearance of word "apple" in the text
Requires: 'apple' to appear in text (with or without capitals)
Returns: 'fruit' or 'computer-company'
"""
instance, location = extractApple(text)
#coding the decision tree model
if instance[0].isupper() :
if sentenceStart(text, index) :
if isPlural(instance) :
return 'fruit'
else :
return 'computer-company'
else :
return 'computer-company'
else :
return 'fruit'
def extractApple(text) :
"""
Requires: some form of 'apple' shows up in text (i.e. capitalized, plural, possessive)
Returns: the form of the first instance found and its starting index in the text
"""
# words = text.split()
# prev = ''
# for index,word in enumerate(words) :
# #is word a variant of apple<'><s><'>?
# if word[:5].lower() == 'apple' and len(word.lower().replace("'","")) <= 6 : #like applet...
# #capital?
# if word[0].isupper() :
# +1 for company!
# #plural?
# #after end of sentence?
return 'Apple',0
def whichAppleTests() :
testcase_file = './test_cases.txt'
with open(testcase_file, 'r') as f :
num = int(f.readline())
for i in xrange(num) :
answer, text = f.readline().split('||')
assert whichApple(text) == answer
return
if __name__ == '__main__' :
whichAppleTests()
#formatted to accept Hackerrank like input
iterations = int(raw_input())
for num in xrange(iterations) :
text = raw_input()
print whichApple(text)
|
93e9763efc8ebf3a8be6748070aa0d36ef9e8adb | vinaybisht/python_tuts | /PythonDictionary.py | 813 | 4.03125 | 4 | # Python dictionary example
class PhoneBook:
def __init__(self):
pass
def _contacts_book(self):
return {"John": "+91 1234567890",
"Ron": "+91 0235687900",
"Xian": "+91 2035689782"}
phone_book = PhoneBook()
local_contacts = phone_book._contacts_book()
print(local_contacts)
local_contacts["John"] = "+910000000000"
print("//Updated value of key John//")
print(local_contacts)
del local_contacts["Xian"]
print("//Deleted Xian from dictionary//")
print(local_contacts)
local_contacts["Remo"] = "+1 6898789502"
print("//Added Remo to dictionary//")
print(local_contacts)
print("//Printing a value from key//")
print(local_contacts["John"])
print("//Printing key and Values of dictionary//")
for key, value in local_contacts.items():
print(value)
|
63110de931af7b0e5c65ac9218248c7fd6bf8d91 | YasminMuhammad/python_Calender | /comparisons.py | 578 | 4.03125 | 4 | #three number to find the max number
def max_num(number1 , number2 ,number3) :
if number1>=number2 and number1>=number3 :
return number1
elif number2>=number3 and number2>=number1 :
return number2
else :
return number3
#هي فانكشن جاهزه اصلا بس هي مرقعه و خلاص
print(max_num(20,15,9))
#بنقارن استرينج بقا
def macth_string(string1,string2) :
if string1==string2 :
print("Matched")
else:
print("Not matched")
macth_string("ali", "ali")
|
e30e57fca4fb72154ce1c990da08ca29ce0527c0 | aliakseik1993/skillbox_python_basic | /module1_13/module2_hw/task_8.py | 1,024 | 4.21875 | 4 | print('Задача 8. Обмен значений двух переменных')
# Что нужно сделать
# Дана программа, которая запрашивает у пользователя два слова, а затем выводит их на экран два раза.
a = input('Введите первое слово: ')
b = input('Введите второе слово: ')
print(a,b)
a, b = b, a
print(a,b)
# Задача: поменять значения переменных a и b местами.
# Изменять, удалять, менять местами 6-ю, 7-ю, 8-ю и последнюю строчки нельзя.
# Но в 9-ю строку можно вставлять сколько угодно кода, не трогая последний принт.
# Пример результата работы программы:
# Введите первое слово: Сок
# Введите второе слово: Вода
# Сок Вода
# Вода Сок |
59144d643f806628e1237ab1b1bf2e3909db1a6f | brennanhunt16/Monty-Hall-Code | /montyhall!.py | 1,620 | 3.921875 | 4 | import random
def thegame(numberoftests):
switch = 0
stay = 0
doors = {1: "ZONK!", 2: "ZONK!", 3: "ZONK!"}
for i in range(numberoftests):
#creating random car door
car = random.randint(1,3)
doors[car]= "car!"
original = {}
original.update(doors)
#picking a random door
pickdoor = random.randint(1,3)
#remove zonk value for one two doors not picked
pickdoorvalue = doors[pickdoor]
del doors[pickdoor]
#get remaining door to chose from
for i in doors:
if doors[i] == "ZONK!":
del doors[i]
break
#print(doors)
doors[pickdoor] = pickdoorvalue
#print(doors)
#switching from original pick to new pick
newpickdoor = 0
for i in doors:
#print(pickdoor)
if i != pickdoor:
newpickdoor = i
#print(f"{pickdoor} + end")
#counting values for switch and stay
#print((original))
if original[newpickdoor] == "car!":
switch += 1
elif original[pickdoor] == "car!":
stay += 1
#resetting door values
doors = {1: "ZONK!", 2: "ZONK!", 3: "ZONK!"}
#printing out the results
print(f"If you would have swtiched, you would have got the car {switch} times out of {numberoftests}")
print(f"If you would have stayed, you would have got the car {stay} times out of {numberoftests}")
def main():
thegame(100000)
main() |
6b9d35b39d28a277854b4aec7b1cb84a0e57fb72 | gloomysun/pythonLearning | /18-异步IO/3_async_await.py | 747 | 3.640625 | 4 | '''
用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine
实现异步操作
请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:
把@asyncio.coroutine替换为async;
把yield from替换为await。
'''
import asyncio
@asyncio.coroutine
def test():
n = 1
for i in range(50000000):
n = n + i
return n
async def hello():
print('Hello, world!')
r = await test()
print('Hello, again %s' % r)
#
# t= test()
# for x in t:
# print(x)
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
|
80dac5b56b8458172f432080ae7f9d46c6918b98 | parlad/PythonExe | /DirectorySt.py | 197 | 3.828125 | 4 | tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
tel['jack']
del tel['sape']
tel['irv'] = 4127
print(tel)
list(tel)
print(sorted(tel))
'guido' in tel
print('jack' not in tel) |
5273bd131681ccf4ba341e85c866ee594d0e2ae9 | jadeaxon/hello | /Python 3/lp3thw/ex07/ex7.py | 1,077 | 4.3125 | 4 | #!/usr/bin/env python3
# Prints a string literal.
print("Mary had a little lamb.")
# Uses format() method to replace {} placeholder.
print("Its fleece was white as {} {}.".format('yellow', 'snow'))
# Prints a string literal.
print("And everywhere that Mary went.")
# Use * overload to print a string multiple times.
print("." * 12) # What'd that do?
# A one-character string.
end1 = "L"
# A one-character string.
end2 = "e"
# A one-character string.
end3 = "m"
# A one-character string.
end4 = "o"
# A one-character string.
end5 = "n"
# A one-character string.
end6 = "a"
# A one-character string.
end7 = "d"
# A one-character string.
end8 = "e"
# A one-character string.
end9 = "r"
# A one-character string.
end10 = "a"
# A one-character string.
end11 = "d"
# A one-character string.
end12 = "e"
# Watch that comma at the end. Try removing it to see what happens.
# Append strings with + operator. Use 'end' named arg to suppress default newline.
print(end1 + end2 + end3 + end4 + end5 + end6, end='')
# Append strings.
print(end7 + end8 + end9 + end10 + end11 + end12)
|
5b398119ebc498b556d39c43503904a6bb97389b | jd-shah/Portfolio | /GitHub_Classroom_Issue_Creator/issue_creator.py | 1,699 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 18:04:17 2020
@author: shahj
Github Classroom is used to share assignments with students.
If class is programming based, one might need to share "issues" with each student as a part of the
assignment.
This feature isn't available in Github Classroom yet.
Till they release the official feature, this is the script that can be used to do that manually for
all students.
"""
"""
Library used: PyGithub - https://pygithub.readthedocs.io/en/latest/index.html
"""
"""
Algorithm:
"""
import json
from github import Github
#Assignment Prefix; to identify assignment repos of students
#Issue title; one that needs to be added
#Issue body; one that needs to be added
stud_repo_prefix = "week-6"
issue_title = "Issue 3 from python"
issue_body = "There would be a formatted content"
#Fetch Github Credentials frmo JSON file
with open('./creds.json') as cred:
credential = json.load(cred)
cred.close
#Log in to the account:
git_account = Github(credential["git-account"],credential["git-password"])
for repo in git_account.get_user().get_repos():
r_name = repo.name
if(r_name.startswith(stud_repo_prefix)):
print(r_name)
#check if there exist the expected issue
issue_exist = False
s_issues = repo.get_issues(state="open")
for s_issue in s_issues:
if(s_issue.title == issue_title):
issue_exist = True
break
#if not then add the issue to the repo
if(issue_exist == False):
repo.create_issue(title = issue_title, body = issue_body)
else:
print("Issue exist in this repo")
|
922aad079cd705e62e289f05562e1db5d35f3a6c | IvanBasOff/python | /ex06_files/ex06.py | 547 | 3.734375 | 4 | import os
import csv
print(os.path.join("Users", "bob", "st.txt"))
#
st = open("st.txt", "w")
st.write("Test string")
st.close()
#
with open("st.txt", "w") as f:
f.write("test string number 2")
#
with open("st.txt", "r") as f:
print(f.read())
#CSV
with open("st2.csv", "w") as f:
w = csv.writer(f,
delimiter = ",")
w.writerow(["one", "two", "three"])
w.writerow(["four", "five", "six"])
#
with open("st2.csv", "r") as f:
r = csv.reader(f, delimiter = ",")
for row in r:
print(",".join(row))
|
7502ac73fd14234ce87c5e8928eea4cd6652cabf | FabioMenacho/backend | /semana1/dia3/practica.py | 867 | 3.765625 | 4 | # f = open('alumnos.csv','a')
# print("REGISTRO ALUMNO: ")
# nombre = input("NOMBRE: ")
# email = input("EMAIL: ")
# celular = input("CELULAR: ")
# f.write(nombre + "," + email + "," + celular + '\n')
# f.close()
# fr = open('alumnos.csv','r')
# alumno = fr.read()
# print(alumno)
# fr.close()
fr = open('alumnos.csv','r')
alumnos = fr.read()
print(alumnos)
lstAlumnosData = []
lstAlumnos = alumnos.splitlines()
print(lstAlumnos)
for objAlumno in lstAlumnos:
lstObjAlumno = objAlumno.split(',')
print(lstObjAlumno)
nombre = lstObjAlumno[0]
email = lstObjAlumno[1]
celular = lstObjAlumno[2]
dictAlumno = {
'nombre': nombre,
'email': email,
'celular': celular
}
print(dictAlumno)
lstAlumnosData.append(dictAlumno)
print(lstAlumnosData)
fr.close() |
7e3a30f50c02e52b5fe56e2df210365f150979d2 | josemariap/python | /practica_exception.py | 921 | 4.0625 | 4 |
# exceptions
def suma(num1, num2):
return num1+num2
def resta(num1, num2):
return num1-num2
def multiplica(num1, num2):
return num1*num2
def divide(num1,num2):
try:
return num1/num2
except ZeroDivisionError:
print("No esta permitido la division por 0")
return "Error en la operación"
while True:
try:
op1=(int(input("Introduce el primer número: ")))
op2=(int(input("Introduce el segundo número: ")))
break
except ValueError:
print("No se puede ingresar letras")
operacion=input("Introduce la operación a realizar (suma,resta,multiplica,divide): ")
if operacion=="suma":
print(suma(op1,op2))
elif operacion=="resta":
print(resta(op1,op2))
elif operacion=="multiplica":
print(multiplica(op1,op2))
elif operacion=="divide":
print(divide(op1,op2))
else:
print ("Operación no contemplada")
print("Continua la ejecución del programa..")
|
7b76d03d498d056c60a9e61343ba5ba4a8b35da6 | ChrisJaunes/generating_test_paper | /Generator/genProgramming/p12.py | 1,662 | 3.59375 | 4 | import numpy.random as random
from sample import ProgrammingProblemDesc, ProgrammingProblemSTD
def generatorProblemDesc() -> ProgrammingProblemDesc:
return ProgrammingProblemDesc("拿硬币", """
桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。
我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。
示例 1:
输入:3
4 2 1
输出:4
解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。
示例 2:
输入:3
2 3 10
输出:8
示例 3:
输入:4
7 5 3 1
输出:10
限制:
1 <= n <= 4
1 <= coins[i] <= 10
""")
def generatorProblemSTD() -> ProgrammingProblemSTD:
return ProgrammingProblemSTD("Java", """
import java.io.*;
import java.util.*;
public class Solution {
static public int minCount(int[] coins) {
int count = 0;
for(int coin: coins){
//右移一位相当于除以2,和1按位与相当于除2取余
count += (coin >> 1) + (coin & 1);
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] coins = new int[n];
for (int j = 0; j < n; ++j){
coins[j] = in.nextInt();
}
System.out.println(minCount(coins));
}
}
""")
def generatorProblemTestSingle(f, seed: int = 2021):
random.seed(seed)
n = random.randint(1, 4)
print(n, file=f)
print(" ".join([str(random.randint(1, 10)) for _ in range(n)]), file=f) |
d3bc2dd31d895fc04140e85544d7814fb4f5dbb2 | ashinzekene/public-apis-py | /app/utils/scrap.py | 811 | 3.625 | 4 | from bs4 import BeautifulSoup
import requests
def fetch_url_text(url):
"""
Fetch for a url and return the response
"""
return requests.get(url).text
def scrap(html, selector, attr):
"""
Scrap for text in an html text
"""
soup = BeautifulSoup(html, "html.parser")
sels = soup.select(selector)
try:
return sels[0][attr]
except IndexError:
return "Not Found"
def scrap_url(url, selector, attr="src"):
"""
For scraping web pages
"""
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
sels = soup.select(selector)
print(sels)
try:
urls = list(map(lambda sel: {'url': sel[attr], 'title': sel.string }, sels))
print(urls)
return urls
except IndexError:
return "Not Found" |
45e36c4cd57248ab08165fd76de646c6ce1e1442 | yakovitskiyv/algoritms | /unlike_deal_test.py | 1,044 | 3.984375 | 4 | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def print_linked_list(vertex):
while vertex:
print(vertex.value, end=" -> ")
vertex = vertex.next
print("None")
def get_node_by_index(node, index):
while index:
node = node.next
index -= 1
return node
def solution(node, idx):
cur_node = get_node_by_index(node, idx)
if idx == 0:
head_node = get_node_by_index(node, idx+1)
return head_node
if cur_node.next is None:
previous_node = get_node_by_index(node, idx-1)
previous_node.next = None
return node
previous_node = get_node_by_index(node, idx-1)
next_node = get_node_by_index(node, idx+1)
previous_node.next = next_node
return node
def test():
node3 = Node("node3", None)
node2 = Node("node2", node3)
node1 = Node("node1", node2)
node0 = Node("node0", node1)
new_head = solution(node0, 1)
# result is node0 -> node2 -> node3
test() |
61dd4e65ea1affca9a0ec3ccecea12605245f743 | Skya-neko/DataMining | /ch4_class-1-1.py | 1,957 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 9 15:07:13 2021
@author: Vivian
"""
'''語法錯誤 Syntax error'''
'''在寫程式的時候寫出電腦看不懂的腳本(script)。'''
# NameError =================================================================
# 第一種:未命名的function(函式)
pritn('Hello World!')
# >>> NameError: name 'pritn' is not defined
# 第二種:未命名的variable(變數)
if x == y :
print('yes')
# >>> NameError: name 'x' is not defined
# # =========================================================================
# SyntaxError ===============================================================
# 第一種:string 沒有被寫完整
print('Hello World!!)
# >>> SyntaxError: EOL while scanning string literal
# # =========================================================================
# TypeError =================================================================
print('1'+1)
# >>> TypeError: can only concatenate str (not "int") to str
# # =========================================================================
'''邏輯錯誤 Logical error'''
'''語法沒有錯誤且程式可以執行的情況下,輸出的結果卻不合理'''
# 想要將台幣換算成美元,卻用錯誤的算法
# 台幣30元可以換成1美元
TWD = 30
print('台幣TWD換算成美元後,總共:',TWD*30,'美元')
'''執行錯誤 Execution error'''
'''當程式執行到一半時,被電腦強制結束,無法執行完畢,就是發生執行錯誤。'''
# # ZeroDivisionError =======================================================
z = 1/0
# >>> ZeroDivisionError: division by zero
# # =========================================================================
# # IndexError ==============================================================
list_1 = [1,2,3]
print(list_1[3])
# >>> IndexError: list index out of range
# # ========================================================================= |
7bb14517bb66afc2697c7696a6ca89e451a54eea | perrinod/hacker-rank-solutions | /Algorithms/Strings/Caesar Cipher/solution.py | 666 | 3.875 | 4 | # https://www.hackerrank.com/challenges/caesar-cipher-1/problem
#!/bin/python3
import math
import os
import random
import re
import sys
def caesarCipher(s, k):
encryptedString = ""
for i in range (0, len(s)):
if(s[i].isalpha()):
a = 'A' if s[i].isupper() else 'a'
encryptedString += chr(ord(a) + (ord(s[i]) - ord(a) + k) % 26)
else:
encryptedString += s[i]
return encryptedString
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
k = int(input())
result = caesarCipher(s, k)
fptr.write(result + '\n')
fptr.close() |
1768fdda8b973b3f88d45f9383c11afd51de3be3 | teclivre/Python | /Desafios- Python/Desafio-10.py | 456 | 3.859375 | 4 | # Conversão de real para dolar.
print('\n \n Agora vamos ver quantos dolares você pode comprar com os Reais que está em sua carteira. \n \n ')
name = input('Primeiro me diga seu nome: ')
d = float (input('Dite o valor do dolar no dia de hoje: $'))
r= float (input('\n \n Agora me diga quanto você tem em sua carteira? R$'))
dollar = r*d
print('\n \n Olá, {} em sua carteira tem R${:.2f} e você pode comprar ${:.2f}.\n \n '.format(name,r,dollar)) |
014888e15f15be2d8c3c05a774d573b095d73fff | krishnasree45/Practice-Codes | /array_in_pendulum/my_method.py | 986 | 3.734375 | 4 | # code
"""
The minimum element out of the list of integers, must come in center position of array. If there are even elements,
then minimum element should be moved to (n-1)/2 index (considering that indexes start from 0)
The next number (next to minimum) in the ascending order, goes to the right, the next to next number goes
to the left of minimum number and it continues like a Pendulum.
Input:
2
5
1 3 2 5 4
5
11 12 31 14 5
Output:
5 3 1 2 4
31 12 5 11 14
"""
T = int(input())
for _ in range(T):
size = int(input())
array = list(map(int, input().split()))
new_array = list()
index = (size-1) // 2
array.sort()
for i in array:
new_array.append(i)
new_array[index]=array[0]
left = index-1
right = index+1
for i in range(1, size, 2):
new_array[right] = array[i]
if i+1 < size:
new_array[left] = array[i+1]
left -= 1
right += 1
for i in new_array:
print(i, end=" ")
print()
|
4edb28de7c66ecb8c16b4b5ece613a568287d639 | leandrovianna/programming_contests | /URI/OBI2013Fase1Replay/175_1.py | 305 | 3.703125 | 4 | def check(a, b, c, d):
return (a * d == b * c)
a, b, c, d = raw_input().split();
a = int(a)
b = int(b)
c = int(c)
d = int(d)
if (check(a, b, c, d)
or check(a, d, c, b)
or check(c, b, a, d)
or check(b, a, c, d)
or check(a, b, d, c)):
print "S"
else:
print "N"
|
d96aedcb01aad344e044c2accf5f1ec88c598d52 | altareen/csp | /09Tuples/tupleoperations.py | 873 | 4.375 | 4 | # initializing a tuple
drinks = ("tea", "coffee", "juice")
print(drinks)
print(type(drinks))
# initializing a tuple with a single element
soda = ("cola",)
print(type(soda))
# retrieving an element with square bracket notation
chai = drinks[0]
print(chai)
# using slicing to get a new tuple
result = drinks[:2]
print(result)
# using len() to determine the number of elements
qty = len(drinks)
print(qty)
# using a for loop with a tuple
for item in drinks:
print(item)
# using a comparison operator with a tuple
result = (8, 5, 17, 500) < (8, 5, 23, 19)
print(result)
# multiple assignment with a tuple
results = [98, 17]
(total, count) = results
print(total)
print(count)
# using a tuple as a dictionary key
res = {("Smith", "Alice"):92, ("Jones", "Bob"):89}
print(res)
# using the sorted() method with a tuple
beverages = sorted(drinks)
print(beverages)
|
355c8d82baf73e81ff64c656175316f5e07f9ec1 | michalgar/Attendance | /extensive_main.py | 1,466 | 4.15625 | 4 | """
This file will include the main functionality of the program.
It should display a menu of actions to the user and invoke the relevant function
"""
import Logic
# Display a menu to the user
print("\nWhat would you like to do?")
print("1- Add employee")
print("2- Delete employee")
print("3- Mark attendance")
print("4- Generate a report")
user_action = input("Please select an action by typing its corresponding number: ")
# Sub-action
if user_action == '1':
print("\nYou chose to add employee.\nPlease select one of the methods below:")
print("1- Add employee manually")
print("2- Add employee from file")
sub_action = input("Please select an action by typing its corresponding number: ")
if sub_action == '1':
Logic.Employee.add_employee()
elif user_action == '2':
print("\nYou chose to delete employee.\nPlease select one of the methods below:")
print("1- Delete employee manually")
print("2- Delete employee from file")
sub_action = input("Please select an action by typing the corresponding number: ")
elif user_action == '3':
pass
elif user_action == '4':
print("\nYou chose to generate report.\nPlease select one of the methods below:")
print("1- Generate attendance report of an employee")
print("2- Generate monthly attendance report for all employees")
print("3- Generate late attendance report")
sub_action = input("Please select an action by typing the corresponding number: ")
|
188b4605acd90546e36dc98f886468ad9d2246a0 | TheCyberian/Hacking-Secret-Ciphers---Implementations | /simple_substitution_cipher.py | 3,095 | 4.125 | 4 | import sys, random
"""
To implement the simple substitution cipher, choose a random letter to encrypt each letter of the alphabet.
Use each letter once and only once. The key will end up being a string of 26 letters of the alphabet in random order.
There are 26! possible keys, which is equal to 26*25*24*.....*2*1 = 403,291,461,126,605,635,584,000,000 possible orderings for keys.
Pretty much impossible to brute force with the current computing power.
Although the number of possible keys is very large (26! ≈ 288.4, or about 88 bits),
this cipher is not very strong, and is easily broken.
Provided the message is of reasonable length (see below),
the cryptanalyst can deduce the probable meaning of the most common symbols by doing a simple frequency distribution analysis
of the ciphertext. Pattern analysis.
"""
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# LETTERS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY Z[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
def main():
myMessage = 'If a man is offered a fact which goes against his instincts, he will scrutinize it closely, and unless the evidence is overwhelming, he will refuse to believe it. If, on the other hand, he is offered something which affords a reason for acting in accordance to his instincts, he will accept it even on the slightest evidence. The origin of myths is explained in this way. -Bertrand Russell'
myKey = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
myMode = 'encrypt' # set to 'encrypt' or 'decrypt'
checkValidKey(myKey)
if myMode == 'encrypt':
translated = encryptMessage(myKey, myMessage)
elif myMode == 'decrypt':
translated = decryptMessage(myKey, myMessage)
print('Using key %s' % (myKey))
print('The %sed message is:' % (myMode))
print(translated)
print()
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
sys.exit('There is an error in the key or symbol set.')
def encryptMessage(key, message):
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = ''
charsA = LETTERS
charsB = key
if mode == 'decrypt':
# For decrypting, we can use the same code as encrypting. We
# just need to swap where the key and LETTERS strings are used.
charsA, charsB = charsB, charsA
# loop through each symbol in the message
for symbol in message:
if symbol.upper() in charsA:
# encrypt/decrypt the symbol
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
# symbol is not in LETTERS, just add it
translated += symbol
return translated
def getRandomKey():
key = list(LETTERS)
random.shuffle(key)
return ''.join(key)
if __name__ == '__main__':
main()
|
ff7ac260d818478f3e7cd9006571a3079ddf1e7e | Yobretaw/AlgorithmProblems | /EPI/Python/LinkedList/8_2_reverseSingleLinkedList.py | 698 | 3.890625 | 4 | import sys
import os
import math
from linkedlist import *
"""
============================================================================================
Given a linear nonrecursive function that reverses a singly linked list. The function should
use no more than constant storge beyond that needed for the list itself.
============================================================================================
"""
def reverse(l):
if not l:
return
prev = None
curr = l
while curr:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
return prev
l = ll_generate_ascending_list(10)
print l
print reverse(l)
|
01c170576f8bd2361a372a8091430a239551d184 | sankeerth/Algorithms | /Graph/python/common/detect_cycle_directed.py | 833 | 3.734375 | 4 | from Graph.python.common.graph_adj_list import Graph
def detect_cycle(graph):
visited = {node: False for node in graph.adj_list}
cycle_list = list()
def detect_cycle_util(s):
visited[s] = True
stack[s] = True
cycle_list.append(s)
for v in graph.adj_list[s]:
if not stack[v]:
detect_cycle_util(v)
else:
print(cycle_list + [v])
cycle_list.pop()
for node in graph.adj_list:
if not visited[node]:
stack = {node: False for node in graph.adj_list}
detect_cycle_util(node)
graph = Graph()
graph.add_directed_edge(0, 1)
graph.add_directed_edge(0, 2)
graph.add_directed_edge(1, 2)
graph.add_directed_edge(2, 0)
graph.add_directed_edge(2, 3)
graph.add_directed_edge(3, 3)
detect_cycle(graph) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.