blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
51a17e64d2967bdbe06323a92f24b992e4f7b75e | rishabh-22/Problem-Solving | /two_two.py | 611 | 4.03125 | 4 | """
given an array of numbers, find the possible numbers in it which are powers of two.
"""
def power_of_two(n):
x = int(n) if n[0] != '0' else 0
return x and (not(x & (x - 1)))
def two_two(a):
sub_strings = []
i = 0
while i < len(a):
for l in range(1, len(a)+1-i):
sub_strings.append(a[i:i+l])
i += 1
count = 0
for p in sub_strings:
if power_of_two(p):
count += 1
return count
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
a = input()
result = two_two(a)
print(result)
|
c42bd40088a7b315f0b7d764e1671da36e28fbbb | Pearltsai/lesson7HW | /lesson7HW_1.py | 188 | 3.578125 | 4 | s=[]
x=int(input('學生數量'))
for i in range(x):
y=int(input('學生成績'))
s.append(y)
print('最高:',max(s))
print('最低:',min(s))
print('平均:',sum(s)/x)
|
0c1878735feb10a5b207a1bf93b2e1a2893dfa7e | JamieBort/LearningDirectory | /Python/Courses/LearnToCodeInPython3ProgrammingBeginnerToAdvancedYourProgress/python_course/Section4Modules/29ExerciseTimeAndMatplotlibPyplot.py | 3,256 | 3.984375 | 4 | # NOT DONE - COME BACK TO to address the following:
# Need to do the following.
# 1. see TODO comment below: consolidate all these for loops below.
# 2. graph plot code copied from ../LearningDirectory/Python/LearnToCodeInPython3ProgrammingBeginnerToAdvancedYourProgress/python_course/Section4Modules/28Matplotlib.py
# 3. provide correct error handling/validation
# Exercise:
# Create a program to help the user type faster.
# Give them a word and ask them to write it five times.
# Check how many seconds it took them to type the word at each round.
# In the end, tell the user how many mistakes were made.
# And show a chart with the typing speed evolution during the 5 rounds.
# Solution:
import time as t
import matplotlib.pyplot as plt
word_to_practice = input("Please type a word that you would like to practice typing more quickly:\n") # does not have correct validation - crashes if a string is not entered
print("The word is: ", word_to_practice)
number_of_attempts = int(input("Please enter an integer for the number of attemps you'd like to try.\n")) # does not have correct validation - crashes if an integer is not entered
print("The number of attempts is: ", number_of_attempts)
def measure_elapsed_time(word):
my_list = []
print("The word to practice is: ", word)
before = t.time() # the amount of time since the epoch.
attempt = input("Please attempt to type that word again.\n")
after = t.time() # the amount of time since the epoch.
my_list.append(attempt)
my_list.append(after-before)
return my_list
# this is not needed
def check_spelling(thelist):
if word_to_practice == thelist:
print("they're the same")
else:
print("They're not the same")
def master_function(wordToPractice): # this function calls measure_elapsed_time()
my_dictionary = {}
i=0
x = []
while i < number_of_attempts:
x.append(i+1) # generating x array for the graph plot.
myList = measure_elapsed_time(wordToPractice)
my_dictionary[i] = myList
i += 1
# print("X IS: ", x)
# TODO: consolidate all these for loops below.
y = []
for key in my_dictionary:
y.append(my_dictionary[key][1]) # generating y array.
print("The ", key + 1, " attempt was ", round(my_dictionary[key][1], 4), " seconds long.")
# print("Y IS: ", y)
talley = 0
for key in my_dictionary:
if my_dictionary[key][0] != word_to_practice:
talley += 1
print("There were ", talley, "mistakes made.")
# my_dictionary["Number of incorrect spellings"] = talley
# print("my_dictionary: ", my_dictionary)
# generating the graph
# import matplotlib.pyplot as plt # remove this
# x = [1,2,3,4]
# y = [1500,1200,1100,1800]
# y = []
# print(y)
# for key in my_dictionary: # generating y array
# print("key: ", key)
# print("my_dictionary[key][1]: ", my_dictionary[key][1])
# y.append(my_dictionary[key][1])
# print(y)
# legend = ["January", "February", "March", "April"]
# plt.xticks(x,legend)
plt.bar(x,y)
# plt.ylabel("Sales in US$")
# plt.title("Monthly Sales")
plt.plot(x,y)
plt.show()
master_function(word_to_practice) |
ba75cea529e9d54b7da04825cd0cd0fe4c45de49 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4165/codes/1585_2895.py | 152 | 3.625 | 4 | var1=float(input("quantidade de jogos"));
var2=float(input("valor do jogo"));
var3=float(input("valor do frete"));
var4=(var1*var2)+var3 ;
print(var4); |
03a9120991f6eadbec9e80a80e49add0110b06ff | choijaehyeokk/BAEKJOON | /1978_소수 찾기.py | 348 | 3.671875 | 4 | import sys
N = int(sys.stdin.readline().rstrip())
numbers = list(map(int, sys.stdin.readline().split()))
cnt = 0
def is_div(n: int)->bool:
for i in range(2, n):
if n % i == 0:
return False
return True
for i in range(len(numbers)):
if numbers[i] == 1:
continue
elif is_div(numbers[i]): cnt += 1
print(cnt) |
4e7570f3bae74debc4239a9265afde57872f8d69 | Bhargavij-learnings/python_training_assignments | /sum.py | 125 | 3.640625 | 4 | def sum(*args):
result=0
for value in args:
result=result+value
return result
s=sum(10,20,30)
print(s/3)
|
17c0aee7fb6d064a34f1a4a2c923aaf09560c45d | leonhostetler/undergrad-projects | /numerical-analysis/09_odes/ode_rk4.py | 1,146 | 3.84375 | 4 | #! /usr/bin/env python
"""
Solves the initial value ODE of the form
dy/dt = f(y,t)
with the initial condition y(0) = y_0. It is solved using the fourth-order
Runge-Kutta method.
Leon Hostetler, Mar. 2017
USAGE: python ode_rk4.py
"""
from __future__ import division, print_function
import matplotlib.pyplot as plt
import numpy as np
def f(y, t):
return y + 1
T = 1 # Final time
N = 10 # Number of time slices
y_list = [1.0] # Initial value
t_list = [0.0] # Initial time
dt = T/N # Time step
for i in range(N):
k1 = dt*f(y_list[i], i*dt)
k2 = dt*f(y_list[i] + k1/2, i*dt + dt/2)
k3 = dt*f(y_list[i] + k2/2, i*dt + dt/2)
k4 = dt*f(y_list[i] + k3, i*dt + dt)
y_list += [y_list[i] + (k1 + 2*k2 + 2*k3 + k4)/6]
t_list += [t_list[i] + dt]
# This is the exact solution
t_list2 = np.linspace(0, T, 1000)
exact_y = 2*np.exp(t_list2) - 1
# Plot the results
plt.rc('text', usetex=True)
plt.title("A Plot of Multiple Functions")
plt.plot(t_list2, exact_y, label=r"$y(t) = 2e^t - 1$")
plt.plot(t_list, y_list, label="Approx.")
plt.legend(loc=2)
plt.xlabel(r"$t$")
plt.show()
|
7d6b81cc02757a1eee09e6246567bda0080dec68 | junyoung-o/PS-Python | /by date/2021.02.23/2164-1.py | 912 | 3.546875 | 4 | import time
start = time.time()
n = int(input())
class CQueue():
def __init__(self):
self.front = 0
self.rear = 0
self.q = [-1] * int(n / 2 + 0.5)
def is_empty(self):
if(self.rear == self.front):
return True
return False
def push(self, target):
self.q[self.rear] = target
self.rear += 1
def pop(self):
if(self.is_empty()):
return -1
self.front += 1
return self.q[self.front - 1]
def get_size(self):
return len(self.q)
def pop_point(self, point):
del self.q[point]
q = CQueue()
for i in range(2, n+1, 2):
num = (n + 3) - i
q.push(i)
if(n % 2 != 0):
q.push(n)
point = 0
while(q.get_size() != 1):
q.pop_point(point)
point += 1
if(point >= q.get_size()):
point = 0
print(q.q[0])
finish = time.time()
print(finish - start)
|
df66f4962c2fc5cfe73564737faad80a0bd1daa5 | DimonYin/Coursera_Courses_Dimon_Yin | /Data Structures and Algorithms (UCSD & NRUHSE)/Course 1_Algorithmic Toolbox/Week3/Programming Assignment 3_Greedy Algorithms/change.py | 610 | 3.859375 | 4 | # Uses python3
def get_change(rem):
value_list = [1, 5, 10]
# Sort first
sorted_value_list = sorted(value_list, reverse=True)
coin_list = []
for value in sorted_value_list:
coins = int(rem/value)
coin_list = coin_list + [value] * coins # Add needed coins into output coin list
rem = rem - coins * value # Update the remaining change
# Once rem = 0, we just return the list
if rem == 0:
return len(coin_list)
# If comes this step, that means there is no solution
return "No solution"
m = int(input())
print(get_change(m))
|
2da4a38d9a64a10f43cf134eb3becff31992f78a | wwzhen/leetcode_w | /排序算法/归并排序.py | 979 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/6/8 12:07
# @Author : wwzhen
class Sort(object):
def sort(self, nums):
return self._sort(nums)
def _sort(self, nums):
if len(nums) < 2:
return nums
middle_place = len(nums) // 2
left = nums[0: middle_place]
right = nums[middle_place:]
return self._merge(self._sort(left), self._sort(right))
def _merge(self, left, right):
result = list()
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]:
result.append(left[0])
del left[0]
else:
result.append(right[0])
del right[0]
while len(left):
result.append(left[0])
del left[0]
while len(right):
result.append(right[0])
del right[0]
return result
if __name__ == '__main__':
s = Sort()
print(s.sort([6, 5, 4, 3, 2, 1, 9]))
|
5d7dbc8884f44894e0424c346308169a889383ff | RevathiRKNair/hello-world | /universal gates.py | 1,400 | 3.71875 | 4 | #! /usr/bin/python
a= input("enter first no:")
b= input("second number:")
class Gate(object):
def __init__(self,a,b):
self.input[0] = a
self.input[1] = b
self.output = None
def logic(self):
raise NotImplementedError
def output(self):
self.logic()
return self.output
class AndGate(Gate):
def logic(self):
self.output = self.input[0] and self.input[1]
return self.output
class OrGate(Gate):
def logic(self):
self.output = sef.input[0] or self.input[1]
return self.output
class NotGate(Gate):
def logic(self):
self.output = not self.input[0]
return self.output
c= input(" choose the operation: \n 1.NAND \n 2.NOR \n")
if c==1:
class NandGate(AndGate, NotGate):
def logic(self):
andout = super (NandGate, self).logic()
Gate.__init__(self, andout)
self.output = NotGate.logic(self)
return self.output
print ("output =",self.output)
else:
class NorGate(OrGate, NotGate):
def logic(self):
orout = super(NorGate, self).logic()
Gate.__init__(self, orout)
self.output = NotGate.logic(self)
return self.output
print ("output =",self.output)
|
b0b50262dad3e15d2ca74eeb2e99a1b258d3de5e | artorious/python3_dojo | /test_simple_test_functions_unittests.py | 2,071 | 3.546875 | 4 | #!/usr/bin/env python3
""" Tests for simple_test_functions.py """
import unittest
from simple_test_functions import *
class TestSimpleTestFunctions(unittest.TestCase):
""" Test class for simple_test_functions.py """
def setUp(self):
print('Setting up...........')
def tearDown(self):
print('..........Tearing down')
# test max_of_three_bad()
def test_max_of_three_bad_1(self):
self.assertEqual(max_of_three_bad(2, 3, 4), 4)
def test_max_of_three_bad_2(self):
self.assertEqual(max_of_three_bad(4, 3, 2), 4)
def test_max_of_three_bad_3(self):
self.assertEqual(max_of_three_bad(3, 2, 4), 4)
# test max_of_three_good()
def test_max_of_three_good_1(self):
self.assertEqual(max_of_three_good(2,3,4), 4)
def test_max_of_three_good_2(self):
self.assertEqual(max_of_three_good(4,3,2), 4)
def test_max_of_three_good_2(self):
self.assertEqual(max_of_three_good(3,2,4), 4)
# test maxmum()
def test_maximum_1(self):
self.assertEqual(maximum([2, 3, 4, 1]), 4)
def test_maximum_2(self):
self.assertEqual(maximum([4, 3, 2, 1]), 4)
def test_maximum_3(self):
self.assertEqual(maximum([-2, -3, 0, -21]), 0)
# test sum_up()
def test_sum_up_1(self):
self.assertEqual(sum_up([0, 3, 4]), 7)
def test_sum_up_2(self):
self.assertEqual(sum_up([-3, 0, 5]), 2)
# test ListManager - Some code that can throw an exception
def test_list_manager_1(self):
lstmgr = ListManager([1, 2, 3])
self.assertEqual(lstmgr.get(2), 3)
def test_list_manager_2(self):
lstmgr = ListManager([1, 2, 3])
self.assertEqual(lstmgr.get(3), 3)
def test_list_manager_3(self):
lstmgr = ListManager([1, 2, 3])
self.assertEqual(lstmgr.get(0), 1)
def test_list_manager_4(self):
lstmgr = ListManager([1, 2, 3])
self.assertEqual(lstmgr.get(0), 0)
if __name__ == '__main__':
unittest.main()
|
f65ce6bcb5a1ac81d3077e33351dca4eeaeccfa6 | Alibi14/thinkpython-solutions | /polindrome.py | 382 | 3.828125 | 4 | def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_polindrome(word):
if len(word) <= 1:
return True
if first(word) != last(word):
return False
print(middle(word))
print('space')
return is_polindrome(middle(word))
print(is_polindrome('redivider'))
|
83647cf3f12a1e32c7f784a83adb497429f0fb9d | HappyRocky/pythonAI | /LeetCode/22_Generate_Parentheses.py | 1,987 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 10:41:46 2018
@author: gongyanshang1
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
给定整数n,要求输出 n 对左右括号的所有可能的有效组合。
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
def generateParenthesis(n):
"""
:type n: int
:rtype: List[str]
递归法。
起始有 n 个左括号和 n 个右括号需要拼接到字符串中。
先将结果字符串初始化为空。
每次递归时,选择其中一种括号,拼接到结果字符串的最右边。分为两种情况:
1、如果剩余左括号和右括号的数量相等,那么下一步只能放左括号
2、如果剩余右括号多于左括号,那么既可以放左括号,又可以放右括号
不可能出现左括号多于右括号的情况
"""
def fun_rec(left_count, right_count):
'''
将left_count个左括号和right_count右括号进行有效组合
'''
if left_count == 0 and right_count == 0:
return ['']
if left_count == 0:
return [''.join([')'] * right_count)]
if right_count == 0:
return [''.join([')'] * right_count)]
if left_count == right_count: # 左右数量相等时,只能先放左括号
remain_list = fun_rec(left_count - 1, right_count)
return ['(' + x for x in remain_list]
else: # 左括号少于右括号(不可能大于),则左右括号都可以放
remain_list = fun_rec(left_count - 1, right_count)
l1 = ['(' + x for x in remain_list]
remain_list = fun_rec(left_count, right_count - 1)
l2 = [')' + x for x in remain_list]
return l1 + l2
return fun_rec(n, n)
if '__main__' == __name__:
n = 3
print(generateParenthesis(n)) |
d0dd79192d3f492f5fd40f2d18e737bdee4eda90 | gerardo-valq/Python_done_works | /Firsttermproject.py | 12,579 | 3.609375 | 4 |
# February 13, 2016
# Angeles Rodriguez Hernandez A01173339
# Gerardo Arturo Valderrama Quiroz A01374994
# Omar Rodrigo Orendain Romero A01374568
# Alfredo Alarcon Valencia A01375414
# Group 4
# Project
# START
# Import Turtle Library
from turtle import *
#Assigning a speed
speed(10)
# Color Settings
bgcolor("#160D50")
fillcolor ("#141417")
# ---------Configurating Background---------
# Back Buildings
pencolor("#001069")
penup()
setpos(-700, -90)
pendown()
#Function definition back buildongs
def back_build ():
left (90)
forward (300)
right (90)
forward (40)
left(90)
forward (20)
right (90)
forward(27)
right (90)
forward (20)
left (90)
forward (40)
right (90)
forward (300)
left(90)
forward (5)
left (90)
forward (300)
right (50)
forward (60)
right (135)
forward(40)
left(135)
forward (60)
right (130)
forward (340)
left (90)
forward (10)
left (90)
forward (320)
right (90)
forward (50)
right (90)
forward (320)
left (90)
forward (2)
left (90)
forward (250)
right (90)
forward (50)
right (90)
forward (250)
left (90)
forward (2)
left (90)
forward (180)
right (90)
forward (50)
right (90)
forward (180)
left (90)
forward (2)
left (90)
right (90)
forward (1)
#Function use back buildings
for counter in range (4):
fillcolor ("#001069")
begin_fill()
back_build()
end_fill()
#Function definition back buildings 2
pencolor("#2F365E")
penup()
setpos(-700, -100)
pendown()
def back_build2 ():
left (90)
forward (300)
right (90)
forward (50)
right (90)
forward (300)
left (90)
forward (2)
left (90)
forward (160)
right (90)
forward (50)
right (90)
forward (160)
left (90)
forward (2)
left (90)
forward (230)
right (90)
forward (50)
right (90)
forward (230)
left (90)
forward (2)
left (90)
forward (300)
right (90)
forward (50)
right (90)
forward (300)
left (90)
forward (2)
left (90)
forward (160)
right (90)
forward (50)
right (90)
forward (160)
left (90)
forward (2)
left (90)
right (90)
forward (1)
#Function use back buildings 2
for counter in range (7):
fillcolor ("#2F365E")
begin_fill()
back_build2()
end_fill()
# --------Building primary buildings-------
#New color adjustments
pencolor("#141417")
fillcolor ("#141417")
# Function Definition Buildings
def buildings (lenght):
forward (80)
left(90)
forward(lenght + 100)
left(90)
forward(80)
left(90)
forward(lenght + 100)
left (90)
# Function Use Buildings
lenght = 100
penup()
setpos(-650, -100)
pendown()
for counter in range (2):
begin_fill()
buildings (lenght)
forward (90)
lenght = lenght + 40
end_fill()
# Function Definition Skyscrapers
def skyscrapers ():
forward (100)
left (90)
forward(400)
left(90)
forward (100)
left (90)
forward (400)
left (90)
# Function Use Skyscrapers
for counter in range (1):
begin_fill()
forward (10)
skyscrapers ()
end_fill()
# Function Definition of the tallest Skyscrapers
def tall_skyscraper():
forward (100)
left (90)
forward(475)
left(90)
forward (100)
left (90)
forward (475)
left (90)
# Function Use tallest Skyscrapers
for counter in range (1):
begin_fill()
forward (120)
tall_skyscraper()
end_fill()
# Function Definition asimetric building
def asi_building ():
forward (90)
left (90)
forward (200)
left(90)
forward (30)
right(90)
forward(20)
left(90)
forward(30)
left(90)
forward(20)
right(90)
forward(30)
left(90)
forward(200)
left(90)
# Function Use asimetric building
for counter in range (1):
begin_fill()
forward(105)
fillcolor("#10101A")
asi_building()
end_fill()
# Function Definition asimetric building 2
def asi_build2():
forward(100)
left(90)
forward(210)
left(120)
forward(100)
left(60)
forward(160)
left(90)
# Function Use asimetric building 2
for counter in range(1):
begin_fill()
forward(80)
asi_build2()
end_fill()
# Function Definition Street
def street():
right (120)
forward (300)
left(120)
forward (400)
left(120)
forward (300)
left (60)
forward(45)
# Function Use Street
for counter in range (1):
fillcolor("#3D3D4F")
begin_fill()
forward(70)
street()
end_fill()
# Function Definition Line of the street
def line ():
left(100)
forward(300)
right(100)
forward(110)
right(100)
forward(300)
right(80)
# Function Use Line of the street
for counter in range (1):
fillcolor("#FAFCFC")
begin_fill()
line()
end_fill()
#Move the pen
penup ()
forward (50)
pendown ()
# Function use asimetric building
for counter in range (1):
fillcolor ("#141417")
begin_fill()
asi_building()
end_fill()
forward (90)
# Function definition taller asimetric building
def asi_build3 ():
forward (90)
left (90)
forward (320)
left (90)
forward (15)
right (90)
forward (30)
left (90)
forward (15)
right (90)
circle(15,180)
right (90)
forward (15)
left(90)
forward (30)
right(90)
forward(15)
left (90)
forward (320)
# Function use taller asimetric building
fillcolor ("#141417")
begin_fill()
penup()
forward (20)
pendown ()
asi_build3()
end_fill()
# Move the pen
penup ()
left (90)
forward (110)
pendown ()
# Function use skyscraper
fillcolor ("#141417")
begin_fill()
skyscrapers()
end_fill()
penup()
forward (120)
pendown ()
# Function definition taller asimetric building 2
def asi_build4 ():
forward (100)
left (90)
forward (320)
left (45)
forward (25)
right (45)
forward (30)
left (60)
forward(27)
left (60)
forward (27)
left (60)
forward (30)
right (45)
forward (25)
left (45)
forward (320)
left (90)
# Function use taller asimetric building 2
fillcolor ("#141417")
begin_fill()
asi_build4 ()
end_fill()
forward (80)
# Function use asimetric building 2
fillcolor ("#141417")
begin_fill()
asi_build2 ()
end_fill()
forward (90)
# Function use skyscraper
fillcolor ("#141417")
begin_fill()
skyscrapers()
end_fill()
# -------Doing the windows of the buildings----------
#Function Definition windows
def windows(between_win, lenght_win):
fillcolor("#FFFFD4")
left(90)
penup()
forward(9)
pendown()
right(90)
for counter in range(4):
penup()
forward(between_win)
pendown()
begin_fill()
left(90)
forward(10)
left(90)
forward(lenght_win)
left(90)
forward(10)
left(90)
forward(lenght_win)
left(90)
penup()
forward(29)
pendown()
for counter in range(4):
begin_fill()
left(90)
forward(lenght_win)
left(90)
forward(10)
left(90)
forward(lenght_win)
left(90)
forward(10)
left(90)
penup()
forward(between_win)
pendown()
right(90)
end_fill()
right(90)
#Collocating windows
#First building
setpos(-650, -100)
for counter in range (5):
between_win = 18
lenght_win = 10
windows(between_win, lenght_win)
penup()
setpos(-560,-100)
pendown()
#Second building
for counter in range (6):
between_win = 18
lenght_win = 10
windows(between_win, lenght_win)
penup()
setpos(-460,-100)
pendown()
#Third building
for counter in range (10):
between_win = 23
lenght_win = 15
windows(between_win, lenght_win)
penup()
setpos(-340,-100)
pendown()
#Fourth building
for counter in range (12):
between_win = 23
lenght_win = 15
windows(between_win, lenght_win)
penup()
setpos(-235,-100)
pendown()
#Fifth building
for counter in range (5):
between_win = 19
lenght_win= 7
windows(between_win, lenght_win)
penup()
left(90)
forward(10)
right(90)
forward(45)
pendown()
begin_fill()
circle(7)
end_fill()
penup()
setpos(-140,-100)
pendown()
#Sixth building
for counter in range (4):
between_win = 19
lenght_win= 12
windows(between_win, lenght_win)
penup()
backward(3)
left(90)
forward(8)
right(90)
forward(7)
pendown()
begin_fill()
forward(75)
left(90)
forward(40)
left(120)
forward(80)
left(150)
end_fill()
penup()
setpos(28,-100)
pendown()
#Seventh building
for counter in range (5):
between_win = 19
lenght_win= 7
windows(between_win, lenght_win)
penup()
left(90)
forward(10)
right(90)
forward(45)
pendown()
begin_fill()
circle(7)
end_fill()
penup()
setpos(138,-100)
pendown()
#Eighth building
for counter in range (8):
between_win = 21
lenght_win= 15
windows(between_win, lenght_win)
penup()
left(90)
forward(15)
right(90)
forward(20)
pendown()
begin_fill()
forward(50)
left(90)
forward(25)
left(90)
forward(12)
right(90)
circle(13,180)
right(90)
forward(12)
left(90)
forward(28)
left(90)
end_fill()
penup()
setpos(248,-100)
pendown()
#Nineth building
for counter in range (10):
between_win = 23
lenght_win = 15
windows(between_win, lenght_win)
penup()
setpos(382,-100)
pendown()
#tenth building
for counter in range (8):
between_win = 19
lenght_win = 8
windows(between_win, lenght_win)
penup()
left(90)
forward(15)
right(90)
forward(36)
pendown()
begin_fill()
forward(28)
left(90)
forward(38)
left(60)
forward(22)
left(60)
forward(22)
left(60)
forward(38)
left(90)
end_fill()
penup()
setpos(482,-100)
pendown()
#Eleventh Building
for counter in range (4):
between_win = 19
lenght_win= 12
windows(between_win, lenght_win)
penup()
backward(3)
left(90)
forward(8)
right(90)
forward(7)
pendown()
begin_fill()
forward(75)
left(90)
forward(40)
left(120)
forward(80)
left(150)
end_fill()
penup()
setpos(570,-100)
pendown()
#Twelveth building
for counter in range (10):
between_win = 23
lenght_win = 15
windows(between_win, lenght_win)
# -------Final detailas and decoration--------
#Filling sides of the road
for counter in range (1):
fillcolor("#1F1111")
penup()
setpos(-650,-100)
pendown()
begin_fill()
forward(580)
right(120)
pensize(4)
forward(300)
pensize(1)
right(60)
forward(560)
right(90)
forward(260)
left(90)
penup()
setpos(650,-100)
pendown()
forward(620)
left(120)
pensize(4)
forward(300)
pensize(1)
left(60)
forward(560)
left(90)
forward(260)
end_fill()
#Doing a moon
fillcolor ("#FFFF99")
penup()
setpos(-40,300)
pendown()
begin_fill()
left(22)
circle(50,270)
penup()
circle(50,90)
pendown()
end_fill()
fillcolor ("#160D50")
begin_fill()
left(35)
circle(38,200)
pencolor("#160D50")
circle(38,160)
end_fill()
#Doing some stars
penup()
pensize(3)
pencolor("#FFFF99")
setpos(-600,300)
dot("#FFFF99")
setpos(-630,295)
dot("#FFFF99")
setpos(-575,246)
dot("#FFFF99")
setpos(-478,268)
dot("#FFFF99")
setpos(-640,378)
dot("#FFFF99")
setpos(-350,320)
dot("#FFFF99")
setpos(-212,400)
dot("#FFFF99")
setpos(-150,320)
dot("#FFFF99")
setpos(-70,266)
dot("#FFFF99")
setpos(0,320)
dot("#FFFF99")
setpos(25,249)
dot("#FFFF99")
setpos(130,356)
dot("#FFFF99")
setpos(138,338)
dot("#FFFF99")
setpos(220,275)
dot("#FFFF99")
setpos(640,325)
dot("#FFFF99")
setpos(310,340)
dot("#FFFF99")
setpos(359,300)
dot("#FFFF99")
setpos(428,300)
dot("#FFFF99")
setpos(467,234)
dot("#FFFF99")
setpos(519,250)
dot("#FFFF99")
# End Turtle Library
done()
# END
|
c71c4117f2a0a7b9bb9fff082be42009aaa34122 | alex123012/Bioinf_HW | /first_HW/first_hw_5.py | 405 | 4 | 4 | a = int(input('Enter number of iterations '))
if a < 2:
raise ValueError('Number of iterations is too small for this program')
fir = float(input('Enter number '))
sec = float(input('Enter number '))
fir, sec = (sec, fir) if sec > fir else (fir, sec)
for _ in range(a-2):
c = float(input('Enter number '))
fir = c if c > fir else fir
sec = c if c > sec and c < fir else sec
print(sec) |
eeaf26cbd6371adae985d368a581ab58e6a8576c | Oscar-Oliveira/Data-Structures-and-Algorithms | /E_Data_Structures/ds_03_05_graph_03.py | 2,037 | 3.9375 | 4 | """
Bellman-Ford Algorithm
- See: https://www.youtube.com/watch?v=obWXjtg0L64
- See: https://www.programiz.com/dsa/bellman-ford-algorithm
"""
INFINITY = float("inf")
def bellman_ford_shortest_path(graph, start):
previous = {}
distances = {}
for neighbour in graph.keys():
previous[neighbour] = None
distances[neighbour] = INFINITY
distances[start] = 0
for _ in range(len(graph)-1): #Run this until is converges
for current_node in graph.keys():
for neighbour, distance in graph[current_node].items():
if distances[neighbour] > distances[current_node] + distance:
distances[neighbour] = distances[current_node] + distance
previous[neighbour] = current_node
# Check for negative weight cycle
for current_node in graph.keys():
for neighbour, _ in graph[current_node].items():
if distances[neighbour] > (distances[current_node] + graph[current_node][neighbour]):
return None, None
return (distances, previous)
def main():
graph = {
"A": {"B":5, "C":10},
"B": {"D":3},
"C": {"E":1},
"D": {"E":6},
"E": {"B":-7}
}
"""
5 -> B -- 3 -> D
/ < |
A -7 6
\ \ >
10 -> C -- 1 -> E
"""
distances, previous = bellman_ford_shortest_path(graph, "A")
if distances and previous:
data = zip(sorted(distances.items()), sorted(previous.items()))
s = "{:^10} | {:^10} | {:^10}"
print(s.format("vertex", "shortest", "previous"))
print(s.format("", "distance", "vertex"))
print(s.format("-" * 10, "-" * 10, "-" * 10))
for line in data:
(a, b), (_, d) = (e_, _) = line
print(s.format(str(a), str(b), str(d)))
else:
print("Negative weight cycle were found")
if __name__ == "__main__":
main()
print("Done!!")
|
7685a94ddc185210f20c849c67723a5a49aca81a | Duskamo/controlledcar_determinedSim | /src/Maze.py | 732 | 3.625 | 4 |
from graphics import *
class Maze:
def __init__(self,win):
self.win = win
self.initialize()
def initialize(self):
# Set Borders
self.c = Rectangle(Point(50,50), Point(750,550))
self.c.setWidth(5)
# Set Maze
self.l1 = Line(Point(50,200), Point(550,200))
self.l1.setWidth(5)
self.l2 = Line(Point(250,350), Point(750,350))
self.l2.setWidth(5)
self.goalField = Rectangle(Point(550,350), Point(750,550))
self.goalField.setWidth(3)
self.goalField.setFill("red")
self.goalText = Text(Point(650,450),"GOAL")
self.goalText.setSize(35)
def draw(self):
self.c.draw(self.win)
self.l1.draw(self.win)
self.l2.draw(self.win)
self.goalField.draw(self.win)
self.goalText.draw(self.win)
|
9b3c3285b5c7223f64fda59f4076f880a2066139 | ravi089/Algorithms-In-Python | /String/anagram.py | 239 | 4.125 | 4 | # Check if two strings are anagram or not.
def anagram(strg1, strg2):
return ''.join(sorted(strg1)) == ''.join(sorted(strg2))
if __name__ == '__main__':
strg1 = 'stressed'
strg2 = 'desserts'
print (anagram(strg1, strg2))
|
528bf7f28b40ed04b63e709a39d3d65388f6cb1c | davidalejandrolazopampa/Mundial | /19.py | 288 | 3.65625 | 4 | medidas=[]
for x in range(1,6):
medidas.append(int(input("Agregar Lista: ")))
y=(medidas[0]+medidas[1]+medidas[2]+medidas[3]+medidas[4])/5
desviación=[abs(medidas[0]-y),abs(medidas[1]-y),abs(medidas[2]-y),abs(medidas[3]-y),abs(medidas[4]-y)]
print(medidas)
print(desviación)
|
704ee14892f11c8f632c73f3351dbc2b19d87baf | jlshix/nowcoder | /python/20_stack_with_min.py | 835 | 3.875 | 4 | """
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
"""
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
# s1 是普通栈, s2 是最小栈
self.s1 = []
self.s2 = []
def push(self, node):
# write code here
# 此时 s2 压入的是当前值对应的最小值
self.s1.append(node)
if not self.s2 or self.min() > node:
self.s2.append(node)
else:
m = self.min()
self.s2.append(m)
def pop(self):
# write code here
self.s1.pop()
self.s2.pop()
def top(self):
# write code here
return self.s1[-1]
def min(self):
# write code here
return self.s2[-1] |
a6fc982c4ec3547f94609f65f94e732c0d15568e | nameera0408/Practical-introduction-to-python_Brainheinold | /ch3_11sol.py | 191 | 3.703125 | 4 | kg = eval(input("Enter Your Weights in Kg: "))
pound = round(weight_kg * 2.20,1)
print("Your Weight in Pounds is :",pound)
#1/10 means pounds having only one number after the decimal point
|
b86652b54b86e491790790a5915e77899cbc1e7f | greenfox-velox/zsoltfekete | /week-03/day-02/35.py | 160 | 3.859375 | 4 | def factorial(input_number) :
factorta = 1
for i in range(1, input_number+1):
factorta = factorta * i
return factorta
print(factorial(10))
|
0b21bb3e1c9a5c50e1a3455267476d1176fa5266 | gconsidine/project-euler | /012.py | 1,236 | 3.984375 | 4 | #Greg Considine
#Project Euler -- Problem 12
import math
# Returns the number of divisors for any given number (triangular numbers in
# this case).
def getDivisorCount(n):
divCount = 1
i = 2
while i <= math.sqrt(n):
if n % i == 0:
divCount += 1
i += 1
return divCount * 2
# Exhuastively search through positive integers searching for the first
# triangular number to have over 500 divisors.
tNum = 3
divCount = 0
i = 2
while True:
tNum += (i+1)
if tNum % 2 == 0:
divCount = getDivisorCount(tNum)
print("Triangular Number: ", tNum, " Divisor Count: ", divCount)
if divCount > 500:
print(tNum)
break
i += 1
'''
I was stumped on this one for quite a while until I read an interesting tidbit
about the count of divisors of a given number. It's only necessary to count
the divisors less than or equal to the square root of a number. If you double
that, you get the total count of divisors for the number. Very useful
considering we're not interested in WHAT the divisors are, only how many
there are.
Implementing this idea drastically reduced the execution time to
a mere 9.140s compared to the tens of minutes the brute-force method was
taking before I force-quit.
'''
|
bc5fc54c9136c4886779ec12ad3b58563d1d66cd | Activity00/Python | /leetcode/1_linked_list/25. Reverse Nodes in k-Group.py | 1,932 | 3.921875 | 4 | """
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 1, 2, 3, 4, 5
class Solution:
def reverse(self, head: ListNode):
cur = head
pre = None
while cur:
nt = cur.next
cur.next = pre
pre = cur
cur = nt
return pre
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
tmp_head = ListNode(None)
tmp_head.next = head
pre = end = tmp_head
while end.next:
count = k
while count > 0 and end:
end = end.next
count -= 1
if end is None:
break
nt = end.next
end.next = None
start = pre.next
pre.next = self.reverse(start)
start.next = nt
pre = start
end = pre
return tmp_head.next
"""
刚看到题目感觉就是成对反转的加强版,只要在那基础上迭代就可以完成。 而实际上真正去做的时候遇到问题1.想把逆转过程也写进循环去这导致了多个临时变量操作后混乱
2.当决定拆出逆转过程却看到链表一直链接到末尾而没有灵活转化3.总是绝的这个方法好陷入,把可以相对简单内存换时间的使用其他数据结构的思路忽略了。
看到现在这个答案就相对清晰了, 总的三个变量, 然后利用reverse反转链表
""" |
ff72a8e2bba4fc92b1a34317125f48a87b05f741 | hornedwarboy/AlgoToolBoxCoursera | /week3/MaximumSalary(Q7).py | 1,145 | 4.25 | 4 | def isLargestOrEqualto(digit,max_digit):
#This function checks for the best digit or number which makes the largest sequence of number(A/Q).
return int(str(digit) + str(max_digit)) >= int(str(max_digit) + str(digit))
def largestNumber(lst):
#This is the list where our ans is stored is stored as list.
answer = []
while lst != []:
max_digit = 0
#Iterating through each digit.
for digit in lst:
#But the for loop will continue iterating and will give the largest possible number or digit in the given sequence.
if isLargestOrEqualto(digit,max_digit):
max_digit = digit
#When for loop ends the we will get the first digit or number suitable to get the highest number combination.
answer.append(max_digit)
#At the ending of while loop we will remove that digit or number from that list.And continue.
lst.remove(max_digit)
return answer
#Driver Code.
n = int(input())
lst = [int(i) for i in input().split()]
print(''.join([str(i) for i in largestNumber(lst)]))
|
d7e8a6ead48abe0c5f3d23e569afecfb6e09c54e | gordon-sk/PycharmProjects | /PHYS_2237/bikeQuadraticResistanceHill_Chapter2V2.py | 13,511 | 3.828125 | 4 | # Edited by Gordon Kiesling, 1/26/17 for Phys 2237, edits are documented below with comments
# Program 2.3 Solution for the position and velocity of a bicycle traveling along a hill with quadratic air resistance
# (bikeQuadraticResistanceHill_Chapter2V1.py)
#
# Give the command python bikeQuadraticResistanceHill_Chapter2V2.py -h to get help command on input parameters
# This program is based on bikeQuadraticResistanceHill_Chapter2V1.py and allows for motion from 0 initial
# speed at a constant force
#
# This program solves a set of two simultaneous ("coupled") differential equations
# The coupled equations are for the horizontal motion of a bicycle starting above a transition speed vTrans at
# constant power P and experiencing quadratic air resistance
# dx/dt = v and dv/dt = P/mv - C*rho*A*v*v/2m - g*sin(theta)
# 1) P is the constant power of the bicyclist
# 2) C is a scaling constant for the strength of the air resistance force
# 3) rho is the air density
# 4) m is the mass of the bicycle and its rider
# 5) A is the effective area of the bicycle and rider
#
# For speeds less than or equal to the transition speed vTrans, the acceleration equation is for a
# constant force F0
# dx/dt = v and dv/dt = F0/m - C*rho*A*v*v/2m - g*sin(theta)
#
# The constant force F0 is calculated as P/vTrans
#
# The coupled differential equations are solved to obtain v(t) and x(t)
#
# Using input parameters for theta (degrees), v0 (m/s), maximumTime (s), timeStep (s), power (watts),
# cResistance, rho (kg/m^3), mass (kg), area (m^2)
# Defaults are vTrans = 7 m/s, theta = 3.0 deg, v0 = 4 m/s, maximumTime = 400 s, timeStep = 2 s,
# power = 400 watts, cResistance = 1 , rho = 1.2 kg/m^3, mass = 70 kg, area = 0.33 m^2
#
import matplotlib
matplotlib.use('TkAgg') # special code to make plots visible on Macintosh system
import matplotlib.pyplot as plt # get matplotlib plot functions
import sys # used to get the number of command line arguments
import argparse # argument parser library
import numpy as np # numerical functions library used by python
import math as mp # used for the definition of pi
from scipy.integrate import odeint # import only this single method for solving differential equations
#
# Define the input parameter options and assign the default values and the variable types using the argument parser library
#
parser = argparse.ArgumentParser()
parser.add_argument('--vTrans', default=7.0, type=float, help="Transition speed for constant force to constant power,, default is 7 m/s")
parser.add_argument('--theta', default=0.0, type=float, help="Angle of the hill, default is 0.0 deg")
parser.add_argument('--v0', default=0.0, type=float, help="Initial speed with v0 >= 0 in m/s, default is 0 m/s")
parser.add_argument('--maxT', default=200.0, type=float, help="Maximum time range in s, default is 200 s")
parser.add_argument('--deltaT', default=2.0, type=float, help="Iteration time step in s, default is 2 s")
parser.add_argument('--power', default=400.0, type=float, help="Constant power level by rider, default is 400 watts")
parser.add_argument('--cFactor', default=1.0, type=float, help="Quadratic resistance scale factor, default is 1.0")
parser.add_argument('--rho', default=1.2, type=float, help="Air density in kg/m^3, default is 1.2 kg/cubic-meter")
parser.add_argument('--mass', default=70.0, type=float, help="Mass of rider + bicycle in kg, default is 70 kg")
parser.add_argument('--area', default=0.33, type=float,
help="Effective cross sectional area of rider+bicycle in square meters, default is 0.33 square meters")
args = parser.parse_args()
#
# Get the input parameters from the command line
# A FEW NEW LINES BELOW HERE HAVE TO ADDED AND SOME LINES MAY HAVE TO BE CHANGED
# (the number of added or changed lines should be less than 20)
#
numberOfArguments = len(sys.argv)
if (numberOfArguments == 1):
print "\n All the default paramter choices are used" # there is always at least one argument
# and that first one is the name of the python script itself
thetaDegrees = args.theta # the hill angle in degrees, where positive angles mean motion up hill
thetaRadians = thetaDegrees * mp.pi / 180.0
#
# Assign the variables in the program to the variable option names in the argument list
#
v0 = args.v0
if (v0 < 0.0):
print "\n Cannot have the initial speed", v0, " be less than zero"
print "\n Program is exiting\n"
exit(1)
maximumTime = args.maxT
timeStep = args.deltaT
power = args.power
cResistance = args.cFactor
rho = args.rho
mass = args.mass
area = args.area
vTrans = args.vTrans # Added by Student
if vTrans < 0: # Added by student
print("\nCannot have the transition speed " + str(vTrans) + " be less than zero")
print("\n Program is exiting\n")
exit(1)
F0 = power/vTrans # Added by Student
resistanceFactor = cResistance * rho * area / (2 * mass)
gHillAcceleration = 9.81 * mp.sin(thetaRadians)
#
# define the time derivative functions dv/dt = P/mv - C*rho*A*v*v/2m and dx/dt = v
# this function is used only if the RK4 algorithm choice is made
#
def fDerivative(variableList, t): # variableList dummy list array since there is more than one differential equation
v = variableList[0] # speed in the x direction
if v <= vTrans: # Factoring in constant force before constant power
dvdt = F0/mass - resistanceFactor * v * v - gHillAcceleration # Added by Student
else:
dvdt = power / (mass * v) - resistanceFactor * v * v - gHillAcceleration # The usual situation past 7 m/s
# the time derivative of velocity in the x direction according to the power and the air resistance
dxdt = v # the time derivative of postion in the x direction is the velocity
return [dvdt, dxdt] # return the two derivatives as a list object containing two elements
terminalSpeed = 0
resistanceCase = True # put in check if the resistance does not exist because of parameter choices, to prevent a divison by zero
if ((rho <= 0.0 or cResistance <= 0 or area <= 0) and thetaDegrees <= 0):
resistanceCase = False # there is no terminal speed with no resistance
else:
#
# For finding the roots of a polynomial function one can use the roots method from the np library
# For a polynomial of the form c0 + c1*v + c2*v*v + c3v*v*v the syntax is
# coeff = [c3, c2, c1, c0]
# rootList = np.roots(coeff)
# The cubic equation for this problem may have three roots, but only the positivereal solution is physically correct
# The cubic equation is cResistance*rho*area*v*v*v + 2*mass*g*sin(theta)*v - 2*P = 0
# So the coefficients are
# c0 = 2*P
# c1 = 2*mass*g*sin(theta)
# c2 = 0
# c3 = cFactor*rho*area
coeff = [cResistance * rho * area, 0, 2 * mass * gHillAcceleration, -2 * power]
rootList = np.roots(coeff)
#
# Extract the correct root for the terminal speed from this list
#
listLength = len(rootList)
if (listLength > 3):
print "\n Program error, number of cubic equation roots = ", listLength
exit(1)
rootIndex = 0
vTerminalList = []
while rootIndex < listLength:
rootReal = rootList[rootIndex].real
rootImaginary = rootList[rootIndex].imag
if (rootReal >= 0.0 and abs(rootImaginary) < 1.0e-05):
vTerminalList.append(rootReal)
rootIndex += 1
if (len(vTerminalList) != 1):
print "\n Program error, number of candidates for terminal velocity is ", vTerminalList
exit(1)
terminalSpeed = vTerminalList[0]
print "\n Motion along a hill with quadratic air resistance for mass = ", mass, " kg, v0 = ", v0, " m/s"
print " The angle of the hill is ", thetaDegrees, " degrees",
if (thetaDegrees > 0.0):
print ", and the motion is uphill"
hillAngleString = "Hill angle = " + str(thetaDegrees) + " degrees, uphill"
if (thetaDegrees < 0.0):
print ", and the motion is downhill"
hillAngleString = "Hill angle = " + str(thetaDegrees) + " degrees, downhill"
if (thetaDegrees == 0.0):
print ", and the motion is horizontal"
hillAngleString = "Hill angle = " + str(thetaDegrees) + " degrees, horizontal"
print " Power = ", power, " watts, resistance scale factor = ", cResistance
print " air density = ", rho, " kg/cubic-meter, cross sectional area = ", area, " square meters"
print " time step = ", timeStep, " s, maximum time range = ", maximumTime, " s"
if (resistanceCase):
print " Predicted terminal speed ", terminalSpeed, " m/s"
print " The RK4 algorthim from the odeint library will be used"
print " "
nTimeSteps = int(maximumTime / timeStep)
timeGrid = np.linspace(0, maximumTime, nTimeSteps) # time grid used for the iteration steps
labelString = 'Numerical solution, odeint library'
# obtain the differential equation solutions using the odeint method from the ScyPy library
initialValuesSpeedPosition = [v0, 0.0] # starting values of velocity and position for the iteration
twoSolution = odeint(fDerivative, initialValuesSpeedPosition,
timeGrid) # odeint returns a list of values which is the NRK4 solution
vSolution = twoSolution[:, 0] # velocity function of time obtained with RK4 solution
xSolution = twoSolution[:, 1] # position function of time obtained with RK4 solution
nTimeStep = 0
# Do the iteration over time steps from 0 to the maximum time requested
maximumVelocity = -1.0e+12
minimumVelocity = +1.0e+12
maximumPosition = -1.0e+12
minimumPosition = +1.0e+12
while nTimeStep < nTimeSteps: # loop over the time range
velocity = vSolution[nTimeStep]
if (velocity < minimumVelocity):
minimumVelocity = velocity
if (velocity > maximumVelocity):
maximumVelocity = velocity
position = xSolution[nTimeStep]
if (position < minimumPosition):
minimumPosition = position
if (position > maximumPosition):
maximumPosition = position
nTimeStep = nTimeStep + 1 # go to the next time
# The iteration loop has concluded to produce the limits of the plot
# compose string variables about the time parameters for use in putting text on the plot
v0String = 'Initial velocity = ' + str(v0) + ' m/s'
powerString = 'Constant power = ' + str(power) + ' watts'
cResistanceString = 'Quadratic resistance factor = ' + str(cResistance)
massString = 'Total mass = ' + str(mass) + ' kg'
rhoString = 'Air density = ' + str(rho) + ' kg/cubic-meter'
terminalSpeedString = 'Predicted terminal speed = ' + str(terminalSpeed) + ' m/s'
print "\n Final calculated speed = ", vSolution[nTimeSteps - 1], " m/s"
print " Final calculated position = ", xSolution[nTimeSteps - 1], " m"
# code to set up the two plots in a single figure
plt.figure(1) # start a figure
plt.subplot(211) # this sets the upper half plot for the v(t)
plt.plot(timeGrid, vSolution, 'ro', label=labelString) # red dots for the numerical solution plot
xTextPosition = 0.4 * maximumTime
if (resistanceCase):
plt.text(0.3 * maximumTime, 1.05 * terminalSpeed, terminalSpeedString) # text to document the parameters used
plt.text(xTextPosition, 0.82 * terminalSpeed, v0String) # text to document the parameters used
plt.text(xTextPosition, 0.69 * terminalSpeed, powerString) # text to document the parameters used
plt.text(xTextPosition, 0.56 * terminalSpeed, cResistanceString) # text to document the parameters used
plt.text(xTextPosition, 0.43 * terminalSpeed, massString) # text to document the parameters used
plt.text(xTextPosition, 0.30 * terminalSpeed, rhoString) # text to document the parameters used
plt.text(xTextPosition, 0.10 * terminalSpeed, hillAngleString) # text to document the parameters used
else:
xTextPosition = 0.53 * maximumTime
plt.text(xTextPosition, 0.82 * maximumVelocity, v0String) # text to document the parameters used
plt.text(xTextPosition, 0.69 * maximumVelocity, powerString) # text to document the parameters used
plt.text(xTextPosition, 0.56 * maximumVelocity, cResistanceString) # text to document the parameters used
plt.text(xTextPosition, 0.43 * maximumVelocity, massString) # text to document the parameters used
plt.text(xTextPosition, 0.30 * maximumVelocity, rhoString) # text to document the parameters used
plt.text(xTextPosition, 0.10 * maximumVelocity, hillAngleString) # text to document the parameters used
plt.xlabel('Time (s)') # add axis labels
plt.ylabel('Velocity (m/s)')
plt.title('Motion Along A Hill With Quadratic Air Resistance')
plt.grid(True)
plt.ylim(0.0, int(1.6 * maximumVelocity))
plt.legend(loc=2)
plt.subplot(212) # this sets the lower half plot for the x(t)
plt.plot(timeGrid, xSolution, 'bo', label=labelString) # blue dots for the numerical solution plot
plt.grid(True)
plt.ylim(0.0, int(1.2 * maximumPosition))
plt.legend(loc=2)
plt.xlabel('Time (s)') # add axis labels
plt.ylabel('Position (m)')
plt.show() # show the complete figure with the upper and lower subplots
|
6894c08b2da437e9ac627ef08c5249c49877ef41 | yyeunggg/Leetcode-Practice | /DP/646. Maximum Length of Pair Chain.py | 1,901 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 12:09:21 2020
@author: steve
"""
"""
646. Maximum Length of Pair Chain
https://leetcode.com/problems/maximum-length-of-pair-chain/
"""
# Can use DP in this problem
"""
Runtime: 2240 ms, faster than 39.90% of Python3 online submissions for Maximum Length of Pair Chain.
Memory Usage: 14.3 MB, less than 49.78% of Python3 online submissions for Maximum Length of Pair Chain.
"""
class Solution:
def findLongestChain(self, pairs):
pairs = sorted(pairs) #O(nlgn)
indices = {}
global_max = 0
for pair in pairs:
if pair[1] not in indices:
indices[pair[1]] = 1
for end_points in indices:
if end_points < pair[0]:
indices[pair[1]] = max(indices[pair[1]],indices[end_points]+1)
global_max = max(global_max,indices[pair[1]])
return global_max
"""
Much much faster
Runtime: 208 ms, faster than 95.84% of Python3 online submissions for Maximum Length of Pair Chain.
Memory Usage: 14 MB, less than 89.38% of Python3 online submissions for Maximum Length of Pair Chain.
"""
class Solution:
def findLongestChain(self, pairs):
pairs = sorted(pairs,key = lambda x: x[1]) #O(nlgn,sort based on end point, so that long intervals will be thrown to back)
global_max = 0
current_point = [-float('inf'),-float('inf')]
for pair in pairs:
if pair[0] > current_point[1]:
current_point = pair
global_max += 1
return global_max
pairs = [[1,2], [2,3], [3,4]]
pairs = [[1,2], [2,3], [3,4],[4,5],[6,7],[7,8],[7,9],[6,7],[4,7],[1,3]]
sol = Solution()
print(sol.findLongestChain(pairs)) |
07a8db376caba62126c25ada7524c042462d7656 | ggstuart/pyasteroids | /pyasteroids/mass.py | 3,012 | 3.546875 | 4 | from math import pi, cos, sin, sqrt, atan
from random import random, randint, choice
MIN_RADIUS = 20
MAX_DENSITY = 0.05
class Point(object):
def __init__(self, position, arena):
self.arena = arena
self.arena.place(self, *position)
def position(self):
return self.arena.where_is(self)
def difference(self, other):
my_pos = self.position()
your_pos = other.position()
return (my_pos[0] - your_pos[0], my_pos[1] - your_pos[1])
def distance(self, other):
dx, dy = self.difference(other)
return sqrt(dx**2 + dy**2)
def angle(self, other):
dx, dy = self.difference(other)
return atan(dy/dx)
def draw(self, cr, *coefficients):
cr.set_source_rgb(1, 1, 1)
x, y = self.position()
radius = 1
cr.arc(coefficients[0]*x, coefficients[1]*y, radius * min(coefficients), 0, 2 * pi)
cr.fill()
class Mass(Point):
def __init__(self, position, mass, velocity, density, arena):
"""position (x, y) in m, mass in kg, velocity (x, y) in m/tick"""
self.mass = float(mass)
self.velocity = velocity
self.density = density
super(Mass, self).__init__(position, arena)
def radius(self):
return MIN_RADIUS + sqrt((self.mass/self.density)/pi)
def momentum(self):
return [v * self.mass for v in self.velocity]
def apply_force(self, x, y):
"""forces in Newtons"""
self.velocity = [v + f/self.mass for f, v in zip([x, y], self.velocity)]
# @activate(level='move')
def move(self):
self.arena.move(self, *self.velocity)
def energy(self):
return 0.5 * self.mass * (self.velocity[0]**2 + self.velocity[1]**2)
# @activate(level='collision_response')
# def on_collision_response(self):
# """
# If masses collide they pass energy to each other
# depending on the direction of travel
# velocity in the x-direction
# """
# warnings = [item for item, message in self.arena.collision_checker.collisions[self] if message == 'warning']
# if warnings:
# other = choice(warnings)
# force = tuple([v * self.mass * 0.5 for v in self.velocity])#deceleration to zero * mass
# self.apply_force(*tuple(-1*f for f in force))
# other.apply_force(*force)
#
# collisions = [item for item, message in self.arena.collision_checker.collisions[self] if message == 'collision']
# if collisions:
# other = choice(collisions)
# force = tuple([v * self.mass for v in self.velocity])#deceleration to zero * mass
# self.apply_force(*tuple(-1*f for f in force))
# other.apply_force(*force)
def draw(self, cr, *coefficients):
cr.set_source_rgba(1, 1, 1, self.density/MAX_DENSITY)
x, y = self.position()
cr.arc(coefficients[0]*x, coefficients[1]*y, self.radius() * min(coefficients), 0, 2 * pi)
cr.fill()
|
80c54bba5df60fe28d42a19d20f4e43be3704b96 | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/leetcode/P6xx/P657_RobotReturntoOrigin.py | 1,539 | 4.1875 | 4 | """
Tag: string, matrix
There is a robot starting at position (0, 0), the origin, on a 2D plane.
Given a sequence of its moves, judge if this robot ends up at (0, 0)
after it completes its moves.
The move sequence is represented by a string, and the character moves[i]
represents its ith move. Valid moves are R (right), L (left), U (up), and
D (down). If the robot returns to the origin after it finishes all of its
moves, return true. Otherwise, return false.
Note: The way that the robot is "facing" is irrelevant. "R" will always
make the robot move to the right once, "L" will always make it move
left, etc. Also, assume that the magnitude of the robot's movement is
the same for each move.
Example 1: Input: "UD" Output: true
Explanation: The robot moves up once, and then down once.
All moves have the same magnitude, so it ended up at the origin where
it started. Therefore, we return true.
Example 2: Input: "LL" Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the
left of the origin. We return false because it is not at the origin at
the end of its moves.
"""
from typing import List
class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
assert Solution().judgeCircle("UD")
assert not Solution().judgeCircle("LL")
assert Solution().judgeCircle("URULLDLDRR")
print('Tests Passed!!')
|
5553dcfbc8d3bcbe9a0af369aa5202aef6c58e7f | i-Xiaojun/PythonS9 | /Day12/1.装饰器进阶.py | 964 | 3.71875 | 4 | # 装饰器带参数实现
# FLAG = False
# def wrap_flag(FLAG):
# def wrap(func):
# def inner(*args,**kwargs):
# if FLAG:
# print('-----Before------')
# ret = func(*args,**kwargs)
# if FLAG:
# print('======After=======')
# return ret
# return inner
# return wrap
#
# @wrap_flag(FLAG)
# def func():
# print('I`m Func')
#
# func()
# 多个装饰器装饰同一个函数
# def wrap1(func):
# def inner(*args,**kwargs):
# print('1-----Before------1')
# ret = func(*args,**kwargs)
# print('1======After=======1')
# return ret
# return inner
#
# def wrap2(func):
# def inner(*args,**kwargs):
# print('2-----Before------2')
# ret = func(*args,**kwargs)
# print('2======After=======2')
# return ret
# return inner
#
# @wrap1
# @wrap2
# def func():
# print('I`m Func')
#
# func() |
0c1721f1ca9493d92456f47be3b55124606176bc | Grey2k/yandex.praktikum-alghoritms | /tasks/sprint-5/M - Heap Sift Up/sift_up.py | 265 | 3.5 | 4 | def sift_up(heap: list, idx: int) -> int:
if idx == 1:
return idx
parent_idx = idx // 2
if heap[parent_idx] < heap[idx]:
heap[idx], heap[parent_idx] = heap[parent_idx], heap[idx]
idx = sift_up(heap, parent_idx)
return idx
|
5635b2b20ec83bbfc96123cf3e3fa757db80fecf | eulersformula/Lintcode-LeetCode | /Longest_Substring_Without_Repeating_Characters.py | 1,892 | 3.71875 | 4 | # Lintcode 384//Medium//Adobe//Amazon//Yelp//Bloomberg//Yelp
# Leetcode 3//Medium
#Given a string, find the length of the longest substring without repeating characters.
#Example:
#For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
#For "bbbbb" the longest substring is "b", with the length of 1.
#Challenge: O(n) time.
#Use array to record earliest char appearing time. Refresh starting point when a repeating character is found.
#Time complexity: O(n). Space complexity: O(1)
class Solution:
# @param s: a string
# @return: an integer
def lengthOfLongestSubstring(self, s):
if s == None or s == '':
return 0
letters = [-1] * 256
st = 0
maxLen = 0
for (i, c) in enumerate(s):
pos = ord(c)
if letters[pos] >= st: #Mistake 1: repeating condition
ed = letters[pos]
maxLen = max(maxLen, i - st)
st = ed + 1
letters[pos] = i
maxLen = max(maxLen, len(s) - st) #Mistake 2: don't forget to check this final stage
return maxLen
# 第二次方案:T:O(n); S: O(L); L is the length of vocab
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
len_s = len(s)
if len_s <= 1:
return len_s # 易错点1:返回值不符合要求(一开始写成return s)
max_len, chars = 1, {s[0]:0}
for idx in range(1, len_s):
if s[idx] in chars:
if len(chars) > max_len:
max_len = len(chars)
cur_chars = list(chars.keys())
for c in cur_chars:
if chars[c] < chars[s[idx]]:
del chars[c]
chars[s[idx]] = idx
return max(max_len, len(chars)) # 易错点2:没有最后check
|
baf9a7f27bbb8bb66f3565d3b3be2daf9651d090 | dongrerohan421/python3_tutorials | /06_strings.py | 686 | 4.34375 | 4 | '''
This program explains Pytho's string
'''
# Escape character usefule to jump over any character.
# Use double back slash to print back slash in your output.
a = 'I am \\single quoted string. Don\'t'
b = "I am \\double quoted string. Don\"t"
c = """I am \\triple quoted string. Don\'t"""
print (a)
print (b)
print (c)
# To calculate length of string use len() function
print ("Lentgth of the string c is: ")
print (len(c))
d = "Hello "
e = "World"
f = 5
# '+' operator can be used as concatenation operator to join multiple strings.
print (d + e)
# Use '*' operator to print letter multiple times
print (d * 10)
# Use str() to convert integer to string.
print (d + str(f))
|
3d61675b72846e370d755723e8d9af1fd7b549b7 | andrefsp/models-to-production | /rnd/common/model_builder.py | 4,756 | 3.546875 | 4 | """ Code for building models """
import tensorflow as tf
class Model(object):
"""
Base model class
::
All models on Neuron must subclass and implement this methods.
"""
def __init__(self, config):
self.config = config
def get_callbacks(self, session):
""" Returns a list of callbacks. Implementors can use this to send
callbacks into Keras training methods, or for setting up callbacks for
custom training methods (which will need to be manually handled).
The session is provided for implementors to use if necessary.
"""
return []
def _prepare_export_path(self):
for path, _, files in tf.gfile.Walk(self.config.export_path):
for file in files:
rm_path = (
'%s%s' % (path, file)
if path.endswith('/') else '%s/%s' % (path, file)
)
tf.gfile.Remove(rm_path)
try:
tf.gfile.DeleteRecursively(self.config.export_path)
except tf.errors.NotFoundError:
pass
def build(self):
""" Implementors should build the model, e.g. create the tensorflow
graph or the compiled keras Model with this method. """
raise NotImplementedError("Implement build() method")
def train(self, session, *args, train_data_iterator=None,
dev_data_iterator=None, **kwargs):
""" Implementors should train the model with this method.
Parameters
----------
session : tf.Session
The tensorflow session to use.
train_data_iterator : Iterable
Most implementors will provide the training data in the form of
an iterable or iterator here.
dev_data_iterator : Iterable
Implementors should make this optional, and may allow a development
set to be used during training via supplying the iterable here.
"""
raise NotImplementedError("Implement train() method")
def evaluate(self, session, *args, evaluate_data_iterator=None, **kwargs):
""" Implementors should evaluate the model with this method.
Parameters
----------
session : tf.Session
The tensorflow session to use.
evaluate_data_iterator : Iterable
Most implementors will provide the evaluation data in the form of
an iterable or iterator here.
"""
raise NotImplementedError("Implement evaluate() method")
def predict(self, session, *args, predict_data_iterator=None, **kwargs):
""" Implementors should evaluate the model with this method.
Parameters
----------
session : tf.Session
The tensorflow session to use.
predict_data_iterator : Iterable
Most implementors will provide the prediction data in the form of
an iterable or iterator here.
"""
raise NotImplementedError("Implement predict() method")
def save_tf_export(self, session):
""" We use tensorflow serving for our production models, this method
must save the model in the tensorflow serving format for the model to
be usable with tensorflow serving."""
raise NotImplementedError("Implement save_tf_export() method")
def load_tf_export(self, session):
""" This method must be implemented if we wish to restore a model
saved in the tensorflow serving format for use in python. """
raise NotImplementedError("Implement load_tf_export() method")
def save_keras_model(self, session):
""" This method is used to save in the keras .h5 format. If you
train your model with Keras training, or evaluate using Keras methods,
then you'll need to save it in this format to be able to restore the
model and continue training or perform the evaluation. """
raise NotImplementedError("Implement save_keras_model() method")
def load_keras_model(self, session):
""" This method is used to restore a model from the keras .h5 format.
If you train your model with Keras training, or evaluate using Keras
methods, then you'll need to save it in this format to be able to
restore the model and continue training or perform the evaluation. """
raise NotImplementedError("Implement save_keras_model() method")
def save_checkpoint(self, session, checkpoint=None):
saver = tf.train.Saver()
saver.save(session, checkpoint or self.config.checkpoint)
def load_checkpoint(self, session, checkpoint=None):
saver = tf.train.Saver()
saver.restore(session, checkpoint or self.config.checkpoint)
|
6d33ea99fbe4e278828c35a4ba1e74112d3cf430 | kfrankc/code | /python/max_path_tree.py | 1,202 | 4.03125 | 4 | # Given a binary tree, find the maximum path sum.
# The path may start and end at any node in the tree.
# Example :
# Given the below binary tree,
# 1
# / \
# 2 3
#
# Return 6.
import sys
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# DP function
def helper(self, Root, max_arr):
if Root is None:
return 0
left = self.helper(Root.left, max_arr)
right = self.helper(Root.right, max_arr)
current = max(Root.val, max(Root.val + left, Root.val + right))
max_arr[0] = max(max_arr[0], max(current, left + Root.val + right))
return current
# @param Root : root node of tree
# @return an integer
def maxPathSum(self, Root):
max_arr = [-sys.maxint - 1]
self.helper(Root, max_arr)
return max_arr[0]
# TEST
# 4
# / \
# 3 5
# / \
# 1 2
# Return 2 + 3 + 4 + 5 = 14
root = TreeNode(4)
node = TreeNode(3)
root.left = node
root.right = TreeNode(5)
node.left = TreeNode(1)
node.right = TreeNode(2)
s = Solution()
print s.maxPathSum(root)
|
df4b00fbab5c9844961181e0e34ae6424bdc45db | shivampuri20/LPTHW | /exp14.py | 343 | 3.546875 | 4 | class thing(object):
def __init__(self):
self.number =0
def function(self):
print("i got called")
def add_me(self,more):
self.number+=more
return self.number
a=thing()
b=thing()
a.function()
b.function()
print a.add_me(20)
print b.add_me(30)
print a.add_me(40)
print a.number
print b.number
|
d4c5968e7381220b270cb9dbe29d00d71e7c9c01 | abhiwalia15/practice-programs | /set_operations.py | 354 | 3.828125 | 4 | #python program to find perform different set operations .
#display the two sets.
E = {0,1,2,3,4,5,6,7,8,9,10}
N = {2,4,6,8}
#union of sets (U)
print("UNION =",E | N)
#intersection of sets (n)
print("INTERSECTION =",E & N)
#difference of sets (-)
print("DIFFERENCE =",E - N)
#SYMMETRIC DIFFERENCE OF SETS (/_\)
print("SYMMETRIC DIFFERENCE =",E ^ N)
|
89c98799fa77253ef5f66b5ffa7e988db69c23c7 | pixilcode/B7-Python | /hangmanBrendonBown.py | 966 | 3.890625 | 4 | #Excercise 3: Hangman
word = (input('Word >>> ')).lower();
answer = ('_' * len(word));
guesses = set(['']);
chances = int(input('Chances >>> '));
incorrect = 0;
for num in range(50):
print();
while incorrect < chances:
print('Already Guessed: ' + str(guesses));
guess = ((input('Letter >>> '))[0:1]).lower();
guesses.add(guess);
letterNum = 0;
correct = False;
for letter in word:
if guess == letter:
answer = answer[0:letterNum] + guess + answer[letterNum + 1:];
correct = True;
letterNum += 1;
if correct:
print('Good job!');
else:
print('Incorrect');
incorrect += 1;
print(answer);
complete = True;
for letter in answer:
if letter == '_':
complete = False;
break;
if complete:
print('Congratulations! You won!');
break;
print();
else:
print('I\'m sorry. You lost.');
|
e35f1c78bbc87d9616f7df776b23a2367f20bf84 | Leopold0801/numpy-pandas_exercise | /numpy_copy.py | 531 | 3.625 | 4 | import numpy as np
a = np.arange(4)
# array([0, 1, 2, 3])
b = a
c = a
d = b
a[0] = 11
print(a)
# array([11, 1, 2, 3])
d[1:3] = [22, 33] # array([11, 22, 33, 3])
print(a) # array([11, 22, 33, 3])
print(b) # array([11, 22, 33, 3])
print(c) # array([11, 22, 33, 3])
#copy() 的赋值方式没有关联性
b = a.copy() # deep copy
print(b) # array([11, 22, 33, 3])
a[3] = 44
print(a) # array([11, 22, 33, 44])
print(b) # array([11, 22, 33, 3]) |
bc82c5e7522b04054b4340828fa0015584c531d5 | ayamschikov/python_course | /lesson_2/1.py | 630 | 4.0625 | 4 | # 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list = [1, 'test', [], {'key': 'value'}, ('tuple', 'tuple'), 3.0, None, True]
for element in my_list:
print(f"element {element} is type of {type(element)}")
|
ecc3aad5add8aa3e89ed740a4221ce121e126677 | vinlok/vinlok.github.io | /_posts/algorithms/arrays/leetcode/max_profit_buy_sell.py | 177 | 3.5 | 4 |
algo:
1. set low price to = 9999
2. max_profit = 0
3. now iterate on prices:
if price > low:
max_profit= max(price-low,max_profit)
else:
low=prices
|
b2e4bfa81bb861b7ff5d98d8d68b87d83c7adaba | MelloWill36/Python-Curso-em-Video | /75.py | 499 | 4.0625 | 4 | num = (int(input('Digite um numero: ')),
int(input('Digite um numero: ')),
int(input('Digite um numero: ')),
int(input('Digite um numero: ')))
print(f'Voce digitou os valores {num}')
print(f'O valor 9 apareceu na {num.count(9)} vezes')
if 3 in num:
print(f'O valor 3 apareceu na {num.index(3)+1}ª')
else:
print('O valor 3 nao foi digitado em nenhuma posiçao')
print('Os valores pares digitados foram ', end='')
for n in num:
if n % 2 == 0:
print(n,end=' ')
|
011a0023f285b66d9349c38863090b6eb2851603 | nkmk/python-snippets | /notebook/arithmetic_operator_list_tuple_str.py | 1,160 | 3.953125 | 4 | l1 = [1, 2, 3]
l2 = [10, 20, 30]
t1 = (1, 2, 3)
t2 = (10, 20, 30)
s1 = 'abc'
s2 = 'xyz'
print(l1 + l2)
# [1, 2, 3, 10, 20, 30]
print(t1 + t2)
# (1, 2, 3, 10, 20, 30)
print(s1 + s2)
# abcxyz
# print(l1 + 4)
# TypeError: can only concatenate list (not "int") to list
print(l1 + [4])
# [1, 2, 3, 4]
# print(t1 + 4)
# TypeError: can only concatenate tuple (not "int") to tuple
print(t1 + (4,))
# (1, 2, 3, 4)
l1 += l2
print(l1)
# [1, 2, 3, 10, 20, 30]
t1 += t2
print(t1)
# (1, 2, 3, 10, 20, 30)
s1 += s2
print(s1)
# abcxyz
l = [1, 10, 100]
t = (1, 10, 100)
s = 'Abc'
print(l * 3)
# [1, 10, 100, 1, 10, 100, 1, 10, 100]
print(t * 3)
# (1, 10, 100, 1, 10, 100, 1, 10, 100)
print(s * 3)
# AbcAbcAbc
print(3 * l)
# [1, 10, 100, 1, 10, 100, 1, 10, 100]
# print(l * 0.5)
# TypeError: can't multiply sequence by non-int of type 'float'
print(l * -1)
# []
l *= 3
print(l)
# [1, 10, 100, 1, 10, 100, 1, 10, 100]
t *= 3
print(t)
# (1, 10, 100, 1, 10, 100, 1, 10, 100)
s *= 3
print(s)
# AbcAbcAbc
l1 = [1, 2, 3]
l2 = [10, 20, 30]
print(l1 + l2 * 2)
# [1, 2, 3, 10, 20, 30, 10, 20, 30]
print((l1 + l2) * 2)
# [1, 2, 3, 10, 20, 30, 1, 2, 3, 10, 20, 30]
|
039e56614b5e1f48dcedef53dcc536cbee9cef6a | DhanashriMadhav/DSA | /strings/reverse.py | 144 | 4.15625 | 4 | def reverse(str1):
i=-1
while i>=(-len(str1)):
print(str1[i],end="")
i-=1
str1=input("enter the string")
reverse(str1)
|
b8a7172cbe9576221f2ac75f6296cc278c6db95b | borekon/divicaubot | /utils.py | 906 | 3.546875 | 4 | import os
def get_files_by_file_size(dirname, reverse=True):
""" Return list of file paths in directory sorted by file size """
# Get list of files
onlyfiles = [f for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, f))]
# Re-populate list with filename, size tuples
for i in xrange(len(onlyfiles)):
onlyfiles[i] = (os.path.join(dirname,onlyfiles[i]), os.path.getsize(os.path.join(dirname,onlyfiles[i])))
# Sort list by file size
# If reverse=True sort from largest to smallest
# If reverse=False sort from smallest to largest
onlyfiles.sort(key=lambda filename: filename[1], reverse=reverse)
# Re-populate list with just filenames
for i in xrange(len(onlyfiles)):
onlyfiles[i] = onlyfiles[i][0]
return onlyfiles
if __name__ == "__main__":
print 'This is not a standalone script' |
7f5b0e5928ae4060611b6337b397b4322d5a7c01 | 1MT3J45/pyprog | /area.py | 332 | 3.796875 | 4 | class Area:
def __init__(self):
self.r = 0
self.s = 0
def display(self):
a = 3.14 * self.r * self.r
return a
class New(Area):
def __init__(self,r,s):
self.r = r
self.s = s
def show(self):
s = self.display()
print "Circle area: ",s
a = self.s * self.s
return a
n = New(12,15)
print "Square area: ", n.show()
|
9bf95cc73befc55b5a8b8eeef454c7698c99412b | green-fox-academy/FKinga92 | /week-02/day-02/reverse.py | 381 | 3.65625 | 4 | # - Create a variable named `aj`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements in `aj`
# - Print the elements of the reversed `aj`
aj = [3, 4, 5, 6, 7]
for i in range(len(aj)//2 +1):
if i != len(aj)//2:
aj[i] += aj[len(aj)-i -1]
aj[len(aj)-i -1] = aj[i] - aj[len(aj)-i -1]
aj[i] -= aj[len(aj)-i -1]
print(aj)
|
de920a51cd51a4584878e94a4828474f5ea8bf18 | jbenaventeheras/supremebot | /config.py | 631 | 3.65625 | 4 | import datetime
INTRO = """This is a Supreme bot"""
file_obj = open("keys.txt")
print(INTRO)
product_url = input('Copy and Paste Product URL (must contain "https://www."):\n')
if "https://www." not in product_url:
product_url = "https://www." + product_url
current_datetime = datetime.datetime.now()
keys = {}
keys["product_url"] = product_url
for line in file_obj:
line_list = line.split(":")
keys[line_list[0].strip()] = line_list[1].strip()
if line_list[0] == "exp_year":
card_year = int(line_list[1])
card_year -= current_datetime.year
keys[line_list[0].strip()] = card_year + 1
|
2ef5a19ca08c1b199614d87c762414aba597675d | systemchip/python-for-everyone | /c5/cgi-bin/dice.py | 341 | 3.609375 | 4 | #!/usr/bin/env python3
import random
# 헤더를 출력한다
print("Content-Type: text/html")
print("") # 헤더와 몸체를 구별하는 빈 행
# 무작위 수를 얻는다
no = random.randint(1, 6)
# 화면에 출력한다
print("""
<html>
<head><title>Dice</title></head>
<body>
<h1>{num}</h1>
</body>
</html>
""".format(num=no))
|
cc774b543d143f1f17d6a2d88d465a762070b05c | AlvarocJesus/Exercicios_Python | /AulaTeorica/exerciciosModulos/exercicio4/main.py | 591 | 3.546875 | 4 | import verificaSenha
def main():
senha = input('Digite sua senha: ')
if verificaSenha.tamanhoMin(senha):
if verificaSenha.letraMaiuscula(senha):
if verificaSenha.letraMinuscula(senha):
if verificaSenha.umNum(senha):
print('Senha forte!')
else:
print('Senha tem que ter pelo menos 1 numero')
else:
print('Senha tem que ter pelo menos 1 uma letra minúscula')
else:
print('Senha tem que ter pelo menos 1 maiúscula')
else:
print('Senha tem que ter pelo menos 8 caracteres')
if __name__ == '__main__':
main()
|
e2c8f85229419f9abc9e3c77083b0dd152e2cd1f | llgeek/leetcode | /433_MinimumGeneticMutation/solutoin.py | 1,382 | 3.5625 | 4 | from collections import deque
class Solution:
def minMutation(self, start: 'str', end: 'str', bank: 'List[str]') -> 'int':
def buildGraph(bank):
bankset = set(bank)
graph = {}
for node in bankset:
if node not in graph:
graph[node] = set()
for i in range(len(node)):
for c in 'ACGT':
if node[i] != c and node[:i] + c + node[i+1:] in bankset:
graph[node].add(node[:i] + c + node[i+1:])
if node[:i] + c + node[i+1:] not in graph:
graph[node[:i] + c + node[i+1:]] = {node}
else:
graph[node[:i] + c + node[i+1:]].add(node)
del bankset
return graph
graph = buildGraph(bank + [start])
queue = deque()
queue.append((start, 0))
visited = set()
visited.add(start)
while queue:
node, depth = queue.popleft()
if node == end:
return depth
elif node in graph:
for nebnode in graph[node]:
if nebnode not in visited:
visited.add(nebnode)
queue.append((nebnode, depth+1))
return -1
|
920dcc7ec5ecc898379400a8a66f75d21f3840f9 | xwqiang/PyTest | /Test/SetTest.py | 559 | 3.5625 | 4 | '''
@author: xuwuqiang
'''
# import matplotlib.pyplot as plt
# -*- coding: utf-8 -*-
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1)
def PlotDemo1():
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1)
x = []
y = []
f = open('/Users/xuwuqiang/Documents/backyard/datas/teminalSum.csv')
for item in f:
value = item.split('\t')
print value
# x.append(value[0])
# y.append(value[1])
print x
print y
# ax.plot([],[2,3,4,5,6])
# plt.show()
if __name__ == "__main__":
PlotDemo1() |
81a01565bf7be47feb941567b4971eb4736fcfcb | noserider/school_files | /myfirstbasic.py | 169 | 3.8125 | 4 | print ("What is your name?")
firstname = input()
print ("Hello,",firstname)
print ("What is your surname?")
surname = input()
print ("Hello,",firstname,surname)
|
8b1c62c61d616f51a668b8f4410040cb53c5b153 | pgThiago/learning-python | /python-exercises-for-beginners/009.py | 543 | 4 | 4 | # Tabuada em Python
print('==' * 4)
print('\033[34mTABUADA\033[m')
print('==' * 4)
n = int(input("Digite o valor que deseja saber a tabuada: "))
print("{} x {:2} = {}".format(n, 2, n * 2))
print("{} x {:2} = {}".format(n, 3, n * 3))
print("{} x {:2} = {}".format(n, 4, n * 4))
print("{} x {:2} = {}".format(n, 5, n * 5))
print("{} x {:2} = {}".format(n, 6, n * 6))
print("{} x {:2} = {}".format(n, 7, n * 7))
print("{} x {:2} = {}".format(n, 8, n * 8))
print("{} x {:2} = {}".format(n, 9, n * 9))
print("{} x {:2} = {}".format(n, 10, n * 10))
|
85cc423f5e8356863e1e6ee7f534427b04576527 | karthiklingasamy/Python_Sandbox | /B11_T5_Comprehension_Nested_For_Loop.py | 252 | 4.15625 | 4 | # List Comprehension using nested for loop
my_list = []
for letter in 'abcd':
for num in range(4):
my_list.append((letter,num))
print(my_list)
my_list1 = [(letter,num) for letter in 'abcd' for num in range(4)]
print(my_list1)
|
37c29ee436436c8c77313fe89b52ee7fce3bbb80 | Raj-kar/Python | /functions advance/unpacking_dict.py | 709 | 3.96875 | 4 | # 1st example
def greetings(first, second):
print(first + " greets " + second)
# greetings("Raj", "Rahul")
names = {"first": "Raj", "second": "Rahul"}
greetings(**names) # unpack the dict
# 2nd example
def calculate(num1, num2, num3):
print(num1+num2*num3)
calculate(1, 2, 3) # noraml pass values
nums = dict(num1=1,num2=2,num3=3)
calculate(**nums) # unpacking and pass te values
# we can also pass **kwargs or other variables , example :-
def calculate_2(num1, num2, num3,**kwargs):
print(num1+num2*num3)
print(".... print kwargs")
print(kwargs)
# calculate(1, 2, 3) # noraml pass values
nums = dict(num1=1,num2=2,num3=3,name="Raj",id=1,marks=85)
calculate_2(**nums) |
2fa41df6b5b723c18c1c713cfad22a015f9add68 | rodrigopc-bit/treinamento-maratona | /H. Ovni/ovni.py | 218 | 3.625 | 4 | t=int(input())
for i in range(t):
a=input().split(" ")
b=int(a[0])+int(a[1])
if b>int(a[2]):
print("NAO CABE!",end="" if i==t-1 else "\n")
else:
print("CABE!",end="" if i==t-1 else "\n") |
a842726c573bca40852b9aabaf82aaf0e78b3ec0 | skogsbrus/advent_of_code_2018 | /01-part2.py | 957 | 3.828125 | 4 | import argparse
from pathlib import Path
from functools import reduce
from operator import add, sub
"""
You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.
"""
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=Path, default='input/01.txt', help='Path to input')
return parser.parse_args()
def main():
args = get_args()
seen_freqs = {}
freq_sum = 0
seen_freqs[0] = 1
freq_changes = args.input.read_text().strip().split('\n')
while True:
for f in freq_changes:
op = f[0]
change = int(f[1:])
freq_sum = freq_sum + change if op == '+' else freq_sum - change
if freq_sum in seen_freqs:
print(freq_sum)
return
seen_freqs[freq_sum] = 1
if __name__ == "__main__":
main()
|
84720e95fc3d774974684e6ea424c13a79795986 | wcneill/Project-Euler-Solutions | /pe010.py | 898 | 3.921875 | 4 | import pe007 as p7
from timeit import default_timer as timer
def runtime(func, args):
"""
This method will run and return total run time of any function passed
to it.
:param func: The function to time.
:param args: Positional arguments for the function
:return: Runtime in fractional seconds
"""
start = timer()
func(*args)
print(timer() - start)
def sumprime(stop):
"""
This method sums primes below a given range (exclusive)
:param stop: integer value. sumprime will sum all of the prime numbers
below "stop"
:return: sum of all primes less than the parameter "stop"
"""
stop = int(stop)
sum = 0
i = 1
while i < stop:
if p7.is_prime(i):
sum = sum + i
i += 1
else:
i += 1
print(sum)
return sum
if __name__ == '__main__':
runtime(sumprime, [2e6]) |
645f2bcb7ab5792eba761c8903b286b020314217 | ABCmoxun/AA | /AB/linux1/day10/day09_exercise/01_mysum.py | 281 | 3.78125 | 4 | # 1. 写一个函数,mysum,可以传入任意个实参的数字,返回所有实参的和
# def mysum(....):
# ....
# print(mysum(1,2,3,4)) # 10
# print(mysum(5,6,7,8,9)) # 35
def mysum(*args):
return sum(args)
print(mysum(1,2,3,4)) # 10
print(mysum(5,6,7,8,9)) # 35 |
dc378420d3184a1b070a823b713b9f12bd800c48 | confettimimy/Python-for-coding-test | /• 프로그래머스/JadenCase 문자열 만들기.py | 673 | 3.859375 | 4 | # 첫 번째 나의 풀이 -> 정확성 43.8
def solution(s):
ls = s.split()
for i in range(len(ls)):
ls[i] = ls[i][0].upper() + ls[i][1:].lower()
# word[0] = word[0].upper() # 문자열 요소 변경불가라는 사실 잊지말기!!!
#word[0].upper() + word[1:].lower() # word[i]가 아니라 ls[i]로 해야 됨!
#print(word) # word만 바뀌고 ls 원본 자체는 안바뀜
answer = ""
for data in ls:
answer += (data + " ")
return answer.rstrip()
# 두 번째 다른 사람의 풀이 -> 테스트케이스 16만 미통과 상태
def solution(s):
return s.lower().title()
|
b6e96a5ccd19e524d7613b6ffdc408f584e8920d | beauthi/contests | /BattleDev/032020/ex4.py | 1,678 | 3.5 | 4 | from itertools import permutations
def compute_score(sacha_card, my_card):
if sacha_card == "feu":
if my_card == "eau":
return 1
if my_card == "plante":
return -1
if my_card == "glace":
return -1
return 0
if my_card == "feu":
return - compute_score(my_card, sacha_card)
if sacha_card == "eau":
if my_card == "plante":
return 1
if my_card == "sol":
return -1
return 0
if my_card == "eau":
return - compute_score(my_card, sacha_card)
if sacha_card == "plante":
if my_card == "poison":
return -1
if my_card == "sol":
return 1
if my_card == "vol":
return -1
return 0
if my_card == "plante":
return - compute_score(my_card, sacha_card)
if sacha_card == "glace" and my_card == "feu":
return 1
if sacha_card == "vol" and my_card == "plante":
return 1
return 0
n = int(input())
sacha = input().split()
cards = input().split()
perm = permutations(cards)
win = None
for p in perm:
score = 0
sacha_card_idx, card_idx = 0, 0
while sacha_card_idx != len(sacha) and card_idx != len(cards):
cur_score = compute_score(sacha[sacha_card_idx], p[card_idx])
if cur_score == 1:
sacha_card_idx += 1
elif cur_score == -1:
card_idx += 1
else:
sacha_card_idx +=1
card_idx += 1
if sacha_card_idx == len(sacha) and card_idx != len(cards):
win = p
break
if win is None:
print("-1")
else:
print(" ".join(x for x in win))
|
1be24512439e947ee7dd1be15fec482c8fac8ea7 | tannupriyasingh/Coding-Practice | /Tree/maxDeptSolution.py | 559 | 3.625 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class maxDeptSolution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
height = 0
if root:
if root.children == []:
return 1
for childNode in root.children:
height = max(height, self.maxDepth(childNode))
height += 1
return height |
cd6fb80cb9443d7609c90ad2ca9ca65f60c61216 | thamilanban-MM/Python-Programming | /Beginner Level/sum of N natural numb.py | 166 | 3.734375 | 4 | N=raw_input("")
if isinstance(N,str):
if ((N>='a') and (N<='z') or (N>='A') and (N<='Z')):
print("invalid input")
else:
N=int(N)
sum=(N*(N+1))/2
print(sum)
|
e7a002437ec9559a776502bdb847de6aeefc35d1 | seungjaeryanlee/clarity | /tests/test_recursion.py | 3,623 | 3.59375 | 4 | #!/usr/bin/env python3
"""
This file defines unit tests for the recursion module.
"""
from clarity.Board import Board
from clarity.Move import Move
from clarity.MoveType import MoveType
from clarity.recursion import divide, perft, negamax, _negamax_recur
from clarity.Sq import Sq
class TestRecursion:
"""
This class tests the recursion module.
"""
def test_perft(self):
"""
Tests the perft() function of the recursion module.
"""
# Perft results from https://chessprogramming.wikispaces.com/Perft+Results
board = Board()
assert perft(board, 1) == 20
assert perft(board, 2) == 400
board = Board('r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1')
assert perft(board, 1) == 48
assert perft(board, 2) == 2039
board = Board('8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1')
assert perft(board, 1) == 14
assert perft(board, 2) == 191
board = Board('r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1')
assert perft(board, 1) == 6
assert perft(board, 2) == 264
board = Board('rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8')
assert perft(board, 1) == 44
assert perft(board, 2) == 1486
board = Board('r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10')
assert perft(board, 1) == 46
assert perft(board, 2) == 2079
# Perft from https://www.chessprogramming.net/perfect-perft/
board = Board('3k4/3p4/8/K1P4r/8/8/8/8 b - - 0 1')
assert perft(board, 1) == 18
assert perft(board, 2) == 92
assert perft(board, 3) == 1670
assert perft(board, 4) == 10138
board = Board('8/8/4k3/8/2p5/8/B2P2K1/8 w - - 0 1')
assert perft(board, 1) == 13
assert perft(board, 2) == 102
assert perft(board, 3) == 1266
assert perft(board, 4) == 10276
def test_perft_mate(self):
"""
Tests the perft() function of the recursion module where terminal node exists.
"""
board = Board('k7/ppp5/8/8/8/8/8/K6R w - - 0 1')
assert perft(board, 1) == 16
assert perft(board, 2) == 105
assert perft(board, 3) == 1747
assert perft(board, 4) == 11314
def test_negamax(self):
"""
Tests the negamax() function of the recursion module.
"""
# TODO add more tests
# test that the best move negamax() returns gives the best score from _negamax_recur()
board = Board()
best_move = negamax(board, 1)
best_score = _negamax_recur(board, 1)
board.make_move(best_move)
assert board.eval() == -best_score
# test that _negamax_recur() gives the best score
board = Board()
moves = board.move_gen()
best_score = _negamax_recur(board, 1)
for move in moves:
captured_piece, castling, ep_square, half_move_clock = board.make_move(move)
assert best_score >= -board.eval()
board.undo_move(move, captured_piece, castling, ep_square, half_move_clock)
def test_negamax_mate(self):
"""
Tests the negamax() function of the recursion module with mate in X positions.
"""
board = Board('k7/ppp5/8/8/8/8/8/K6R w - - 0 1')
best_move = negamax(board, 1)
assert best_move == Move(Sq.H1, Sq.H8, MoveType.QUIET)
board = Board('q6k/8/8/8/8/8/5PPP/7K b - - 0 1')
best_move = negamax(board, 1)
assert best_move == Move(Sq.A8, Sq.A1, MoveType.QUIET)
|
deb4e33d166bea120edb15beb03e39a1210ac609 | MilapPrajapati70/AkashTechnolabs-Internship | /day 4/task 2 (4).py | 583 | 4.40625 | 4 | # 2.Create a class cal2 that will calculate area of a circle.
# Create setdata() method that should take radius from the user. Create area() method that will calculate area .
# Create display() method that will display area
class cal2:
def setdata(self):
self.r = float(input("enter the radius of circle :"))
print (" the radius of circle is :",self.r)
def area(self):
self.carea= 3.14*self.r*self.r
def display(self):
print("area of circle is:" , self.carea)
myc = cal2()
myc.setdata()
myc.area()
myc.display()
|
dfe35b15056e92993d389a093acd6457b0fb2d0e | ajonaed/Python-DS | /Chapter 1/list_comprehension.py | 501 | 4.0625 | 4 | #Regular List
result = []
for i in range(0,21):
if i % 2 == 0:
result.append(i)
print(result)
# List creation using List Comprehensive syntax
results=[i for i in range(0,21) if i % 2 == 0]
print(results)
'''Both should create a new List, but way of creating a list is different
the comprehensive syntax is more compact
Rules: first define the iterator variable, i
then write the for loop as usual,
at the end, use the condition when i should be added to new List '''
|
256321ce4520d6bdaa4df53a35b55019137f33f6 | alexkie007/offer | /LeetCode/树/617. 合并二叉树.py | 1,383 | 4.125 | 4 | """
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ \
4 5
/ \ \
5 4 7
注意: 合并必须从两个树的根节点开始。
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1 and not t2: return
root = TreeNode((t1.val if t1 else 0 ) + (t2.val if t2 else 0))
root.left = self.mergeTrees(t1.left if t1 is not None else None, t2.left if t2 is not None else None)
root.right = self.mergeTrees(t1.right if t1 is not None else None, t2.right if t2 is not None else None)
return root |
75bfa2e2da70b19778274844f8b2ab8afee1e5ea | hujeff/select_lunch | /V2.1/main.py | 1,695 | 3.84375 | 4 | import select_lunch
import random
def select_food():
lst = select_lunch.selectlunch() #从函数中获得的是一个元祖
lst = [x.strip() for x in lst]
randomchoice = random.choice(lst)
lst.remove(randomchoice)
choice_a = input('我们吃%s可好?(好或不好)'% randomchoice) #请用户判断所选内容是否符合要求
while True:
if choice_a == '好': #如果用户选择好
print('那我们就吃%s啦!\n'% randomchoice)
return randomchoice
else: #如果用户选择不好
if lst: #如果列表不为空
c4 = random.choice(lst) #则重新选择随机内容,如果是午餐选择lunch里的内容,如果是选好餐别则选对应餐别的列表内容
choice_a = input('不想吃的话,吃%s好不好呢?(好或不好)' %c4) #输出上一个被客户否定的内容和重新选择的内容,再次询问是否合适。
lst.remove(c4) #删除已选择的内容,避免重复
randomchoice = c4 #将新选择的内容复制给c3,在下次输出时会输出本次选择并被否定的内容
else: #如果列表为空
reselect = input('已经没有了,要不要重新选一次呢?(输入“要”就重新选择)') #输入是否继续运行
if reselect == '要': #如果要继续运行
lst = select_lunch.selectlunch() #则重新将列表复制给lst
randomchoice(lst) #重新到while开始循环
else:
print('好吧,那你自个想吃的吧')
exit()
select_food() |
d473bd24568222cf40e25b99f0799d5d9625af80 | Vinz974/GomoBot | /gomoku_game/Game_board.py | 6,675 | 3.75 | 4 | import copy
class Board:
def __init__(self):
self.size = 9
self.white = []
self.black = []
self.win = False
self.board = [['.' for x in range(self.size)] for y in range(self.size)]
self.winLog = "Win!"
self.c = 'x'
self._isBlack = True
def _inBoard(self,(x,y)):
return x>=0 and x<self.size and y>=0 and y<self.size
def _isValidMove(self,(x,y)):
return self._inBoard((x,y)) and self.board[x][y]=='.'
def turn(self):
return color(len(self.black)==len(self.white))
def __getitem__(self,num): return self.board[num]
def __len__(self): return 5
def printBoard(self):
for i in range(self.size):
print (10 - i%10 - 1),
print(" ")
for i in range(self.size):
for j in range(self.size):
print(self.board[i][j]),
print (i + 1),
print (" ")
def updateBoard(self,(x,y)):
if(self._isBlack):
self.c = 'x'
else:
self.c = 'o'
if self._isBlack:
if self._isValidMove((x,y)):
self.black.append([x,y])
self.board[x][y] = 'x'
else:
print("Error input, please enter a valid coordinate")
else:
if self._isValidMove((x,y)):
self.white.append([x,y])
self.board[x][y] = 'o'
else:
print("Error input, please enter a valid coordinate")
self.printBoard()
if self.checkWin(x,y):
if self._isBlack:
print("Black")
else:
print("White")
print(self.winLog)
self.win = True
self._isBlack = not self._isBlack
def checkWin(self,x,y):
if (self._checkH(x,y) or self._checkV(x,y) or self._checkL(x,y) or self._checkR(x,y)):
return True
else:
return False
def _checkH(self,x,y):
temp_count = 1
tempx = x
tempy = y
for i in range(4):
tempy += 1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
tempy = y
for i in range(4):
tempy-=1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
if temp_count>4:
return True
else:
return False
def _checkV(self,x,y):
temp_count = 1
tempx = x
tempy = y
for i in range(4):
tempx += 1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
tempx = x
for i in range(4):
tempx-=1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
if temp_count>4:
return True
else:
return False
def _checkL(self,x,y):
temp_count = 1
tempx = x
tempy = y
for i in range(4):
tempx += 1
tempy += 1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
tempx = x
tempy = y
for i in range(4):
tempx-=1
tempy-=1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
if temp_count>4:
return True
else:
return False
def _checkR(self,x,y):
temp_count = 1
tempx = x
tempy = y
for i in range(4):
tempx += 1
tempy -= 1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
tempx = x
tempy = y
for i in range(4):
tempx-=1
tempy+=1
if (self._inBoard((tempx,tempy)) and self.board[tempx][tempy] == self.c):
temp_count +=1
else:
break
if temp_count>4:
return True
else:
return False
def move(self,(y,x)):
"""
(y,x) : (int,int)
return: board object
Takes a coordinate, and returns a board object in which
that move has been executed. If self.win is True (the
board that move() is being executed on has already been
won), then the move/piece-placement is not executed, and
a copy of self is returned instead.
If the coordinate entered is invalid (self._valid_move((y,x))==False)
then the game is over, and win statement is set to explain that
the opposite player wins by default
"""
turn = self.turn()
other = copy.deepcopy(self)
if self.win:
#print("The Game Is Already Over")attack
return other
if not other._isValidMove((y,x)):
turn.swap()
other.winstatement = "Invalid Move ({1},{2}) Played: {0} Wins by Default\n".format(str(turn),y,x)
other.win = True
return other
other.board[y][x] = turn.symbol
other.black.append((y,x)) if turn.isBlack else other.white.append((y,x))
other.checkWin(x,y)
return other
class color:
"""
A simple color class.
Initializes with a bool argument:
Arbitrarily, True->color is black
False->color is white
"""
def __init__(self, isBlack):
if isBlack:
self.isBlack = True
self.color = "BLACK"
self.symbol = "x"
else:
self.isBlack = False
self.color = "WHITE"
self.symbol = "o"
def __eq__(self, other):
return type(self)==type(other) and \
self.color==other.color
def __ne__(self,other): return not (self == other)
def __str__(self): return self.color
def __repr__(self): return str(self)
def swap(self): #swaps a color object from Black->White or reverse
self.__init__(not self.isBlack)
def getNot(self): #returns a color object != self
return color(not self.isBlack) |
56aa3d18111b7b364e7696671f21e08278732667 | ROHANNAIK/datasleuthing | /Ex_Files_UaR_Python/Ex_Files_UaR_Python/Exercise Files/assign/problem1_7.py | 451 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 28 16:02:31 2017
@author: Rohan
"""
#%%
def problem1_7():
b1 = input("Enter the length of one of the bases: ")
b1 = float(int (b1))
b2 = input("Enter the length of the other base: ")
b2 = float(int (b2))
h = input("Enter the height: ")
h = float(int (h))
A = (1/2)*(b1+b2)*h
print("The area of a trapezoid with bases",b1,"and",b2,"and height",h,"is",A)
#%% |
36e25227a020fc944d185657e93e98db8785e6b8 | shahpriyesh/PracticeCode | /DynamicProgramming/FreedomTrail.py | 748 | 3.515625 | 4 | class FreedomTrail:
def freedomTrail(self, ring, key):
steps = 0
size = len(ring) - 1
for ch in key:
left = ring.find(ch)
right = size - ring.rfind(ch)
if left < right:
ring = self.rotate(ring, left)
else:
ring = self.rotate(ring, right)
steps += (min(left, right) + 1)
return steps
def rotate(self, ring, k):
size = len(ring)
res = [0]*size
for i in range(size):
res[(i+k)%size] = ring[i]
return ''.join(res)
object = FreedomTrail()
print(object.freedomTrail("godding", "gd"))
print(object.freedomTrail("godding", "godding"))
print(object.freedomTrail("abcde", "ade")) |
cb96b509015272dd421a3deba84568b2e9561c05 | Badr24/Code-in-Place-Projects | /project.py | 8,699 | 4.34375 | 4 |
""""
This program is a blood group test, the program first will ask to register an account with username and blood type
then it will store it in a dictionary as key and value.
The next the program will store the accounts in csv file in append mode to make sure not to overwrite the file
following the program will show a the result of the blood compatibilities with a donor and recipient types
"""
NAMELENGTH = 14
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 600
CONTROL_TYPES = ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-']
def main():
print("--- Welcome to Blood Types Compatibilities Program --- \n This program shows your blood type Compatibilities" )
accounts = create_account()
store_accounts(accounts)
blood_result(accounts)
def create_account():
"""
input: the user will input username
output: the register_users dictionary will updated
"""
# create empty list
registered_users = {}
# prompt user to enter his account information username and password
register_open = True
while register_open:
# user enter username and check if the blood_types minimum is 2 ch and whithin given range
username = enter_user(NAMELENGTH)
print("\n")
# user enter blood_type and check if the blood_type minimum is 2 ch
blood_type = enter_blood_type()
# check if confirmed_password match password
confirm_blood_type = input("please confirm your blood type: ")
while blood_type != confirm_blood_type :
print(" your confirmed blood type does not match your blood_type")
confirm_blood_type = input("please confirm your blood type: ")
# stores responses in the dictionary
registered_users[username] = blood_type
# ask user if he want to register another account
repeat = input("\n Hit any key to register another name or hit no to proceed: ")
if repeat == "no":
register_open = False
# counts will show how many usres regigsterd
count = count_users(registered_users)
print("\n --- the total registered users are " + str(count) + " ---")
return registered_users
def enter_blood_type():
print("Please enter your blood type \n Blood type should be one of the following blood types :" + "\n" + str(CONTROL_TYPES))
blood_type = input(" Enter Blood type: ")
# check if the blood type within given types
while not in_control (blood_type):
print("your blood type is not valid, it should be one of the following blood types :" + "\n" + str(CONTROL_TYPES))
blood_type = input("please re-enter valid blood type : ")
return blood_type
def enter_user(length):
print("your name should be not more than " + str(NAMELENGTH)+ " characters")
username = input("Enter your name: ")
# check if the username minimum tryies is 6 ch
count = 3
while len(username) > length:
print("your username should " + str(NAMELENGTH)+ " characters ")
username = input("please re-enter valid username: ")
count += 1
if count == 3:
exit()
# todo not repeated username
return username
def count_users(userdict):
count = 0
for key in userdict:
if isinstance(userdict[key], dict):
count += count_keys(userdict[key])
count += 1
return count
def store_accounts(registered_accounts):
#create csv to store accounts and will use append mode to not overwrite the file
with open("output_data.csv","a") as out_file:
for key,value in registered_accounts.items():
out_file.write(str(key) + ',' + str(value))
out_file.write("\n")
def in_control (blood_type1):
# loob in each element in the control list and return true if there is match
for i in range (len(CONTROL_TYPES)):
if blood_type1 == CONTROL_TYPES[i]:
return True
def blood_result(accounts):
for key, value in accounts.items():
# loop over the dictionary to get the result , each type separatley
if value == CONTROL_TYPES[0]: #A+
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type A+ represent about 35.7% of the adult population."
donator = " you can donate to A+ AB+"
recipient = " you can receive from A+ A- O+ O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[1]: #A-
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type A- represent about 6.3% of the adult population."
donator = " you can donate to A+ A- AB+ AB-"
recipient = " you can receive from A- O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[2]: #B+
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type B+ represent about 8.5% of the adult population."
donator = " you can donate to B+ AB+"
recipient = " you can receive from B+ B- O+ O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[3]: #B-
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type B- represent about 1.5% of the adult population."
donator = " you can donate to B+ B- AB+ AB-"
recipient = " you can receive from B- O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[4]: # O+
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type O+ represent about 37.4% of the adult population."
donator = " you can donate to O+ A+ B+ AB+"
recipient = " you can receive from O+ O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[5]: # O-
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type O- represent about 6.6% of the adult population."
donator = " you can donate to Everyone"
recipient = " you can receive from O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[6]: # AB+
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type AB+ represent about 3.4% of the adult population."
donator = " you can donate to AB+"
recipient = " you can receive from Everyone"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if value == CONTROL_TYPES[7]: # AB-
intro = ("hi " + str(key) + ", your blood type is " + str(value) +".")
# According to the Stanford School of Medicine, in the United States:
info = "People with the blood type AB- represent about 0.6% of the adult population."
donator = " you can donate to AB+ AB-"
recipient = " you can receive from AB- A- B- O-"
print(intro)
print(info)
print(donator)
print(recipient)
print("Thank you!")
print("\n")
if __name__ == '__main__':
main() |
71394caacf26f286a465c8b24df40c88cd59710d | ausaki/data_structures_and_algorithms | /two_sum.py | 455 | 3.734375 | 4 | def two_sum(sequence, sum):
sequence = sorted(sequence)
i = 0
j = len(sequence) - 1
while i < j:
tmp = sequence[i] + sequence[j]
if tmp == sum:
yield sequence[i], sequence[j]
i += 1
j += 1
elif tmp < sum:
i += 1
else:
j -= 1
if __name__ == '__main__':
sequence = [1, 2, 3, 4, 5, 5]
for n, m in two_sum(sequence, 5):
print(n, m)
|
fe394fc1640b1193d8344765fb6838f6be4fe2b9 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Cryptography/Transposition Cipher/transposition_cipher.py | 1,350 | 4.03125 | 4 | import math
key = int(input("Enter key: "))
# Encryption
def encryption(msg):
cipher = ""
text_len = float(len(msg))
text_list = list(msg)
col = key
# maximum row of the matrix
row = int(math.ceil(text_len / col))
# the empty cells at the end are filled with '/'
fill_null = int((row * col) - text_len)
text_list.extend("/" * fill_null)
# create Matrix and insert message
matrix = [text_list[i : i + col] for i in range(0, len(text_list), col)]
# print matrix
for i in matrix:
print(i)
# read matrix column-wise
key_index = 0
for i in range(col):
cipher += "".join([row[key_index] for row in matrix])
key_index += 1
return cipher
def decryption(c, key):
col = key
col, row = key, math.ceil(len(c) / key)
no_of_blanks = row * col - len(c)
filled = row - no_of_blanks
chars = list(c)
if no_of_blanks != 0:
for i in range(filled, 1 + key):
chars.insert(row * i - 1, " ")
tmp = [
chars[j + i]
for j in range(row)
for i in range(0, len(chars), row)
if (j + i) < len(chars)
]
return "".join(tmp)
msg = input("Enter message: ")
cipher = encryption(msg)
print("Encrypted Message: {}".format(cipher))
print("Decryped Message: {}".format(decryption(cipher, key)))
|
1f91cfd457f4e4d07702c4a207ebbfc903eee5be | Afra55/algorithm_p | /sort/selection_sort.py | 785 | 3.953125 | 4 | """
选择排序, O(n^2)
"""
from random import shuffle
def findsmallest(arr):
"""
获取列表中最小值的 index
:param arr: 列表
:return: index
"""
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
"""
选择排序
:param arr: 列表
:return: 排序后的列表
"""
new_arr = []
for i in range(len(arr)):
smallest_index = findsmallest(arr)
new_arr.append(arr.pop(smallest_index))
return new_arr
random_data = list(range(100))
shuffle(random_data)
print('无序列表:', random_data)
print('排序后:', selection_sort(random_data))
|
48c0acebab1df40f37c1a0519e6e65f271d6115d | praveena2mca/praveena | /oddeven.py | 169 | 4.25 | 4 | y=int(input("enter the n value")
if(y%2==0):
print("the given number is even")
elif(y%2==1):
print("the given number is odd")
else:
print("the wrong input")
|
1646031137156a19601e5a4dbacff58b68b6c80b | eestec-lc-thessaloniki-it-team/Algorithm-Training | /Meeting_9-11-2019/Harrys-Giannis/heapSort.py | 522 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Simple Implementation of Heap using th heapq library. Heapify will transform the
#list to a heap and then we can use heappop to always get the minimum element
#of the heap. With a simple appending we will get the ordered list. O(n)+O(nlogn)
import heapq
def heapSort(l):
something=l[:]
heapq.heapify(something)
return [heapq.heappop(something) for i in range(len(l))]
l=[6, 1, 6, 8, 3, 5, 99, 5, 11, 16, 76, 34, 64, 24, 75, 98, 62, 47]
sortedList=heapSort(l) |
76f8f292838f492d64f3ff870c37eb8d2d716125 | ledbagholberton/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 155 | 3.609375 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
suma = 0
for i in range(1, 10):
if i in my_list:
suma = suma + i
return(suma)
|
92e0090200e83b0e01d6affc227d30c19118f0c3 | jfxugithub/python | /regular_expression.py | 3,155 | 3.890625 | 4 | """
[] 匹配[]中列举的字符(代表一个字符)
\d 可以匹配一个数字
\D 匹配非数字
\w 可以匹配一个字母,数字,下划线
\W 匹配非字符
\s 可以匹配一个空格(也包括tab等空白符)
\S 匹配非空格
. 可以匹配任意一个字符
* 表示任意多个字符(包括0个)
+ 表示至少一个字符
? 表示0个或一个字符
{n} 表示n个字符
{n,} 表示至少n个字符
{n,m} 表示n-m个字符
\b 匹配字间,用的少,需要网上查
"""
#####example
# \d{3}\s+\d{3,8}
# 从左到右,匹配3个数字,至少一个空白符,3-8个数字
# eg:"101 23456"
import re
"""
[0-9a-zA-Z\_] 表示范围(可以匹配一个数字、字母或者下划线)
A|B 可以匹配A或者B
^ 表示 行开头:^\d -->必须以数字开头
$ 表示结束:\d$ -->必须以数字结尾
"""
####python 的字符串前面加一个r代表字符串中不需要转义字符
s = "ABC\\_001" # 双斜杠被转义成单斜杠
print(s)
s = r"ABC\\_001" # 双斜杠正常输出
print(s)
"""========python 中re模块包含了所有正则表达式的功能============"""
##########################################匹配
# re.match(r"正则表达式",字符串)
# 如果匹配返回一个match对象,否则返回None
print('*' * 30)
s = "123_4567"
print(re.match(r'^\d{3}\_\d{3,8}$', s))
###########################################用于split()切分字符串
s = 'a,b ,c ,d , r'
print(s.split(",")) # 无法识别连续的空格
# 结果:['a', 'b ', 'c ', 'd ', ' r']
s = 'a,b ,c ,d , r'
print(re.split(r"[\s\,]+", s)) # 正则表达式匹配空格和逗号(至少一个)
##############################################用于分组
# 注意用()可以进行分组
s = "010-1234"
matchE = re.match(r"^(\d{3})-(\d+$)", s)
print(matchE.group(0))
print(matchE.group(1))
print(matchE.group(2))
print(matchE.group())
#######检查邮箱
email = 'jinzhengen@qq.com'
pat = '^[0-9a-zA-Z]{4,20}@[0-9a-zA-Z]{2,10}[.][com]{3}$'
result_01 = re.match(pat, email)
if result_01 is not None:
print(result_01.group())
else:
print(None)
############检查手机号
phone_nu = '13802507347'
pat = '^1[3-9]\d{9}$'
result_02 = re.match(pat, phone_nu)
if result_02 is not None:
print(result_02.group())
else:
print(None)
####re模块的高级使用
str = 'life is short, i use python!'
#以' '或者以' ,'或者以', '进行分组
res = re.split(r",?\s+,?",str)
print(res) #['life', 'is', 'short', 'i', 'use', 'python!']
# 查找所有能匹配到的字符/字符串
res = re.findall('\S+o\S+', str)
print(res) #['short', 'python!']
#对正则表达式匹配到的字符进行替换/修改
print('*'*20)
res = re.sub(r'\s+','_',str,2) #参数:正则表达式:要被替换成的字符/字符串:被操作的字符串:匹配个数(不写默认为全部)
print(res) #life_is_short, i use python!
res = re.subn(r'\s+','_',str)
print(res) #('life_is_short, i use python!', 5) 元祖中的5是被替换的次数 |
f2b42f7fdbd15e8c9d5343bbd3ff7aca8a8d4099 | MStevenTowns/Python-1 | /SecretMessage.py | 1,508 | 3.96875 | 4 | # M. Steven Towns
#Assignment 8
#2/4/2014
encoder=True
while encoder:
msg=raw_input('What do you want to encode?: ')
shift=int(raw_input('what do you want to shift it by?: '))%26
secret_msg=""
for i in range(len(msg)):
letter=msg[i]
if letter.isalpha():
if letter.isupper():
if ord(letter)+shift>90:
new_letter=chr(ord(letter)+shift-26)
elif ord(letter)+shift<65:
new_letter=chr(ord(letter)+shift+26)
else:
new_letter=chr(ord(letter)+shift)
secret_msg+=new_letter
else:
if ord(letter)+shift>122:
new_letter=chr(ord(letter)+shift-26)
elif ord(letter)+shift<97:
new_letter=chr(ord(letter)+shift+26)
else:
new_letter=chr(ord(letter)+shift)
secret_msg+=new_letter
else:
secret_msg+=letter
print secret_msg
again=True
while again:
prompt=(raw_input("Do you want to encode another message?: ")).lower()
if prompt=="no":
encoder=False
print "Good luck agent!"
again=False
elif prompt=="yes":
print "Security protocol engaged!\nSecuring network."
again=False
else:
again=True
print "Try that again, I couldn't understand that."
|
8fe61f094c63b3b807aac938d3f4d2a0c0b36075 | capuanob/Cyber-Cell | /user_interface.py | 1,433 | 3.796875 | 4 |
class UI():
def print_menu(self):
print(
"Welcome to Cyber Cell! Would you like to view instructions on how to play? [Y/N]")
if self.validate_input():
self.print_instructions()
def validate_input(self):
response = input("Enter your choice: ")
while response != 'Y' and response != 'N':
print("Incorrect input, please try again.")
response = input("Enter your choice: ")
return True if response == 'Y' else False
def print_instructions(self):
print("""
You play as the warden of your own virtual prison and are tasked with maintaining the security of
your grounds and the safety of those within your walls.
HOW TO PLAY:
At the end of each round, you are granted investment points (IP) which can be used to
\t1) Hire an additional guard
\t2) Install a security camera
\t3) Increase prisoner morale
Your choices have consequences and will impact the moods and motives of your prisoners and guards.
If you perform poorly and allow prisoners to escape, you will LOSE.
In order to WIN, you must achieve >90% prisoner morale or maintain your prison for a month.
TIP:
Listen to the gossip around the prison, it just may help you prevent a prison break!
With that, best of luck warden, your prison awaits!
""")
|
9f633cc6eafdf9b2fad8fffa4787f6cc032522c6 | alexluong/algorithms | /leetcode/non-decreasing-array/Solution.py | 802 | 3.578125 | 4 | class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
isPossible = True
before = None
running = nums[0]
larger = 0
for i in range(len(nums)):
num = nums[i]
if num < running:
larger = larger + 1
if larger == 2:
isPossible = False
break
if i > 1 and before > num:
if i != len(nums) - 1 and running > nums[i + 1]:
isPossible = False
break
if i != 0:
before = running
running = num
return isPossible
print(Solution().checkPossibility([1, 2, 4, 5, 3])) |
f5f475396a9e70f89688d34d3e7b89a80869b787 | silvisig/pep20g06 | /modul6/modul6_1.py | 6,024 | 3.828125 | 4 | # iterators
class ListIterator():
def __init__(self, my_list: list):
self.my_list = my_list
def __next__(self):
if len(self.my_list) == 0:
raise StopIteration
return self.my_list.pop(0)
# o lista e un ob care se modifica , prin pop il modificam ,
# prin lista tin o anumita stare despre ob meu
# next returneaza cat si modifica atributul my_list care e o lista
def __iter__(self):
return self
# # deci se modifica si ob in sine.
# iterator = ListIterator([1, 2, 3])
# for i in interator:
# print(i)
#
# print(iterator.__next__())
# print(iterator.my_list)
# print(iterator.__next__())
# print(iterator.__next__())
# print(iterator.__next__())
#
#
# # obiectul e modificat si ramane nemodificat
#
# class intIterator():
# listed_number = []
#
# def __init__(self, numar: int):
# self.numar = numar
# for i in range(1, self.numar + 1):
# self.listed_number.append(i)
#
# def __iter__(self):
# return self
#
# def __next__(self):
# if len(self.listed_number) == 0:
# raise StopIteration
#
# return self.listed_number.pop(0)
# class IntObject():
# def __init__(self,nr):
# self.nr =nr
# # def __iter__(self):
# # return IntIterar
# int_object = IntObject(3)
#
#
# #lambda functions
#
# # o functie ce se scrie sub o alta forma
# def func1(a,b):
# return a+b
# func1 = lambda a,b: a+b #returneaza ce e dupa :
# # folosesti obiectul functiei pt nu a mai consuma variabile si a nu mai salva in memorie
#
#
# #fctie lambda care primeste 1 arg si returneaza acel arg la putereaa2a
#
# func1= lambda x : pow (x,2)
# print (func1(3))
#
# #map functie+ob iterabil list string
# def process_chr(char:str):
# chr( ord(char)+1)
text = 'my_test to process'
# result= map(process_chr,text)
# print(result)
# print(dir(result)) #ob poate fi itera cu for prin fiecare el din aceasta mapare
# for new_obj in result:
# print(new_obj)
result = map(lambda char: chr(ord(char) + 1), text)
for new_obj in result:
print(new_obj)
# o mapare intre o lista care contine primele 100 de nr si le mapez la nr respective /2
my_list = [x for x in range(100)]
for i in map(lambda k: k / 2, my_list):
print(i)
# filter
list_number = [i for i in range(10)]
result = map(lambda k: k if k % 2 == 0 else None, list_number)
# result e un generator si se consuma odata ce a trecut prin for
for i in result:
print(i)
result = filter(lambda a: a > 5, list(
result)) # filter returrneaza obiectul , mapare intre valoare de adevar a functiei si returneaza sau nu obiectul din lista
for i in result:
print(i)
# filtru pt un set de caractere si fiecare dntre caractere sa verfice daca char >m si daca da sa nu treaca de filtru
text = "".join([chr(i) for i in range(97, 123)])
print(text)
var = filter(lambda a: a > 'm', text)
for i in var:
print(i)
# daca chr +1 >100
text = "".join([chr(i) for i in range(97, 123)])
var = filter(lambda a: ord(a) + 1 > 100, text)
for i in var:
print(i)
# any- atata timp cat unu din ob iterabile e true
# any pt orice ob iterabil ca si un filstru care returneaza True doar daca unu din ob e TRUE
my_list = [1, 'a', True, False, False]
my_lis_F = [0, '', None, True, False, False]
print(any(my_list))
print(any(my_lis_F))
# all
# if all ob are true atunci e true , un ob nu e true,returneaza false
my_list = [1, 'a', True]
my_lis_F = [1, 'a', True, False]
print(all(my_list))
print(all(my_lis_F))
# inheretance-mostenire
class Wolf():
bark = True
def hunt(self):
print('Hunting')
raise NotImplemented # cainele nu tre sa mosteneasca atributul vanatoare
def method_1(self):
pass
class Dog(Wolf): # numele clasei care e mostenita
def method_2(self):
pass
dog = Dog() # apelam clasa dog vin din metoda new si init
print('dog barks:', dog.bark)
dog.method_2()
class Food(object): # animal e o super clasa
def __init__(self, species=None, foodprep=None):
self.species = species
self.foodprep=foodprep
def veggies(self):
print('nimic')
class Spanac(Food):
greenvegies = True
def __init__(self, species):
super().__init__(species)
self.attribute = 'vegies'
def soup(self):
print("supa de spanac")
class Verdeturi(Spanac):
bark = True
def __init__(self, species):
super().__init__(species)
self.attribute = 'wild'
def has_more_green(self):
print('adaugam verdeturi')
class Mealprep:#
def __init__(self):
class Car():
__key = 123510
_engine = 1.8
def __init__(self, color):
self.attribute = color
self.__key = 7894
self._engine = 2
def start(self):
self__engine_code = 12
print('start')
class Dog(Coyote,Car, Wolf, Animal): # stg la dreapta , first parintii next bunici etcpt mostenirept clase care au legatura, pt cele care n au leg ordinea n-are prioritate
def __init__(self, species):
super().__init__(species)
self.attribute = 'domestic'
# def hunt(self):
# print('can t do that')
def method_2(self):
pass
dog = Dog('dog')
print('dog barks: ', dog.bark)
dog.method_2()
dog.method_1()
dog.hunt()
print(dog.attribute)
dog.has_more_teeth() # apelam metoda din clasa coyote bicoz a mostenit atributele
dog.start()
class Suv(Car):
def __init__(self,color, size):
super(Suv,self).__init__(color)
self.size = size
self._Car__key = 12
self._engine = 2
def all_wheel_drive(self):
print('activam 4X4')
suv = Suv("verde",12)
print(suv._Car__key)
print(suv._engine)#accesam variabile private
#atr private in clasa parinte pe self se pot modifica in cls respectiva __si numele var
#in clasa copil , self reprezinta cls copil ,pt modificarea var trebe numele cls parinte
suv.start()
print(suv._Car__engine_code)
suv._Car__engine_code = 20
print(suv._Car__engine_code) |
5878b0991e8f553f609e0a01d6f0c8630f659b7c | liquse14/MIT-python | /python교육/Code05-05.py | 148 | 3.703125 | 4 | a=int(input("정수를 입력하세요:"))
if a %2==0:
print("짝수를 입력했군요.")
else:
print("홀수를 입력했군요.")
|
7a31bd7409c5445ed43f24eeb932cef002338221 | bayajeed/Python | /hello.py | 287 | 3.90625 | 4 | #This is my first practice of PYTHON
print ("hello! this is my new world ")
""" hEA
ALDKJF JASDJFLK
ASDF AJSLFJS D
FASDF JASLDFJ
ADF;AJFLASF
ADSFJAKLDFJ
LJSLKDFJDSFL """
name="Bayaljeed"
print("Name "+name, type(name))
age=20
weight = 50
print("Age",age, type(age), "\nWeight " ,weight)
|
abbc0dedebc1dfb2dbb5880f871073e26a554932 | tobeyOguney/Zoo-of-Algorithms | /Insertion Sort/solution.py | 579 | 4.21875 | 4 | # Implements the insertion sort algorithm
# O(n^2) time | O(1) space
def insertion_sort(lis):
for i in range(1, len(lis)):
current_item = lis.pop()
is_last = True
for j in range(i):
if current_item < lis[j]:
lis.insert(j, current_item)
is_last = False
break
if is_last:
lis.insert(i, current_item)
if __name__ == "__main__":
lis = [8, 5, 2, 9, 5, 6, 3]
insertion_sort(lis)
assert lis == [2, 3, 5, 5, 6, 8, 9], lis
print("You're all set!") |
6904a397edeada6708c584a70b9cb1ee0d645916 | adikmamytov/codify_homework | /adilet_mamytov_tuple.py | 420 | 4.28125 | 4 | # adilet mamytov
# Дан кортеж (1, '2', 3, 4, '5', 6, 7, '8') сформируйте новый без строк с помощью цикла for и проверки на int:
# type(i) == int, где i - новый элемент в цикле
my_tuple = (1, '2', 3, 4, '5', 6, 7, '8')
temp_tuple=[]
for i in my_tuple:
if type(i)==int:
temp_tuple.append(i)
new_tuple=tuple(temp_tuple)
print(new_tuple) |
fee108c1664ba50eef708c18e01723f805936c6d | kabaksh0507/exercise_python_it-1 | /sampleproject/book/BeginningPython3_O_REILLY/chapter6/6-5.py | 292 | 3.796875 | 4 | elm_list = {'name':'Hydrogen', 'symbol':'H', 'number':1}
class Elements():
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
hydrogen = Elements(**elm_list)
print(hydrogen.name, hydrogen.symbol, hydrogen.number) |
b93a9c42e583e01813d5521acff4b1cbc91ead5c | anatshk/SheCodes | /Exercises/lecture_8/lecture_8_ex1.py | 5,795 | 4.3125 | 4 | # Question 6: In sum...
def sum_(n):
"""Computes the sum of all integers between 1 and n, inclusive.
Assume n is positive.
"""
if n == 0:
return 0
return n + sum_(n - 1)
# print(sum_(1)) # 1
# print(sum_(5)) # 15
# Question 7: Misconceptions
def sum_every_other_number(n):
"""Return the sum of every other natural number
up to n, inclusive.
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return n + sum_every_other_number(n - 2)
# print(sum_every_other_number(8)) # 20
# print(sum_every_other_number(9)) # 25
def fibonacci(n):
"""Return the nth fibonacci number.
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# print(fibonacci(11)) # 89
# Question 8: Hailstone
def hailstone(n):
"""Print out the hailstone sequence starting at n, and return the
number of elements in the sequence.
If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. Repeat this process until n is 1.
"""
num_steps = 1
print(n)
if n == 1:
return num_steps
if n % 2:
# n is odd
return num_steps + hailstone(n * 3 + 1)
else:
# n is even
return num_steps + hailstone(n // 2)
# a = hailstone(10)
# print('num of steps: {}'.format(a))
# prints: 10, 5, 16, 8, 4, 2, 1
# a == 7
# Question 12: Insect Combinatorics
def paths(m, n):
"""Return the number of paths from one corner of an
M by N grid to the opposite corner.
"""
if m == 1 or n == 1:
return 1 # when grid is 1D, only 1 path is available
return paths(m - 1, n) + paths(m, n - 1) # m - 1 - insect moved up, next grid has less rows, n - 1 - insect moved right, next grid has less columns
# print(paths(2, 2)) # 2
# print(paths(5, 7)) # 210
# print(paths(117, 1)) # 1
# print(paths(1, 157)) # 1
# MIT exercises
# https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/lectures/MIT6_189IAP11_rec_problems.pdf
def multiplication_1(a, b):
"""
Write a function that takes in two numbers and recursively multiplies them together.
:param a:
:param b:
:return:
"""
if b == 1:
return a
return a + multiplication_1(a, b - 1)
print(multiplication_1(2, 3)) # 6
print(multiplication_1(4, 7)) # 28
print(multiplication_1(8, 1)) # 8
print(multiplication_1(1, 3)) # 3
def base_exp_2(base, exp):
"""
Write a function that takes in a base and an exp and recursively computes base**exp.
You are not allowed to use the ** operator!
:param base:
:param exp:
:return:
"""
if exp == 0:
return 1
return base * base_exp_2(base, exp - 1)
# print(base_exp_2(2, 3)) # 8
def print_3(n):
"""
Write a function using recursion to print numbers from n to 0.
:param n:
:return:
"""
print(n)
if n == 0:
return
print_3(n - 1)
# print_3(5)
def print_4(n):
"""
Write a function using recursion to print numbers from 0 to n (you just need to change one line in the program
of problem 1).
:param n:
:return:
"""
if n == 0:
print(0)
return
print_4(n - 1)
print(n)
# print_4(5)
def str_reverse_5(s):
"""
Write a function using recursion that takes in a string and returns a reversed copy of the string.
The only string operation you are allowed to use is string concatenation.
:param s:
:return:
"""
if s == '':
return ''
return s[-1] + str_reverse_5(s[:-1])
# print(str_reverse_5('abcde'))
def is_prime_6(n):
"""
Write a function using recursion to check if a number n is prime (you have to check whether n is divisible by
any number below n).
(from Wikipedia: https://en.wikipedia.org/wiki/Recursive_definition#Prime_numbers)
The set of prime numbers can be defined as the unique set of positive integers satisfying:
a. 1 is not a prime number
b. any other positive integer is a prime number if and only if it is not divisible by any prime number smaller
than itself.
The primality of the integer 1 is the base case; checking the primality of any larger integer X by this definition
requires knowing the primality of every integer between 1 and X, which is well defined by this definition.
That last point can be proved by induction on X, for which it is essential that the second clause says
"if and only if"; if it had said just "if" the primality of for instance 4 would not be clear, and the
further application of the second clause would be impossible.
:param n: number to divide
:return:
"""
if n == 1:
return False # 1 is not prime
for num in range(2, n):
if is_prime_6(num):
if n % num == 0:
# n is divisible by a smaller prime number - n is not prime
return False
return True # n is not divisible by any smaller primes - n is prime
# print(is_prime_6(2)) # True
# print(is_prime_6(10)) # False
# print(is_prime_6(17)) # True
# print(is_prime_6(25)) # False
def fibonacci_7(n):
"""
Write a recursive function that takes in one argument n and computes Fn, the nth value of the Fibonacci
sequence. Recall that the Fibonacci sequence is defined by the relation Fn = Fn−1 + Fn−2 where F0 = 0 and F1 = 1.
Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
:param n:
:return:
"""
if n == 0:
return 0
if n == 1:
return 1
return fibonacci_7(n - 1) + fibonacci_7(n - 2)
# print(fibonacci_7(2)) # 1
# print(fibonacci_7(5)) # 5
# print(fibonacci_7(9)) # 34
|
f66150d36c94db6ef61e8190d74b28eec042da1f | marciniakmichal1989/PythonTraining | /Mix-master/Nauka/Nauka/Front End/calculator.py | 2,044 | 3.828125 | 4 | from tkinter import *
root = Tk()
root.title("Calculator")
entry_box = Entry(root, width=35, borderwidth=5)
entry_box.grid(row=0, column=0, columnspan=3, padx= 10, pady= 10)
#-------------------------------------------
def button_click(number):
current = entry_box.get()
entry_box.delete(0, END)
entry_box.insert(0, str(current) + str(number))
def button_clear():
entry_box.delete(0,END)
def button_add():
pass
#-------------------------------------------
button7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7))
button7.grid(row=1, column =0)
button8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8))
button8.grid(row=1, column =1)
button9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9))
button9.grid(row=1, column =2)
button4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4))
button4.grid(row=2, column =0)
button5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5))
button5.grid(row=2, column =1)
button6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6))
button6.grid(row=2, column =2)
button1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1))
button1.grid(row=3, column =0)
button2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2))
button2.grid(row=3, column =1)
button3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3))
button3.grid(row=3, column =2)
button0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0))
button0.grid(row=4, column =0)
button_clear = Button(root, text="Clear", padx=79, pady=20, command=button_clear)
button_clear.grid(row=4, column =1, columnspan=2)
button_plus = Button(root, text="+", padx=39, pady=20, command=button_add)
button_plus.grid(row=5, column =0)
button_equal = Button(root, text="=", padx=91, pady=20, command=lambda: button_click())
button_equal.grid(row=5, column =1, columnspan=2)
root.mainloop() |
e0101539e3f43e778a32e67ede5f2fad7e25b322 | RogerioLS/HackerRank | /AvaliacaoParaPythonBasico/provaDoisBasico.py | 1,327 | 3.890625 | 4 | import math
import os
import random
import re
import sys
class Rectangle:
def __init__ (self, width, length):
self.width = width
self.length = length
def area(self):
return 2*(self.length + self.width)
pass
"""length = float(input('enter length:'))
width = float(input('enter width:'))
rectangle = Rectangle(length, width)
print( rectangle.perimeter())
enter length:5
enter width:10
30.0"""
class Circle:
def __init__ (self, radius):
self.radius = radius
def area(self):
return 2*3.14*self.radius
pass
""" radius = float(input("Enter radius of circle"))
my_circle = circle (radius)
print(my_circle.area())
"""
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
queries = []
for _ in range(q):
args = input().split()
shape_name, params = args[0], tuple(map(int, args[1:]))
if shape_name == "rectangle":
a, b = params[0], params[1]
shape = Rectangle(a, b)
elif shape_name == "circle":
r = params[0]
shape = Circle(r)
else:
raise ValueError("invalid shape type")
fptr.write("%.2f\n" % shape.area())
fptr.close()
|
0ef99b13d515c26cf74089688ee5ea81873110ed | nshefeek/work | /snippets/sentence.py | 676 | 3.71875 | 4 | class Sentence:
def __init__(self, line):
self.line = line
self.pos = 0
self.words = self.line.split()
def __iter__(self):
return self
def __next__(self):
if self.pos >= len(self.words):
raise StopIteration
index = self.pos
self.pos += 1
return self.words[index]
mysentence = Sentence('This is my sentence to test')
#for word in mysentence:
# print(word)
print(next(mysentence))
print(next(mysentence))
print(next(mysentence))
print(next(mysentence))
print(next(mysentence))
print(next(mysentence))
print(next(mysentence))
print(next(mysentence))
|
f37c911be55e150fd9a6dc60529cedbd767ae1e2 | aandr26/Learning_Python | /Pluralsight/Core_Python_Getting_Started/4_Introducing_Strings_Collections_and_Iteration/string_literals.py | 184 | 3.6875 | 4 | # Multiline strings
""" This is
a multiline
string"""
''' So
is
this. '''
m = 'This string\nspans multiple\nlines'
print(m)
k = 'A \\ in a string'
print(k)
s = 'parrot'
print(s[0])
|
a6989f43a875c69352bd5b004d9f2cad31a85314 | askdjango/snu-web-2016-09 | /class-20160928/report/박연준_에너지자원공학과/multiplication.py | 294 | 3.796875 | 4 | # 특정 수를 입력받아서, 구구단을 출력하는 프로그램을 작성
number = int(input("구구단 숫자를 입력하시오.\n"))
print("\n{} 구구단\n".format(number))
for i in range(1, 10):
answer = number * i
print("{} x {} = {}".format(number, i, answer))
|
fb51e712cf83f0b2a96c8569f6975b333016b0a8 | RanChenSignIn/Numpy_Pandas_Seaborn | /Numpy/numpy_Netease_could/numpy_index.py | 626 | 3.875 | 4 | import numpy as np
A=np.arange(3,15)#生成3-14的数据
print(A)
print("A[0]",A[0])
print('取第四个元素:',A[3])#取第四个
A=np.arange(3,15,1).reshape(3,4)#重排为3*4矩阵
print(A)
A2=A[2,2]#取A,array中的第2行第2列的元素
print(A[2,2])#同上
print(A2)
print(A[2][2])#取A,array中的第2行第2列的元素
print(A[:2][:2])
A23=A[:,2]#第二列所有的数据
print(A23)
for row in A:#打印每一行
print(row)
for column in A.T:#没有column,通过翻转打印column
print(column)
print(list(A.flat))#把3*4的array转变成一行的列表
# for item in A.flat:
# print(item)
|
7517f4a6a0079717894908445d0840d529cbf9d5 | QuickRecon/CascadeCalculator | /Cylinder.py | 1,218 | 3.71875 | 4 | class Cylinder:
_gasloss = 5 # Fudge factor for gas lost during the transfer due to whips and such
def __init__(self, volume, pressure, label, max_pressure):
self.volume = volume
self.pressure = pressure
self.label = label
self.max_pressure = max_pressure
def transfill(self, cylinder):
pv1 = self.volume * self.pressure
pv2 = cylinder.volume * cylinder.pressure
volume_sum = self.volume + cylinder.volume
new_pressure = ((pv1+pv2)/volume_sum) - self._gasloss
if new_pressure > self.max_pressure:
self.pressure = self.max_pressure
pv3 = self.volume * self.pressure # Now we need to go "backwards" to get the pressure in the bank
cylinder.pressure = ((pv1 + pv2-pv3)/cylinder.volume) - self._gasloss
else:
self.pressure = new_pressure
cylinder.pressure = new_pressure
def print_cylinder(self):
print("Cylinder: " + self.label)
print("Size: " + str(self.volume) + " L")
print("Pressure: " + str(round(self.pressure)) + " bar")
def copy(self):
return Cylinder(self.volume, self.pressure, self.label, self.max_pressure)
|
4586160ecabbfbd3bdb13875f13638a22a50fd1d | Andyporras/portafolio1 | /portafolio1_parte 2.py | 3,792 | 4.34375 | 4 | """
nombre:
pasarAentero
entrada:
num=numero entero mayor que cero
salida:
numero entero
retrincciones:
numero mayor que cero con decimales
"""
def pasarAentero(num):
if(isinstance(num,float) and num>0):
#comprobacion de numero tipo flotante
return pasarAentero_aux(num)
else:
return "El número debe ser positivo"
def pasarAentero_aux(num):
if(isinstance(num,float)):
num=num%10**10*100000
num=int(num)
return pasarAentero_aux(num)
elif(num%10==0):
return pasarAentero_aux(num//10)
else:
return suma_aux(num,0)
def suma_aux(num,indice):
if(num==0):
return 0
else:
suma=num%10*10**indice
return suma+suma_aux(num//10,indice+1)
#--------------------------------------------------------
"""
nombre:
contarDigitosFlotante
entrada:
numero de tipo float
salida:
cantida de digito que tiene el numero
retrincciones:
numero de tipo flotante
"""
def contarDigitosFlotante(num):
if(isinstance(num,float)and num>0):
#comprobacion de numero tipo flotante
num=num%10**10*100000
num=int(num)
if(num%10==0):
return contarDigitosFlotante(num//10)
else:
return contarDigitosFlotante_aux(num)
elif(num<0):
return contarDigitosFlotante(num*-1)
elif(num%10==0):
return contarDigitosFlotante(num//10)
elif(num>0):
return contarDigitosFlotante_aux(num)
else:
return "digite un numero flotante"
def contarDigitosFlotante_aux(num):
if(num==0):
return 0
else:
return 1+contarDigitosFlotante_aux(num//10)
#------------------------------------------------------
"""
nombre:
indice
entrada:
num=numero entero positivo.
indice= numero entero positivo
salida:
numero que esta en la posicion que pidio en el indice
retrincciones:
indice=numero entero positivo mayor o igual que 0
num=numero entero mayor que cero
"""
def indice(num,indice):
if(isinstance(num,int)and num>0 and isinstance(indice,int)and indice>=0):
largo= largo_aux(num)
comparar=num-1
return indice_aux(num,indice+1,largo,comparar)
else:
return "error, digite un numero entero positivo"
def indice_aux(num,indice,largo,comparar):
if(num==0):
return 0
elif(num<comparar)and num>10:
suma=num%10
return suma+indice_aux(num%10//10,indice,largo,comparar)
elif(num<comparar)and num<10:
return num+indice_aux(num//10,indice,largo,comparar)
elif(indice==largo):
return num%10+indice_aux(num%10//10,indice,largo,comparar)
else:
largo=largo-indice
return indice_aux(num//(10**largo),indice,largo,comparar)
def largo_aux(num):
if(num==0):
return 0
else:
return 1+largo_aux(num//10)
#---------------------------------------------------------------
"""
nombre:
sumaIndice
entrada:
numeros entero positivo
salida:
suma de los numero que se pidio en el indice
retrincciones:
num=numero entero mayor que 0
indice=numero entero positivo mayor o igual que cero
indice2=numero entero positivo mayor que cero cero
"""
def sumaIndice(num,indice1,indice2):
if(isinstance(num,int)and isinstance(indice1,int)and isinstance(indice2,int)and indice1>=0 and indice2>=0):
if(num>0):
numeroAsumar=indice(num,indice1)
numeroAsumar2=indice(num,indice2)
suma=numeroAsumar*10+numeroAsumar2
return suma+sumaIndice(num%10//10,numeroAsumar,numeroAsumar)
else:
return 0
else:
return "error,digite un numero entero positivo"
|
3ac07c343d5a2908ab23efda5a4c85c14fde46ef | yabincui/topcoder | /dp/CustomerStatistics.py | 810 | 3.640625 | 4 | class CustomerStatistics:
class Node:
def __init__(self, name):
self.name = name
self.count = 1
def __lt__(self, other):
return self.name < other.name
def reportDuplicates(self, customerNames):
nodes = []
for name in customerNames:
found = False
for node in nodes:
if node.name == name:
node.count += 1
found = True
break
if not found:
nodes.append(self.Node(name))
nodes.sort()
result = []
for node in nodes:
if node.count > 1:
result.append('%s %d' % (node.name, node.count))
print result
return tuple(result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.