blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
889cbcdf068e31c2d220b9795010d509bf1aac39 | momchilantonov/SoftUni-Programming-Basics-With-Python-April-2020 | /While-Loop/While-Loop-Exercise/04_walking.py | 410 | 4.03125 | 4 | steps_count = 0
goal = 10000
while steps_count < goal:
command = input()
if command == 'Going home':
steps_to_home = int(input())
steps_count += steps_to_home
break
else:
walked_steps = int(command)
steps_count += walked_steps
if steps_count >= goal:
print(f'Goal reached! Good job!')
else:
print(f'{goal - steps_count} more steps to reach goal.')
|
ac365e0927468c06f3983268e0d6819f3c5ef2f7 | bpham1525/DevNetTest | /TestFile.py | 578 | 3.640625 | 4 | class TestClassA:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def testfuncA(self):
d = self.a
e = self.b
return d + e
class TestClassB(TestClassA):
def __init__(self):
TestClassA.__init__(self)
self.d = 4
self.c = 5
def testfuncB(self):
return self.d + self.c
def testfuncC(self):
return self.d + self.c
if __name__ == '__main__':
print('Hello World')
ta = TestClassA()
tb = TestClassB()
print(ta.testfuncA())
print(tb.testfuncC())
|
f5d7c06055eda24b80b226570a5e92faeae9d0cd | daniel-reich/ubiquitous-fiesta | /v3iQ4XiW385SrkWKo_5.py | 468 | 3.53125 | 4 |
def check(lst):
for i in range(len(lst)-1):
if lst[i+1] == lst[i]:
return True
return False
def final_result(lst):
while check(lst):
indexes = []
for i in range(len(lst)-1):
char = lst[i]
if char == lst[i+1]:
for y in range(i, len(lst)):
if lst[y] == char:
indexes.append(y)
else:
break
break
for x in sorted(indexes, reverse=True):
del lst[x]
return lst
|
9e37d2c0d861dde0d828778d54f57d67dcad7864 | jbacon/DataMiningPythonPrograms | /ChaosTheoryPrograms/SimpleBifurcationDiagramQuadraticFunction.py | 3,075 | 3.703125 | 4 | #Josh Bacon
#Gisela
#quadc1.py
import math
import turtle
import sys
#The Quadratic Function
def Q(c, x):
return (x * x + c)
#Creates the Axis for the graph
#horizontal c-axis from -1.75 to 0.25
#vertical x-axis from -3 to 3
def drawAxis(pen):
pen.up()
pen.goto(-0.01, -3)
pen.write(-3, False, align="right")
pen.down()
pen.goto(0.01, -3)
pen.goto(0, -3)
pen.goto(0, 3)
pen.goto(-0.01, 3)
pen.write(3, False, align="right")
pen.goto(0.01, 3)
pen.write(" x", False, align="left")
pen.up()
pen.goto(-1.75, 0)
pen.down()
pen.goto(.25, 0)
pen.write("c", False, align="left")
pen.up()
#Marks the c-axis with vertical mark and writes value
def markAxis(pen, c):
pen.up()
pen.goto(c, 0.1)
pen.down()
pen.goto(c, -0.1)
pen.up()
pen.goto(c, -0.2)
pen.write(round(c, 2), False, align="center")
pen.up()
#Calculates and plots on the graph the eventual Orbit of 0
#using a seed of 0
#itereate 100 times to get to the limiting behavior
#plot the next 50 iterates - dot size 3 seems good
def eventualOrbit(pen, c):
orbitNum = 0
for i in range(100):
orbitNum = Q(c, orbitNum)
for i in range(50):
orbitNum = Q(c, orbitNum)
pen.up()
pen.goto(c, orbitNum)
pen.dot()
pen.up()
#Draws the first interval on the graph
#[-0.75, 0.25] : Exactly 10 c values, including -.75 & .25
def drawFirstInterval(pen) :
c = 0.25
pen.color("red")
markAxis(pen, c)
for i in range(0, 10) :
c = 0.25 - i/9 #Is i/9, and not i/10 because interval is inclusive of both endpoints instead of just 1.
eventualOrbit(pen, c)
markAxis(pen, c)
#Draws the second interval on the graph
#[-1.25, -0.75) : Exactly 10 c values, including only -1.25
def drawSecondInterval(pen) :
pen.color("blue")
for i in range(1, 11) :
c = -0.75 - ((i/10) * 0.5)
eventualOrbit(pen, c)
markAxis(pen, c)
#Draw the third interval on the graph
#[-1.4, -1.25) : Exactly 21 c values, including only -1.4. Makes the graph look like a line
def drawThirdInterval(pen) :
pen.color("green")
for i in range (1, 22) :
c = -1.25 - ((i/21) * 0.15)
eventualOrbit(pen, c)
markAxis(pen, c)
#Draws the fourth interval on the graph
#[-1.75, -1.4) : Exactly 6 c values, including only -1.75
def drawFourthInterval(pen) :
pen.color("red")
for i in range (1, 7) :
c = -1.4 - ((i/6) * 0.35)
eventualOrbit(pen, c)
markAxis(pen, c)
def main():
screen = turtle.Screen()
screen.setworldcoordinates(-1.8,-3, .3, 3)
screen.tracer(1000)
pen = turtle.Turtle()
pen.shape("circle")
pen.pensize(3)
pen.hideturtle()
drawAxis(pen)
c = 0.25
pen.color("red")
markAxis(pen, c)
drawFirstInterval(pen)
drawSecondInterval(pen)
drawThirdInterval(pen)
drawFourthInterval(pen)
screen.exitonclick()
main()
|
66b20965db4d1fc9315bd0983d3cb8fed8b06e5b | DidioArbey/MisionTIC2022-Ciclo1-FundamentosDeProgramacion | /clase13/pandas_workshop.py | 3,078 | 3.703125 | 4 | """
* Series: Estructura de una dimensión.
* DataFrame: Estructura de dos dimensiones (tablas).
* Panel: Estructura de tres dimensiones (cubos).
"""
import pandas as pd
import numpy as np
# Series(data=lista, index=indices, dtype=tipo) : Devuelve un objeto de tipo Series
# con los datos de la lista lista, las filas especificados en la lista indices
# y el tipo de datos indicado en tipo.
s = pd.Series(['Matemáticas', 'Historia', 'Economía', 'Programación', 'Inglés'], dtype='string'); print(s, "\n")
s = pd.Series({'Matemáticas': 6.0, 'Economía': 4.5, 'Programación': 8.5}); print(s, "\n")
print(s[1:3], "\n")
print(s['Economía'], "\n")
print(s[['Programación', 'Matemáticas']], "\n")
# Filtrar la serie
print(s > 5, "\n")
print(s[s > 5], "\n")
s = pd.Series([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]); print(s)
print(s.size)
print(s.index)
print(s.count())
print(s.sum())
print(s.cumsum())
print(s.value_counts())
print(s.value_counts(normalize=True))
print(s.min())
print(s.max())
print(s.mean())
print(s.std())
print(s.describe(), "\n")
# Aplicar una función
s = pd.Series(['a', 'b', 'c']); print(s)
print(s.apply(str.upper), "\n")
print(s.apply(lambda x : str(x)+"123"), "\n")
# DataFrame(data=diccionario, index=filas, columns=columnas, dtype=tipos) :
# Devuelve un objeto del tipo DataFrame cuyas columnas son las listas contenidas
# en los valores del diccionario diccionario, los nombres de filas indicados en
# la lista filas, los nombres de columnas indicados en la lista columnas y los
# tipos indicados en la lista tipos.
datos = {
'nombre' : ['María', 'Luis', 'Carmen', 'Antonio'],
'edad' : [18, 22, 20, 21],
'grado' : ['Economía', 'Medicina', 'Arquitectura', 'Economía'],
'correo' : ['maria@gmail.com', 'luis@yahoo.es', 'carmen@gmail.com', 'antonio@gmail.com']
}
df = pd.DataFrame(datos);
print(df, "\n")
df = pd.DataFrame([['María', 18], ['Luis', 22], ['Carmen', 20]], columns=['Nombre', 'Edad']);
print(df, "\n")
df = pd.DataFrame(np.random.randn(4, 3), columns=['a', 'b', 'c']);
print(df, "\n")
df = pd.read_csv('https://raw.githubusercontent.com/asalber/manual-python/master/datos/colesterol.csv')
print(df, "\n")
print(df.describe(), "\n")
print(df.loc[2, 'colesterol'], "\n")
print(df.loc[:3, ('colesterol','peso')], "\n")
print(df['colesterol'], "\n")
# Agregar una nueva serie
df['diabetes'] = pd.Series([False, False, True, False, True])
print(df, "\n")
print(df['altura'].apply(lambda x : x * 100), "\n")
print(df.groupby('sexo').groups, "\n")
print(df.groupby(['sexo','edad']).groups, "\n")
print(df.groupby('sexo').agg(np.mean), "\n")
datos = {
'nombre':['María', 'Luis', 'Carmen'],
'edad':[18, 22, 20],
'Matemáticas':[8.5, 7, 3.5],
'Economía':[8, 6.5, 5],
'Programación':[6.5, 4, 9]}
df = pd.DataFrame(datos)
print(df, "\n")
df1 = df.melt(id_vars=['nombre', 'edad'], var_name='asignatura', value_name='nota')
print(df1, "\n")
print(df1.pivot(index=['nombre', 'edad'], columns='asignatura', values='nota'), "\n")
print(df1.pivot(index='nombre', columns='asignatura', values='nota'), "\n") |
22d8447bb96d97eff0361bf0a2e3c199391538ba | Tiashaadhya005/webdev_django_project | /graph_code.py | 2,599 | 3.796875 | 4 | class Graph:
def __init__(self):
self.vertices=31
self.graph=[[],
[2,9,14,21,28],[3],[20],[5],[6],[18],[8],[],
[10,22],[11,24],[12],[13,30],[],
[15],[20],[17],[18],[7,30],[],
[16,4],[9],[23],[10],[25],[26,29],[27],[],
[24],[12],[19,31],[]]
def isNotVisited(self,x, path):
size = len(path)
for i in range(size):
if (path[i] == x):return 0
return 1
def findpaths(self,src, dst, allpath):
q = []
path = []
path.append(src)
q.append(path.copy())
#print(q)
while (q):
path = q.pop(0)
#print(path)
last = path[len(path) - 1]
if (last == dst):allpath.append(path)
for i in range(len(self.graph[last])):
if (self.isNotVisited(self.graph[last][i], path)):
newpath = path.copy()
newpath.append(self.graph[last][i])
q.append(newpath)
return allpath
# if __name__ == "__main__":
# src = 2
# dst = 4
# g=Graph()
# #g.add_edge()
# allpath=g.findpaths(src, dst, [])
# print("answer: ",allpath)
'''
def add_edge(self):
self.graph[1].append([2,9,14,21,28])
self.graph[2].append([3])
self.graph[3].append([20])
self.graph[4].append([5])
self.graph[5].append([6])
self.graph[6].append([18])
self.graph[7].append([8])
self.graph[8].append([]) #last stoppage of the route
self.graph[9].append([10,22])
self.graph[10].append([11,24])
self.graph[11].append([12])
self.graph[12].append([13,30])
self.graph[13].append([]) #last stoppage of the route
self.graph[14].append([15])
self.graph[15].append([20])
self.graph[16].append([17])
self.graph[17].append([18])
self.graph[18].append([7,30])
self.graph[19].append([])#last stoppage of the root
self.graph[20].append([16,4])
self.graph[21].append([9])
self.graph[22].append([23])
self.graph[23].append([10])
self.graph[24].append([25])
self.graph[25].append([26,29])
self.graph[26].append([27])
self.graph[27].append([])#last stoppage of the root
self.graph[28].append([24])
self.graph[29].append([12])
self.graph[30].append([19,31])
self.graph[31].append([])#last stoppage of the root
print(self.graph)
''' |
5f7db8a4f2e54c5e44fc188e352783581774058e | fyp858585/codewars | /codewars_code/codewars67.IntegersRecreation One.5kyu.py | 380 | 3.5625 | 4 | def list_squared(m,n):
answer = []
for i in range(m,n+1):
li = []
for j in range(1,i+1):
if i % j ==0:
li.append(i**2)
a = sum(li) **0.5
if int(a) == a:
answer.append([int(a),sum(li)])
return answer
if __name__ == '__main__':
r= list_squared(1,250)
print(r)
|
7d615b32a108244092a02d71a7d7eee02b50648d | anupjungkarki/IWAcademy-Assignment | /Assignment 1/Function/answer16.py | 276 | 4.3125 | 4 | # Write a Python program to square and cube every number in a given list of integers using Lambda.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums)
for_square = list(map(lambda x: x ** 2, nums))
print(for_square)
for_cube = list(map(lambda x: x ** 3, nums))
print(for_cube)
|
29ecd5c97783209197ce8acd8fadd5e26301f0e1 | MattHeffNT/axi-draw-lols | /agents.py | 5,596 | 4.28125 | 4 | """
Write your code to play tic-tac-toe in this file.
Have a look over the example agent `make_first_avaliable_move` before implimenting
your own agent.
"""
# Import the function engine from engine.py
# If you get an error saying you can't find engine, check that engine.py (from the same wattle
# folder as this file) is in the same folder on your computer
from engine import engine
# Example agent
def make_first_avaliable_move(board):
"""
An agent that only plays in the first available position
Input: A tic tac toe board in its string representation nine characters (either "X"s, "O"s or "."s)
Output: A string representation of the input board with our move made on it
A valid strategy (if not a very good one) is to place your piece in the first
open place on the tic tac toe board. An agent that does this isn't going to win
every game but it is able to play a move onto every possible board so its a good start
to see how the system operates with a valid agent
"""
# Work out which pieces we are playing
"""
Summary of thinking:
- Starting with the premise that "X" always play first we can infer two things
-> if the number of X's and O's are equal X should play next
-> if the number of empty squares ('.') is odd (empty board = 9, one move each = 7, ....)
then X should be playing
- Using the first inference we will make the comparison and return one of two things based on the result
-> Structure of the code: an if statement with different return calls within each condition
"""
# Work out which pieces we are playing
# Compare the number of "X"s and "O"s
if board.count("X") == board.count("O"):
# If equal number of X's and O's then we are playing "X"s (if statement)
our_pieces = "X"
# If not then we must be playing "O"s (else)
else:
our_pieces = "O"
# Seize the top centre (position number 1)
# check that its an available move (if statement)
# generate the board with our move on it
# return the board (on the spot return call)
"""this turned out to be a terrible strategy and wasn't implemented. The only way to win, was not to play (position 1)!"""
# Replace the first "." with our pieces
"""
Conveniently there is a bound method for string objects called "replace"
looking at the documentation it can take three arguments: a string of the character(s) to
be replaced, what to replace those character(s) with and (optionally) how many times to do so.
Calling this bound method on `board` which returns us a new string with our requested changes that
we will call `first_open_move`
"""
move = board.replace('.',our_pieces,1)
# Give out move back to the engine
return move
def stringify (str):
""" function modified from https://www.geeksforgeeks.org/python-program-to-convert-a-list-to-string/ .... converts array to string """
# initialize an empty string
str1 = ""
# traverse in the string
for ele in str:
str1 += ele
# return string which we will then pass to engine
return str1
def your_agent(board):
"""
The engine will pass this function the current game-board;
after adding your prefered move to the board, return it back to the engine.
SHALL WE PLAY A GAME!
"""
# convert board to list (need better name for array)
# If equal number of X's and O's then we are playing "X"s (if statement)
if board.count("X") == board.count("O"):
our_pieces = "X"
# if we move first
else:
our_pieces = "O"
""" take middle piece then corner 2 and 6"""
# 0 1 2
# 3 4 5
# 6 7 8
wins = []
for a, b, c in (
(0, 1, 2), # top row Here's the board:
(3, 4, 5), # middle row 0 1 2
(6, 7, 8), # bottom row 3 4 5
(0, 3, 6), # left column 6 7 8
(1, 4, 7), # middle column
(2, 5, 8), # right column
(0, 4, 8), # top-left to bottom-right diagonal
(2, 4, 6), # top-right to bottom-left diagonal
):
# send array to be converted back to string then replace board with updated values
list = []
for i in (board):
list.append(i)
moves_a = a
moves_b = b
moves_c = c
print (f"this is a: {a}, this is b: {b}, this is c: {c}")
if list[a] == '.':
print (a)
list[a] = our_pieces
print (list)
move = board.replace(board,stringify(list))
return move
elif list[a] != '.' and list[b] == '.':
list[b] = our_pieces
# print (list)
# print (f"this is the move: {move}")
# print (f"this is the board: {board}")
"""
All the functions above (our agent(s) and any helper functions) are just sitting there waiting
to be called and put to use. The actual calling of the function is done by the engine code
which takes in an agent function and plays out all the possible games with that agent
We imported the engine function from engine.py at the top of the file, to run an agent
we call engine and pass in the agent
When you're ready with `your_agent` you can replace the agent function that is being called
"""
#When you're ready swap over which line is being commented out
# engine(make_first_avaliable_move)
engine(your_agent) |
53e2d20fa771204e44bba0e403dbb732f61b8bdb | nmasharani/ProjectEuler | /Python/euler4.py | 603 | 4.21875 | 4 | # A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
from sys import exit
def reverseNum(num):
strng = (str(num))[::-1]
#print strng
return int(strng)
left, right = 999, 999
numbers = []
while left > 99:
while right > 99:
product = left * right
reverse = reverseNum(product)
if product == reverse:
numbers.append(product)
right -= 1
left -= 1
right = 999
numbers.sort()
index = len(numbers) - 1
print numbers[index]
|
36b74ec36c2edfd32a9106df77c6faec3822e9f1 | AnTznimalz/python_prepro | /Prepro2019/Pizza_number.py | 341 | 3.65625 | 4 | box = set()
def cal(num,wow):
if wow+6 <= num:
box.add(wow+6)
cal(num, wow+6)
if wow+9<=num:
box.add(wow+9)
cal(num, wow+9)
if wow+20<=num:
box.add(wow+20)
cal(num, wow+20)
num = int(input())
if num<6:
print("no")
else:
cal(num,0)
for i in sorted(box):
print(i) |
af03e1c63da6c5b5eec4c98fa19cb6020a359b1c | reyllama/leetcode | /Python/C47.py | 996 | 3.84375 | 4 | """
47. Permutations II
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
"""
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# idea from @vubui
res = []
def _permute(num, cur, lim):
if len(cur)==lim:
res.append(cur[:]) # Save a copy of cur
return
for i in range(len(num)):
if i>0 and num[i]==num[i-1]:
continue
cur.append(num[i])
_permute(num[:i]+num[i+1:], cur, lim)
cur.pop()
_permute(sorted(nums), [], len(nums))
return res
"""
Runtime: 44 ms, faster than 88.32% of Python online submissions for Permutations II.
Memory Usage: 13.6 MB, less than 68.17% of Python online submissions for Permutations II.
""" |
829c71d0cc847fda4f1d8d074fbb2ae639de3ba9 | amirjodeiri/Assignment | /list_organize.py | 442 | 4.3125 | 4 | cars = ["bmw", "benz", "audi", "kia", "toyota"]
print(cars)
# sort the list alphabetically permanently
cars.sort()
print(cars)
# sort the list in reverse alphabetical order permanently
cars.sort(reverse=True)
print(cars)
# sort the list in alphabetical order temporarily
print(sorted(cars))
# finding the length of the list (the number of items in the list)
cars = ["bmw", "benz", "audi", "kia", "toyota"]
print(len(cars))
print(cars[-2])
|
14e29f2eacd637a3e663a6d25146957f879715a6 | arpiagar/HackerEarth | /search-insert-position/solution.py | 622 | 3.78125 | 4 | #https://leetcode.com/problems/search-insert-position/solution/
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums)-1
return self.find_in_array(nums, target, start, end)
def find_in_array(self, nums, target, start, end):
mid = int((start+end)/2)
if start > end:
return start
if nums[mid] == target:
return mid
if target > nums[mid]:
return self.find_in_array(nums, target, mid+1, end)
else:
return self.find_in_array(nums , target, start, mid-1)
|
e79ea12fb4c3962ec99b808d7435d39df7092255 | markvilar/pyVO | /utilities.py | 2,139 | 3.515625 | 4 | import numpy as np
import cv2
import csv
from typing import Tuple, List
def visualize_harris_corners(img: np.ndarray, points_and_response: List[Tuple[float, np.ndarray]], radius=4, thickness=2):
"""
Visualizes the rgb image and the Harris corners that are detected in it.
:param img: The image.
:param points_and_response: The response and image coordinates of the Harris corners.
:param radius: The radius of the circles drawn around the Harris corners.
:param thickness: The thickness of the circles drawn around the Harris corners.
"""
img_copy = img.copy()
for response, point in points_and_response:
cv2.circle(img_copy, tuple(point), radius, (255,255,255), thickness)
cv2.imshow("Harris Corners", img_copy)
def visualize_lucas_kanade(target_img: np.ndarray, warped_img: np.ndarray, error_img: np.ndarray, size=(215, 215)):
"""
Visualizes the target image, warped image and error image in the Lucas-Kanade method.
:param target_img: The target image.
:param warped_img: The warped image.
:param error_img: The error image.
:param size: The size of the images after resizing.
"""
target_img = cv2.resize(src=target_img, dsize=size)
warped_img = cv2.resize(src=warped_img, dsize=size)
error_img = cv2.resize(src=error_img*error_img, dsize=size)
img_stack = np.concatenate((target_img, warped_img, error_img), axis=1)
cv2.imshow("LK", img_stack)
cv2.waitKey(250)
def read_convergence_log(file_name):
"""
Loads a .csv file containing the number of steps used for successful
convergence of the LK method.
:param file_name: The file name.
"""
with open(file_name, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
cumulative_convergence_steps = 0
n_readings = 0
for row in csv_reader:
n_readings += 1
cumulative_convergence_steps += int(row['n_convergence_steps'])
print("Convergence log for {} ...".format(file_name))
print("Average amount of convergence steps: {}".format(cumulative_convergence_steps/n_readings))
|
327b89d08007d5e18a70b5aae321b16cdc4ec9f7 | logyball/advent_of_code_2020 | /day_2/solver.py | 562 | 3.546875 | 4 | file_input = open("input.txt", "r")
txt = file_input.read().splitlines()
# tup def (low bound, high bound, letter, password)
def check_password(t: tuple):
cnt = 0
for ltr in t[3]:
if ltr == t[2]:
cnt += 1
if t[0] <= cnt <= t[1]:
return True
return False
cnt = 0
for line in txt:
split_ln = line.split()
low, high = split_ln[0].split('-')
letter = split_ln[1].strip(':')
password = split_ln[2]
t = (int(low), int(high), letter, password)
if check_password(t):
cnt += 1
print(cnt)
|
e1e90abc92102acdc98286e3295f6b19cef12b02 | rubiodamian/syperCrawler | /sypercrawler/lib/linkcheck.py | 651 | 3.875 | 4 | from urllib2 import urlopen, HTTPError, URLError
'''Checks if an url is broken or not and returns the request status code
"response" can be a status code (404,500,200) or,
if the request have a redirection (like 301 or 302),
the url of that redirection'''
def check_url(url):
try:
response = urlopen(url=url, timeout=10)
if(response.geturl() != url):
return response.geturl()
else:
return response.getcode()
except HTTPError as e:
return e.getcode()
except URLError as e:
print('Exception', e, type(e))
except Exception as e:
print('Exception', e, type(e))
|
302f6f870a66c38801a9cdc9cf0073dcd3994ad7 | rajeshpandey2053/python_assignment | /function/F18.py | 93 | 3.703125 | 4 | string = input("Enter the string: ")
func = lambda str: str.isnumeric()
print(func(string)) |
9a941aad797390db70bd6f31f942e9f0ad3ee0f2 | michaelarg/kaggle | /nucleus /python_scripts/u-net_tf.py | 9,292 | 3.71875 | 4 | import os,sys
import numpy as np
import tensorflow as tf
#import weakref
from tflearn.layers.conv import conv_2d, max_pool_2d
#def u_net():
#def variables)
X = tf.placeholder(tf.float32, shape=[None, 640, 960, 3], name="X")
y = tf.placeholder(tf.float32, shape=[None, 640, 960, 1], name="y")
a = tf.constant(2, name = 'start')
b= tf.constant(3)
c = tf.add(a,b)
#tf.scalar_summary("cost", c)
'''this function will be used to concatenate the matrices on the same row of the symmetric u pattern'''
def con_concat(matA , matB, filter_n , name):
# up_conv = upconv_2D(matA, n_filter, flags, name)
return tf.concat([matA, matB ], axis = -1, name="concat_{}".format(name)) #values,axis,name = 'concat'
def upconv_2D(tensor, n_filter, name):
return tf.layers.conv2d_transpose(tensor,filters=n_filter,kernel_size=2,strides=2,name="upsample_{}".format(name))
'''
What does with tf.variable_scope mean? Often we want to share variables between values - for example if we have one image filter
function, and the filter is some matrix X. We want to multiply A by X and B by X. Instead of initialising the function twice and
having to store X essentially twice. We can share the X variable between A and B.
So instead we may create variables in a seperate bit of code and pass the to the functions that use them.
THis breaks encapsulation - the code that builds the graph must document the names, types, and shapes of variables to create.
when the code changes, the callers may have to create more or less, or different variables.
Alternatively - we use classes to create a model, where the classes take care of managing the variables they need.
WIthout classes tensorflow provides a variable scope mechanism that allows to easily share named variables while contructing a graph.
https://www.tensorflow.org/versions/r1.2/programmers_guide/variable_scope
-
'''
filter_list=[64, 128, 256, 512,1024]
'''here we want to define what actually happens in the convolution'''
def conv2d_layers(input, filter_size, name , pool=True):
tensor1 = input
print "input tensor" , tensor1
print "test1"
with tf.variable_scope("layer_{}".format(name)):
# print type(tensor1)
# print index
# print filter_num
tensor = tf.layers.conv2d(tensor1, filter_size , kernel_size = [3,3],padding = 'VALID' , activation = None, name = "conv1_layer{}".format(name))
print "test2"
tensor = tf.nn.relu(tensor ,name = "relu1_{}".format(name))
tensor = tf.layers.conv2d(tensor, filter_size , kernel_size = [3,3],padding = 'VALID' , activation = None, name = "conv2_layer{}".format(name))
print "test2"
tensor = tf.nn.relu(tensor ,name = "relu2_{}".format(name))
#possible batch normalisation layer
if pool == True:
pool = tf.layers.max_pooling2d(tensor, (2,2), strides = (2,2) , name="pool_{}".format(name))
# return pool
# else:
# return tensor
return tensor, pool
else:
return tensor
# enumerate.next()
#we actually can't throw away the original tensor after the pooling operation because we use it in the concat step
'''define the architecture'''
def maxpool_scale(convleft, upconvright):
print "its working!"
# print tensor.shape[1]
# print in_tensor.shape[1]
#We are using zero padding and a stride of 1 so our equation becomes we have the current dimension W1 and W2:
#W2 = (W1 - F + 2P)/S + 1 :
#Becomes W2 = (W1 - F)/1 + 1
#Need to solve this equation to get the size of the filter for the max pooling op to produce the right sized matrices
a = convleft.shape[1]
b = upconvright.shape[1]
xx = a+1 - b
scale_conv4 = tf.layers.max_pooling2d(convleft, pool_size=(xx,xx), strides = 1)
return scale_conv4
def unet_deconv(tensor, filter_size, name):
tf.nn.conv2d_transpose(tensor, filters= filter_size, kernel_size = 2, strides = 2, name="upsample_{}".format(name))
def build_unet(input_tensor):
#Left Side:
conv1,pool1 = conv2d_layers(input_tensor , 64 , name = "conv1")
conv2,pool2 = conv2d_layers(pool1 , 128 , name = "conv2")
conv3, pool3 = conv2d_layers(pool2 , 256 , name = "conv3")
conv4, pool4 = conv2d_layers(pool3 , 512 , name = "conv4")
conv5 = conv2d_layers(pool4 , 1024 , name = "conv5", pool = False)
#Right Side:
upconv6 = upconv_2D(conv5, 512 , name = "upconv6")
scale_conv4 = maxpool_scale(conv4, upconv6)
conv6 = con_concat(scale_conv4, upconv6, 1024, name = 'concat')
conv6 = conv2d_layers(conv6 , 512 , name = "conv_up6", pool = False)
upconv7 = upconv_2D(conv6, 256 , name = "upconv7")
scale_conv3 = maxpool_scale(conv3, upconv7)
conv7 = con_concat(scale_conv3, upconv7, 512, name = 'concat')
conv7 = conv2d_layers(conv7 , 256 , name = "conv_up7", pool = False)
upconv8 = upconv_2D(conv7, 128 , name = "upconv8")
scale_conv2 = maxpool_scale(conv2, upconv8)
conv8 = con_concat(scale_conv2, upconv8, 256, name = 'concat')
conv8 = conv2d_layers(conv8, 128 , name = "conv_up8", pool = False)
upconv9 = upconv_2D(conv8, 64 , name = "upconv9")
scale_conv1 = maxpool_scale(conv1, upconv9)
conv9 = con_concat(scale_conv1, upconv9, 128, name = 'concat')
conv9 = conv2d_layers(conv9 , 64 , name = "conv_up9", pool = False)
return tf.layers.conv2d(conv9, 2, (1,1), name='finaloutput', activation = tf.nn.sigmoid, padding = 'VALID')
''' intersection over union is a common metric for assessing performance in semantic segementations of tasls.
Think about image segmentation.
You want to identify Stop signs in your model. What you would do to train the model is to put a recetangle around the stop
sign in the image.
Then your model would attempt to do the same. Ideally your produced mask or rectangle would overlap the trained rectangle of
the stop sign perfectly and receive an IOU of 1. If it overlaps it half the area we would receive an IOU of .5
so area of intersection/area of two boxes
'''
def iou(train , test):
return value
def train_loss(xtrain, ytest):
loss = iou(xtrain, ytest)
global_setup = tf.train.get_or_create_global_step() #what is this? Returns and create (if necessary) the global step tensor.
#global step tensor refers to the number of batches seen by the graph.
optimiser = tf.train.AdamOptimizer()
return optimiser.minimize(loss, global_step = global_setup)
def main():
tf.reset_default_graph()
X = tf.placeholder(tf.float32, shape=[None, 572, 572, 1], name="X")
y = tf.placeholder(tf.float32, shape=[None, 640, 960, 1], name="y")
pred = build_unet(X)
tf.add_to_collection("inputs", X)
tf.add_to_collection("outputs", pred)
'''
What are the following lines doing?
get collection - used for building graphs, returns a list of values in the collection with the given name
so then we ask what is tf.graphkeys.update_ops
tf.graphkeys -> the standard library uses various well known names to collect and retrieve values assosciated with a graph.
Basically says - update the moving averages before finishing teh training step
explained well here: http://ruishu.io/2016/12/27/batchnorm/
'''
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = train_loss(pred , y)
with tf.Session() as sess:
writer = tf.summary.FileWriter('outputs', sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
#print sess.run(c)
#print 'printing in the session' , sess.run(X)
# writer = tf.summary.FileWriter('./graphs', sess.graph)
# writer = tf.train.SummaryWriter(logs_path, graph=tf.get_default_graph())
writer.close()
if __name__ == '__main__':
main()
#with tf.Session() as sess:
# print(sess.run(h))
#up6 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv5), conv4], axis=3)
'''
l: feature maps
k: feature maps as outputs
n * m : filter size
k = number of filters
f = filter spatial extent
s = stride
p = padding
w1 = width
h1 = height
d1 = dimension of input
Example with MNIST:
input image: 1*28*28
convd with 5*5 filter size stride of 1 and padding
w2= (w1- f + 2p)/s + 1
h2 = (h1 - f + 2ps)/s + 1
d2 = k
w2 = (28- (5-1)) = 24
h2 = (28- (5-1)) = 24
d2 = 32
thus 32X24X24 -> weights(F*F*D1) * K weights + K biases (5*5*1+1) * 32 = 832 parameters
maxpool1 = 2x2 window is replaced with max value w2 = (w1-F)/s + 1 -> (28-5)/2 + 1
= 32X12X12
conv2d2 = (12-(3-1))=10 -> 32X10X10 -> weights(F*F*D1) * K weights + K biases (3*3*32+1) * 32 = 9248 parameters
maxpool2 = 32X5X5
572X572
p=0
s =2
3X3 filter
w2 = (572 - (3-1)) = 570
h2 = (572 - (3-1)) = 570
d2 = 64
w2= (w1- f + 2p)/s + 1
h2 = (h1 - f + 2ps)/s + 1
d2 = k
similarly for the third
max pool -> (568-2)/2 + 1 = 283 + 1 = 284
cov layer = (284 - (3-1)) = 282
cov layer = 280
max pool -> (280-2)/2 + 1 = 140X140
conv = 138
conv = 136
max pool = 68X68 ----- filters number also doubling
conv = 66
conv 64
max pool = 32
conv = 30
conv = 28X28
-------- upsampling-decoding ------------
input image
'''
|
b5ba2dc9f3e637494e65e13e4fa2d90b816b6bab | GrnTeaLatte/AlienInvasion | /Chapter_8/8-11_unchanged_magicians.py | 434 | 3.90625 | 4 | def show_magicians(magicians, great_magicians):
while magicians:
add_great = magicians.pop()
print("The Great " + add_great.title())
great_magicians.append(add_great)
def make_great(great_magicians):
print("\nThe following magicians are great: ")
for name in great_magicians:
print(name)
magicians = ['doofus', 'joe', 'moe']
great_magicians = []
show_magicians(magicians[:], great_magicians)
make_great(great_magicians) |
f17b99c61027532fd88887c3919d0752c040a0c7 | martincordero/1-de-Carrera | /Clase_13_05.py | 304 | 3.90625 | 4 | def palabras(frase):
'''
Función que recibe una frase y devuelve un diccionario con las palabras
'''
palabras = frase.split()
longitud = map(len, palabras)
palabras = dict(zip(palabras, longitud))
return palabras
frase = input('Introduce una frase: ')
print(palabras(frase)) |
ca9c38704bb656bf6238b8e23edc6e70877ead6e | Pandiarajanpandian/Python---Programming | /Beginner Level/AmstrongNumber.py | 165 | 3.90625 | 4 | x=int(input("enter a number"))
temp=x
sum=0
while (temp>0):
a=temp%10
sum=sum+a**3
temp=temp//10
if (sum==x):
print("yes")
else:
print("no")
|
d29f67c54163010ee10329dc1f4aae4161cc7a8c | Alan-Liang-1997/CP1404-Practicals | /prac_04/quick_pick.py | 488 | 3.984375 | 4 | import random
number_quick_picks = int(input('How many quick picks would you like to generate? '))
for line in range(0, number_quick_picks):
quick_pick_list = []
for i in range(0, 6):
calculated_int = random.randint(1, 45)
while calculated_int in quick_pick_list:
calculated_int = random.randint(1, 45)
quick_pick_list.append(calculated_int)
for value in sorted(quick_pick_list):
print("{:3}".format(value), end=" ")
print()
|
7ce8cf25ce9aa78272b5865ee6cb603391e4b04b | CS-NSI/Sorting_algorithms | /insert.py | 200 | 3.53125 | 4 | def insert(t,i): #ok
for current_index in range(i-1,-1,-1):
if t[current_index] > t[current_index+1]:
swap(t,current_index,current_index+1)
else:
break |
4c95ade35dd14ee9a9b61a70b20ebd829299bf56 | ponchitaz/my_py | /Task1-noOOP.py | 662 | 4.0625 | 4 | import random
theText = input('Tell me a story: ')
theWords = theText.split()
def shuffledText(singleWord):
singleWord = list(singleWord)
random.shuffle(singleWord)
singleWord = ''.join(singleWord)
return singleWord
def main():
for singleWord in theWords:
if len(singleWord) > 3:
if singleWord[-1] == ",":
print(singleWord[0] + '' + shuffledText(singleWord[1:-2]) + '' + singleWord[-2::], end=" ")
else:
print(singleWord[0] + '' + shuffledText(singleWord[1:-1]) + '' + singleWord[-1], end=" ")
else:
print(singleWord, end=" ")
main() |
f175c07fbb64e5e29882cadea8d71d9f2477074f | prajwalprabhu/password_generator | /main.py | 638 | 3.625 | 4 | import random
import tkinter as tk
password=''
alphbets='''qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM123456789'''
def generate(e1):
global password
required_charecters=int(e1.get())
password=random.sample(alphbets,required_charecters)
e2=tk.Entry(root)
e2.pack()
e2.insert(0,password)
root=tk.Tk()
root.title("Password Generator")
tk.Label(root,text="Enter the number of characters").pack()
e1=tk.Entry(root)
e1.pack()
tk.Label(root,text="To generate password").pack()
tk.Button(root,text=" click here",command=lambda:generate(e1)).pack()
tk.Label(root,text="Password:").pack()
root.mainloop()
|
b0d328709ee4c95982bf341959b8e0e5785b135a | LiuZhipeng-github/python_study | /数据结构/python 基础/sort_way/choosee_sort.py | 790 | 4.03125 | 4 | '''
选择排序:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
以此类推,直到所有元素均排序完毕。
时间复杂度为O(n^2)但不稳定(考虑升序每次选择最大的情况)
'''
def selection_sort(alist):
for j in range(0, len(alist) - 1): # 多次找到每次中最小的数
min = j
for i in range(j + 1, len(alist)):
if alist[min] > alist[i]: # 先找一遍,找到数字最小的下标,就找到了最小的数
min = i
alist[j], alist[min] = alist[min], alist[j]
print(alist)
alist = [7, 6, 5, 7, 3, 1, 2]
selection_sort(alist)
|
6e1773708f70be58f8a124e3cfcb1273924966cf | E-Brons/self.py | /ex-8.2.2.py | 447 | 4.125 | 4 | import random
def get_item_price(x):
return x[1]
def sort_item_prices(list_of_tuples):
''' Sort tuples of ('item', price) from lowest price to highest price
:param arg1: list of tuple items (;item name', item_price)
:type arg1: list of tuples (str, float)
'''
list_of_tuples.sort(key=get_item_price)
products = [('milk', '5.5'), ('candy', '2.5'), ('bread', '9.0')]
sort_item_prices(products)
print(products) |
753d2a93a7f0f53831789856cc668e414531c660 | sumedhasingla/LeetCode | /AllPermutationsOfAString-DFS.py | 1,376 | 3.640625 | 4 | import sys
from copy import deepcopy
'''
Question: Find all possible permutations of a given string
Solution:
'''
class Node(object):
def __init__(self, state, path, inputString):
self.state = state
self.path = path
self.inputString = inputString
def goalTest(self):
if len(self.path) == len(self.inputString) + 1:
return True
else:
return False
def getSuccessorStates(self):
outputStates = []
for a in self.inputString:
if not( a in self.path ):
if len(self.path) <= len(self.inputString)+ 1:
outputStates.append(a)
#print "Input:" , self.state, "CurrentPath:", self.path,"Output:" , outputStates
return outputStates
class Solution(object):
def allPermutations(self, inputString):
"""
type inputString: str
:rtype: List[str]
"""
sol = []
root = Node(0,[0], inputString)
Frontier = []
Frontier.append(root)
while True:
if len(Frontier) == 0:
return sol
parent = Frontier.pop()
if parent.goalTest():
currentSol = parent.path[1:]
sol.append(''.join(currentSol))
outputStates = parent.getSuccessorStates()
for state in outputStates:
newPath = deepcopy(parent.path)
newPath.append(state)
node = Node(state,newPath,inputString)
Frontier.append(node)
def main():
Sol = Solution()
print len(Sol.allPermutations("abcd"))
if __name__ == "__main__":
main() |
32cc232b5d672595c886422fe1cffcf608003fb2 | resync/resync | /resync/url_authority.py | 2,579 | 3.59375 | 4 | """Determine URI authority based on DNS and paths."""
from urllib.parse import urlparse
import os.path
class UrlAuthority(object):
"""Determine URI authority based on DNS and paths.
Determine whether one resource can speak authoritatively
about another based on DNS hierarchy of server names and
path hierarchy within URLs.
Two modes are supported:
strict=True: requires that a query URL has the same URI
scheme (e.g. http) as the master, is on the same server
or one in a sub-domain, and that the path component is
at the same level or below the master.
strict=False (default): requires only that a query URL
has the same URI scheme as the master, and is on the same
server or one in a sub-domain of the master.
Example use:
from resync.url_authority import UrlAuthority
auth = UrlAuthority("http://example.org/master")
if (auth.has_authority_over("http://example.com/res1")):
# will be true
if (auth.has_authority_over("http://other.com/res1")):
# will be false
"""
def __init__(self, url=None, strict=False):
"""Create object and optionally set master url and/or strict mode."""
self.url = url
self.strict = strict
if (self.url is not None):
self.set_master(self.url)
else:
self.master_scheme = 'none'
self.master_netloc = 'none.none.none'
self.master_path = '/not/very/likely'
def set_master(self, url):
"""Set the master url that this object works with."""
m = urlparse(url)
self.master_scheme = m.scheme
self.master_netloc = m.netloc
self.master_path = os.path.dirname(m.path)
def has_authority_over(self, url):
"""Return True of the current master has authority over url.
In strict mode checks scheme, server and path. Otherwise checks
just that the server names match or the query url is a
sub-domain of the master.
"""
s = urlparse(url)
if (s.scheme != self.master_scheme):
return(False)
if (s.netloc != self.master_netloc):
if (not s.netloc.endswith('.' + self.master_netloc)):
return(False)
# Maybe should allow parallel for 3+ components, eg. a.example.org,
# b.example.org
path = os.path.dirname(s.path)
if (self.strict and path != self.master_path
and not path.startswith(self.master_path)):
return(False)
return(True)
|
8abf5047ee328f3c942123ee2c247fb9ee2bb0e4 | chaosWsF/Python-Practice | /leetcode/0463_island_perimeter.py | 1,215 | 3.796875 | 4 | r"""
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents
water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded
by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't
have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with
side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the
island.
Example:
Input: [[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
https://assets.leetcode.com/uploads/2018/10/12/island.png
"""
class Solution:
def islandPerimeter(self, grid):
res = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
if (j == 0) or (grid[i][j-1] == 0):
res += 2
if (i == 0) or (grid[i-1][j] == 0):
res += 2
return res
|
6a256e3aec941333c7098fe2769b5f5d1208399a | fabiogelbcke/CtCI-Python | /stacks and queues/ex1.py | 2,803 | 3.890625 | 4 | class Node:
def __init__(self, initdata=None):
self._data = initdata
self._next = None
@property
def data(self):
return self._data
@property
def next(self):
return self._next
class TripleStack:
"""
Implementation of a triple stack using only one list.
I'm storing the elements of the 1st stack on indexes with
i % 3 == 0, 2nd stack on indexes with i % 3 == 1, and
3rd stack on indexes with i % 3 == 2.
Since indexes on python lists are sequential (i.e. you can't
have a list with 10 elements and then add something at position 15),
everytime I add a new element that's beyond the current length of
the list, I add None to fields as necessary. E.g. if the list has
length 15 and there are already 5 elements on stack 2
(indexes 1,4,7,10,13), if I need to add something to stack 2, it goes
on index 16. I add None on index 15, the node on index 16 and None on index
17. If I need to do it again, i add None on index 18, the node on 19 and
None on 20, and so on
"""
def __init__(self):
self._triplestack = []
@property
def triplestack(self):
return self._triplestack
def generic_push(self, node, stack_no):
i = 0
while 3*i < len(self.triplestack) and self.triplestack[3*i + stack_no] is not None:
i += 1
if 3*i >= len(self.triplestack):
self.triplestack += [None,None,None]
self.triplestack[3*i + stack_no] = node
def push_stack1(self, node=None):
self.generic_push(node, 0)
def push_stack2(self, node=None):
self.generic_push(node, 1)
def push_stack3(self, node=None):
self.generic_push(node, 2)
def generic_pop(self, stack_no):
last_index = len(self.triplestack) - (3 - stack_no)
while last_index > 0 and self.triplestack[last_index] is None:
last_index -= 3
if last_index >= 0:
removed_node = self.triplestack[last_index]
self.triplestack[last_index] = None
return removed_node.data
return None
def pop_stack1(self):
return self.generic_pop(0)
def pop_stack2(self):
return self.generic_pop(1)
def pop_stack3(self):
return self.generic_pop(2)
def generic_peek(self, stack_no):
last_index = len(self.triplestack) - (3 - stack_no)
while last_index > 0 and self.triplestack[last_index] is None:
last_index -= 3
if last_index >= 0:
return self.triplestack[last_index].data
return None
def peek_stack1(self):
return self.generic_peek(0)
def peek_stack2(self):
return self.generic_peek(1)
def peek_stack3(self):
return self.generic_peek(2)
|
bc0a0b9d72baaea1ca6a491d376e5846b4ca8574 | chunlei85/vocab_b | /libs/utils/list_helper.py | 611 | 3.84375 | 4 | # !/usr/bin/python3
# encoding:utf-8
'''
@File : list_helper.py
@Time : 2020/12/15 17:00:37
@Author : AP
@Version : 1.0
@WebSite : ***
'''
# Start typing your code from here
def reverse(s, i: int = None, j: int = None):
"""
翻转
:param s: 需翻转的数组
:param i: 翻转开始位置
:param j: 翻转结束位置
"""
if not i and not j:
i = 0
j = len(s)-1
if s is None or i < 0 or j < 0 or i >= j or len(s) < j + 1:
return
while i < j:
temp = s[i]
s[i] = s[j]
s[j] = temp
i += 1
j -= 1
|
368c83b1b1cad3f8efc3edb0261300adedd01eea | Rudedaisy/CMSC-201 | /Labs/lab11/lab11.py | 791 | 3.6875 | 4 | # File: lab11.py
# Written By: Edward Hanson
# Date: 11/17/15
# Section: 18
# E-mail: ehanson1@umbc.edu
# Description: Translates english words into the "Ong" language.
def main():
word = str(input("Please enter a word to translate into Ong: "))
myWord = ong(word)
myWord.translateOng()
class ong:
def __init__(self, word):
self.word = word
def isVowel(self, letter):
vowels = ["a", "e", "i", "o", "u"]
for vowel in vowels:
if letter.lower() == vowel:
return True
return False
def translateOng(self):
for letter in self.word:
if self.isVowel(letter):
print(letter, end = "")
else:
print(letter, end = "ong")
print()
main()
|
1d6c0129c80de383b6a22f6ac2991f08c3b0c798 | Coderucker/bitbuild | /BitBuild/util/match_os.py | 567 | 3.9375 | 4 | import re
from typing import Match
def match_platform(string: str, to_match_platform_list: list) -> tuple[Match[str], str]:
"""
A Function to Match the preferred operating system.
You need to provide a list of platforms inorder to match it.
Example Usage:
```python
match_platform("build_artifact_linux", ["linux", "android", "unix", "macos", "windows"])
```
"""
for platform in to_match_platform_list:
match_run = re.search(f"{platform}*", string)
if match_run != None:
return (match_run, True) |
07f99a512dff6d38a4b1c2673b0d38797c20c432 | MHM18/hm18 | /hmpro/zhangxiyang/class/Student.py | 375 | 3.796875 | 4 | class Student(object):
name = ""
score= 5
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print ("he")
print('%s %s' %(self.name, self.score))
if __name__ == '__main__':
bart = Student('Bart Li',58)
lily = Student("Lily Ha",79)
bart.print_score()
lily.print_score()
|
f35f30aa7728920b045a747c2c17ffd71a33bed1 | SashoStoichkovArchive/HB_TASKS | /projects/week06/05_04_2019/generators/book_read.py | 537 | 3.546875 | 4 | import keyboard, os
first_part = open("book/001.txt", "r")
second_part = open("book/002.txt", "r")
for line in first_part:
if line.startswith("#"):
input("Next chapter ->")
os.system('cls' if os.name == "nt" else "clear")
print(line[1:])
else:
print(line)
for line in second_part:
if line.startswith("#"):
input("Next chapter ->")
os.system('cls' if os.name == "nt" else "clear")
print(line[1:])
else:
print(line)
first_part.close()
second_part.close()
|
c95481531d8f0d093455cc0a6fc1e088a555b710 | sudeepnarkar/Programming-in-Python | /rename_files.py | 551 | 3.65625 | 4 | import os
def rename_files():
files_list = os.listdir("directory path")
# print(files_list)
char_delete="0123456789"
current_dir = os.getcwd()
print("Current working directory:"+current_dir)
os.chdir("directory path")
for file_name in files_list:
print("Old filename:"+file_name)
os.rename(file_name,file_name.translate(None,"0123456789"))
print("New filename:"+file_name.translate(None,"0123456789"))
print("Printing all the file names:")
os.chdir(current_dir)
rename_files()
|
6d6199828da19fb5636e7e3b4ae8432e1efa4b8f | kiponik/Python | /Lecture1/HomeTask1.py | 581 | 4.03125 | 4 | # Создаём переменные
variable1 = 'variable1'
variable2 = 2
variable3 = True
variable4 = 4.44
# Вывод переменных
print(type(variable4), type(variable3), type(variable2), type(variable1))
print(variable4, variable3, variable2, variable1)
# Ввод данных
inputInt = int(input('Enter the number: '))
inputDecimal = float(input('Enter Decimal Number: '))
inputString = input('Enter String: ')
# Вывод введеных данных
print(type(inputInt), type(inputDecimal), type(inputString))
print(inputInt, inputDecimal, inputString) |
be989d3c0ac16e33383d0e0daf5fcba072c4e79d | monty8800/PythonDemo | /base/19.返回函数.py | 563 | 3.890625 | 4 | # 返回函数
# 1.函数作为返回值
# 求和函数
def calc_sum(*args):
ax = 0
for x in args:
ax = ax + x
return ax
# 不直接返回结果,而是返回一个函数
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
# 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数:
fu = lazy_sum(1,2,3,4,5,6)
print(fu) # <function lazy_sum.<locals>.sum at 0x10392d378>
# 调用fu时才进行求和
print(fu()) # 21
# 2.闭包
|
bf0796a7c2455aaa0328a0988228987679d2c61d | waithope/leetcode-jianzhioffer | /剑指offer/08-二叉树下一个节点.py | 1,929 | 3.90625 | 4 | # -*- coding:utf-8 -*-
'''
二叉树下一个节点
=========================
给定一颗二叉树和其中的一个节点,找出中序遍历序列的下一个节点,树中的节点除了
有两个分别指向左、右子节点的指针,还有一个指向父节点的指针。
'''
class TreeNode(object):
def __init__(self, val, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def getNextNode(node):
'''
三种情况:
1.如果该节点有右子树,则右子树最左的节点就是node的下一个节点;
2.如果该节点没有右子树,且是父节点的左子节点,则父节点是node下一个节点;
3.如果该节点既没有右子树也不是父节点的左子节点,就沿着父节点指针向上回溯,
找到某个是其父节点的左子节点的节点,则其父节点是node的下一个节点,如果回溯
到根节点还没找到,则node没有下一个节点。
'''
if node is None:
return
if node.right:
nextNode = node.right
while nextNode.left:
nextNode = nextNode.left
return nextNode
else:
if node.parent and node == node.parent.left:
return node.parent
elif node.parent and node == node.parent.right:
parent = node.parent
while parent.parent:
if parent == parent.parent.left:
return parent.parent
parent = parent.parent
return None
if __name__ == '__main__':
n1 = TreeNode('a')
n2 = TreeNode('b')
n3 = TreeNode('c')
n4 = TreeNode('d')
n5 = TreeNode('e')
n1.left, n2.parent = n2, n1
n1.right, n3.parent = n3, n1
n2.left, n4.parent = n4, n2
n2.right, n5.parent = n5, n2
print(getNextNode(n5).val == 'a')
print(getNextNode(n3) == None)
|
b7620fe096cecea62b1ed57c9a20b776531732fe | AlekseiNaumov/Home_Work | /lesson6/6_1.py | 1,684 | 3.640625 | 4 | # 1. Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
# Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый,
# зеленый. Продолжительность первого состояния (красный) составляет 7 секунд, второго (желтый) — 2 секунды,
# третьего (зеленый) — на ваше усмотрение. Переключение между режимами должно осуществляться
# только в указанном порядке (красный, желтый, зеленый). Проверить работу примера, создав экземпляр и вызвав описанный
# метод.
from itertools import cycle
from time import sleep
class TrafficLight:
__colors = ['red', 'yellow', 'green']
def running(self):
colors = TrafficLight.__colors
for color in cycle(colors):
if color == 'red':
print(color)
sleep(7)
if color == 'yellow':
print(color)
sleep(2)
if color == 'green':
print(color)
sleep(5)
# while True:
# print(colors[0])
# sleep(7)
# print(colors[1])
# sleep(2)
# print(colors[2])
# sleep(5)
color_l = TrafficLight()
color_l.running()
|
884f6bce115704e0343d3ec429c0365b11ab45e6 | ahmetceylan90/firstApp | /Introduction/Lesson5/while.py | 666 | 3.78125 | 4 | #sonsuz döngü örneği
# while(True):
# print("abc")
###############
# i = 0
# while i <= 100:
# if i % 2 == 0:
# print (i)
# i = i + 1
##########
# i = 1
# cift = 0
# tek = 0
# while i <= 1000:
# if i % 2 == 0:
# cift = cift + 1
# else:
# tek = tek + 1
# i = i + 1
# print(cift)
############
# metin = input("metin gir : ")
# uzunluk = 0
# while uzunluk < len(metin):
# print(metin[uzunluk])
# uzunluk += 1
########
def new_func():
num1 =input("sayi :")
i = 0
toplam = 0
while i < len(num1):
toplam = int(num1[i]) + toplam
i = i+1
print(toplam)
new_func() |
6e9792625e3f1ef71088d1b302d9ad0819f6d582 | tetrismegistus/minutia | /exercises/guided_tutorials/advent15/1_1.py | 208 | 3.53125 | 4 | #!/usr/bin/env python3
floor = 0
for line in open('input.txt'):
for x in line:
if x == '(':
floor += 1
elif x == ')':
floor -=1
print(floor)
print(floor)
|
b57242307803053bffdc9fae80d48000b8cca47e | deyuanyang/python_bioinfo | /get_seq_by_size_range.py | 1,281 | 3.59375 | 4 | #!/usr/bin/env python3
# coding: utf-8
from Bio import SeqIO
import argparse
class fasta_parser():
def __init__(self, fasta):
self.fasta = fasta
def create_seqio_object(self):
return SeqIO.parse(self.fasta, 'fasta')
def get_seq_by_size_range(self, min_seqsize, max_seqsize):
for record in self.create_seqio_object():
seqsize = len(record.seq)
if seqsize >= min_seqsize and seqsize <= max_seqsize:
yield record.format('fasta')
def arguments():
parser = argparse.ArgumentParser(description="This script gets all fasta sequences contained within a length interval")
required = parser.add_argument_group("required arguments:")
required.add_argument("--min", type=int, required=True, help="Minimum sequence length")
required.add_argument("--max", type=int, required=True, help="Maximum sequence length")
required.add_argument("fasta", type=str, nargs="*", metavar="fasta", help="Fasta file(s)")
return parser.parse_args()
if __name__ == '__main__':
args = arguments()
for fasta in args.fasta:
parser = fasta_parser(fasta)
for rec in parser.get_seq_by_size_range(min_seqsize=args.min, max_seqsize=args.max):
print(rec, end='')
|
5a179067df89d0b3282fb1cdc8b037f73b24e8eb | genshang/data-scrape | /app.py | 826 | 3.578125 | 4 | import urllib2
from bs4 import BeautifulSoup
web_page = "https://finance.yahoo.com/quote/FB?p=FB" #created a variable and assigned it the website from yahoo finance FB (getting the website)
page = urllib2.urlopen(web_page)# .urlopen is a function, web_page is the vessel for the website
# print(page)
soup = BeautifulSoup(page, "html.parser") #means we are going to parse through the html file.
name_box = soup.find("h1", attrs={"class": "D(ib)"})
# print(name_box)
name = name_box.text
print(name)
price_box = soup.find("span", attrs={"class": "Fw(b)"})
price = price_box.text
print(price)
import csv #csv = comma separated value
from datetime import datetime
with open("index.csv", "w") as csv_file: #as is an alias, i.e. variable
writer = csv.writer(csv_file)
writer.writerow([name, price, datetime.now()])
|
6d821277fb641301264d66ac93d1bbe786897538 | SKumarMN/DataStructuresPython | /array/subarray_with_zero_sum.py | 387 | 3.75 | 4 | def subArrayExists( arr, n):
s = set()
sum = 0
for i in range(n):
sum +=arr[i]
if(sum == 0 or sum in s):
return True
else:
s.add(sum)
arr2=[4, 2, -3, 1, 6]
arr = [-3, 2, 3, 1, 6]
n = len(arr2)
if subArrayExists(arr2, n) == True:
print("Found a sunbarray with 0 sum")
else:
print("No Such sub array exits!") |
dee933dae3a4ad5fc6ffc7a9e4c36f820e77019e | Ian-Dzindo01/HackerRank_Challenges | /Python/Sherlock_and_Angrams.py | 783 | 3.84375 | 4 | # two strings angrams if letters of one can be rearranged to form the other
# the idea is to traverse the values of this dictionary divide each of the counts by 2 and add that to the tally
s = 'mom'
def sherlockAndAnagrams(s):
subs = []
r = 0
for i in range(1, len(s)):
d = {} #temporarily store the count of the substrings in the dictionary
for j in range(len(s)-i+1): # loop used to extract all of the substrings of the string
subs = ''.join(sorted(s[j:j+i]))
if subs not in d: # sorts them in the dictionary
d[subs] = 1
else:
d[subs] += 1
r += d[subs] - 1
return r
res = sherlockAndAnagrams(s)
print(res)
|
c40a0f74428e0620cadc0497d13d0113d4d0b069 | ziamajr/CS5590PythonLabAssignment | /CS5590 - 01 Lesson 3 InClass/InClass2.py | 501 | 4.25 | 4 | #David Ziama
#ClassID # 3
#June 23, 2017
# Write a program that takes a list of numbers (for example,a=[5,10,15,20,25])
# and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.
#
a = [5, 10, 15, 20, 25]
print(a[0],a[-1])
#def list():
# n = 0
# a = [5, 10, 15, 20, 25]
# numlist = []
# for i in range(0, 2):
# numlist.append(a[n])
# n = n - 1
# print(numlist)
#list()
|
5217771c5fcb6fe749c9892479010c0c9d42a14c | Catedra-Cabify-ETSIT-UPM/madrid_air_quality | /functions/air_quality.py | 2,278 | 3.65625 | 4 | #!/usr/bin/env python3
# Python script with functions to manipulate air quality
# data from datos.madrid.es. It is meant to be imported as
# a library.
import pandas as pd
import numpy as np
def pollutant_daily_ts(path, station_code, pollutant):
"""Return the daily time series of a pollutant measssured
at a station.
Arguments:
path (str): path to the csv file
station_code (int): station code (e.g. 28079035)
pollutant (int): pollutant code (e.g. 8)
Returns:
pandas.core.series.Series: daily time series
"""
# Split and format the station code
station_code = str(station_code)
province = int(station_code[:2])
municipality = int(station_code[2:5])
station = int(station_code[5:9])
# Read and filter the original CSV
aq = pd.read_csv(path, sep=';').query("PROVINCIA == @province & " \
"MUNICIPIO == @municipality & " \
"ESTACION == @station & " \
"MAGNITUD == @pollutant"
).filter(regex=("D\d\d|ANO|MES"))
# Melt the DataFrame from (months x days) to (DateTime x columns)
aq_melted = aq.melt(id_vars=['ANO', 'MES'], var_name='day',
value_name='pollutant').sort_values(by=['MES', 'day'])
aq_melted.index = pd.to_datetime(dict(
year=aq_melted['ANO'],
month=aq_melted['MES'],
day=aq_melted['day'].str[1:].astype(int)
), errors='coerce')
# Get the pollutant time series
ts = aq_melted['pollutant'].replace(0, np.nan)
return ts
def pollutant_daily_ts_several(paths, station_code, pollutant):
"""Return the daily time series of a pollutant measssured
at a station of several years
Arguments:
paths (list): tuplke of paths to the csv files
station_code (int): station code (e.g. 28079035)
pollutant (int): pollutant code (e.g. 8)
Returns:
pandas.core.series.Series: daily time series
"""
series = []
for p in paths:
series.append(pollutant_daily_ts(p, station_code, pollutant))
return pd.concat(series).sort_index()
|
6f113c269dbcd2f5d694d67712f9ad675829aa37 | qiaozhi827/leetcode-1 | /11-并查集/00-union_find.py | 5,977 | 3.578125 | 4 |
class UnionFind1:
def __init__(self, n):
self.count = n
self.parent = []
for i in range(n):
self.parent.append(i)
def find(self, p):
while self.parent[p] != p:
p = self.parent[p]
return p
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
self.parent[p_root] = q_root
self.count -= 1
class UnionFind2:
# 基于size的优化
def __init__(self, n):
self.count = n
self.parent = []
self.size = []
for i in range(n):
self.parent.append(i)
self.size.append(1)
def find(self, p):
while self.parent[p] != p:
p = self.parent[p]
return p
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.size[p_root] > self.size[q_root]:
# 较短的挂在较长的下面
self.parent[q_root] = p_root
self.size[p_root] += self.size[q_root]
else:
self.parent[p_root] = q_root
self.size[q_root] += self.size[p_root]
self.count -= 1
class UnionFind3:
# 基于rank的优化
def __init__(self, n):
self.count = n
self.parent = []
self.rank = []
for i in range(n):
self.parent.append(i)
self.rank.append(1)
def find(self, p):
while self.parent[p] != p:
p = self.parent[p]
return p
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.rank[p_root] > self.rank[q_root]:
# 较短的挂在较长的下面,高度肯定差至少一,所以拼接后高度不变
self.parent[q_root] = p_root
elif self.rank[p_root] < self.rank[q_root]:
self.parent[p_root] = q_root
else:
self.parent[p_root] = q_root
self.rank[q_root] += 1
self.count -= 1
class UnionFind4:
# 路径压缩
def __init__(self, n):
self.count = n
self.parent = []
self.rank = []
for i in range(n):
self.parent.append(i)
self.rank.append(1)
def find(self, p):
while self.parent[p] != p:
# 它的parent不是根,就把它放在parent的parent下
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.rank[p_root] > self.rank[q_root]:
# 较短的挂在较长的下面,高度肯定差至少一,所以拼接后高度不变
self.parent[q_root] = p_root
elif self.rank[p_root] < self.rank[q_root]:
self.parent[p_root] = q_root
else:
self.parent[p_root] = q_root
self.rank[q_root] += 1
self.count -= 1
class UnionFind5:
# 路径压缩
def __init__(self, n):
self.count = n
self.parent = []
self.rank = []
for i in range(n):
self.parent.append(i)
self.rank.append(1)
def find(self, p):
while self.parent[p] != p:
# 它的parent不是根,就把它放在parent的parent下
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.rank[p_root] > self.rank[q_root]:
# 较短的挂在较长的下面,高度肯定差至少一,所以拼接后高度不变
self.parent[q_root] = p_root
elif self.rank[p_root] < self.rank[q_root]:
self.parent[p_root] = q_root
else:
self.parent[p_root] = q_root
self.rank[q_root] += 1
self.count -= 1
class UnionFind6:
# 路径压缩-递归
def __init__(self, n):
self.count = n
self.parent = []
self.rank = []
for i in range(n):
self.parent.append(i)
self.rank.append(1)
def find(self, p):
if self.parent[p] != p:
# 它的parent不是根,就把它放在parent的根下
self.parent[p] = self.find(self.parent[p])
return self.parent[p]
def is_connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.rank[p_root] > self.rank[q_root]:
# 较短的挂在较长的下面,高度肯定差至少一,所以拼接后高度不变
self.parent[q_root] = p_root
elif self.rank[p_root] < self.rank[q_root]:
self.parent[p_root] = q_root
else:
self.parent[p_root] = q_root
self.rank[q_root] += 1
self.count -= 1
if __name__ == '__main__':
obj = UnionFind2(5)
print(obj.count)
obj.union(3, 4)
print(obj.count)
obj.union(3, 2)
print(obj.count)
|
e5f29a9fb7c2d4106d32342267a4290ff0ae999f | med10d/Code_Suggestions | /adventure_Suggestions.py | 7,121 | 4.0625 | 4 | class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.moves = 0
# Your code works great for allowing the user to navigate to the different rooms in your adventure game. These comments
# are suggestions for how you could potentially condense your code, allowing you to reuse some parts of your code.
# Instead of creating four different Room classes, you could try creating one Room class. Then, you could initialize
# four room objects, by passing in values to the constructor of the Room class that make each room different. Here is an
# example of how to do this:
#
# class Room(): # Probably do not want to inherit Player in this class, because Room is not a "type of" Player.
# def __init__(self, room, direction1, neighbor1, direction2, neighbor2):
# self.room = room
# self.direction1 = direction1
# self.neighbor1 = neighbor1
# self.direction2 = direction2
# self.neighbor2 = neighbor2
#
# # The code below uses the class variables defined above in the return message, instead of hardcoding the message.
# def __repr__(self):
# return (f"Welcome to Room {self.room}. Use {self.direction1} to move to Room {self.neighbor1}, or "
# f"{self.direction2} to move to Room {self.neighbor2}.")
class Room_1(Player):
def __init__(self):
self.room = 1
def __repr__(self):
return "Welcome to Room 1. Use d to move to Room 2, or s to move to Room 3."
class Room_2(Player):
def __init__(self):
self.room = 2
def __repr__(self):
return "Welcome to Room 2. Use a to move to Room 1, or s to move to Room 4."
class Room_3(Player):
def __init__(self):
self.room = 3
def __repr__(self):
return "Welcome to Room 3. Use w to move to Room 1, or d to move to Room 4."
class Room_4(Player):
def __init__(self):
self.room = 4
def __repr__(self):
return "Welcome to Room 4. Use w to move to Room 2, or a to move to Room 3."
class Game:
def __init__(self):
name = input("What is your name, adventurer? ")
self.player = Player(name, 1)
def play_game(self):
# Instead of creating four room variables here, you could create a "rooms" dictionary, as shown below. This
# would let you access any room object by using its index number. For example, "rooms[1]" would give you the
# Room object for room 1:
#
# rooms = {1: Room(room=1, direction1="d", neighbor1=2, direction2="s", neighbor2=3),
# 2: Room(room=2, direction1="a", neighbor1=1, direction2="s", neighbor2=4),
# 3: Room(room=3, direction1="w", neighbor1=1, direction2="d", neighbor2=4),
# 4: Room(room=4, direction1="w", neighbor1=2, direction2="a", neighbor2=3)}
# current_room = rooms[1]
room_1 = Room_1()
room_2 = Room_2()
room_3 = Room_3()
room_4 = Room_4()
room = room_1.room
game_active = True
print("Welcome to Adventure, {}!".format(self.player.name))
print("There are four rooms that you can explore. The rooms a laid out as follows:")
print("Top Left: Room 1 Top Right: Room 2")
print("Bottom Left: Room 3 Bottom Right: Room 4")
print("Your adventure starts in room number 1.")
print("")
while game_active:
move = input("Use w, a, s, and d to move. Type q to quit the game.")
print("")
if move == "q".lower():
print("Game over!")
print("You made {} moves.".format(self.player.moves))
game_active = False
# Lastly, you could replace the "elif" conditions in your code below that start with "elif move == ", by
# using the commented code below one time. This code uses the "rooms" dictionary from the previous comment.
#
# elif move.lower() != current_room.direction1 and move.lower() != current_room.direction2:
# print("There's nowhere to go! Try a different direction.")
# print("")
# elif move.lower() == current_room.direction1:
# current_room = rooms[current_room.neighbor1]
# self.player.moves += 1
# print(current_room)
# print("")
# elif move.lower() == current_room.direction2:
# current_room = rooms[current_room.neighbor2]
# self.player.moves += 1
# print(current_room)
# print("")
elif move == "w".lower():
if room == room_1.room or room == room_2.room:
print("There's nowhere to go! Try a different direction.")
print("")
elif room == room_3.room:
room = room_1.room
self.player.moves += 1
print(room_1)
print("")
elif room == room_4.room:
room = room_2.room
self.player.moves += 1
print(room_2)
print("")
elif move == "a".lower():
if room == room_1.room or room == room_3.room:
print("There's nowhere to go! Try a different direction.")
print("")
elif room == room_2.room:
room = room_1.room
self.player.moves += 1
print(room_1)
print("")
elif room == room_4.room:
room = room_3.room
self.player.moves += 1
print("")
print(room_3)
elif move == "s".lower():
if room == room_3.room or room == room_4.room:
print("There's nowhere to go! Try a different direction.")
print("")
elif room == room_1.room:
room = room_3.room
self.player.moves += 1
print(room_3)
print("")
elif room == room_2.room:
room = room_4.room
self.player.moves += 1
print(room_4)
print("")
elif move == "d".lower():
if room == room_2.room or room == room_4.room:
print("There's nowhere to go! Try a different direction.")
print("")
elif room == room_1.room:
room = room_2.room
self.player.moves += 1
print(room_2)
print("")
elif room == room_3.room:
room = room_4.room
self.player.moves += 1
print(room_4)
print("")
else:
print("That's not a valid input.")
print("")
game = Game()
game.play_game()
|
9b22b5c1f379f0c001e9c38d5ba5fc2987d361a1 | Wambuilucy/CompetitiveProgramming | /HackerRank/IntroToTutorialChallenges.py | 169 | 3.75 | 4 | #! /usr/bin/python3
# https://www.hackerrank.com/challenges/tutorial-intro
v = int(input())
n = int(input())
ar = input()
arr = ar.split(' ')
print(arr.index(str(v)))
|
32b3b52a9e2db1fd18c0ae1045585f2c98349e01 | brandonPauly/pythonToys | /exercisesInClass.py | 1,200 | 4.03125 | 4 | def pattern(n):
'print a recursive pattern'
if n == 1:
print(1, end = ' ')
else:
pattern(n-1)
print(n, end=' ')
pattern(n-1)
def cheer(n):
'recursively print a cheer'
if n <= 1:
print('Hurrah!')
else:
print("Hip")
cheer(n-1)
def printLst(lst):
'''recursively prints the items in lst, one per line,
starting with the item in index 0, without modifying lst'''
if len(lst) == 0:
return
elif len(lst) == 1:
print(lst[0])
else: # lst has at least two items
print(lst[0])
printLst(lst[1:])
def recFact(n):
'return the product of the numbers between 1 and n'
if n == 1:
return 1
else:
return n * recFact(n-1)
def iterFact(n):
'return the product of the numbers between 1 and n'
prod = 1
for i in range(1, n+1):
#print(i)
prod = prod * i
return prod
def revVertical(n):
'''recursively print the digits of n, least significant to
most significant, one per line'''
if n < 10:
print(n)
else:
print(n % 10)
revVertical (n // 10)
|
4dd972497846b6d3acaf307fde7ad07e26572e73 | GuhanSGCIT/Trees-and-Graphs-problem | /distance between both magnets.py | 2,105 | 3.96875 | 4 |
"""
Given coordinates of two pivot points (x0, y0) & (x1, y1) in coordinates plane.
Along with each pivot, two different magnets are tied with the help of a string
of length r1 and r2 respectively. Find the distance between both magnets when they
repelling each other and when they are attracting each other.
Input description
First line has point x0,y0
second line has point x1,y1
Third line has length of string r1,r2
Output description
Distance while repulsion
Distance while attraction
Explanation
We have two pivots points on coordinates, so distance between these points are D = ((x1-x2)2 +(y1-y2)2 )1/2.
Also, we can conclude that distance between magnet is maximum while repulsion and that too should be the distance between pivots + sum of the length of both strings.
In case of attraction we have two cases to take care of:
Either the minimum distance is the distance between pivots – the sum of the length of both strings
Or minimum distance should be zero in case if the sum of the length of strings is greater than the distance between pivot points.
Input
0 0
5 0
2 2
Output
9
1.0
Input
1 2
2 3
4 5
Output
10
0
input:
1 2
2 3
3 4
output:
8
0
input:
55 66
44 47
5 9
output:
35
7.9544984001001495
input:
2 515
35 556
332 551
output:
935
0
input:
1 1
2 2
3 3
output:
7
0
Hint
As we all know about the properties of magnet that they repel each other when they are facing each other with
the same pole and attract each other when they are facing each other with opposite pole.
Also, the force of attraction, as well as repulsion, always work in a straight line.
"""
import math
def pivotDis(x0, y0, x1, y1):
return math.sqrt((x1 - x0) * (x1 - x0)
+ (y1 - y0) * (y1 - y0))
def minDis( D, r1, r2):
return max((D - r1 - r2), 0)
def maxDis( D, r1, r2):
return D + r1 + r2
x0,y0 = map(int,input().split())
x1,y1 = map(int,input().split())
r1,r2 = map(int,input().split())
D = pivotDis(x0, y0, x1, y1)
print(int(maxDis(D, r1, r2)))
print(minDis(D, r1, r2)) |
08350051a33919912ce69610c9b17b26ef173614 | YANG007SUN/hackerrank_challenge | /easy/gemstones.py | 325 | 3.640625 | 4 | # https://www.hackerrank.com/challenges/gem-stones/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
def gemstones(arr):
res = []
for i in range(len(arr)):
res +=list(set(arr[i]))
d = dict(Counter(res))
counter = 0
for k in d:
if d[k]==len(arr):counter +=1
return counter |
d5aa740943edc76795f72b39c568444c839f5db5 | gjogjreiogjwer/jzoffer | /数组/旋转数组的最小数字.py | 1,974 | 4.375 | 4 | # -*- coding:utf-8 -*-
'''
旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,
数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
example1:
输入:[3,4,5,1,2]
输出:1
example2:
输入:[2,2,2,0,1]
输出:0
解:采用二分法。设置两个指针,分别指向头尾。
若中间元素大于第一个指针,即它位于前面的递增数组,更新第一指针指向中间元素;
若中间元素小于第一个指针,即它位于后面的递增数组,更新第二指针指向中间元素;
第一指针总是指向前面,第二指针总是指向后面;
当两指针相邻时,第二指针指向最小元素。
特殊情况,当第一指针=第二指针=中间元素,可能出现 [1,0,1,1,1],此时之能从头到尾遍历。
'''
class Solution(object):
def minArray(self, numbers):
"""
:type numbers: List[int]
:rtype: int
"""
if len(numbers) < 1:
return None
left = 0
right = len(numbers) - 1
while numbers[left] >= numbers[right]:
if right-left == 1:
return numbers[right]
mid = (left+right) // 2
if numbers[left] == numbers[right] and numbers[right] == numbers[mid]:
return self.minNum(left, right, numbers)
if numbers[left] <= numbers[mid]:
left = mid
else:
right = mid
# 没有旋转
return numbers[left]
def minNum(self, left, right, numbers):
r = numbers[left]
for i in range(left+1, right+1):
if r > numbers[i]:
r = numbers[i]
return r
if __name__ == '__main__':
a = Solution()
print (a.minArray([1,3,5]))
|
33e055d6db5e05a8e240e54b4890a4f7a3dd3b5c | HJTGit/git | /Python学习/什么是dict.py | 191 | 3.703125 | 4 | #新来的Paul同学成绩是 75 分,请编写一个dict,把Paul同学的成绩也加进去。
d = {
'Adam': 95,
'Lisa': 85,
'Bart': 59,
'Paul': 75
}
print (d.get('Adam')) |
9a66ccc78167a67cfbccd0b16f9ea23d7ea286bc | lobstersalad/EPIPython | /PrimitiveTypes/parity.py | 567 | 3.984375 | 4 | def parity(x: int) -> int:
result = 0
while x:
print("x is currently: " + str(bin(x)[2:]))
result ^= 1
print("result is currently " + str(result))
a = x & ~(x - 1)
print ("a is " + str(bin(a)[2:]))
x &= (x - 1)
return result
while True:
try:
number = int(input("Enter a decimal number: "))
print("Your number in binary is: " + str(bin(number)[2:]))
print("The parity of your number is " + str(parity(number)))
break
except ValueError:
print("Invalid input")
|
bf83092923c75b816b1a5d97a1c66416e889f528 | Anderson-Lab/data-301-student | /book/Chapter 1 Tables Observations Variables/1.1 Introduction to Tabular Data.py | 23,539 | 4.4375 | 4 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py,md
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Chapter 1. Tables, Observations, and Variables
#
# # 1.1 Introduction to Tabular Data
#
# What does data look like? For most people, the first image that comes to mind is a spreadsheet, with numbers neatly arranged in a table of rows and columns. One goal of this book is to get you to think beyond tables of numbers---to recognize that the words in a book and the markers on a map are also data to be collected, processed, and analyzed. But a lot of data is still organized into tables, so it is important to know how to work with **tabular data**. In fact, most machine learning algorithms can only process data that can be roughly considered **tabular data**. Where does this show up?
# Let's look at a tabular data set. Shown below are the first 5 rows of a data set about the passengers on the Titanic. This data set contains information about each passenger (e.g., name, sex, age), their journey (e.g., the fare they paid, their destination), and their ultimate fate (e.g., whether they survived or not, the lifeboat they were on).
#
# <img src="titanic_data.png" width="800">
# In a tabular data set, each row represents a distinct observation and each column a distinct variable. Each **observation** is an entity being measured, and **variables** are the attributes we measure. In the Titanic data set above, each row represents a passenger on the Titanic. For each passenger, 14 variables have been recorded, including `pclass` (their ticket class: 1, 2, or 3) and `boat` (which lifeboat they were on, if they survived).
# ## Storing Data on Disk and in Memory
# How do we represent tabular data on disk so that it can be saved for later or shared with someone else? The Titanic data set above is saved in a file called `titanic.csv`. Let's peek inside this file using the shell command `head`.
#
# _Jupyter Tip_: To run a shell command inside a Jupyter notebook, simply prefix the shell command by the `!` character.
#
# _Jupyter Tip_: To run a cell, click on it and press the "play" button in the toolbar above. (Alternatively, you can press `Shift+Enter` on the keyboard.)
# !head /data301/data/titanic.csv
# The first line of this file contains the names of the variables, separated by commas. Each subsequent line contains the values of those variables for a passenger. The values appear in the same order as the variable names in the first line and are also separated by commas. Because the values in this file are separated (or _delimited_) by commas, this file is called a **comma-separated values** file, or **CSV** for short. CSV files typically have a `.csv` file extension, but not always.
#
# Although commas are by far the most common delimiter, you may encounter tabular data files that use tabs, semicolons (;), or pipes (|) as delimiters.
# How do we represent this information in memory so that it can be manipulated efficiently? In Python, the `pandas` library provides a convenient data structure for storing tabular data, called the `DataFrame`.
import pandas as pd
pd.DataFrame
# To read a file from disk into a `pandas` `DataFrame`, we can use the `read_csv` function in `pandas`. The first line of code below reads the Titanic dataset into a `DataFrame` called `df`. The second line calls the `.head()` method of `DataFrame`, which returns a new `DataFrame` consisting of just the first few rows (or "head") of the original.
df = pd.read_csv("/data301/data/titanic.csv")
df.head()
# _Jupyter Tip_: When you execute a cell in a Jupyter notebook, the result of the last line is automatically printed. To suppress this output, you can do one of two things:
#
# - Assign the result to a variable, e.g., `df_head = df.head()`.
# - Add a semicolon to the end of the line, e.g., `df.head();`.
#
# I encourage you to try these out by modifying the code above and re-running the cell!
# Now that the tabular data is in memory as a `DataFrame`, we can manipulate it by writing Python code.
# ## Observations
#
# Recall that **observations** are the rows in a tabular data set. It is important to think about what each row represents, or the **unit of observation**, before starting a data analysis. In the Titanic `DataFrame`, the unit of observation is a passenger. This makes it easy to answer questions about passengers (e.g., "What percentage of passengers survived?") but harder to answer questions about families (e.g., "What percentage of families had at least one surviving member?")
# What if we instead had one row per _family_, instead of one row per _passenger_? We could still store information about _how many_ members of each family survived, but this representation would make it difficult to store information about _which_ members survived.
#
# There is no single "best" representation of the data. The right representation depends on the question you are trying to answer: if you are studying families on the Titanic, then you might want the unit of observation to be a family, but if you need to know which passengers survived, then you might prefer that it be a passenger. No matter which representation you choose, it is important to be conscious of the unit of observation.
# ### The Row Index
#
# In a `DataFrame`, each observation is identified by an index. You can determine the index of a `DataFrame` by looking for the **bolded** values at the beginning of each row when you print the `DataFrame`. For example, notice how the numbers **0**, **1**, **2**, **3**, **4**, ... above are bolded, which means that this `DataFrame` is indexed by integers starting from 0. This is the default index when you read in a data set from disk into `pandas`, unless you explicitly specify otherwise.
# Since each row represents one passenger, it might be useful to re-index the rows by the name of the passenger. To do this, we call the `.set_index()` method of `DataFrame`, passing in the name of the column we want to use as the index. Notice how `name` now appears at the very left, and the passengers' names are all bolded. This is how you know that `name` is the index of this `DataFrame`.
df.set_index("name").head()
# _Warning_: The `.set_index()` method does _not_ modify the original `DataFrame`. It returns a _new_ `DataFrame` with the specified index. To verify this, let's look at `df` again after running the above code.
df.head()
# Nothing has changed! If you want to save the `DataFrame` with the new index, you have to explicitly assign it to a variable.
df_by_name = df.set_index("name")
df_by_name.head()
# If you do not want the modified `DataFrame` to be stored in a new variable, you can either assign the result back to itself:
#
# `df = df.set_index("name")`
#
# or use the `inplace=True` argument, which will modify the `DataFrame` in place:
#
# `df.set_index("name", inplace=True)`.
#
# These two commands should only be run once. If you try to run them a second time, you will get an error. Don't just take my word for it---create a cell below and try it! The reason for the error is: after the command is executed the first time, `name` is no longer a column in `df`, since it is now in the index. When the command is run again, `pandas` will try (and fail) to find a column called `name`.
#
# Thus, the interactivity of Jupyter notebooks is both a blessing and a curse. It allows us to see the results of our code immediately, but it makes it easy to lose track of the state, especially if you run a cell twice or out of order. Remember that Jupyter notebooks are designed to be run from beginning to end. Keep this in mind as you run other people's notebooks and as you organize your own notebooks.
# ### Selecting Rows
#
# Now that we have set the (row) index of the `DataFrame` to be the passengers' names, we can use the index to select specific passengers. To do this, we use the `.loc` selector. The `.loc` selector takes in a label and returns the row(s) corresponding to that index label.
#
# For example, if we wanted to find the data for the father of the Allison family, we would pass in the label "Allison, Master. Hudson Trevor" to `.loc`. Notice the square brackets.
df_by_name.loc["Allison, Master. Hudson Trevor"]
# Notice that the data for a single row is printed differently. This is no accident. If we inspect the type of this data structure:
type(df_by_name.loc["Allison, Master. Hudson Trevor"])
# we see that it is not a `DataFrame`, but a different data structure called a `Series`.
# `.loc` also accepts a _list_ of labels, in which case it returns multiple rows, one row for each label in the list. So, for example, if we wanted to select all 4 members of the Allison family from `df_by_name`, we would pass in a list with each of their names.
df_by_name.loc[[
"Allison, Master. Hudson Trevor",
"Allison, Miss. Helen Loraine",
"Allison, Mr. Hudson Joshua Creighton",
"Allison, Mrs. Hudson J C (Bessie Waldo Daniels)"
]]
# Notice that when there are multiple rows, the resulting data is stored in a `DataFrame`.
#
# The members of the Allison family happen to be consecutive rows of the `DataFrame`. If you want to select a consecutive set of rows, you do not need to type the index of every row that you want. Instead, you can use **slice notation**. The slice notation `a:b` allows you to select all rows from `a` to `b`. So another way we could have selected all four members of the Allison family is to write:
df_by_name.loc["Allison, Master. Hudson Trevor":"Allison, Mrs. Hudson J C (Bessie Waldo Daniels)"]
# This behavior of the slice may be surprising to you if you are a Python veteran. We will say more about this in a second.
# What if you wanted to inspect the 100th row of the `DataFrame`, but didn't know the index label for that row? You can use `.iloc` to **select by position** (in contrast to `.loc`, which **selects by label**).
#
# Remember that `pandas` (and Python in general) uses zero-based indexing, so the position index of the 100th row is 99.
df_by_name.iloc[99]
# You can also select multiple rows by position, either by passing in a list:
df_by_name.iloc[[99, 100]]
# or by using slice notation:
df_by_name.iloc[99:101]
# Notice the difference between how slice notation works for `.loc` and `.iloc`.
#
# - `.loc[a:b]` returns the rows from `a` up to `b`, _including_ `b`.
# - `.iloc[a:b]` returns the rows from `a` up to `b`, _not including_ `b`.
#
# So to select the rows in positions 99 and 100, we do `.iloc[99:101]` because we want the rows from position 99 up to 101, _not including 101_. This is consistent with the behavior of slices elsewhere in Python. For example, the slice `1:2` applied to a list returns one element, not two.
test = ["a", "b", "c", "d"]
test[1:2]
# ### What Makes a Good Index?
#
# Something odd happens if we look for "Mr. James Kelly" in this `DataFrame`. Although we only ask for one label, we get two rows back.
df_by_name.loc["Kelly, Mr. James"]
# This happened because there were two passengers on the Titanic named "James Kelly". In general, a good row index should uniquely identify observations in the data set. Names are often, but not always, unique. The best row indexes are usually IDs that are guaranteed to be unique.
#
# Another common row index is time. If each row represents a measurement in time, then it makes sense to have the date or the timestamp be the index.
# ## Variables
# Recall that **variables** are the columns in a tabular data set. They are the measurements that we make on each observation.
# ### Selecting Variables
#
# Suppose we want to select the `age` column from the `DataFrame` above. There are three ways to do this.
# 1\. Use `.loc`, specifying both the rows and columns. (_Note:_ The colon `:` is Python shorthand for "all".)
df.loc[:, "age"]
# 2\. Access the column as you would a key in a `dict`.
df["age"]
# 3\. Access the column as an attribute of the `DataFrame`.
df.age
# Method 3 (attribute access) is the most concise. However, it does not work if the variable name contains spaces or special characters, begins with a number, or matches an existing attribute of `DataFrame`. For example, if `df` had a column called `head`, `df.head` would not return the column because `df.head` already means something else, as we have seen.
# Notice that the data structure used to store a single column is again a `Series`, not a `DataFrame`. So single rows and columns are stored in `Series`.
# To select multiple columns, you would pass in a _list_ of variable names, instead of a single variable name. For example, to select both the `age` and `sex` variables, we could do one of the following:
# +
# METHOD 1
df.loc[:, ["age", "sex"]].head()
# METHOD 2
df[["age", "sex"]].head()
# -
# Note that there is no way to generalize attribute access (Method 3 above) to select multiple columns.
# ### The Different Types of Variables
# There is a fundamental difference between variables like `age` and `fare`, which can be measured on a numeric scale, and variables like `sex` and `home.dest`, which cannot.
#
# Variables that can be measured on a numeric scale are called **quantitative variables**. Just because a variable happens to contain numbers does not necessarily make it "quantitative". For example, consider the variable `survived` in the Titanic data set. Each passenger either survived or didn't. This data set happens to use 1 for "survived" and 0 for "died", but these numbers do not reflect an underlying numeric scale.
#
# Variables that are not quantitative but take on a limited set of values are called **categorical variables**. For example, the variable `sex` takes on one of two possible values ("female" or "male"), so it is a categorical variable. So is the variable `home.dest`, which takes on a larger, but still limited, set of values. We call each possible value of a categorical variable a "category". Although categories are usually non-numeric (as in the case of `sex` and `home.dest`), they are sometimes numeric. For example, the variable `survived` in the Titanic data set is a categorical variable with two categories (1 if the passenger survived, 0 if they didn't), even though those values are numbers. With a categorical variable, one common analysis question is, "How many observations are there in each category?".
#
# Some variables do not fit neatly into either category. For example, the variable `name` in the Titanic data set is obviously not quantitative, but it is not categorical either because it does not take on a limited set of values. Generally speaking, every passenger will have a different name (the two James Kellys notwithstanding), so it does not make sense to analyze the frequencies of different names, as one might do with a categorical variable. We will group variables like `name`, that are neither quantitative nor categorical, into an "other" category.
#
# Every variable can be classified into one of these three **types**: quantitative, categorical, or other. The type of the variable often dictates the kind of analysis we do and the kind of visualizations we make, as we will see later in this chapter.
#
# `pandas` tries to infer the type of each variable automatically. If every value in a column (except for missing values) can be cast to a number, then `pandas` will treat that variable as quantitative. Otherwise, the variable is treated as categorical. To see the type that Pandas inferred for a variable, simply select that variable using the methods above and look for its `dtype`. A `dtype` of `float64` or `int64` indicates that the variable is quantitative. For example, the `age` variable above had a `dtype` of `float64`, so it is quantitative. On the other hand, if we look at the `sex` variable,
df.sex
# its `dtype` is `object`, so `pandas` will treat it as a categorical variable. Sometimes, this check can yield surprises. For example, if you only looked the first few rows of `df`, you might expect `ticket` to be a quantitative variable. But if we actually look at its `dtype`:
df.ticket
# it appears to be an `object`. That is because there are some values in this column that contain non-numeric characters. For example:
df.ticket[9]
# As long as there is one value in the column that cannot be cast to a numeric type, the entire column will be treated as categorical, and the individual values will be strings (notice the quotes around even a number like 24160, indicating that `pandas` is treating it as a string).
df.ticket[0]
# If you wanted `pandas` to treat this variable as quantitative, you can use the `to_numeric()` function. However, you have to specify what to do for values like `'PC 17609'` that cannot be converted to a number. The `errors="coerce"` option tells `pandas` to treat these values as missing (`NaN`).
pd.to_numeric(df.ticket, errors="coerce")
# If we wanted to keep this change, we would assign this column back to the original `DataFrame`, as follows:
#
# `df.ticket = pd.to_numeric(df.ticket, errors="coerce")`.
#
# But since `ticket` does not appear to be a quantitative variable, this is not actually a change we want to make.
# There are also categorical variables that `pandas` infers as quantitative because the values happen to be numbers. As we discussed earlier, the `survived` variable is categorical, but the values happen to be coded as 1 or 0. To force `pandas` to treat this as a categorical variable, you can cast the values to strings. Notice how the `dtype` changes:
df.survived.astype(str)
# In this case, this is a change that we actually want to keep, so we assign the modified column back to the `DataFrame`.
df.survived = df.survived.astype(str)
# ## Summary
#
# - Tabular data is stored in a data structure called a `DataFrame`.
# - Rows represent observations; columns represent variables.
# - Single rows and columns are stored in a data structure called a `Series`.
# - The row index should be a set of labels that uniquely identify observations.
# - To select rows by label, we use `.loc[]`. To select rows by (0-based) position, we use `.iloc[]`.
# - To select columns, we can use `.loc` notation (specifying both the rows and columns we want, separated by a comma), key access, or attribute access.
# - Variables can be quantitative, categorical, or other.
# - Pandas will try to infer the type, and you can check the type that Pandas inferred by looking at the `dtype`.
# # Exercises
# **Exercise 1.** Consider the variable `pclass` in the Titanic data set, which is 1, 2, or 3, depending on whether the passenger was in 1st, 2nd, or 3rd class.
#
# - What type of variable is this: quantitative, categorical, or other? (_Hint:_ One useful test is to ask yourself, "Does it make sense to add up values of this variable?" If the variable can be measured on a numeric scale, then it should make sense to add up values of that variable.)
# - Did `pandas` correctly infer the type of this variable? If not, convert this variable to the appropriate type.
## YOUR CODE HERE
## BEGIN SOLUTION
print(df.head())
print("data type before",df.pclass.dtype)
df.pclass = df.pclass.astype("category")
print("data type after",df.pclass.dtype)
## END SOLUTION
# ## YOUR TEXT HERE
# ### BEGIN SOLUTION
# Should be categorical but it is numeric (int64 type). We should change it to categorical.
# ### END SOLUTION
# Exercises 2-7 deal with the Tips data set (`/data301/data/tips.csv`). You can learn more about this data set on the first page of [this reference](http://www.ggobi.org/book/chap-data.pdf).
# **Exercise 2.** Read in the Tips data set into a `pandas` `DataFrame` called `tips`.
#
# - What is the unit of observation in this data set?
# - For each variable in the data set, identify it as quantitative, categorical, or other, based on your understanding of each variable. Did `pandas` correctly infer the type of each variable?
## YOUR CODE HERE
## BEGIN SOLUTION
tips = pd.read_csv("/data301/data/tips.csv")
print(tips.head())
print(tips.dtypes)
## END SOLUTION
# ## YOUR TEXT HERE
# ### BEGIN SOLUTION
# Unit of observation is a single bill or trip to the restaurant.
#
# total_bill: numeric, tip: numeric, size is an integer numeric, and the rest are categorical. Though arguments could be made that smoker for instance could be binary. We could also make them explicitly categorical.
#
# Yes. Pandas has roughly inferred the correct type.
# ### END SOLUTION
# **Exercise 3.** Make the day of the week the index of the `DataFrame`.
#
# - What do you think will happen when you call `tips.loc["Thur"]`? Try it. What happens?
# - Is this a good variable to use as the index? Explain why or why not.
## YOUR CODE HERE
## BEGIN SOLUTION
tips = tips.set_index("day")
print(tips.head())
print(tips.loc["Thur"])
## END SOLUTION
# ## YOUR TEXT HERE
# ### BEGIN SOLUTION
# The index is reasonable depending on how you plan to study the data. Often we want our index to be unique, so in that case `day` is not appropriate.
# ### END SOLUTION
# **Exercise 4.** Make sure the index of the `DataFrame` is the default (i.e., 0, 1, 2, ...). If you changed it away from the default in the previous exercise, you can use `.reset_index()` to reset it.
#
# - How do you think `tips.loc[50]` and `tips.iloc[50]` will compare? Now try it. Was your prediction correct?
# - How do you think `tips.loc[50:55]` and `tips.iloc[50:55]` will compare? Now try it. Was your prediction correct?
# YOUR CODE HERE
## BEGIN SOLUTION
tips = tips.reset_index()
print("loc[50]")
print(tips.loc[50])
print("iloc[50]")
print(tips.iloc[50])
print("loc[50:55]")
print(tips.loc[50:55])
print("iloc[50:55]")
print(tips.iloc[50:55])
## END SOLUTION
# ## YOUR TEXT HERE
# ### BEGIN SOLUTION
# As you can see, there are some small differences of note for this dataset, which include the number of rows returned is one less with `iloc[50:55]`. In general, they would be really different because one is using the `index` and one is using the numerical indices.
# ### END SOLUTION
# **Exercise 5.** How do you think `tips.loc[50]` and `tips.loc[[50]]` will compare? Now try it. Was your prediction correct?
## YOUR CODE HERE
### BEGIN SOLUTION
print(tips.loc[50])
print(tips.loc[[50]])
print(type(tips.loc[50]),type(tips.loc[[50]]))
### END SOLUTION
# ## YOUR TEXT
# ### BEGIN SOLUTION
# As you can see, the biggest difference is the data type returned, which really matters for subsequent calls. Sometimes you would like the Series object and other times you want the data frame.
# ### END SOLUTION
# **Exercise 6.** What data structure is used to represent a single column, such as `tips["total_bill"]`? How could you modify this code to obtain a `DataFrame` consisting of just one column, `total_bill`?
## YOUR CODE HERE
### BEGIN SOLUTION
print(tips["total_bill"])
print(type(tips["total_bill"]))
print(tips[["total_bill"]])
print(type(tips[["total_bill"]]))
### END SOLUTION
# **Exercise 7.** Create a new `DataFrame` from the Tips data that consists of just information about the table (i.e., whether or not there was a smoker, the day and time they visited the restaurant, and the size of the party), without information about the check or who paid.
#
# (There are many ways to do this. How many ways can you find?)
## YOUR CODE HERE
### BEGIN SOLUTION
print("No single solution. Open ended.")
### END SOLUTION
# ### Reflection
# Based on your experiments with the labs this week, share something new that had not been mentioned in class such as a tidbit of information.
|
0baae2da4abde3904fe7935aec0270b37d5f9ca9 | ArunaRanjitha/guvi | /code/Five.py | 118 | 3.609375 | 4 | p,q,r=input().split()
max(p,q,r)
if(p>q) and (p>r):
print(p)
elif(q>p) and (q>r):
print(q)
else:
print(r)
|
da8c4755834d9aabbf3019a6439c6c1b04d4af82 | thomasmcclellan/pythonfundamentals | /11.02_OOP_attributesAndMethods.py | 1,444 | 4.5 | 4 | # Attributes are characteristics of an object
# Methods are operations we can perform on an object
class Dog():
def __init__(self,breed,name): #Methods look likes functions within the class and have the __#__ syntax
self.breed = breed #Attribute involves self.#
self.name = name #self operates similarly to the 'this' keyword in JS
my_dog = Dog('Lab','Sammy') #Now that we have the attribute of breed, we need to supply said attribute
print(my_dog.breed) #Lab
print(my_dog.name) #Sammy
# Class Object Attributes (COA)
# Goes outside any methods at top to pertain to all methods
class Dog():
# COA
species = 'Mammal'
def __init__(self,breed,name):
self.breed = breed
self.name = name
my_dog = Dog('Lab','Sammy')
print(my_dog.breed) #Lab
print(my_dog.name) #Sammy
print(my_dog.species) #Mammal
# Methods => functions defined within the body of a class
# Used to perform operations within the attributes of objects and are essential in incapsulation concepts of the OOP paradigm => essential in dividing the responsibilities in programming
# Methods are the whole point in creating your own object
class Circle():
pi = 3.14
def __init__(self,radius = 1): #If no radius is given, it defaults at 1
self.radius = radius
def area(self):
return self.radius * self.radius * Circle.pi
def set_radius(self,new_r):
self.radius = new_r
myc = Circle(3)
myc.set_radius(999)
print(myc.area()) |
607d3dd3832d7e114afde579e4f2546e1d10aa6e | rugbyy/AlgorithmChallenges | /fizzbuzz/fizzbuzz.py | 422 | 3.578125 | 4 | def fizz_buzz(self, num):
if num == 0: # seems this should have been < 1 instaed of == 0. need to read instructions carefully
raise ValueError
if not num:
raise TypeError
num_list = []
for n in range(1,16):
if n % 3 == 0 and n % 5 == 0:
num_list.append("FizzBuzz")
elif n % 5 == 0:
num_list.append("Buzz")
elif n % 3 == 0:
num_list.append("Fizz")
else:
num_list.append(str(n))
return num_list |
fe1ecf93898bcf75553daf0b914c336647bada4c | Daishijun/InterviewAlgorithmCoding | /ZuoShenBook/stringQ/statisticString.py | 1,304 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Date : 2019/4/20
# @Time : 18:44
# @Author : Daishijun
# @File : statisticString.py
# Software : PyCharm
'''
字符串的统计字符串
'''
def getCountString(string):
if not string:
return ''
res = string[0]
num =1
for i in range(1, len(string)):
if string[i] == string[i-1]:
num +=1
else:
res = res + '_'+str(num)+'_'+string[i]
num = 1
return res+'_'+str(num)
'''给第一个字符串的统计字符串,再给一个整数index,返回统计字符串代表的原字符串上index位置上的字符
'''
def getCharAt(cstr, index):
if not cstr:
return 0
stage = True
cur = ''
num = 0
ssum = 0
for i in range(len(cstr)):
if cstr[i] == '_':
stage = not stage
elif stage:
ssum +=num
if ssum > index:
return cur
num = 0
cur = cstr[i]
else:
num = num*10+ord(cstr[i])-ord('0')
ssum = ssum*10 + ord(cstr[i])-ord('0')
if ssum>index:
return cur
else:
return 0
if __name__ == '__main__':
string = 'aaabbadddffc'
print(getCountString(string))
cstr = getCountString(string)
print(getCharAt(cstr, 3))
|
09682bcc29af9bec3b191578cf9d11583960c991 | bhavisheythapar/LeetCode | /groupAnagrams/groupAnagrams.py | 308 | 3.984375 | 4 | def groupAnagrams (str):
dict={}
for element in str:
sorted_word=str(sorted(i))
if sorted_word not in dict:
dict[sorted_word]=[]
dict[sorted_word].append(i)
return dict.values()
ex1 = ["eat", "tea", "tan", "ate", "nat", "bat"]
str="abcde"
groupAnagrams(ex1) |
f89a270de40aa5ab9195c691e171680683a26106 | aos/advent | /2018/day06/part_1.py | 2,466 | 3.625 | 4 | # Day 6 - Puzzle 1
# What is the size of the largest area?
import collections
def largest_area(inp_arr):
areas = collections.defaultdict(int)
max_x, max_y = _grid_size(inp_arr)
grid = _generate_grid(max_x, max_y)
populated = _populate_grid(inp_arr, grid, max_x, max_y)
for y, row in enumerate(populated):
for x, cell in enumerate(row):
if len(cell) == 1:
areas[cell[0]] += 1
borders = {}
for y, row in enumerate(populated):
for x, cell in enumerate(row):
if len(cell) == 1:
if x == 0 or y == 0 or x == max_x or y == max_y:
borders[cell[0]] = True
return max({k: areas[k] for k in (set(areas) - set(borders))}.values())
def _populate_grid(inp_arr, grid, max_x, max_y):
for y in range(max_y + 1):
for x in range(max_x + 1):
# Calculate manhattan distance for each cell to the input_array
# And use the one with the minimum distance
min_point = None
m = 1e9
for point in inp_arr:
d = _d_manh((x, y), point)
if d < m:
m = d
min_point = point
grid[y][x] = [min_point]
elif d == m:
grid[y][x].append(point)
return grid
def _generate_grid(x, y):
return [[[] for i in range(x + 1)] for i in range(y + 1)]
def _grid_size(inp):
max_x = 0
max_y = 0
for x, y in inp:
if x > max_x:
max_x = x
if y > max_y:
max_y = y
return max_x, max_y
def _d_manh(p_1, p_2):
"""
Calculates the manhattan distance between 2 points
Args:
p_1 (tuple[int]): The first point
p_2 (tuple[int]): The second point
Returns:
int: The sum of taking the absolute value of
p_1_x - p_2_x and p_1_y - p_2_y
"""
x_1, y_1 = p_1
x_2, y_2 = p_2
return abs(x_1 - x_2) + abs(y_1 - y_2)
TEST_INPUT = [
(1, 1),
(1, 6),
(8, 3),
(3, 4),
(5, 5),
(8, 9)
]
if __name__ == '__main__':
# Tests
assert(_d_manh(TEST_INPUT[0], TEST_INPUT[1]) == 5)
assert(_grid_size(TEST_INPUT) == (8, 9))
assert(largest_area(TEST_INPUT) == 17)
print('All tests passed!')
with open('./day06-input.txt') as f:
a = [tuple(int(i) for i in line.strip().split(',')) for line in f]
print(largest_area(a))
|
6cb5ec8533c242d9a80e6408fd35a1b06d4317e2 | Md-Saif-Ryen/roc-pythonista | /OOP/Calculator.py | 470 | 3.90625 | 4 | class Calculator:
# Write methods to add(), subtract(), multiply() and divide()
def add(self, num1, num2):
self.add = num1 + num2
return self.add
def subtract(self, num1, num2):
self.subtract = num1 - num2
return self.subtract
def multiply(self, num1, num2):
self.multiply = num1 * num2
return self.multiply
def divide(self, num1, num2):
self.divide = num1 / num2
return self.divide
|
a2d39b6382d66687417e4d335798e25f4762f41c | tripathyas/Online-Hackathon | /codeutility.py | 388 | 3.515625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 2.7
A.sort()
i = 0
num = 1
while i < len(A) and A[i] <= 0:
i += 1
while i < len(A):
if A[i] == num:
num+=1
elif A[i] > num:
break
i += 1
return num |
0b8bce1a911df9858fd81fb20902dcdd76545b5e | kbtania/Labs | /lab_map_filter_reduce/Tasks/reduce_filter2.py | 434 | 3.75 | 4 | # Дано масив (список) елементів цілого типу.
# Знайти суму додатних елементів.
from functools import reduce
count = int(input('Count el: '))
previous_list = [int(input('Enter element: ')) for x in range(count)]
positive_num = list(filter(lambda x: x > 0, previous_list))
positive_sum = reduce(lambda positive_sum, x: positive_sum + x, positive_num, 0)
print(positive_sum)
|
0a39d7e8fe212f64f06a1c50090714b50567b231 | xiangcao/Leetcode | /Python_leetcode/99_recover_binary_search_tree.py | 2,119 | 3.875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
firstMisplaced = secondMisplaced = None
import sys
lastVisited = TreeNode(-sys.maxint-1)
#Wrong.
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
self.recoverTree(root.left)
if self.lastVisited > root.val:
if not self.firstMisplaced:
self.firstMisplaced = root
else:
self.secondMisplaced = root
self.lastVisited = root.val
self.recoverTree(root.right)
#think about it. the code below will be executed multile times.
if self.firstMisplaced and self.secondMisplaced:
self.firstMisplaced.val, self.secondMisplaced.val = self.secondMisplaced.val, self.firstMisplaced.val
#Accepted
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self._recoverTree(root)
if self.firstMisplaced and self.secondMisplaced:
self.firstMisplaced.val, self.secondMisplaced.val = self.secondMisplaced.val, self.firstMisplaced.val
def _recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
self._recoverTree(root.left)
if self.lastVisited.val > root.val and not self.firstMisplaced:
self.firstMisplaced = self.lastVisited
if self.lastVisited.val > root.val and self.firstMisplaced:
self.secondMisplaced = root
self.lastVisited = root
self._recoverTree(root.right)
sol = Solution()
node= TreeNode(2)
node.right = TreeNode(1)
sol.recoverTree(root)
|
1b0404aa3de9a6d98a360008e95c2d8164ba1465 | sailakshmi-mk/pythonprogram1 | /venv/co4/5. Class publisher.py | 907 | 4.125 | 4 | class Publisher:
"information about books"
def __init__(self, pubname):
self.pubname = pubname
def display(self):
print("Publisher Name:", self.pubname)
class Book(Publisher):
def __init__(self, pubname, title, author):
Publisher.__init__(self, pubname)
self.title = title
self.author = author
def display(self):
print("Title: ", self.title)
print("Author: ", self.author)
class Python(Book):
def __init__(self, pubname, title, author, price, no_of_pages):
Book.__init__(self, pubname, title, author)
self.price = price
self.no_of_pages = no_of_pages
def display(self):
print("Title: ", self.title)
print("Author: ", self.author)
print("Price: ", self.price)
print("Number of pages: ", self.no_of_pages)
s1 = Python("ak books", "Taming Python By Programming ", ' Jeeva Jose ', 200, 219)
s1.display() |
6a85e507b567026f9e6ec7734020b8e2a7ba7f17 | neerajjadhav3012/Programming | /Stack_Queue/BalancedParenthesesCheck.py | 1,614 | 4.25 | 4 |
# coding: utf-8
# # Balanced Parentheses Check
#
# ## Problem Statement
#
# Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character than these, no spaces words or numbers. As a reminder, balanced parentheses require every opening parenthesis to be closed in the reverse order opened. For example ‘([])’ is balanced but ‘([)]’ is not.
#
#
# You can assume the input string has no spaces.
#
# ## Solution
#
# Fill out your solution below:
# In[15]:
def balance_check(s):
starting = ("[", "{", "(")
pairs = [("[","]"), ("{","}"), ("(", ")") ]
seen = []
for char in s:
if char in starting:
seen.append(char)
else:
if seen == []:
return False
if (seen.pop(), char) not in pairs:
return False
return len(seen) == 0
# In[16]:
balance_check('[]')
# In[17]:
balance_check('[](){([[[]]])}')
# In[18]:
balance_check('[](){([[[]]])}(')
# # Test Solution
# In[19]:
"""
RUN THIS CELL TO TEST YOUR SOLUTION
"""
from nose.tools import assert_equal
class TestBalanceCheck(object):
def test(self,sol):
assert_equal(sol('[](){([[[]]])}('),False)
assert_equal(sol('[{{{(())}}}]((()))'),True)
assert_equal(sol('[[[]])]'),False)
print("ALL TEST CASES PASSED")
# Run Tests
t = TestBalanceCheck()
t.test(balance_check)
#
|
32546ed9a098998b6290208aa4050f85666fc441 | habahut/CS112-Spring2012 | /Friday Classes/core/input.py | 2,178 | 3.640625 | 4 | #dont need the thing at the top because this is not an executable file
import pygame
from pygame.locals import *
class KeyDownListener(object):
def on_keydown(self,event):
pass
def on_keyup(self, event):
pass
class MouseListener(object):
def on_click(self,event): pass
def on_motion(self,event): pass
class InputManager(object):
def __init__(self):
self._key = []
self._mouse = []
def add_listener(self, listener):
self._keydown.append(listener)
def add_mouse_listener(self,listener):
self._mouse.append(listener)
"""
def old_add_listener(self):
for key in keys:
if key not in self._listeners:
self._listeners[key] = []
self._listeners[key].appened(listener)
####
# key : objects listening for that key to be pressed
"""
def handle_event(self,event):
if event.type == KEYDOWN
for listener in self._key:
listener.on_keydown(event)
elif event.type == KEYUP:
for listener in self._key:
listener.on_keyup(event)
elif event.type == MOUSEBUTTONDOWN:
for listener in self._mouse:
listener.on_buttondown(event)
elif event.type == MOUSEBUTTONUP:
for listener in self._mouse:
listener.on_buttonup(event)
elif event.type == MOUSEMOTION:
for listener
# for each key that is pressed, call key_down on the objects
# that are going to be affected by keypress
"""
if event.type == KEYDOWN and event.key == K_SPACE:
## dont want this:
#print "game.player.jump()"
#print "sounds.play(jump)"
"want to call the methods from somewhere else so the"
"input manager doesn't need to have access to every other class"
elif event.type == KEYDOWN and event.key == K_RETURN:
## also dont want this:
#print "game.pause()"
#print "game.openMenu()"
#print "sounds.play(pause)"
"""
|
cbd1b9111b4bfc61488027a5aa594fc9a536fd8d | linzer0/karel-python | /karel.py | 3,660 | 3.734375 | 4 | from gui import Gui
from tkinter import *
class World():
def print_world(self):
for i in self.world:
print(*i)
print('\n')
def get_karel(self):
x = -1
y = -1
for i in range(len(self.world)):
for j in range(len(self.world[i])):
if self.world[i][j] == 'K':
x = i
y = j
break
return (x, y)
def __init__(self, world):
self.world = world
class Robot():
##############
# Directions #
# 0 - down #
# 1 - right #
# 3 - left #
# 2 - up #
##############
def loop(self):
self.gui.window.mainloop()
def __init__(self):
self.block = 0
self.gui = Gui(Tk())
while(self.gui.world == ""): #There we are waiiting for attaching the map
self.gui.window.update()
while(self.gui.run_pressed == False): #There we are waiiting for attaching the map
self.gui.window.update()
self.world = World(self.gui.world)
tx, ty = self.world.get_karel()
#self.world.print_world()
self.direction = 1
self.x = tx
self.y = ty
def move(self):
oldx = self.x
oldy = self.y
if self.front_is_clear() == False:
self.gui.bug()
else:
if self.direction == 0:
self.x += 1;
if self.direction == 2:
self.x -= 1;
if self.direction == 1:
self.y += 1;
if self.direction == 3:
self.y -= 1;
self.world.world[oldx][oldy] = self.block; #Restoring previous box in WORLD
self.gui.render_object(self.block, oldx, oldy) #Restoring previous box in GUI
self.block = self.world.world[self.x][self.y] #Remembering previous and current box
#self.world.world[self.x][self.y] = 'K'; #Moving Karel in World
self.gui.render_object('K', self.x, self.y) #Moving Karel to next box GUI
for i in range(int(15000 / self.gui.speed)):
self.gui.window.update()
def turn_left(self):
self.direction = (self.direction + 1) % 4;
self.gui.direct = self.direction
def next_possition(self):
curx = self.x
cury = self.y
if self.direction == 0:
curx += 1;
if self.direction == 2:
curx -= 1;
if self.direction == 1:
cury += 1;
if self.direction == 3:
cury -= 1;
return (curx, cury)
def front_is_clear(self):
futx, futy = self.next_possition()
height = len(self.world.world)
width = len(self.world.world[0])
if futx >= height or futy >= width or self.world.world[futx][futy] == -1:
return False
return True
def beepers_present(self):
return int(self.block) >= 1;
def pick_beeper(self):
if self.beepers_present() == True:
self.block = max(self.world.world[self.x][self.y] - 1, 0)
self.world.world[self.x][self.y] = self.block;
#self.gui.render_object(self.world.world[self.x][self.y], self.x, self.y)
self.gui.render_object('K', self.x, self.y)
else:
self.gui.bug()
def put_beeper(self):
self.world.world[self.x][self.y] += 1
self.block = self.world.world[self.x][self.y]
self.gui.render_object(self.block, self.x, self.y)
self.gui.render_object('K', self.x, self.y)
def wait(self):
self.gui.window.mainloop()
|
c2d92dc6c6e4f8b291ad08da61c177b9423ca11c | Victoriasaurio/Exercises | /Mutante.py | 2,358 | 3.734375 | 4 | x = int(input("Ingrese el tamaño del array --> "))
adn = input("Ingresar la secuencia del ADN --> ")
_array = []
_adn_array = []
# STRING-ARRAY
for a in adn:
_array.append(a)
c = 0
i = 0
h = x
# MATRIZ
while c < x:
_adn_array.append(_array[i:h])
i += x
h += x
c +=1
#HORIZONTAL
eje_y = 0
eje_x = 0
contador_A = 0
contador_C = 0
contador_G = 0
contador_T = 0
_igual = 0
_general = 0
while eje_x < x:
while eje_y < x:
if _adn_array[eje_x][eje_y] == 'A':
contador_A += 1
elif _adn_array[eje_x][eje_y] == 'C':
contador_C += 1
elif _adn_array[eje_x][eje_y] == 'G':
contador_G += 1
elif _adn_array[eje_x][eje_y] == 'T':
contador_T += 1
eje_y += 1
if contador_A >= 4 or contador_C >= 4 or contador_G >= 4 or contador_T >= 4:
_general += 1
contador_A = 0
contador_C = 0
contador_G = 0
contador_T = 0
eje_y = 0
eje_x += 1
#VERTICAL
eje_y = 0
eje_x = 0
contador_A = 0
contador_C = 0
contador_G = 0
contador_T = 0
while eje_x < x:
while eje_y < x:
if _adn_array[eje_y][eje_x] == 'A':
contador_A += 1
elif _adn_array[eje_y][eje_x] == 'C':
contador_C += 1
elif _adn_array[eje_y][eje_x] == 'G':
contador_G += 1
elif _adn_array[eje_y][eje_x] == 'T':
contador_T += 1
eje_y += 1
if contador_A >= 4 or contador_C >= 4 or contador_G >= 4 or contador_T >= 4:
_general += 1
contador_A = 0
contador_C = 0
contador_G = 0
contador_T = 0
eje_y = 0
eje_x += 1
#DIAGONAL
eje_x = 0
diagonal = 0
letra = ''
while eje_x < x:
if letra != _adn_array[eje_x][eje_x]:
letra = _adn_array[eje_x][eje_x]
diagonal = 1
else:
diagonal += 1
if diagonal >= 4:
_general += 1
diagonal = 1
eje_x += 1
if _general > 1:
print('Es mutante')
# AAAAAAGGGGACCCCATTTTACGTAATGGCAC
# TAAAAATGGGACTCCATTATACGTTATGGCAC
#['A', 'A', 'A', 'A', 'A']
#['G', 'G', 'G', 'G', 'G']
#['C', 'C', 'C', 'C', 'C']
#['T', 'T', 'T', 'T', 'T']
#['A', 'C', 'G', 'T', 'A']
# [
# ['T', 'A', 'A', 'A', 'A'],
# ['A', 'T', 'G', 'G', 'G'],
# ['A', 'C', 'T', 'C', 'C'],
# ['A', 'T', 'T', 'T', 'T'],
# ['A', 'C', 'G', 'T', 'T']]
|
be031abb14007940c96be57f24e5184fdfdc575d | bikennepal/Python-Basic | /user_input.py | 134 | 4.1875 | 4 | # input function
# user input
name=input("enter your name")
print("This is your name" + name)
#Input is always taken as string |
9983abbb454982bd007ef6850fa38184256d5475 | greenblues1190/Python-Algorithm | /LeetCode/9. 트리/310-minimum-height-trees.py | 1,769 | 4.09375 | 4 | # https://leetcode.com/problems/minimum-height-trees/
# A tree is an undirected graph in which any two vertices are connected by exactly
# one path. In other words, any connected graph without simple cycles is a tree.
# Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges
# where edges[i] = [ai, bi] indicates that there is an undirected edge between
# the two nodes ai and bi in the tree, you can choose any node of the tree as the root.
# When you select a node x as the root, the result tree has height h.
# Among all possible rooted trees, those with minimum height (i.e. min(h))
# are called minimum height trees (MHTs).
# Return a list of all MHTs' root labels. You can return the answer in any order.
# The height of a rooted tree is the number of edges on the longest downward path
# between the root and a leaf.
from typing import List
import collections
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2:
return range(n)
# convert edges to graph
graph = collections.defaultdict(list)
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
# find inital leaves
leaves = []
for key in range(n):
if len(graph[key]) == 1:
leaves.append(key)
# remove leaves until nodes less than 2 left
while n > 2:
n -= len(leaves)
new_leaves = []
for leaf in leaves:
neighbor = graph[leaf].pop()
graph[neighbor].remove(leaf)
if len(graph[neighbor]) == 1:
new_leaves.append(neighbor)
leaves = new_leaves
return leaves
|
032e8138940a597508a66bd2f53025b6b00d5162 | reentrant/python_exercises | /book_learning/list_permutations.py | 1,841 | 4.15625 | 4 | #!/usr/bin/python -tt
# Source:
# LEARNING TO PROGRAM WITH PYTHON
# Richard L. Halterman
"""
Example: List Permutations
"""
from itertools import permutations
DEBUG = True
counter = 0
def permute(prefix, suffix):
'''
Recursively shifts all the elements in suffix into prefix
'''
global counter
counter += 1
if DEBUG:
print("\tpermute args: ", "-" * 10, end = ' ')
print(counter, prefix, suffix)
suffix_size = len(suffix)
if suffix_size == 0:
print (prefix)
else:
for i in range(0, suffix_size):
new_pref = prefix + [suffix[i]]
if DEBUG:
print(i," new_pre: -->", prefix, " ", [suffix[i]])
# print(new_pref, end = ' ')
new_suff = suffix[:i] + suffix[i + 1:]
if DEBUG:
print(i, "new_suff: -->", suffix[:i], suffix[i + 1:])
# print(new_suff)
permute(new_pref, new_suff)
def tab(n):
print('\t' * n, end='')
def trace_permute(prefix, suffix, depth):
suffix_size = len(suffix)
if suffix_size == 0:
pass
else:
for i in range(0, suffix_size):
new_pre = prefix + [suffix[i]]
new_suff = suffix[:i] + suffix[i + 1:]
tab(depth)
print(new_pre, new_suff, sep = ':')
trace_permute(new_pre, new_suff, depth + 1)
def print_permutations(lst):
'''
Calls the recursive permute function
'''
permute([], lst)
# Define a main() function
def main():
print_permutations(list('abc'))
print("=" * 20)
trace_permute([], list("abc"), 0)
print("=" * 20)
name = 'iter'
for p in permutations(list(name)):
print(p)
print("=" * 20)
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
|
78f13ae8cccfb13c7bcecc9bf11a38c4e966611b | CRFranco/TWELVE-MONKEYS | /versao2_entities/macacos.py | 2,233 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
'''
Created on 24 de mai de 2016
@author: cristiano.franco
'''
from random import randint
class Macaco :
_descricao = None
_life = 0
def __init__(self, descricao):
self._descricao = descricao
self._life = 5
def get_descricao(self):
return self.__descricao
def get_life(self):
return self.__life
def del_descricao(self):
del self.__descricao
def del_life(self):
del self.__life
def comer(self, alimento):
if(len(alimento) > 0):
print("comendo ", type(alimento[0]))
print("sobraram ",len(alimento)-1, type(alimento[0]))
alimento.pop(0)
self._life += 1
print("aumentando a vida do", type(self), " para", self._life)
else:
self._life -= 1
print("diminuindo a vida do", type(self), " para", self._life)
descricao = property(get_descricao, del_descricao, "descricao's docstring")
life = property(get_life, del_life, "life's docstring")
class MacacoPrego(Macaco):
pass
class MicoSagui(Macaco):
pass
class MacacoZumbi(Macaco):
def comer(self, alimento):
''' O primeiro laço serve para impedir que um macaco zumbi coma a si mesmo, quando so existirem dois macacos
e um deles é zumbi e o indice do alimento caia em si mesmo.
'''
indice = 0;
while(self == alimento[indice] and len(alimento) > 1):
indice = randint(0, len(alimento)-1)
if(len(alimento) > 0 and self != alimento[indice]):
print("comendo ", type(alimento[indice]))
print("sobraram ",len(alimento)-1, type(alimento[indice]))
alimento.pop(indice)
self._life += 1
print("aumentando a vida do", type(self), " para", self._life)
else:
self._life -= 1
print("diminuindo a vida do", type(self), " para", self._life)
|
b4793b2b916119635c0df76b48690b24dbd10c62 | carlos2020Lp/progra-utfsm | /guias/2012-2/septiembre-3/fibo-menores.py | 229 | 3.84375 | 4 | m = int(raw_input('Ingrese m: '))
print 'Los numeros de Fibonacci menores que', m, 'son:'
anterior = 0
actual = 1
print 0
while actual < m:
print actual
suma = anterior + actual
anterior = actual
actual = suma
|
ddb3bce7f4a1d53a386f06f83150d6a97cd020ef | therouterninja/Studies | /hackerrank/algorithms/03_strings/01_pangrams.py | 299 | 4.03125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
mystring = raw_input()
all_values = set()
total = 0
for char in mystring:
all_values.add(char.lower())
for value in all_values:
total += ord(value)
if total == 2879:
print "pangram"
else:
print "not pangram" |
c06602210d9435abc93d044504a3cbcaaa67504e | enthusiasm99/crazypython | /02/P43-ternary_operator_test.py | 374 | 3.765625 | 4 | a = 5
b = 3
st = 'a大于b' if a > b else 'a小于b'
print(st)
st = print('crazyit'), 'a大于b' if a > b else 'a小于b'
print(st)
st = print('crazyit'); x = 20 if a>b else 'a不大于b'
print(st)
print(x)
c = 5
d = 5
print('c大于d' if c>d else ('c小于d' if c<d else 'c等于d'))
print('c大于d') if c>d else (print('c小于d') if c<d else print('c等于d')) |
44afd7bd1f0ce0421d99a4868dce566036a6581f | deepshikhadas20/Data-visualization | /Data-visualization-master copy/Teacher refrence/plot.py | 215 | 3.59375 | 4 | import pandas as pd
import plotly.express as px
df = pd.read_csv("line_chart_csv")
fig = px.line(df,x="Year",y="Per capita income", color="Country",
title="per Capita")
fig.show() |
5503fbdc6bf437f0c22b557f4ae8188258e079b8 | 1412qyj/PythonAdvanced | /code/2.python高级知识-多进程/filesCopy.py | 4,340 | 3.71875 | 4 | # 完成将一个文件夹和文件复制到另一个文件夹中
import os
import multiprocessing
# 1.定义一个文件夹复制器的类
import time
class FolderCopy(object):
def __init__(self):
self.file_names = []
self.file_name = None
self.source_file_name = None
self.dest_file_name = None
self.queue = None
self.source_folder_path = input("输入原文件地址:")
self.source_folder_name = input("输入原文件名:")
self.dest_folder_path = input("输入存文件的地址:")
self.dest_folder_name = r"%s/%s[副本]" % (self.dest_folder_path, self.source_folder_name)
# self.source_file_name = r"%s\%s" % (self.old_folder_path, self.old_folder_name)
# self.new_folder = r"%s\%s[副本]" % (self.new_folder_path, self.old_folder_name)
def get_file_names(self):
"""获取原文件夹中文件列表"""
if os.path.exists(self.source_folder_path): # 判断原文件是否存在
self.file_names = os.listdir(self.source_folder_path)
else:
print("源文件不存在")
return self.file_names
def make_folder(self):
"""根据原有文件夹创建新的文件夹"""
# 判断该文件夹是否存在
if os.path.exists(self.dest_folder_name):
print("该文件夹存在")
self.dest_folder_name = None
else:
os.mkdir(self.dest_folder_name)
def copy_file(self, *args):
"""将原有文件夹中文件复制到新文件夹中"""
queue, file_name, source_file_name, dest_file_name = args
print("%s正在复制文件%s" % (os.getpid(), file_name))
# 复制原有文件
try:
with open(source_file_name, "rb") as f:
content = f.read()
except Exception as e:
content = None
print("读取%s文件有%s问题" % (file_name, e))
write_ok = None
# 判断读取出来的值是否为空
if content is not None:
try:
with open(dest_file_name, "wb") as f:
f.write(content)
except Exception as e:
write_ok = False
print("写入%s文件有%s问题" % (file_name, e))
if write_ok is False:
queue.put("%s-文件复制有问题" % file_name)
else:
queue.put("%s" % file_name)
else:
queue.put("%s-文件复制有问题" % file_name)
def display(self):
"""电子显示"""
all_file_num = len(self.file_names)
while True:
file_name = self.queue.get(timeout=2)
if file_name.find("-") != -1:
file_name = file_name.split("-")[0]
if file_name in self.file_names:
self.file_names.remove(file_name)
copy_rate = (all_file_num - len(self.file_names)) * 100 / all_file_num
print("\r%.2f...(%s)" % (copy_rate, file_name) + " " * 50, end="")
if copy_rate >= 100:
break
def run(self):
# 创建文件夹
self.make_folder()
# 获取文件列表
self.file_names = self.get_file_names()
print(self.file_names)
# 创建进程对象
pool = multiprocessing.Pool(2)
self.queue = multiprocessing.Manager().Queue() # 进程队列用来存数据
# 开始建任务
for file_name in self.file_names:
# 向进程池中添加任务
self.file_name = file_name
self.source_file_name = r"%s/%s" % (self.source_folder_path, self.file_name)
self.dest_file_name = r"%s/%s" % (self.dest_folder_name, self.file_name)
pool.apply_async(self.copy_file,
args=(self.queue, self.file_name, self.source_file_name, self.dest_file_name,))
pool.close() # 禁止再添加新任务
self.display()
print()
if __name__ == '__main__':
folder_copy = FolderCopy()
folder_copy.run()
# /Users/toby/Downloads/PythonAdvanced/code/2.python高级知识-多进程/案例文件夹/原文件夹
# 原文件夹
# /Users/toby/Downloads/PythonAdvanced/code/2.python高级知识-多进程/案例文件夹/复制到的文件夹
|
b59c23d5f82e155a207339d374c2be6d13b2c770 | upadhyay-arun98/PythonForME | /Basic Python Programming/1. Input-Process-Output/computeLoan.py | 427 | 4.21875 | 4 |
annual_rate = float(input("Enter Yearly Interest Rate\n"))
monthly_rate = annual_rate/1200
years = int(input("Enter number of years, for example 5: \n"))
loan_amount = float(input("Enter loan amount, example 120000.95 \n"))
EMI = loan_amount * monthly_rate / (1 - 1/(1 + monthly_rate)**(years*12))
total_payment = EMI * years * 12
print("The monthly payment is", EMI)
print("The total payment is", total_payment) |
9dac8e190ab71b6da89e4269ecd0e3f081ff43a5 | congyingTech/Basic-Algorithm | /medium/clone-graph.py | 609 | 3.515625 | 4 | # encoding:utf-8
"""
给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。
class Node {
public int val;
public List<Node> neighbors;
}
"""
# Definition for a Node.
class Node(object):
def __init__(self, val = 0, neighbors = []):
self.val = val
self.neighbors = neighbors
class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
if __name__ == "__main__":
pass
|
b8a730d4c5a0f950f6806f53474c73e61f5938ee | davll/practical-algorithms | /algo.py/algo/tree/segment_tree.py | 1,913 | 3.5625 | 4 | # Segment Tree
# 1. The root represents the whole array A[0:N]
# 2. Each leaf represents a single element A[i]
# 3. The internal nodes represents the union of elementary intervals A[i:j]
import math
class SegmentTree:
def __init__(self, arr):
n = len(arr)
ns = 2 * (2 ** int(math.ceil(math.log2(n)))) - 1
st = [None] * ns
def fill_data(ss, se, si):
# check if arr[ss:se] is a one-element array
if se - ss == 1:
st[si] = arr[ss]
else:
mid = (ss + se-1) // 2
a1 = fill_data(ss, mid+1, si * 2 + 1)
a2 = fill_data(mid+1, se, si * 2 + 2)
st[si] = a1 + a2
return st[si]
fill_data(0, n, 0)
self.storage = st
self.n = n
# sum of A[qs:qe]
def sum(self, qs, qe):
st, n = self.storage, self.n
def find_sum(ss, se, qs, qe, si):
if qs <= ss and qe >= se:
return st[si]
if se <= qs or ss >= qe:
return 0
mid = (ss + se-1) // 2
a1 = find_sum(ss, mid+1, qs, qe, 2 * si + 1)
a2 = find_sum(mid+1, se, qs, qe, 2 * si + 2)
return a1 + a2
return find_sum(0, n, qs, qe, 0)
# update A[i]
def update(self, i, val):
st, n = self.storage, self.n
def find_update(ss, se, i, diff, si):
if i < ss or i >= se:
return
st[si] += diff
if se - ss > 1:
mid = (ss + se-1) // 2
find_update(ss, mid+1, i, diff, 2 * si + 1)
find_update(mid+1, se, i, diff, 2 * si + 2)
find_update(0, n, i, val, 0)
# References:
# https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/
# https://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/
if __name__ == "__main__":
pass
|
10c218a4ccf3446983c711948d892b565545e994 | yxc775/SeniorRoject | /Database/stockDB_init.py | 2,470 | 4.03125 | 4 | '''
A SQLite-based local SQL database for effect testing and verification purposes.
This program is mainly used for testing stock data passing and storage
in SQL and design improvement.
This part initializes an empty sqlite local database with structures designed in database.jpeg
with no additional table for stocks created, in purpose of database initialization and test.
@author: Yunxi Kou - yxk383
'''
import sqlite3
# Connect to SQLite database.
conn = sqlite3.connect('Stockprice_test.db')
print("Database opened.")
# Create SQL Cursors for command.
curs = conn.cursor()
# table initialize.
'''
method
'''
curs.execute('DROP TABLE IF EXISTS method') # DATABASE STRUCTURE TEST DROP. COMMENT OUT AFTER COMPLETION.
#conn.commit()
curs.execute(
'''
CREATE TABLE IF NOT EXISTS method (
id INT PRIMARY KEY NOT NULL,
name CHAR(20) NOT NULL,
description text
)
''')
conn.commit()
'''
user
'''
curs.execute('DROP TABLE IF EXISTS user') # DATABASE STRUCTURE TEST DROP. COMMENT OUT AFTER COMPLETION.
#conn.commit()
curs.execute(
'''
CREATE TABLE IF NOT EXISTS user (
id INT PRIMARY KEY NOT NULL,
first_name CHAR(20) NOT NULL,
middle_name CHAR(20),
last_name CHAR(20) NOT NULL,
gender INT NOT NULL,
wechat_id CHAR(20),
email CHAR(30),
prefer_method_id INT,
FOREIGN KEY(prefer_method_id) REFERENCES method(id)
)
''')
conn.commit()
'''
report
'''
curs.execute('''DROP TABLE IF EXISTS report''') # DATABASE STRUCTURE TEST DROP. COMMENT OUT AFTER COMPLETION.
curs.execute(
'''
CREATE TABLE IF NOT EXISTS report (
id INT PRIMARY KEY NOT NULL,
user_id INT NOT NULL,
date INT NOT NULL,
FOREIGN KEY(user_id) REFERENCES user(id)
)
''')
conn.commit()
'''
stock_info
'''
curs.execute('''DROP TABLE IF EXISTS stock_info''') # DATABASE STRUCTURE TEST DROP. COMMENT OUT AFTER COMPLETION.
curs.execute(
'''
CREATE TABLE IF NOT EXISTS stock_info (
id INT PRIMARY KEY NOT NULL,
name CHAR(30),
market TEXT
)
''')
conn.commit()
'''
user_stock
'''
curs.execute('''DROP TABLE IF EXISTS user_stock''') # DATABASE STRUCTURE TEST DROP. COMMENT OUT AFTER COMPLETION.
curs.execute(
'''
CREATE TABLE IF NOT EXISTS user_stock (
user_id INT NOT NULL,
stock_id INT NOT NULL,
FOREIGN KEY(user_id) REFERENCES user(id)
FOREIGN KEY(stock_id) REFERENCES stock_info(id)
)
''')
print('Database re-initialize complete.')
conn.close() |
7642d27291f51f92bf2a827c4adfdeefbab5c683 | dariadec/kurs_python | /10/zad_1_wprowadzenieOOP_piesel.py | 468 | 3.53125 | 4 | class Dog:
def __init__(self, name, color, breed):
self.name = name
self.color = color
self.breed = breed
def bark(self):
return self.name + " says Hau"
def wag(self):
return self.name + "is wagging his tail"
obj_pimpek = Dog("Pimpek", "white", "jamnik")
obj_szarek = Dog("Szarek", "grey", "colie")
obj_burek = Dog("Burek", "white", "labrador")
print(obj_pimpek.bark())
print(obj_pimpek.wag()) |
17d7604962a5322eafcbe217c7ff251dc52323fe | parkjaewon1/python | /ch06/fat1.py | 130 | 3.78125 | 4 | def fat1(num):
result = 1
for i in range(1, num + 1):
result *= i
return result
print(fat1(3))
print(fat1(5)) |
0462ccecd6000d59ca342107fac0e2ed230b62d1 | just4cn/algorithm | /sort_algorithm/insertion_sort.py | 362 | 3.78125 | 4 | # coding: utf-8
def insertion_sort(nums):
if not nums:
return
length = len(nums)
# 从第1个数开始排序(第0个默认有序)
for i in xrange(1, length):
key = nums[i]
j = i - 1
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key
return nums
|
d0e9de6520d8ee9a354b208f1ae5ce4e599e6e09 | Herna7liela/New | /Question5.py | 954 | 4.1875 | 4 | # Based in the definition of the mathematical constant e, as the sum of an infinite
# series (see wikipedia: http://en.wikipedia.org/wiki/E_%28mathematical_constant%29)
# create a program that ask the user for the number of terms used to calculate the
# approximation, and returns its value.
# because e is the sum of 1/factorial of a number n, I used the previous questions code.
number = int(input("Enter number to calculate contant e of: "))
fac = 1
i = 0
acc = 0
#while number != "":
for i in range(1,number+1):
fac = fac*i
#print(fac)
for j in range(i):
acc = acc + 1/(fac)
print (acc)
#number = int(input("Enter number to calculate contant e of: "))
# BEST WAY BELOW
# number_of_terms = int(input("how many terms? "))
# total = 1
# factorial = 1
# for counter in range(number_of_terms+1):
# factorial = factorial * (counter + 1)
#total = total + 1/factorial
# print("e= ", total)
|
2351c73df5fc1afdc90adea116506ea4d5bee1e1 | Neil-Do/HUS-Python | /Python 100 Problem/Problem41.py | 138 | 3.75 | 4 | def printTuple():
t = tuple(i**2 for i in range(1, 10))
half = len(t) // 2
print(t[:half])
print(t[half:])
printTuple()
|
e0674ff4cc06b6da7a09f26951f680e42e3393ff | JesseStorms/exercises | /01-basic-python/08-sets/02-remove-duplicates/student.py | 203 | 3.59375 | 4 | # Write your code here
def remove_duplicates(xs):
seen = set()
res = []
for thing in xs:
if thing not in seen:
seen.add(thing)
res.append(thing)
return res |
1bc088e0f040d9554a2579a3052f7c650f987fa4 | indraastra/puzzles | /euler/prob001.py | 124 | 3.703125 | 4 | #!/usr/bin/python
from __future__ import print_function
print(sum(n for n in range(1000) if (n % 3) == 0 or (n % 5) == 0))
|
7d19e7fca4207f3ef4c0bdb8a5c11fe012b6e641 | behnamasadi/PythonTutorial | /Tutorials/class/inheritence.py | 1,052 | 4 | 4 | # https://stackoverflow.com/questions/4015417/python-class-inherits-object
# Is there any reason for a class declaration to inherit from object?
# In Python 2: always inherit from object explicitly. Get the perks.
# In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it needs to
# work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you
# behind the scenes.
# Python methods are always virtual
class Base:
value = None
def __init__(self, value=1):
self.value = value
return
def info(self):
print(f'This is Base and value is {self.value}')
print('This is Base and value is {}'.format(self.value))
class derived2(Base):
def __init__(self):
return
class derived1(Base):
def __init__(self, base_val=2, class_val=3):
super().__init__(base_val)
self.class_val = 3
return
Base_obj = Base(10)
Base_obj.info()
derived1_obj = derived1()
derived1_obj.info()
|
8da9b75117bcd50435936664d470dd50f7fad315 | apanana/rosalind | /mer.py | 697 | 3.65625 | 4 | """
Given: A positive integer n<=10^5 and a sorted array A[1...n] of integers from
-10^5 to 10^5, a positive integer m<=10^5 and a sorted array B[1...m] of
integers from -10^5 to 10^5.
Return: A sorted array C[1...n+m] containing all the elements of A and B.
"""
def mer(xs,ys):
zs = []
i,j = 0,0
while i < len(xs) and j < len(ys):
if xs[i] < ys[j]:
zs.append(xs[i])
i += 1
else:
zs.append(ys[j])
j += 1
# fill remainder
zs += xs[i:]
zs += ys[j:]
return zs
f = open("rosalind_mer.txt","r")
f.readline()
xs = [int(x) for x in f.readline().strip('\n').split(" ")]
f.readline()
ys = [int(y) for y in f.readline().strip('\n').split(" ")]
zs = mer(xs,ys)
print(*zs, sep=" ")
|
aa2f2595699137a5ffa4ad8bcf99bbb55c878b1a | cp4011/Algorithms | /热题/208_实现 Trie (前缀树).py | 2,150 | 4.3125 | 4 | """实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。 保证所有输入均为非空字符串。
"""
class Trie:
def __init__(self): # 用dict模拟字典树即可
""" Initialize your data structure here. """
self.root = {}
def insert(self, word): # Trie树的每个节点本身不存储字符,是整个树的路径信息存储字符,
""" Inserts a word into the trie. :type word: str :rtype: None """
node = self.root
for char in word: # Python 字典 setdefault() 方法和 [get()方法]类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值
node = node.setdefault(char, {}) # 如果key在字典中,返回对应的值;如果不在字典中,则插入key及设置的默认值default并返回default,default默认值为None
node["end"] = True # 有些节点存储"end"标记位:则标识从根节点root到当前node节点的路径构成一个单词
def search(self, word):
""" Returns if the word is in the trie. :type word: str :rtype: bool """
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return "end" in node
def startsWith(self, prefix):
"""Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool"""
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
|
efd370844802e61c304bc119d39f4a37560c1d93 | thinkphp/matrix | /linesToDec.py | 1,216 | 3.984375 | 4 | '''
Se da o matrice binara Matrix de tip (m,n). Fiecare linie retine
cifrele reprezentarii binare a unui numar natural. Se cere
afisarea numerelor in baza 10, un numar reprezentand unei linii,
cat si suma lor.
Exemplu:
m = 5, n = 4;
0 0 1 1 3
1 0 0 1 9
Matrix = 1 1 1 0 14 31
0 0 0 0 0
0 1 0 1 5
*/
'''
def pow(a, b):
p = 1
for i in range(1, b + 1):
p *= a
return p
def toDec(arr):
n = len(arr)
num = 0
t = 0
for i in range(n - 1, -1, -1):
num = num + arr[i] * pow(2, t)
t += 1
return num
def main():
n = 5
m = 4
matrix = [[-1 for j in range(0, m)] for i in range(0, n)]
for i in range(0, n):
for j in range(0, m):
while matrix[i][j] != 0 and matrix[i][j] != 1:
matrix[i][j] = int(input(f"matrix[{i}][{j}] = "))
for i in range(0, n):
for j in range(0, m):
print(matrix[i][j], end = " ")
print()
arr = []
s = 0
for i in range(0, n):
for j in range(0, m):
arr.append(matrix[i][j])
ans = toDec(arr)
s += ans
print(ans)
arr.clear()
print("Suma: ", s)
main()
|
9c3d9ccf658772d9a60ad197d75483518406ab4a | Ricardo301/CursoPython | /Desafios/Desafio050.py | 142 | 4.0625 | 4 | s = 0
for x in range(0, 6):
num = int(input('Digite um valor: '))
if num % 2 == 0:
s += num
print('A soma dos pares é: ', s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.