blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
24a27609d78be6a95322c562a1bd94558650eada | charvey/advent-of-code | /2020/12.py | 1,971 | 3.53125 | 4 | from aocd import data, submit
import math
input = data
def manhattan(pos):
return abs(pos[0]) + abs(pos[1])
def turtle():
x = 0
y = 0
a = 0
for line in input.splitlines():
action = line[0]
value = int(line[1:])
if action == "N":
y += value
elif action == "S":
y -= value
elif action == "W":
x -= value
elif action == "E":
x += value
elif action == "L":
a += math.radians(value)
elif action == "R":
a -= math.radians(value)
elif action == "F":
x += round(math.cos(a) * value)
y += round(math.sin(a) * value)
return x, y
def waypoint():
ship_x = 0
ship_y = 0
waypoint_x = 10
waypoint_y = 1
for line in input.splitlines():
action = line[0]
value = int(line[1:])
if action == "N":
waypoint_y += value
elif action == "S":
waypoint_y -= value
elif action == "W":
waypoint_x -= value
elif action == "E":
waypoint_x += value
elif action == "L":
r = math.radians(value)
_waypoint_x = waypoint_x * math.cos(r) - waypoint_y * math.sin(r)
_waypoint_y = waypoint_x * math.sin(r) + waypoint_y * math.cos(r)
waypoint_x = round(_waypoint_x)
waypoint_y = round(_waypoint_y)
elif action == "R":
r = -math.radians(value)
_waypoint_x = waypoint_x * math.cos(r) - waypoint_y * math.sin(r)
_waypoint_y = waypoint_x * math.sin(r) + waypoint_y * math.cos(r)
waypoint_x = round(_waypoint_x)
waypoint_y = round(_waypoint_y)
elif action == "F":
ship_x += waypoint_x * value
ship_y += waypoint_y * value
return ship_x, ship_y
submit(manhattan(turtle()), part='a')
submit(manhattan(waypoint()), part='b')
|
5d0689cfb3f59669f78b7b36a62dc7163ad4e2c2 | astronstar/leetcodeoffer | /51.py | 1,217 | 3.640625 | 4 | # 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
# 示例 1:
# 输入: [7,5,6,4]
# 输出: 5
class Solution:
def reversePairs(self, nums: List[int]) -> int:
self.cnt=0
def merge(nums,start,mid,end):
tmp=[]
i=start
j=mid+1
while i<=mid and j<=end:
if nums[i]<=nums[j]:
tmp.append(nums[i])
i+=1
else:
self.cnt+=mid-i+1
tmp.append(nums[j])
j+=1
while i<=mid:
tmp.append(nums[i])
i+=1
while j<=end:
tmp.append(nums[j])
j+=1
for i in range(len(tmp)):
nums[start+i]=tmp[i]
def mergeSort(nums,start,end):
if start>=end:return
mid=(start+end)//2
mergeSort(nums,start,mid)
mergeSort(nums,mid+1,end)
merge(nums,start,mid,end)
mergeSort(nums,0,len(nums)-1)
return self.cnt |
f8b43e00093f66e7077e2e7b7fd40dc8b1ae3c54 | resteumark24/mark.py | /probleme/3.Sa se afiseze media numerelor pare.py | 946 | 4.09375 | 4 | #l = []
#num = int(input("How many numbers: "))
#for i in range(num):
# numbers = int(input("Enter number: "))
# l.append(numbers)
#print(sum(l)//3)
#l = []
#num = int(input("How many numbers: "))
#for i in range(num):
# numbers = int(input("Enter number: "))
# l.append(numbers)
#for i in range(num):
# numarPrim = i / 2
# if numarPrim == 0:
# print(sum(numarPrim) // len(num))
#[METODA FINALA]
#import statistics
#list = []
#num = int(input("How many numbers: "))
#for i in range(num):
# numbers = int(input("Enter number: "))
# list.append(numbers)
#x = statistics.mean(list)
#print(x)
import statistics
list = []
num = int(input("How many numbers: "))
for i in range(num):
numbers = int(input("Enter number: "))
list.append(numbers)
x = statistics.mean(numbers)
for i in range(num):
numarPrim = i / 2
if numarPrim == 0:
print(sum(numarPrim) // len(num))
|
c97f9c7a326a2c2fc94e13bfa7ceffa3bb1ce93e | Andrey-Liu/shiyanlou-code | /FindDigits.py | 258 | 3.734375 | 4 | #!/usr/bin/env python3
import sys
if len(sys.argv) < 2:
print("Wrong parameter!")
print("./FindDigits.py file")
print("Target file: ", sys.argv[1])
fd = open(sys.argv[1])
a =''
for char in fd.read():
if char.isdigit():
a += char
print(a)
|
99184493a8e2ebac472a716de7b4393ad2412d2b | msyamkumar/cs220-f20-projects | /lab-p1/double.py | 88 | 3.953125 | 4 | x = input("please enter a number: ")
print("2 times your number is " + str(2*float(x)))
|
38e98e84ec6119fe50f0191ee264915476d8b9c5 | wangxf108/Python-OOP-Practice | /python-OOP-practice.py | 1,231 | 3.921875 | 4 | from random import randint
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def falls_in_rectangle(self, rectangle):
if rectangle.lowleft.x < self.x < rectangle.upright.x\
and rectangle.lowleft.y < self.y < rectangle.upright.y:
return True
else:
return False
class Rectangle:
def __init__(self, lowleft, upright):
self.lowleft = lowleft
self.upright = upright
def area(self):
return (self.upright.x - self.lowlef.x) * \
(self.upright.y - self.lowleft.y)
# Create rectangle object
rectangle = Rectangle(
Point(randint(0, 9), randint(0, 9)),
Point(randint(10, 19), randint(10, 19)))
# Print rectangle coordinates
print("Rectangle Coordinates: ",
rectangle.lowleft.x, ",",
rectangle.lowleft.y, "and",
rectangle.upright.x, ",",
rectangle.upright.y)
# Get point and area from user
user_point = Point(float(input("Guess X: ")), float(input("Guess Y: ")))
user_area = float(input("Guess rectangle area: "))
# Print out the game result
print("Your point was inside rectangle: ", user_point.falls_in_rectangle(rectangle))
print("Your area was off by: ", rectangle.area() - user_area)
|
710a365b283c6820fd425099bb0105ee5aa263f5 | utkamioka/attribute-access-dict-py | /test_map.py | 2,681 | 3.5 | 4 | from unittest import TestCase
from map import Map
class TestMap(TestCase):
def test_getattr(self):
m = Map(a=10, b=20, z=Map(x=100, y=200))
self.assertEqual(m.a, 10)
self.assertEqual(m.b, 20)
self.assertEqual(m.z, dict(x=100, y=200))
self.assertEqual(m.z.x, 100)
self.assertEqual(m.z.y, 200)
with self.assertRaises(KeyError):
_ = m.c
with self.assertRaises(KeyError):
_ = m.z.xx
def test_setattr(self):
m = Map()
with self.assertRaises(KeyError):
_ = m.a
m.a = 'A'
m.b = 'B'
self.assertEqual(m.a, 'A')
self.assertEqual(m.b, 'B')
with self.assertRaises(KeyError):
m.z.x = 'X'
def test_delattr(self):
m = Map(a=10, b=20, z=Map(x=100, y=200))
self.assertEqual(m.a, 10)
self.assertEqual(m.b, 20)
self.assertEqual(m.z.x, 100)
self.assertEqual(m.z.y, 200)
del m.a
with self.assertRaises(KeyError):
_ = m.a
del m.z.x
with self.assertRaises(KeyError):
_ = m.z.x
def test_via_json_loads(self):
import json
book = json.loads('''
{
"title": "吾輩は猫である",
"publish": {
"date": 1905
},
"author": {
"name": "夏目漱石",
"birth": 1867
}
}
''', object_hook=Map)
self.assertEqual(book.title, '吾輩は猫である')
self.assertEqual(book.author.name, '夏目漱石')
self.assertEqual(book.author.birth, 1867)
from operator import attrgetter
ext = attrgetter('title', 'author.name', 'publish.date')
self.assertEqual(ext(book), ('吾輩は猫である', '夏目漱石', 1905))
def test_via_toml_loads(self):
import toml
book = toml.loads('''
title = "吾輩は猫である"
[publish]
date = 1905
[author]
name = "夏目漱石"
birth = 1867
''', _dict=Map)
self.assertEqual(book.title, '吾輩は猫である')
self.assertEqual(book.author.name, '夏目漱石')
self.assertEqual(book.author.birth, 1867)
from operator import attrgetter
ext = attrgetter('title', 'author.name', 'publish.date')
self.assertEqual(ext(book), ('吾輩は猫である', '夏目漱石', 1905))
from operator import itemgetter
ext = itemgetter('title', 'author.name', 'publish.date')
with self.assertRaisesRegex(KeyError, r"'author.name'"):
ext(book)
|
a63e75c9e007312315a2a83666720aa3caac4aca | ryanmiddle/CSCI102 | /Lab1B-Fibonacci.py | 465 | 4.28125 | 4 | #Ryan Middle
#CSCI 101 - A
#Python Lab 1B - Fibonacci
a=1 #initializing n var in fibonacci sequence
b=0 #initializing n-1 var in fibonacci sequence
c=1
n=int(input("please enter how many numbers in the Fibonacci sequence you would like to see")) #initializing step var
for i in range (1, n, 1):
print(c)
c=a+b #fibonacci recurrence statement
b=a #re-initializing n-1 term
a=c #re-initializing n term
n=n+1 #increasing step var
print("end") #that's all, folks!
|
636ff58f648e8d64499c174d6b692ebdc96424b9 | justenpinto/coding_practice | /interviewcake/hashtables/inflight_entertainment.py | 1,534 | 4.6875 | 5 | """
Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane
usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runtimes
will equal the exact flight length.
Write a function that takes an integer flight_length (in minutes) and a list of integers movie_lengths (in minutes) and
returns a boolean indicating whether there are two numbers in movie_lengths whose sum equals flight_length.
When building your function:
1. Assume your users will watch exactly two movies
2. Don't make your users watch the same movie twice
3. Optimize for runtime over memory
"""
def check_movie_lengths(flight_time, movies_lengths):
"""
Runtime: O(n)
Space: O(1)
We make one pass through movie_lengths, treating each item as the first_movie_length. At each iteration, we:
1. See if there's a matching_second_movie_length we've seen already (stored in our movie_lengths_seen set) that is
equal to flight_length - first_movie_length. If there is, we short-circuit and return True.
2. Keep our movie_lengths_seen set up to date by throwing in the current first_movie_length.
"""
movie_lengths_seen = set()
for movie_length in movies_lengths:
remaining_time = flight_time - movie_length
if remaining_time in movie_lengths_seen:
return True
else:
movie_lengths_seen.add(movie_length)
return False
if __name__ == '__main__':
pass
|
bc537211bef91b1014ebfc98c787e2093fcba762 | Apache0001/Curso-de-Python | /Aula01/aula09-1.py | 1,230 | 3.9375 | 4 | nome = "Pablo Oliveira Mesquita".upper() #coloca toda string em CAPS
print('PABLO' in nome)
nome.replace('PABLO','Gabriel') #Substitui uma palavra por outra
print(nome)
frase = "Curso em vídeo python"
print(frase.title()) # title coloca toda palavra em maiuscula
frase2 = "Curso em video"
print(frase2)
print(frase2.strip()) # Remove espaços a esquerda e a direita da string
print(frase2.strip().split()) # Coloca toda palavra em uma lista como se fosse um ventor
print('-'.join(frase2))
print(frase.count("o")) # Conta quantas vezes a letra apareceu
teste = "asduhasduhashudahsudasp"
print(teste[5::2])
print("""Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.""")
|
bb9d4bd95fd2d9a938e84ef2a177f98bdf90f301 | Meghkh/connect_four | /project/connect_four.py | 5,489 | 4.28125 | 4 | """
Connect Four game
about/instructions
STILL TO DO:
- win condition sanitization to stay in range - COMPLETE but needs testing
- user input sanitization to stay in range
- have win condition terminate game - COMPLETE
- include row and column identifiers to improve UX
"""
#print "Hello, World!"
""" initialize board object with rows and columns
could later be replaced with a function that intakes
user defined board size
"""
board = []
#board_height = len(board)
#board_width = len(board[0])
cols = 7
rows = 6
player_flag = 1
win_flag = 0
def create_board():
""" create a new board and initialize all spaces to zero
for now, this function creates a new board, initializes
all places to zero and displays the board
by returning the board and using as parameters for other
board sizes, other functions should be able to handle
changing board sizes
"""
for i in range(rows):
board.append([])
for j in range(cols):
board[i].append(0)
return board
def display_board(board):
""" display the board
include row and column identifiers to help users select move
"""
print "\n"
print "\tROWS\n\t\tCOLUMNS", range(1, cols+1), "\n"
# print "\t\t\tCOLUMNS"
for i in range(rows):
print "\t ", i+1, "\t", "", "\t", str(board[i])
print "\n"
def input_next_move(board, player_flag, win_flag):
""" input coordinates for next move based on user input
NEED TO ADD
- diagonal win conditions
- user input sanitation to keep indexing of array within range
"""
board_height = len(board)
board_width = len(board[0])
print "Select coordinates for next move, Player", player_flag, ":\n"
# row_coordinate = 0
# while row_coordinate != range(board_height-1)
# row_coordinate = int(raw_input(" Which row? "))
# while row_coordinate != range(board_height - 1):
# row_coordinate = int(raw_input("Invalid row selection! Try again: "))
# col_coordinate = int(raw_input(" Which col? "))
# while col_coordinate != range(board_width - 1):
# col_coordinate = int(raw_input("Invalid column selectoin! Try again: "))
row_coordinate = int(raw_input(" Which row? "))
col_coordinate = int(raw_input(" Which column? "))
if board[row_coordinate - 1][col_coordinate - 1] != 0:
print "Coordinate is occupied! Try again!"
else:
board[row_coordinate - 1][col_coordinate - 1] = player_flag
# switch player_flag only when valid move is made
display_board(board)
# print win_flag, "\n"
win_flag = check_win_conditions(board, win_flag)
# print win_flag, "\n"
# input_next_move(board, player_flag, win_flag)
return win_flag
def toggle_player_move(player_move):
if player_move == 1:
player_move += 1
else:
player_move -= 1
return player_move
def check_win_conditions(board, win_flag):
""" checks for a win condition by either user
NEED TO ADD:
- diagonal win conditions
- condition check sanitation to stay in the board
"""
board_height = len(board)
board_width = len(board[0])
# checks for horizontal win condition
for i in range(board_height):
for j in range(board_width - 3):
if board[i][j] == 1 and board[i][j+1] == 1 and board[i][j+2] == 1 and board[i][j+3] == 1:
win_flag = 1
elif board[i][j] == 2 and board[i][j+1] == 2 and board[i][j+2] == 2 and board[i][j+3] == 2:
win_flag = 2
# checks for vertical win condition
for i in range(board_height - 3):
for j in range(board_width):
if board[i][j] == 1 and board[i+1][j] == 1 and board[i+2][j] == 1 and board[i+3][j] == 1:
win_flag = 1
elif board[i][j] == 2 and board[i+1][j] == 2 and board[i+2][j] == 2 and board[i+3][j] == 2:
win_flag = 2
# check for diagonal win condition UL to LR
for i in range(board_height - 3):
for j in range(board_width - 3):
if board[i][j] == 1 and board[i+1][j+1] == 1 and board[i+2][j+2] == 1 and board[i+3][j+3] == 1:
win_flag = 1
elif board[i][j] == 2 and board[i+1][j+1] == 2 and board[i+2][j+2] == 2 and board[i+3][j+3] == 2:
win_flag = 2
# checks for diagonal win condition LL to UP
for i in range(3, board_height):
for j in range(board_width - 3):
if board[i][j] == 1 and board[i-1][j+1] == 1 and board[i-2][j+2] == 1 and board[i-3][j+3] == 1:
win_flag = 1
elif board[i][j] == 2 and board[i-1][j+1] == 2 and board[i-2][j+2] == 2 and board[i-3][j+3] == 2:
win_flag = 2
if win_flag != 0:
print "Congrats, Player", str(win_flag), "you won!"
return win_flag
"""
end of defining functions
begin calling functions
"""
create_board()
display_board(board)
#check_win_conditions(board, win_flag)
#print "input next move is: \n"
#print input_next_move(board, player_flag, win_flag)
#input_next_move(board, player_flag, win_flag)
while input_next_move(board, player_flag, win_flag) == 0:
toggle = toggle_player_move(player_flag)
keep_going = input_next_move(board, toggle, win_flag)
if keep_going != 0:
# print "hello!"
print "Congrats, Player", str(win_flag), "you won!"
break
|
dd0aed2410415d13f471a3aeac271dcc0a6a865b | stvnorg/checkio-python | /days-diff.py | 145 | 3.5 | 4 | from datetime import date
def days_diff(date1,date2):
return abs(date(date1)-date(date2)).days
print (days_diff((1982, 4, 19), (1982, 4, 22)))
|
0b90088d47e7f29b1d4224049cdcb675286bfae1 | ZpRoc/checkio | /c07_pycon_tw/p06_calculate_islands.py | 3,920 | 4.21875 | 4 | # ---------------------------------------------------------------- #
# Calculate Islands
# Help the robots calculate the landmass of their newly discovered island chain.
# (Matrix, geometry)
# ---------------------------------------------------------------- #
# The Robots have found a chain of islands in the middle of the Ocean.
# They would like to explore these islands and have asked for your help
# calculating the areas of each island. They have given you a map of the
# territory. The map is a 2D array, where 0 is water, 1 is land. An island
# is a group of land cells surround by water. Cells are connected by their
# edges and corners. You should calculate the areas for each of the islands
# and return a list of sizes (quantity of cells) in ascending order.
# All of the cells outside the map are considered to be water.
# Input: A map as a list of lists with 1 or 0.
# Output: The sizes of island as a list of integers.
# Precondition: 0 < len(land_map) < 10
# all(len(land_map[0]) == len(row) for row in land_map)
# any(any(row) for row in land_map)
# ---------------------------------------------------------------- #
# ---------------------------------------------------------------- #
# ---------------------------------------------------------------- #
from typing import List
import numpy as np
def checkio(land_map: List[List[int]]) -> List[int]:
### Initialization
MAP = np.array(land_map, dtype=np.uint8)
FLG = np.zeros_like(MAP, dtype=np.uint8)
ROW, COL = np.shape(MAP)
CNT = 0
### Judge
for r in range(ROW):
for c in range(COL):
if MAP[r, c] == 1:
### 该位置周围是否已经被标记:是 跟从标记,否 新标记
flg_slt = FLG[max(r-1, 0):min(r+2, ROW), max(c-1, 0):min(c+2, COL)]
if np.sum(flg_slt) == 0:
CNT = CNT + 1
FLG[r, c] = CNT
else:
FLG[r, c] = np.max(flg_slt)
### Concat
for r in range(ROW):
for c in range(COL):
if FLG[r, c] != 0:
### 该位置周围是否被标记为相同编号:是 pass,否 用小的编号代替大的编号
flg_slt = FLG[max(r-1, 0):min(r+2, ROW), max(c-1, 0):min(c+2, COL)]
if np.sum(flg_slt==0) + np.sum(flg_slt==FLG[r, c]) != np.size(flg_slt):
tmp = np.extract(((flg_slt != 0) & (flg_slt != FLG[r, c])), flg_slt)
FLG = np.where(FLG==tmp[0], FLG[r, c], FLG)
### Count & Sort
aera_list = sorted([np.sum(FLG==cnt+1) for cnt in range(CNT)])
return aera_list[aera_list.count(0):]
# ---------------------------------------------------------------- #
# ---------------------------------------------------------------- #
# ---------------------------------------------------------------- #
if __name__ == '__main__':
print("Example:")
print(checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]))
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]) == [1, 3], "1st example"
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 0, 0]]) == [5], "2nd example"
assert checkio([[0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]]) == [2, 3, 3, 4], "3rd example"
print("Coding complete? Click 'Check' to earn cool rewards!")
|
58228957d7ddc53a3acad8ba997db379ffbac68c | frankiegu/python_for_arithmetic | /力扣算法练习/day65-验证二叉搜索树.py | 2,323 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/5/4 20:49
# @Author : Xin
# @File : day65-验证二叉搜索树.py
# @Software: PyCharm
# 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
#
# 假设一个二叉搜索树具有如下特征:
#
# 节点的左子树只包含小于当前节点的数。
# 节点的右子树只包含大于当前节点的数。
# 所有左子树和右子树自身必须也是二叉搜索树。
# 示例 1:
#
# 输入:
# 2
# / \
# 1 3
# 输出: true
# 示例 2:
#
# 输入:
# 5
# / \
# 1 4
# / \
# 3 6
# 输出: false
# 解释: 输入为: [5,1,4,null,null,3,6]。
# 根节点的值为 5 ,但是其右子节点值为 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):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
res, _, _ = self.isValidBST2(root)
return res
def isValidBST2(self, root):
if not root:
return True, None, None
valid_left, min_left, max_left = self.isValidBST2(root.left)
valid_right, min_right, max_right = self.isValidBST2(root.right)
if not valid_left or not valid_right:
return False, None, None
if valid_left and valid_right and ((max_left and root.val > max_left) or not max_left) and (
(min_right and root.val < min_right) or not min_right):
return True, min_left if min_left else root.val, max_right if max_right else root.val
return False, None, None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.l = []
self.for_each(root)
return sorted(list(set(self.l))) == self.l # 验证是否有重复元素,并且是否是有序的
def for_each(self, root):
if not root:
return
# 中序遍历
self.for_each(root.left)
self.l.append(root.val)
self.for_each(root.right)
|
a6394f553ccd92bf360f41cb339df72893d816bb | Eyasluna/Data-Structures-Algorithms-Nanodegree-Program | /P0/Task3.py | 3,314 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
import re
import itertools
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fixed line telephones in Bangalore.
Fixed line numbers include parentheses, so Bangalore numbers
have the form (080)xxxxxxx.)
Part A: Find all of the area codes and mobile prefixes called by people
in Bangalore.
- Fixed lines start with an area code enclosed in brackets. The area
codes vary in length but always begin with 0.
- Mobile numbers have no parentheses, but have a space in the middle
of the number to help readability. The prefix of a mobile number
is its first four digits, and they always start with 7, 8 or 9.
- Telemarketers' numbers have no parentheses or space, but they start
with the area code 140.
Print the answer as part of a message:
"The numbers called by people in Bangalore have codes:"
<list of codes>
The list of codes should be print out one per line in lexicographic order with no duplicates.
Part B: What percentage of calls from fixed lines in Bangalore are made
to fixed lines also in Bangalore? In other words, of all the calls made
from a number starting with "(080)", what percentage of these calls
were made to a number also starting with "(080)"?
Print the answer as a part of a message::
"<percentage> percent of calls from fixed lines in Bangalore are calls
to other fixed lines in Bangalore."
The percentage should have 2 decimal digits
"""
#Part A
called_number = []
area_num = []
cell_num = []
area_2 = []
final_1 = []
area3 = []
for i in range(len(calls)-1):
if "(080)" in calls[i][0]:
called_number.append(calls[i][1])
#get whole numbers called by 080
for j in range(len(called_number)-1):
if "(" in called_number[j]:
area_num.append(called_number[j])
#get fixed phone numbers from called numbers
for elem in called_number:
if elem[0] == '7'or elem[0] == '8' or elem[0] == '9':
cell_num.append(elem)
#get cell numbers from called numbers
for keys in area_num:
keys = keys.strip()
p = r'\(.*?\)'
pattern = re.compile(p)
area_2.append(pattern.findall(keys))
area_2 = set(list(itertools.chain(*area_2)))
for ele in area_2:
area3.append(ele)
#using regex to find area code from fixed numbers
for mobile in cell_num:
final_1.append(mobile[:4])
for area in area3:
final_1.append(area[1:-1])
if '140' in called_number[0:2]:
final_1.append('140')
#collect all area number to one list
final = sorted(set(final_1))
# using set to remove duplicates.
#since I called <sorted> here, the run time for this could be hard to
#calculate for entire program
print("The numbers called by people in Bangalore have codes:")
for elem in final:
print(elem)
# Part A run time: N+N+N+N+N+N+1= 6N O(6N)
#Part B
fixed_line = []
for a in range(len(called_number)-1):
if '(080)' in called_number[a]:
fixed_line.append(called_number[a])
outcome = round((len(fixed_line)/len(called_number))*100,2)
print(outcome,'percent of calls from fixed lines'
' in Bangalore are calls to other fixed lines in Bangalore.')
#run time: O(N) |
ee1eb7575c775880099853f55de5c4d271962e74 | DouglasKosvoski/URI | /1151 - 1160/1156.py | 106 | 3.578125 | 4 | total = 1
n = 3
m = 2
while n <= 39:
total += (n/m)
n += 2
m *= 2
print('%.2f' % (total))
|
ecb2ef2e489e495a7674b7caa0b1a24fe8336610 | deepakbhavsar43/Python-to-ML | /Machine_Learning/Case_Study/Logistic_Regression_Titanic_Dataset/Inbuilt/Inbuilt.py | 2,536 | 3.53125 | 4 | from dataframe import DataFrame
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from userInput import *
import pandas as pd
import pickle
class Dataset:
def __init__(self):
self.data = pd.read_csv("Dataset/Titanic_Dataset.csv")
def read_dataset(self):
self.data.drop("Embarked", axis=1, inplace=True)
self.x = self.data.drop("Survived", axis=1)
self.y = self.data["Survived"]
return self.x, self.y
def split(self, X, Y):
# Splitting the data for training and testing
self.xtrain, self.xtest, self.ytrain, self.ytest = train_test_split(x, y, test_size=0.3, random_state=0)
return self.xtrain, self.xtest, self.ytrain, self.ytest
def train(self, xTrain, yTrain):
# Creating object of LogisticRegression model
self.model = LogisticRegression()
self.model.fit(self.xtrain, self.ytrain)
return self.model
def predict_label(self, model):
# predicting y label
self.yprediction = model.predict(self.xtest)
print("\nInput given to model :\n", self.xtest)
print("\nPredicted label by the model :\n", self.yprediction)
def score(self, ytest):
# Calculate accuracy of the model
acc = accuracy_score(self.yprediction, ytest)
print("Accuracy : ", acc * 100)
def wr_pickle(self, train, model):
# creating pickle file
outfile = open(model, 'wb')
# saving trained model in pickle file
pickle.dump(train, outfile)
outfile.close()
def rd_pickle(self, model):
# opening pickle file
infile = open(model, 'rb')
# loading the saved model into variable newTraining
self.newTraining = pickle.load(infile)
return self.newTraining
def plot_graph(self):
y = DataFrame(self.y)
print(type(self.x), type(y))
plt.scatter(self.x, y)
plt.show()
if __name__ == "__main__":
Trained_Model_File = "Trained_Model/trained_data"
obj = Dataset()
x, y = obj.read_dataset()
xtrain, xtest, ytrain, ytest = obj.split(x, y)
if args.train:
model = obj.train(xtrain, ytrain)
obj.wr_pickle(model, Trained_Model_File)
print("Model Trained")
elif args.test:
trained = obj.rd_pickle(Trained_Model_File)
obj.predict_label(trained)
obj.score(ytest)
obj.plot_graph() |
4d27d5c8c4f121832db0359a4b6757a8f1400329 | trustthedata/Intro-Python | /src/obj.py | 2,005 | 3.90625 | 4 | # Make a class LatLon that can be passed parameters `lat` and `lon` to the
# constructor
class LatLon:
def __init__(self, lat, lon):
self.lat = lat
self.lon = lon
def set_lat(self, lat):
self.lat = lat
def get_lat(self):
return self.lat
def set_lon(self, lon):
self.lat = lat
def get_lon(self):
return self.lon
# Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the
# constructor. It should inherit from LatLon.
class Waypoint(LatLon):
def __init__(self, name, lat, lon):
self.name = name
super().__init__(lat, lon)
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def __str__(self):
return 'The {} are located at Longitude: {} and Latitude: {}'.format(self.name, self.lon, self.lat)
# Make a class Geocache that can be passed parameters `name`, `difficulty`,
# `size`, `lat`, and `lon` to the constructor. What should it inherit from?
class Geocache(Waypoint):
def __init__(self, name, difficulty, size, lat, lon):
self.difficulty = difficulty
self.size = size
super().__init__(name, lat, lon)
def set_difficulty(self, difficulty):
self.difficulty = difficulty
def get_difficulty(self):
return self.difficulty
def set_size(self, size):
self.size = size
def get_size(self):
return self.size
def __str__(self):
return 'The geocache {} with a size of {} and a difficulty of {} is located at Longitude: {} and Latitude: {}'.format(self.name, self.size, self.difficulty, self.lon, self.lat)
# Make a new waypoint "Catacombs", 41.70505, -121.51521
w = Waypoint("Catacombs", 41.70505, -121.51521)
# Print it
# Without changing the following line, how can you make it print into something
# more human-readable?
print(w)
# Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556
g = Geocache("Newberry Views", 2, 1.5, 44.052137, -121.41556)
# Print it--also make this print more nicely
print(g)
|
26e3398adb6b366480a87b2e3bd0cc03e88cce58 | S-web7272/tanu_sri_pro | /basics/for_with_condition.py | 128 | 4.0625 | 4 | # print all numbers divisible by 3 in range of 1-100
for i in range(1,100):
if i % 3 ==0:
print(i,end=' ')
|
29b83e5b7cfcd1f3467ebf6c3fcccf46d46f2f57 | dmitri-mamrukov/coursera-data-structures-and-algorithms | /course4-strings/assignments/assignment_003_suffix_tree_from_array/test.py | 10,178 | 4.125 | 4 | #!/usr/bin/python3
import functools
import unittest
import suffix_tree_from_array
class Util():
@staticmethod
def _suffix_compare(word, i, j):
"""
Compares suffixes without generating entire suffixes.
Idea:
To compare the suffixes word[i:] and word[j:], compare the letters
at the ith and jth indices. Return -1 if the ith letter comes before
the jth letter, 1 if jth letter comes before the ith letter.
If the letters match, repeat the process with the letter at the (i+1)th
and (j+1)th indices.
"""
length = len(word)
while i < length and j < length:
if word[i] == word[j]:
i += 1
j += 1
elif word[i] < word[j]:
return -1
else:
return 1
return 0
@staticmethod
def _longest_common_prefix_of_suffixes(word, i, j, equal):
"""
Computes the longest common prefix of suffixes, which start at
i + offset and j + offset.
The longest common prefix of two strings S and T is the longest such
string u that u is a prefix of both S and T.
We denote the length of the longest common prefix of S and T as
LCP(S, T).
"""
lcp = max(0, equal)
while i + lcp < len(word) and j + lcp < len(word):
if word[i + lcp] == word[j + lcp]:
lcp += 1
else:
break
return lcp
@staticmethod
def _invert_suffix_array(order):
"""
Inverts the suffix array, using the order array.
"""
pos = [ 0 ] * len(order)
for i in range(0, len(order)):
pos[order[i]] = i
return pos
@staticmethod
def construct_suffix_array(word):
"""
Constructs a suffix array from the given word.
"""
# Sort the index array using the suffix comparison function.
indices = range(len(word))
suffix_array = sorted(indices,
key=functools.cmp_to_key(lambda i, j:
Util._suffix_compare(
word,
i,
j)))
return suffix_array
@staticmethod
def compute_longest_common_prefix_array(word, order):
"""
Computes the longest common prefix array.
"""
if len(word) == 0:
return []
lcp_array = [ 0 ] * (len(word) - 1)
lcp = 0
pos_in_order = Util._invert_suffix_array(order)
suffix_index = order[0]
for i in range(0, len(word)):
order_index = pos_in_order[suffix_index]
if order_index == len(word) - 1:
lcp = 0
suffix_index = (suffix_index + 1) % len(word)
continue
next_suffix_index = order[order_index + 1]
lcp = Util._longest_common_prefix_of_suffixes(word,
suffix_index,
next_suffix_index,
lcp - 1)
lcp_array[order_index] = lcp
suffix_index = (suffix_index + 1) % len(word)
return lcp_array
class SolverSolveTestCase(unittest.TestCase):
def setUp(self):
self.solver = suffix_tree_from_array.Solver()
self.solver._input = self.generate_input
self.solver._output = self.accumulate_output
self.output_list = []
self.index = 0
def tearDown(self):
pass
def generate_input(self):
line = self.input_list[self.index]
self.index += 1
return line
def accumulate_output(self, text):
return self.output_list.append(text)
def verify_input(self):
word = self.input_list[0]
suffix_array_string = self.input_list[1]
suffix_lcp_string = self.input_list[2]
expected_suffix_array = Util.construct_suffix_array(word)
expected_lcp_array = Util.compute_longest_common_prefix_array(
word,
expected_suffix_array)
self.assertEquals(' '.join(map(str, expected_suffix_array)),
suffix_array_string)
self.assertEquals(' '.join(map(str, expected_lcp_array)),
suffix_lcp_string)
"""
Note that the outputs of some tests don't match those from the official
ones. But edge strings remain valid. I think this is due to their code that
builds a suffix tree slightly differently.
My solution still passed all the official tests.
"""
def test_case1(self):
"""
The LCP array contains the longest common prefixes between
adjacent suffixes in the suffix array of string S.
A $
0 1
Suffixes:
A$
$
Sorted suffixes:
$
A$
index order suffix lcp
0 1 $ -
1 2 A$ 0
"""
self.input_list = [
'A$',
'1 0',
'0',
]
expected_result = [
'A$',
'1 2',
'0 2',
]
self.verify_input()
self.solver.solve()
self.assertEquals(expected_result, self.output_list)
def test_case2(self):
"""
The LCP array contains the longest common prefixes between
adjacent suffixes in the suffix array of string S.
A A A $
0 1 2 3
Suffixes:
AAA$
AA$
A$
$
Sorted suffixes:
$
A$
AA$
AAA$
index order suffix lcp
0 3 $ -
1 2 A$ 0
2 1 AA$ 1
3 0 AAA$ 2
"""
self.input_list = [
'AAA$',
'3 2 1 0',
'0 1 2',
]
expected_result = [
'AAA$',
'3 4',
'2 3',
'3 4',
'2 3',
'3 4',
'2 4',
]
self.verify_input()
self.solver.solve()
self.assertEquals(expected_result, self.output_list)
def test_case3(self):
"""
The LCP array contains the longest common prefixes between
adjacent suffixes in the suffix array of string S.
G T A G T $
0 1 2 3 4 5
Suffixes:
GTAGT$
TAGT$
AGT$
GT$
T$
$
Sorted suffixes:
$
AGT$
GT$
GTAGT$
T$
TAGT$
index order suffix lcp
0 5 $ -
1 2 AGT$ 0
2 3 GT$ 0
3 0 GTAGT$ 2
4 4 T$ 0
5 1 TAGT$ 1
"""
self.input_list = [
'GTAGT$',
'5 2 3 0 4 1',
'0 0 2 0 1',
]
expected_result = [
'GTAGT$',
'5 6',
'2 6',
'3 5',
'5 6',
'2 6',
'4 5',
'5 6',
'2 6',
]
self.verify_input()
self.solver.solve()
self.assertEquals(expected_result, self.output_list)
def test_case4(self):
"""
The LCP array contains the longest common prefixes between
adjacent suffixes in the suffix array of string S.
A T A A A T G $
0 1 2 3 4 5 6 7
Suffixes:
ATAAATG$
TAAATG$
AAATG$
AATG$
ATG$
TG$
G$
$
Sorted suffixes:
$
AAATG$
AATG$
ATAAATG$
ATG$
G$
TAAATG$
TG$
index order suffix lcp
0 7 $ -
1 2 AAATG$ 0
2 3 AATG$ 2
3 0 ATAAATG$ 1
4 4 ATG$ 2
5 6 G$ 0
6 1 TAAATG$ 0
7 5 TG$ 1
"""
self.input_list = [
'ATAAATG$',
'7 2 3 0 4 6 1 5',
'0 2 1 2 0 0 1',
]
expected_result = [
'ATAAATG$',
'7 8',
'3 4',
'3 4',
'4 8',
'5 8',
'1 2',
'2 8',
'6 8',
'6 8',
'1 2',
'2 8',
'6 8',
]
self.verify_input()
self.solver.solve()
self.assertEquals(expected_result, self.output_list)
if __name__ == '__main__':
class_names = [
SolverSolveTestCase,
]
suite = unittest.TestSuite()
for c in class_names:
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(c))
unittest.TextTestRunner().run(suite)
|
0a5cf6a35034bc10b39e4a3866b0e1d89396c7f9 | Maffanyamo/Tic-Tac-Toe | /Simple Tic-Tac-Toe (1)/task/tictactoe.py | 1,396 | 3.796875 | 4 | m = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
i = 1
char = "Y"
def main():
print_grid(m)
while i <= 9:
coordinates()
if i == 10:
print("Draw")
def x_or_o(i, char):
if i % 2 == 1:
char = "X"
else:
char = "O"
return char
def coordinates():
x, y = input("Enter the coordinates: ").split()
global i, char
if x.isdigit() == False or y.isdigit() == False:
print("You should enter numbers!")
return coordinates()
x = int(x)
y = int(y)
if x > 3 or y > 3 or x < 1 or y < 1:
print("Coordinates should be from 1 to 3")
coordinates()
elif m[x - 1][y - 1] == " ":
# x_or_o(i, char)
if i % 2 == 1:
char = "X"
else:
char = "O"
m[x - 1][y - 1] = char
print_grid(m)
i += 1
if i > 2 and (m[x - 1] == [char, char, char] or [m[0][y -1], m[1][y - 1], m[2][y - 1]] == [char, char, char] or [m[0][0], m[1][1], m[2][2]] == [char, char, char] or [m[0][2], m[1][1], m[2][0]] == [char, char, char]):
print(char + " wins")
i = 100
return m, i
else:
print("This cell is occupied! Choose another one!")
coordinates()
def print_grid(m):
grid = [" ".join(m[0]), " ".join(m[1]), " ".join(m[2])]
print("-" * 9)
print("|", " |\n| ".join(grid), "|")
print("-" * 9)
main()
|
3efc5a58e7e042f867ee04b8011ba6a44eac9f07 | NightFlightCaptain/python-common | /Algorithms/qiwsir/average_score.py | 1,036 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# __author__ = 'wanhaoran'
"""
问题:
定义一个int型的一维数组,包含40个元素,用来存储每个学员的成绩,循环产生40个0~100之间的随机整数,
(1)将它们存储到一维数组中,然后统计成绩低于平均分的学员的人数,并输出出来。
(2)将这40个成绩按照从高到低的顺序输出出来。
"""
import random
def make_score(num):
scores = [random.randint(0,100) for i in range(num)]
return scores
def less_average(score):
average_score = sum(score)/len(score)
count = 0
for i in range(len(score)):
if score[i] < average_score:
count+=1
# less_ave = [i for i in score if i<average_score]
return average_score,count
if __name__=="__main__":
score = make_score(40)
average_num,less_num = less_average(score)
print('the score of average is:',average_num)
print("the number of less average is:",less_num)
print("the every score is[from big to small]:",sorted(score,reverse=True)) |
f4633b1fd954589282a09ec4c352ad1b33e677ea | gergely-k5a/building-ai | /4. Neural networks/1. Logistic regression/20. logistic-regression.py | 340 | 3.546875 | 4 | import math
import numpy as np
x = np.array([4, 3, 0])
c1 = np.array([-.5, .1, .08])
c2 = np.array([-.2, .2, .31])
c3 = np.array([.5, -.1, 2.53])
def sigmoid(z):
return 1 / (1 + math.exp(-z))
# calculate the output of the sigmoid for x with all three coefficients
print(sigmoid(c1 @ x))
print(sigmoid(c2 @ x))
print(sigmoid(c3 @ x))
|
e0127d0b24e8bfa8d90841bb5c5ea5755f95ef8a | yon-cc/LaboratorioVCSRemoto | /main.py | 634 | 4.1875 | 4 | import math
print("""Bienvenido usuario, para resolver la ecuacion cuadratica, primero ingrese el
valor del numero que acompaña a la elevada al cuadrado, luego el que acompaña a la
x y por último ingrese el numero sin la x.""")
a=int(input("1."))
b=int(input("2."))
c=int(input("3."))
d = b**2 - (4*a*c)
if d > 0:
x1 = (-b+math.sqrt(d))/2*a
x2 = (-b-math.sqrt(d))/2*a
print("X vale 0 cuando toma el valor de",x1,"y",x2,".")
elif d < 0:
print("No existe solución a la ecuación cuadrática dentro del dominio de los números reales.")
else:
x = -b/2*a
print("X vale 0 cuando toma el valor de",x,".")
|
db33be9d8bf3e26008ba2f2dff74629a90119e99 | alina2002200/pythonhmwrk | /hypot14.py | 173 | 3.625 | 4 | import turtle
import numpy as np
turtle.shape('turtle')
def strmm(n):
for i in range(n):
turtle.forward(150)
turtle.right(180-180/n)
strmm(11)
|
865367029d14c77f6e006a3de285701874b0e894 | 35sebastian/Proyecto_Python_1 | /CaC Python/EjerciciosPy2/Ej1.py | 843 | 3.90625 | 4 | #
# Mi resolución:
#
# edad= int(input("Ingrese su edad:"))
# if edad < 18:
# print("Según tu edad eres menor de edad")
# else:
# print("Según tu edad eres mayor de edad")
#
def validarEdad(edad):
while edad < 1:
print("%d no es una edad valida!!!" %edad)
edad = int(input('Hola, Cual es tu edad: '))
return edad
print("*****************************************")
print(" E J E R C I C I O N° 1")
print("*****************************************")
usuario = input('Cual es tu usuario: ')
edad = int(input('Hola %s, Cual es tu edad: ' %usuario))
edad = validarEdad(edad)
if edad >= 18:
print("Tu usuario es %s y tu edad es %d, por lo tanto sos MAYOR de edad" %(usuario, edad))
else:
print("El usuario es %s y tu edad es %d, por lo tanto sos MENOR de edad" %(usuario, edad))
|
61efde5b13a9f16e32bd2afa6e2a1de0fae69cdc | SMDXXX/Practice-Materials | /if_statement.py | 660 | 4.1875 | 4 | x = 5
y = 8
z = 5
a =3
"""
if x>y:
print("x is grater than y") #stement is flase will not do anything
"""
"""
if x<y:
print("x is grater than y")#console will print
"""
"""
if z<y>x:
print('y is greater than z and less than x')#console will print
"""
"""
if z<y>x>a:
print('y is greater than z and less than x and x is grater than a')#console will print
"""
"""
if z <= x:
print("z is less than or equal to x")#console will print
"""
"""
if z == x:#must have 2 "==" for equal to lodgic
print("z is equal to x")#console will print
"""
if z != y:#does not equal
print("z is not equal to y")#console will print
|
ecdd8cfe980b0e60ea261110a4d418a07689889f | yszpatt/PythonStart | /pythonlearn/汉诺塔.py | 529 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-05-05 23:22:04
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
def hanoi(n, x, y, z):
if n == 1:
print(x, '---->', z)
else:
# 将前n-1个盘子移动到y上
hanoi(n - 1, x, z, y)
# 将最底下的盘子移动到z上
print(x, '---->', z)
# 将y上的n-1个盘子移动到z上
hanoi(n - 1, y, x, z)
n = int(input('输入汉诺塔高度:'))
hanoi(n, 'X', 'Y', 'Z')
|
57e21d20f16307c5034c60ea5046cb6302e8c7fc | Simonnn-a/jiangzy11 | /homework1.py | 2,548 | 3.859375 | 4 | #_*_ conding:utf-8 _*-
#@Time:2020/9/16 &{TIME}
# 1、用print函数打印多个值
a=1
b=2311
c=65533
print(a,b,c)
# 2、用print函数不换行打印
print('111',end='')
print('222')
# 3、导入模块的方式有哪些
import
from xxxx import xxxx
# 4、python有哪六种数据类型?不可变数据类型有哪些?可变数据类型有哪些?
Python中的数据类型包括:number(int,float,bool,complex)、string、tuple、list、dict、set
不可变类型:number、string、tuple
可变类型:list、dict、set
# 5、python3中可以支持哪些数值类型?
字符串,数字,列表,字典,元组,集合
# 6、判断变量类型有哪些方式,分别可以用哪些函数?
a1=12321
b1=type(a)
print(b1)
# 7、分别对49.698作如下打印
# 1)四舍五入,保留两位小数
from decimal import Decimal
a2=49.698
b2=Decimal(a2).quantize(Decimal('0.00'))
print(b2)
# 2)向上入取整
import math
a3=2.56
print(math.ceil(a3))
# 3)向下舍取整
print(math.floor(a3))
# 4)计算8除以5返回整型
print(8//5)
# 5)求4的2次幂
print(4**2)
# 6)返回一个(1, 100)随机整数
import random
print(random.randint(1,100))
# 8、依次对变量a, b, c赋值为1, 2, 3
print('a4={},b4={},c4={}'.format(1,2,3))
# 9、截取某字符串中从2索引位置到最后的字符子串
a5='serfadvcs'
print(a5[2:])
# 10、对字符串“testcode”做如下处理:
# 1)翻转字符串
a6='testcode'
print(a6[::-1])
# 2)首字母大写
print(a6.capitalize())
# 3)查找是否包含code子串,并返回索引值
print(a6.find('code',0,len(a6)))
# 4)判断字符串的长度
print(len(a6))
# 5)从头部截取4个长度字符串
print(a6[:4])
# 6)把code替换为123
a7=a6.replace('code','123')
print(a7)
# 7)把“test code”字符串中的两个单词转换为列表中的元素,并打印处理
b3='test code'
c3=b3.split(' ')
print(c3)
# 8)把['test', 'code']把list变量中的元素连接起来
a8=['test', 'code']
a9='-'.join(a8)
print(a9)
# 11、如何打印出字符串“test\ncode”
print(r'test\ncode')
# --------------------------下面先不做
#
# 12、如何创建一个空元组
#
# 13、创建一个只包含元素1的元组,并打印出该变量的类型
#
# 14、元组中元素可以修改?如何更新元组中的元素?
#
# 15、对元组(1, 2, 3, 4, 5)做如下操作:
#
# 1)取倒数第二个元素
#
# 2)截取前三个元组元素
#
# 3)依次打印出元组中所有元素
#
# 16、把元组(1, 2, 3, 4, 5, 6)
# 元素格式化成字符串
|
7f6cbf72c3be8ca9c496c596d68394aa8bbd84a3 | haotwo/pythonS3 | /day3/员工信息表.py | 1,081 | 3.8125 | 4 | # -*- coding:utf-8 -*-
#作者 :Lyle.Li
#时间 :2019/9/26 17:13
#文件 :员工信息表.py
"""python员工信息表操作"""
import sys
import os
def select1():
with open('peopledb','r',encoding="utf-8") as f:
line = f.readlines()
for i in line:
print(i)
def select():
msg = '''
请输入或复制查询命令例如:
1. select name,age from staff_table where age > 22
2. select * from staff_table where dept = "IT"
3. select * from staff_table where enroll_date like "2013"
'''
print(msg)
user_choice_input = input(">>>:")
user_choice_input1=user_choice_input.split(' ')
if user_choice_input=='select name,age from staff_table where age >%s'%(user_choice_input1[7]):
with open('peopledb','r+',encoding='utf-8') as f:
list1=[]
count = 0
for line in f:
i =line.strip().split(',')
if i[2] > user_choice_input1[7]:
list1.append(i)
for s in list1:
count+=1
|
73a8d9cde292188513b5b25d12331c8c0ec6a1e9 | zhulingchen/P1_Facial_Keypoints | /models.py | 2,652 | 3.578125 | 4 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# As an example, you've been given a convolutional layer, which you may (but don't have to) change:
# 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel
self.conv1 = nn.Conv2d(1, 32, 5, stride=2)
## Note that among the layers to add, consider including:
# maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 64, 5, stride=2)
self.bn2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(64, 64, 3, stride=2)
self.bn3 = nn.BatchNorm2d(64)
self.conv4 = nn.Conv2d(64, 128, 3, stride=2)
self.bn4 = nn.BatchNorm2d(128)
self.conv5 = nn.Conv2d(128, 256, 3, stride=2)
self.bn5 = nn.BatchNorm2d(256)
self.linear1 = nn.Linear(256*5*5, 256)
self.bn6 = nn.BatchNorm1d(256)
self.linear2 = nn.Linear(256, 136)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = F.relu(self.bn4(self.conv4(x)))
x = F.relu(self.bn5(self.conv5(x)))
# x = F.adaptive_avg_pool2d(x, (1, 1)) # global average pooling
# x = x.view(x.shape[:2]) # squeeze the shape of (1, 1) at the last two dimensions
x = x.view(x.shape[0], -1) # flatten
x = F.relu(self.bn6(self.linear1(x)))
x = torch.tanh(self.linear2(x))
# a modified x, having gone through all the layers of your model, should be returned
return x |
1f358be10453a473710a8711a3f1a9b79dac2753 | llewellyn123/Dissatation-files | /load and display maze.py | 1,195 | 3.90625 | 4 | from mazelib import *
import random
mazename=""
mazesize=9
mazenum=999
mazearray=[[[0 for _ in range(mazesize)] for _ in range(mazesize)] for _ in range (mazenum)]
import numpy as np
#displays maze using "#" as walls
def displaymaze(a,maze):
lineprint="#"
print("############")
for i in range (0,mazesize):
for x in range(0,mazesize):
if a[maze][i][x]==1:
lineprint=lineprint+ " "
elif a[maze][i][x]==2:
lineprint=lineprint+"|"
else:
lineprint=lineprint+ "#"
print (lineprint, "#")
lineprint="#"
print("############")
#loads maze
for i in range(0,mazenum):
mazename="maze/" +str(i)+".txt"
mazearray[i]=np.loadtxt(mazename)
x=0
mazeselect=0
#allows user to pick what maze they want too look at
while True:
if x<=10:
mazeselect=random.randrange(0,500)
print(mazeselect)
x=x+1
if x>10:
mazeselect=input("pick your maze")
if mazeselect=="end":
break
for i in range (0,mazenum):
if i==int(mazeselect):
displaymaze(mazearray,i)
|
9048d68bf1d6c698d3a0548a71e039f09bdfa39d | ben0bi/ThereWillBeLED_Python | /BeSymbols_x_4.py | 3,790 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# FONT to be used with BeLED.py
# BeSymbols: Some symbols in height 4, like CAL for Calendar, DAT for Date, etc.
# Ben0bi fonts are determined by their size.
# by oki wan ben0bi @ 2018
# Font consists of char arrays.
# a char array has a specific amount of lines with variable line length.
# The line length must match each line in the same char array.
# The line count must match each char in the font array.
# return the char array for a given character.
# returns -1 the character is part of a special character.
symbols_x_4_prechar = ''
def getSymbolArray_x_4(character):
"""Returns the char array associated to the given character."""
global symbols_x_4_prechar
# is it a special character prefix?
if ord(character)==195:
# then set the prefix and return -1
symbols_x_4_prechar=chr(195)
return -1
else:
# add the character. maybe add the special character prefix (again) to the character.
ch = symbols_x_4_prechar + character
symbols_x_4_prechar = '' # reset the prefix character to nothing.
if ch in symbols_x_4_FIDX:
c = symbols_x_4_FIDX.index(ch)
if c>=0 and c<len(symbols_x_4_FONT):
return symbols_x_4_FONT[c]
# the character is not in the list.
print("Character not found: "+character+"("+str(ord(character))+")")
return symbols_x_4_font_notfound
# build a text line screenarray
def buildSymbolArray_x_4(text):
"""Build a text array from a given text."""
txtarr = []
# create the lines
for i in range(4):
txtarr.append([])
# go through each character in the text and add the character to the array.
for c in text:
charr = getSymbolArray_x_4(c)
if charr!=-1:
for y in range(len(charr)):
for x in range(len(charr[y])):
txtarr[y].append(charr[y][x])
return txtarr
# Now follows each char in the font.
# It will be assembled into the x_6_FONT and x_6_FIDX arrays at the bottom of the file.
# This one will be returned directly.
symbols_x_4_font_notfound = [
[0,0,0,0],
[0,2,4,0],
[0,4,2,0],
[0,0,0,0]
]
font_PALETTE = [
[1,2,3,4,5,6,7,8,9,0],
[1,2,3,4,5,6,7,8,9,0],
[1,2,3,4,5,6,7,8,9,0],
[1,2,3,4,5,6,7,8,9,0]
]
# These characters will be added to the FONT array.
# show OFF symbol
font_OFF = [
[4,4,4,0,4,4,0,4,4,0],
[4,0,4,0,4,0,0,4,0,0],
[4,0,4,0,4,4,0,4,4,0],
[4,4,4,0,4,0,0,4,0,0]
]
# Time Symbols
font_CAL = [
[0,0,0,0,0,0,0,0,0,0],
[1,1,0,0,1,1,0,1,0,0],
[1,0,0,1,0,1,0,1,0,0],
[1,1,0,1,1,1,0,1,1,0]
]
font_CLOCK = [
[0,0,0,0,0,0,0,0,0,0],
[1,1,0,1,0,0,1,0,1,0],
[1,0,0,1,0,0,1,1,0,0],
[1,1,0,1,1,0,1,0,1,0]
]
font_TIME = [
[0,0,0,0,0,0,0,0,0,0],
[3,0,0,3,0,7,7,0,7,7],
[3,3,3,3,0,7,0,7,0,7],
[3,0,0,3,0,7,0,0,0,7]
]
font_DATE = [
[0,0,0,0,0,0,0,0,0,0],
[1,1,0,0,0,1,1,0,1,1],
[1,0,1,0,1,0,1,0,0,1],
[1,1,0,0,1,1,1,0,0,1]
]
font_SOLSYS = [
[0,0,0,0,0,0,0,0,0,0],
[0,2,0,0,0,0,0,0,0,0],
[2,2,2,0,1,0,7,0,4,0],
[0,2,0,0,0,0,0,0,0,0]
]
font_LIGHT = [
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,3,2,2,3,0,0,0],
[0,0,3,2,1,1,2,3,0,0],
[0,0,0,3,2,2,3,0,0,0]
]
font_IP = [
[0,0,0,5,0,5,5,0,0,0],
[0,0,0,5,0,5,0,5,0,0],
[0,0,0,5,0,5,5,0,0,0],
[0,0,0,5,0,5,0,0,0,0]
]
font_SPACE = [
[0,0,0],
[0,0,0],
[0,0,0],
[0,0,0]
]
# FIDX represents all the indexes in the FONT array. get a character (here: A) like this: charpixels = FONT[FIDX.index('A')]
# The characters in FIDX MUST have the same order as they are added to the FONT array.
symbols_x_4_FIDX=[]
symbols_x_4_FIDX.extend(('P',' ','0','1','2','3','4','T','D','I'))
# The real character arrays are in the FONT array.
symbols_x_4_FONT=[]
symbols_x_4_FONT.extend((font_PALETTE, font_SPACE, font_OFF, font_CLOCK, font_CAL, font_SOLSYS, font_LIGHT, font_TIME, font_DATE, font_IP))
|
4ebaebb325d4e88a98be2373352e72c0cf6c2274 | rayturner677/polishing_skills | /17_April/stringPrac.py | 729 | 3.921875 | 4 | string1 = input("Enter:")
string2 = input("Enter:")
nw_string1 = []
def sortFunction():
if string1 > string2:
newString(string1, string2)
else:
newString2(string1, string2)
def newString(string1, string2):
for i in string1 or i == ".":
if i in string2:
nw_string1.append(i)
print(i)
else:
string1.replace(i, ".")
nw_string1.append(".")
print(nw_string1)
def newString2(string1, string2):
for i in string2 or i == ".":
if i in string1:
nw_string1.append(i)
print(i)
else:
string1.replace(i, ".")
nw_string1.append(".")
print(nw_string1)
sortFunction()
|
5c00c862946d6a156d4cee0e30c05b3594a6eb86 | Felipet144/Library_Python_Project | /Tarea_6.py | 5,008 | 3.78125 | 4 | import csv
from collections import Counter
# Menu
def menu():
print(
'Bienvenidos al menú de la biblioteca, \n 1. Solicitar un prestamo. \n 2. Consultar día con más solicitudes. \n 3. Consultar autor más solicitado. \n 4. Consultar libro más solicitado. \n 5. Consultar todos los libros prestados de un autor determinado')
choice = input()
if choice == '1':
prestamo()
menu()
if choice == '2':
dia_mas_prestamos()
menu()
if choice == '3':
autor_mas_prestamos()
menu()
if choice == '4':
libro_mas_prestamos()
menu()
if choice == '5':
libros_autor()
menu()
# Leer el archivo con los titulos
def lector_titulos():
with open('libros.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
titulos = [row for row in csvreader]
flat_titulos = [item for sublist in titulos for item in sublist]
return flat_titulos
# Leer el archivo con los autores
def lector_autores():
with open('autores.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
autores = [row for row in csvreader]
flat_autores = [item for sublist in autores for item in sublist]
return flat_autores
# Unir los archivos para crear lista de titulo, autor
def zipper():
titulos = lector_titulos()
autores = lector_autores()
zipped = zip(titulos, autores)
libros = list(zipped)
return libros
# Solicitar un libro prestado (utilizado en el menu)
def prestamo():
lista_libros = zipper()
nombre = input('Ingrese el nombre del libro a solicitar: ')
autor = input('Ingrese el nombre del autor del libro a solicitar: ')
if (nombre, autor) in lista_libros:
dia = input('Ingrese el día en que se está haciendo la solicitud: ')
fecha = input('Ingrese la fecha en la que se está haciendo la solicitud con el formato año-día-mes: ')
rows = [[nombre, autor, dia, fecha]]
filename = 'prestamos.csv'
with open(filename, 'a', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(rows)
print(f'\nSe solicitó el libro {nombre} por {autor}\nVolviendo al menu principal...\n')
else:
print(
f'\nNo se encontró el libro {nombre} por {autor}.\nPor favor, verifique la lista de libros y los datos digitados.\nVolviendo al menu principal...\n')
# Todos los libros prestados de un autor (utilizado en el menu)
def libros_autor():
with open('prestamos.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
prestamos = [row for row in csvreader]
autor = input('Ingrese el nombre del autor a consultar: ')
if any(elemento[1] == autor for elemento in prestamos):
lista_de_autor = [item for item in prestamos if item[1] == autor]
libros_de_autor = [item[0] for item in lista_de_autor]
print(f'\nLos libros prestados del autor {autor} son: {libros_de_autor}\nVolviendo al menu principal...\n')
else:
print(f'\nNo existen prestamos de libros del autor: {autor}\nVolviendo al menu principal...\n')
# Día de la semana en que llegan más personas a pedir préstamos (utilizado en el menu)
def dia_mas_prestamos():
with open('prestamos.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
prestamos = [row for row in csvreader]
dias = [item[2] for item in prestamos]
counter = Counter(dias)
dias_comunes = counter.most_common(2)
solo_dias = [elemento[0] for elemento in dias_comunes]
print(
f'\nEl día con más prestamos es: {solo_dias[0]}, seguido de {solo_dias[1]}.\nVolviendo al menu principal...\n')
# Autor más solicitado (utilizado en el menu)
def autor_mas_prestamos():
with open('prestamos.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
prestamos = [row for row in csvreader]
autores = [item[1] for item in prestamos]
counter = Counter(autores)
autores_comunes = counter.most_common(2)
solo_autores = [elemento[0] for elemento in autores_comunes]
print(
f'\nEl autor con más prestamos es: {solo_autores[0]}, seguido de {solo_autores[1]}.\nVolviendo al menu principal...\n')
# Libro más solicitado (utilizado en el menu)
def libro_mas_prestamos():
with open('prestamos.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
prestamos = [row for row in csvreader]
titulos = [item[0] for item in prestamos]
counter = Counter(titulos)
titulos_comunes = counter.most_common(2)
solo_titulos = [elemento[0] for elemento in titulos_comunes]
print(
f'\nEl libro con más prestamos es: {solo_titulos[0]}, seguido de {solo_titulos[1]}.\nVolviendo al menu principal...\n')
|
c12363d76f1c5a8f50bdf418ba954339f3e1393f | krastykovyaz/python_hse | /Исключающее ИЛИ.py | 155 | 3.953125 | 4 | def xor(x, y):
return x == 0 and y == 1 or x == 1 and y == 0
x = float(input())
y = float(input())
if xor(x, y):
print('1')
else:
print('0')
|
c603f2787f989ee092b4b4106203185ab55d6853 | koking0/Algorithm | /算法与数据结构之美/Algorithm/Greedy/01.找零问题.py | 660 | 3.671875 | 4 | # 假设商店老板需要找零 n 元钱,钱币的面额有:100元、50元、20元、5元、1元,如何找零使得所需钱币的数量最少?
def changeMoney(Denomination: list, amountOfMoney: int):
"""
:param Denomination: 钱币的所有面额
:param amountOfMoney: 找零的目标金额
:return: 不同面额钱币的张数和找不开的金额
"""
count = [0 for _ in range(len(Denomination))]
for index, value in enumerate(Denomination):
count[index] = amountOfMoney // Denomination[index]
amountOfMoney %= Denomination[index]
return count, amountOfMoney
if __name__ == '__main__':
print(changeMoney([100, 50, 20, 5, 1], 376))
|
4b0c89c828134415e4ad1da02a50c6dbf49c664e | rohini-nubolab/Python-Learning | /str_palindrome.py | 254 | 4.4375 | 4 | #Python program to check given string is Palindrome or not
def isPalindrome(s):
return s == s[::-1]
s = "MADAM"
result = isPalindrome(s)
if result:
print("Yes. Given string is Palindrome")
else:
print("No. Given string is not Palindrome")
|
9be74a761703ee5b6ae9cbf29f93645aab2dd250 | shweta4377/GNEAPY19 | /venv/Session7B.py | 1,230 | 4.5 | 4 | class Customer:
# Constructor
def __init__(self, name="NA", phone="NA", email="NA"):
self.name = name
self.phone = phone
self.email = email
c1 = Customer()
# print(c1.__dict__)
c1.name = input("Enter Customer Name: ")
c1.phone = input("Enter Customer Phone: ")
c1.email = input("Enter Customer Email: ")
# print(c1.__dict__)
# Problem : Whatever data you add in object will be temporary
# Because object will be deleted automatically and data will be lost
# Solution:
# Persistence
# 1. Save Data in Files
# 2. Save Data in DataBase
# Object Relational Mapping | ORM
# To create table see the struture of your Object :)
# Type of Object i.e. Class Name will be the Table Name
# Columns in the Table will be those which are attributes of your Object
# Customer -> Table Name
# name phone and email are column names
# Table can have 1 extra column to uniquely identify a row
# That column is primary key
choice = input("Would you like to save Customer (yes/no):")
if choice == "yes":
file = open("/Users/ishantkumar/Downloads/customers.csv", "a")
# CSV Format Data
data = "{},{},{}\n".format(c1.name,c1.phone, c1.email)
file.write(data)
file.close()
|
cdcc4497fcec7f94defaa489309ba82920a1b1e2 | vkaplarevic/MyCodeEvalSolutions | /python/vine_names.py | 1,014 | 3.8125 | 4 | #! /usr/bin/env python
import sys
def find_vine(vines, letters):
wSet = {word: list(word) for word in vines}
result = []
for vine in vines:
to_add = True
for letter in letters:
if letter not in wSet[vine]:
to_add = False
else:
index = wSet[vine].index(letter)
del wSet[vine][index]
if to_add:
result.append(vine)
return result
def main():
if len(sys.argv) != 2:
print('Please provide path to test cases!')
return
test_cases = open(sys.argv[1], 'r')
for line in test_cases:
if line == '\n' or line == '':
continue
tmp = line.strip().split(" | ")
vines = tmp[0].split(" ")
letters = list(tmp[1])
results = find_vine(vines, letters)
if len(results) == 0:
print "False"
else:
print " ".join(results)
test_cases.close()
if __name__ == '__main__':
main()
|
777729b7abb5449104350186cf3da131ec31bd52 | ELFUCAR/PYTHON-PROJECTS-2019 | /random1.py | 147 | 3.609375 | 4 | import random
avg=0
sum=0
n=1000
for x in range(n):
x=int(random.random()*6)+1
sum=sum+x
# print(x)
avg=sum/n
print (avg)
|
680105c9406c526f8f21d54b56d4d9ae31738307 | 7vgt/CSE | /Andrew Esparza-HangMan.py | 1,375 | 3.984375 | 4 | import random
win = "False"
the_count = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
guesses = 10
letters_guessed = []
word_bank = ["futuristic house", "milk and cookies", "snowy forest", "boomerang","spooky house","video game",
"do you know the way","raindrop droptop","jellyfish","thirtyvirus"]
word = random.choice(word_bank)
range_of_letters = len(word)
word_selector_stars = range_of_letters * "*"
if word == "futuristic house":
word_selector_stars = "********** *****"
if word == "milk and cookies":
word_selector_stars = "**** *** *******"
if word == "snowy forest":
word_selector_stars = "***** ******"
if word == "spooky house":
word_selector_stars = "****** *****"
if word == "video game":
word_selector_stars = "***** ****"
if word == "do you know the way":
word_selector_stars = "** *** **** *** ***"
if word == "raindrop droptop":
word_selector_stars = "******** *******"
while guesses > 0:
print(word_selector_stars)
print(word)
output = []
for letter in word:
if letter in letters_guessed:
output.append(letter)
else:
output.append("*")
guess = input("Guess: ")
guesses -= 1
print(output)
guess_lowercase = guess.lower()
letters_guessed.append(guess_lowercase)
if letters_guessed == word:
print("you win")
guess = 0
|
f76b8dd912cfe8f90a364b7761eef073b38954b6 | xanderyzwich/Playground | /python/tools/numbers/print_count_reversed.py | 365 | 4.125 | 4 | """
Print the numbers 1 to 100 in reverse order
"""
def count_reversed(input_integer):
if input_integer == 100:
print(input_integer)
return
else:
count_reversed(input_integer+1)
print(input_integer)
def print_count_reversed():
print_count_reversed(1)
if __name__ == '__main__':
count_reversed()
|
75d687107cae9c3deeafbef9f25379fdceef70c2 | poplock1/Lightweight_ERP | /hr/hr.py | 6,266 | 3.671875 | 4 | """ Human resources module
Data table structure:
* id (string): Unique and random generated identifier
at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters)
* name (string)
* birth_year (number)
"""
# everything you'll need is imported:
# User interface module
import ui
# data manager module
import data_manager
# common module
import common
from os import path
hr_path = path.dirname(__file__)
filename = path.join(hr_path, 'persons.csv')
title_list = ["ID", "Name", "Birth year"]
input_list = ["Name", "Birth year"]
person_id = 0
person_name = 1
person_year = 2
def start_module():
"""
Starts this module and displays its menu.
* User can access default special features from here.
* User can go back to main menu from here.
Returns:
None
"""
table = data_manager.get_table_from_file(filename)
title = "Human Resources menu"
list_options = ["Show table",
"Add",
"Remove",
"Update",
"Oldest person",
"Person closest to average"]
exit_message = "Exit menu"
while True:
ui.print_menu(title, list_options, exit_message)
inputs = ui.get_inputs(["Please enter a number: "], "")
option = inputs[0]
if option == "1":
show_table(table)
elif option == "2":
add(table)
elif option == "3":
list_labels = ["id"]
title = "Please provide index to be removed"
try:
item_id = ui.get_inputs(list_labels, title)[0]
except NameError:
ui.print_error_message("You typed wrong id!")
remove(table, item_id)
elif option == "4":
list_labels = ["id"]
title = "Please provide"
try:
item_id = str(ui.get_inputs(list_labels, title)[0])
except NameError:
ui.print_error_message("You typed wrong id!")
update(table, item_id)
elif option == "5":
ui.print_result(get_oldest_person(table),
'The oldest person is/are:\n')
elif option == "6":
ui.print_result(get_persons_closest_to_average(
table), 'Person closest to the average is:\n')
elif option == "0":
data_manager.write_table_to_file(
path.join(hr_path, 'persons.csv'), table)
return False
else:
raise KeyError("There is no such option.")
def show_table(table):
"""
Display a table
Args:
table (list): list of lists to be displayed.
Returns:
None
"""
ui.print_table(table, title_list)
def add(table):
"""
Asks user for input and adds it into the table.
Args:
table (list): table to add new record to
Returns:
list: Table with a new record
"""
new_birth = 2
while True:
new_record = ui.get_inputs(
input_list, "Please provide personal information:\n")
new_record.insert(0, common.generate_random([]))
if not new_record[new_birth].isdigit() or not int(new_record[new_birth]) >= 1900 or not int(new_record[new_birth]) <= 2020:
ui.print_error_message(
"Wrong value typed. Year must be higher than 1900 and lower than 2020")
else:
break
table = table + [new_record]
return table
def remove(table, id_):
"""
Remove a record with a given id from the table.
Args:
table (list): table to remove a record from
id_ (str): id of a record to be removed
Returns:
list: Table without specified record.
"""
for element in table:
if element[person_id] == id_:
table.remove(element)
return table
def update(table, id_):
"""
Updates specified record in the table. Ask users for new data.
Args:
table (list): list in which record should be updated
id_ (str): id of a record to update
Returns:
list: table with updated record
"""
edited_birth = 2
index = common.get_ind(table, person_id, id_)
for element in table:
if element[person_id] == id_:
while True:
edited_record = ui.get_inputs(
input_list, "Please provide personal information:\n")
edited_record.insert(0, id_)
if not edited_record[edited_birth].isdigit() or not int(edited_record[edited_birth]) >= 1900 or not int(edited_record[edited_birth]) <= 2020:
ui.print_error_message(
"Wrong value typed. Year must be higher than 1900 and lower than 2020")
else:
table[index] = edited_record
break
return table
# special functions:
# ------------------
def get_oldest_person(table):
"""
Question: Who is the oldest person?
Args:
table (list): data table to work on
Returns:
list: A list of strings (name or names if there are two more with the same value)
"""
temp_list = []
for element in table:
temp_list.append(int(element[2]))
min_year = min(temp_list)
min_year_records = []
for element in table:
if int(element[2]) == min_year:
min_year_records.append(element[1])
return min_year_records
def get_persons_closest_to_average(table):
"""
Question: Who is the closest to the average age?
Args:
table (list): data table to work on
Returns:
list: list of strings (name or names if there are two more with the same value)
"""
temp_list = []
for element in table:
temp_list.append(int(element[2]))
current = 2020
s_years = 0
for element in temp_list:
s_years += (current - element)
average = s_years/len(temp_list)
closest = []
i = 0
while len(closest) == 0:
for element in table:
if (current - int(element[2])) == average + i or (current - int(element[2])) == average - i:
closest.append(element[1])
i += 0.1
return closest
|
9ce8c4e3c059066a2b20089e39ddbc898f7c4bd8 | Rahmanism/pythonlearn | /02_01.py | 1,460 | 4.0625 | 4 | # Chapter 02
# lambda functions:
myfunc = lambda x: x * 2
print(myfunc(3))
a = [(3,4), (7,1), (5,9), (2,2)]
a.sort()
print(a)
a = [(3,4), (7,1), (5,9), (2,2)]
a.sort(key = lambda x: x[1])
print(a)
# double elements using map and lambda
a = [1, 3, 4, 0.5]
print(list(map(lambda x: x*2, a)))
# say big or small using map and lambda
a = [10, 11, 25, 7, 9, 100, 6]
print(list(map(lambda x: 'big' if x > 10 else 'small', a)))
# filter even numbers using filter and lambda
a = [10, 11, 25, 7, 9, 100, 6]
print(list(filter(lambda x: x%2 == 0, a)))
# quiz
array = [(1,4,5), (3,2,7), (8,3,6), (9,2,3)]
array.sort(key = lambda a:a[2])
print(array)
mylist = [2,3,5,8,11,14,17,102,44]
print(list(map(lambda x:'Yes' if x%2==1 else 'No',mylist)))
mylist = [2,15,26,8,11,14,17,102,44]
map_list = map(lambda x:x%10,mylist)
filter_list = list(filter(lambda x: x<=4,map_list))
print(filter_list)
mylist = ['yellow', 'red', 'blue','red','yellow','red','blue','purple']
mylist.sort()
mylist = list(map(lambda x: 'color' if x=='red' else x,mylist))
output = list(filter(lambda x: x=='red',mylist))
print(output)
###########################################
print("#######generators")
# generator functions yeild
def firstn():
return (1,2,3)
print(firstn())
def firstn2():
yield 1
yield 2
yield 3
for i in firstn2():
print(i)
def firstn3(n):
num = 0
while (num < n):
yield num
num += 1
for i in firstn3(4):
print(i)
|
6d837254bcda03b85a75ad659894e9c5b3ff6ad6 | Girishn-lab/PythonPratice | /Classes/MenuSetGet.py | 997 | 3.765625 | 4 | setprice = None
class Menu:
def __init__(self):
self.menu_items = []
def add_items(self, item, price):
self.menu_items.append(item)
self.menu_items.append(price)
def show(self):
return self.menu_items
def set_price(self, item, setprice):
for k, v in enumerate(self.menu_items):
if v == item:
self.menu_items.insert(k + 1, setprice)
self.menu_items.pop(k + 2)
def get_price(self, item):
for i, v in enumerate(self.menu_items):
if v == item:
return self.menu_items[i + 1]
m = Menu()
m.add_items("idly", 20)
print(m.show())
m.set_price("idly", 40)
print(m.show())
m.get_price("idly")
print(m.show())
m.add_items("vada", 50)
print(m.show())
m.set_price("vada", 60)
print(m.show())
m.get_price("vada")
print(m.show())
# m.add_items("dosa",35)
# print(m.show())
# m.set_price("dosa",40)
# print(m.show())
# m.get_price("dosa")
# print(m.show())
|
faeaf1249610116a4c905bb4b04f1d85ecc5d7ed | rafaelperazzo/programacao-web | /moodledata/vpl_data/107/usersdata/219/52023/submittedfiles/questao3.py | 253 | 3.734375 | 4 | # -*- coding: utf-8 -*-
p=int(input('Digite um numero p:'))
q=int(input('Digite um numero q:'))
contador=0
i=2
while i<(p) and (q):
if p%i==0 and q%i==0:
contador=contador+1
if q==p+2:
print('S')
else:
print('N')
|
62f958100d52bb930255be0a3e161ac12a4d9bf6 | brettimus/yum-yum-cake | /q5-v3.py | 712 | 3.84375 | 4 | # InterviewCake (Beta Exercise 5)
# Brett Beutell
# June 17, 2014
# Define rectangles as hashes
# r = {"x" : x, "y" : y, "width" : w, "height" : h}
def find_r_int(r1,r2):
result = {}
left_rect, right_rect = (r1,r2) if r1["x"] <= r2["x"] else (r2,r1)
if left_rect["x"] + left_rect["width"] < right_rect["x"]:
return None
result["x"] = right_rect["x"]
result["width"] = min(left_rect["x"] + left_rect["width"] - right_rect["x"],\
right_rect["width"])
lower, higher = (r1,r2) if r1["y"] <= r2["y"] else (r2,r1)
if higher["y"] - higher["height"] >= lower["y"]:
return None
result["y"] = lower["y"]
result["width"] = min(lower["height"], lower["y"] - (higher["y"] - higher["height"]))
return result
|
0c84351c8fca55befc8cc7e055e2e4567ff5d444 | Andkeil/AirBnB_clone | /tests/test_models/test_city.py | 813 | 3.859375 | 4 | #!/usr/bin/python3
"""unittests for City"""
import unittest
import datetime
from models.city import City
class TestCity(unittest.TestCase):
"""class TestCity"""
def setUp(self):
"""setup"""
self.city = City()
def test_city(self):
"""testing for a type of the attributes and
if attributes are not empty"""
city = City()
self.assertIsNotNone(city.id)
self.assertIsNotNone(city.created_at)
self.assertIsNotNone(city.updated_at)
self.assertIsInstance(city.id, str)
self.assertIsInstance(city.created_at, datetime.datetime)
self.assertIsInstance(city.updated_at, datetime.datetime)
self.assertIsNotNone(city.name)
self.assertIsNotNone(city.state_id)
if __name__ == '__main__':
unittest.main()
|
b608a2a313fe598cd0a71e7e9274361cd23412d5 | Oskar-watto/connet-four | /dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup drgon slayer dragon fighting 3.py | 8,719 | 4.03125 | 4 | import random
import time
#asking for name because why not
def getname():
name = input("enter name:")
time.sleep(3)
print(name + " is now playing: dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
#printing some hype about the game
def gamerundown():
#making 'rest' so i dont have to put int time sleep every time
def rest():
time.sleep(3)
print("would you like a rundown of the game: dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3?")
rundown = input("enter [Y] for rundown or enter [N] to skip rundown")
#ask for rundown or to skip
if rundown == 'Y':
print("you have selected to hear a rundown of the game: dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
rest
print("dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3 is an insane text based game!")
rest
print("you will be given a series of choices")
rest
print("the decisions you make will either kill you, or possibly you will survive long enough to die later")
rest
print("can you make it to the end?")
rest
print("or will you be brutally murdered along the way")
rest
print("you adventure in dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
rest
print("lets get into playing dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
elif rundown == 'N':
print("you have selected to skip the rundown of: dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
time.sleep(3)
print("you are free to continue")
else:
print("invalid choice, please try again")
gamerundown()
#game begins and starts printing the intro
def printintro():
print("Welcome to dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
time.sleep(3)
input("ARE YOU READY TO EMBRACE THE PURE SHOCK AND AWE PROVIDED BY: dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3?")
time.sleep(3)
gamerundown()
#asking for rundown or not
time.sleep(3)
getname()
time.sleep(3)
print("you are now playing dragon shadow monster legends fighting dragon heroes dragon monster killing dragons sharknado powerup dragon slayer dragon fghting 3")
time.sleep(3)
print("You are walking through a deep dark forest")
time.sleep(3)
print("a fork in the track appears")
time.sleep(3)
print("you have two options....go right deeper into the forest.... or go left towards a weirdly coloured swamp")
time.sleep(3)
#first choice
def playerchoice():
choice = input ("which way will you go? [L] or [R] or toss a coin [C]")
if choice == 'L':
print("you selected left")
leftA()
#leads to first left answer
elif choice == 'R':
print("you slected right")
rightA()
#leads to first right answer
elif choice == 'C':
print("you want to toss a coin, brave")
cointoss()
else:
print("you made an invalid choice, enter again")
playerchoice
#just in case they dont put in the right thing
#response if coin toss is chosen is always the same
def cointoss():
time.sleep(2)
print("you cant make a decision")
time.sleep(2)
print("is the pressure too overwhelming")
time.sleep(2)
print("either way, you die due to lack of brain power")
time.sleep(2)
end()
input:("[enter] to end")
gamecontinue = False
#comes from choice 1
def leftA():
time.sleep(2)
print("you went left towards the swamp")
time.sleep(2)
print("as you approach the swamp you see a massive crodile and you are eaten alive")
time.sleep(2)
print("death sucks, better luck next time")
time.sleep(2)
end()
input("[enter] to end")
gamecontinue = False
#wrong choice so game ends
#comes from choice one
def rightA():
time.sleep(2)
print("you went right deeper into the forest")
time.sleep(2)
print("you approach a wild charlie, there is a chance he hasn't seen you, but you are unsure")
time.sleep(2)
print("you have two options, take a left and get the hell out of there.... or go right and try to take on the wild charlie")
time.sleep(2)
#second choice
playerchoiceB()
#choosing right from option 1 leads to this (second choice)
def playerchoiceB():
choice = input ("which way will you go? [L] or [R] or toss a coin [C]")
if choice == 'L':
print("you selected left")
leftB()
#leads to second left option
elif choice == 'R':
print("you slected right")
rightB()
#leads to second right option
elif choice == 'C':
print("you want to toss a coin, brave")
cointoss()
#same cointoss ending always
else:
print("you made an invalid choice, enter again")
playerchoiceB
#invalid choice response again
def leftB():
time.sleep(2)
print("you run and manage to escape the charlie")
time.sleep(2)
print("you approach some treasure, but there is one more choice first")
time.sleep(2)
print("in front of you is two doors")
time.sleep(2)
print("they are both identical")
time.sleep(2)
print("but through one lays treasure")
time.sleep(2)
print("and through the other certain death awaits")
time.sleep(2)
print("your choice will have to be random")
time.sleep(2)
print("which way will you go")
time.sleep(2)
playerchoiceC()
#goes to third choice
def rightB():
time.sleep(2)
print("you move to attack the wild charlie")
time.sleep(2)
print("but it has seen you through and is anticipating your attack")
time.sleep(2)
print("it uses jujitsu to slaughter you")
time.sleep(2)
print("death sucks, better luck next time")
time.sleep(2)
end()
input("[enter] to end")
gamecontinue = False
#death and end game
#random number for random door being correct
answer = random.randint(1,2)
#regardless of what the player enters win or die is randomly generated
def playerchoiceC():
choice = input ("which way will you go? [L] or [R] or toss a coin [C]")
if choice == 'L':
print("you selected left")
#it tells you that you go through the left door but depending on the random number generated you have 50/50 chance of winning
if answer == 1:
door1()
elif answer == 2:
door2()
elif choice == 'R':
print("you slected right")
#tells you that the right door has been chosen but 50/50 chance of winning again
if answer == 1:
door1()
elif answer == 2:
door2()
elif choice == 'C':
print("you want to toss a coin, brave")
cointoss()
#still death by cointoss
else:
print("you made an invalid choice, enter again")
playerchoiceC()
def door1():
time.sleep(2)
print("the shadow monster dragon is waiting behind this door")
time.sleep(2)
print("death sucks, better luck next time")
time.sleep(2)
end()
input("[enter] to end")
gamecontinue = False
#door1 ends in death
def door2():
time.sleep(2)
print("your treasure awaits")
time.sleep(2)
print("YOU WIN")
time.sleep(2)
end()
input("[enter] to end")
gamecontinue = False
#door2 ends with a win
def end():
print("GAME OVER")
time.sleep(2)
gamecontinue = True
while gamecontinue == True:
printintro()
playerchoice()
#after the first choice all of the def's lead on to each other
gamecontinue = False
|
3f6909b6683cde312ba18ff075cbb409ecc2cc93 | vinit-patel/Seaborn | /Barplot with data values.py | 747 | 3.5 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = sns.load_dataset("tips")
groupedvalues=df.groupby('day').sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["total_bill"].argsort().argsort()
#Here the rank function is required since the values are not in ascending order, based on the rank of total_bill the bars are colored in ascending order.
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette=np.array(pal[::-1])[rank])#Here the rank determines the color for the bar.
#g=sns.barplot(x='day',y='tip',data=groupedvalues)
for index, row in groupedvalues.iterrows():
g.text(row.name,row.tip, round(row.total_bill,2), color='black', ha="center")
plt.show()
|
9c1ce5ab9239b4b3c22d0d4b93a5082c41349667 | rubengr16/BeginnersGuidePython3 | /5_numbers_booleans_none/1_int.py | 588 | 4.34375 | 4 | # Integral numbers are represented by int type indepently from their size
integer = 1
print(integer)
print('x type:', type(integer))
x = 1111111111111111111111222222222233333333333333333333333333333334444444444444444444444555555555555
print(integer)
print('x type:', type(integer))
# int() function can be used to cast to int
integer = int('98')
print(integer)
print(type(integer))
integer = 1.65
print('x type:', type(integer), integer)
print(int(integer))
# input() function always returns a string, we can also cast it
integer = int(input("Enter a whole number: "))
print(integer) |
53d2f291dd099896c3399c84eaa17bba3778384b | yeshwanthreddy12/Demo | /venv/prime.py | 112 | 3.90625 | 4 | num=90
for i in range(2,num):
if num%2==0:
print("not prime")
break
else:
print('prime') |
4bcc211eea9666c58640f5d73970318ca32fa03e | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk12/033_crayonColors.py | 2,087 | 4.1875 | 4 | def crayonColors():
'''
crayonColors=checks the file with the 1990 crayon colors, removes the ones
listed in the file that were discontinued, and adds the ones listed in
the file that were added to production
@param original=file with the list of colors in 1990
@param removed=file with list of colors discontinued
@param added=file with list of colors added to production
@param final=new file with list of colors in production after 1990's
@param colorList=list holding all the colors from original
@param removeList=list of colors from removed to take from original
note:book says that there is an almond but there is no almond in the file and
the color Apricot was on both the original list and the list of colors added
so I added a bit to remove repeated colors
'''
try:
original=open("Pre1990.txt", 'r')
removed=open("Retired.txt", 'r')
added=open("Added.txt", 'r')
final=open("final.txt", 'w')
colorList=[line.rstrip() for line in original]
for line in added:
if colorList.count(line.rstrip())==0:
colorList.append(line.rstrip())
removeList=[line.rstrip() for line in removed]
for color in colorList:
for noncolor in removeList:
if color == noncolor:
colorList.remove(color)
colorList.sort()
for sep in range(len(colorList)):
colorList[sep]=colorList[sep] + "\n"
final.writelines(colorList)
original.close()
removed.close()
added.close()
final.close()
except:
print("Error.")
if __name__ == "__main__":
def test_crayonColors():
'''
test_crayonColors()=tests the crayonColors() method
@param cont=boolean that determines if program repeats
'''
try:
cont=True
while cont==True:
crayonColors()
end=input("Continue? y or n ")
if end.lower()=="n":
cont=False
except:
print("Error, test.")
test_crayonColors()
|
7de65c53935db2d0ed4ba01139a338b99586e491 | The-afroman/validate_emails_python | /emailCheck.py | 881 | 3.53125 | 4 | from validate_email import validate_email
import csv
valid_email_list = []
invalid_email_list = []
with open('data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for i in readCSV:
email = i[0]
#print(email)
is_valid = validate_email(email , verify=True)
if is_valid is None:
print(email + " VALID!")
valid_email_list.append(email)
else:
print (email + " INVALID!")
invalid_email_list.append(email)
with open('valid.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['VALID_EMAILS'])
for i in valid_email_list:
writer.writerow([i])
with open('invalid.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['INVALID_EMAILS'])
for i in invalid_email_list:
writer.writerow([i])
|
e46137d3fd33abdab6a3b082e2bda097a04e537e | SahilMund/A_ML_Cheatsheets | /Machine Learning A-Z Template Folder/Part 6 - Reinforcement Learning/Section 32 - Upper Confidence Bound (UCB)/UpperConfidenceBound.py | 1,686 | 3.71875 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Ads_CTR_optimisation.csv')
#implementing UCB
N=10000 #Representing the number of customers
d=10 #Representing the no of ad versions
ads_selected=[]
#[0]*d represents a vector containing only zeros of size d. It is because initially the sumber of selection and sum of reward of each round is 0
numbers_of_selections=[0] * d #no. of selection is the variable representing no. of times ad i as selected upto round n
sum_of_reward=[0]*d #sum_of_reward is the variable representing sum of reward of ad i upto round n
total_reward=0
#calculating avg reward and confidence at each round
import math
for n in range(0,N): #for all customers on social media
max_upper_bound=0
ad=0
for i in range(0,d): #for all add versions
if numbers_of_selections[i]>0:
avg_reward = sum_of_reward[i] / numbers_of_selections[i]
#caclulateing confidence(of upper bound only)
delta_i = math.sqrt(3/2 * math.log(n + 1) / numbers_of_selections[i])
upper_bound=avg_reward+delta_i
else:
upper_bound = 1e400
if upper_bound>max_upper_bound:
max_upper_bound=upper_bound
ad=i
ads_selected.append(ad)
numbers_of_selections[ad]=numbers_of_selections[ad]+1
reward=dataset.values[n,ad]
sum_of_reward[ad]=sum_of_reward[ad]+reward
total_reward=total_reward+reward
#Visualizing the results
plt.hist(ads_selected)
plt.title('Histogram of Ads selections')
plt.xlabel('Ads')
plt.ylabel('No.of times each ad was selected')
plt.show()
|
f6a775b831f4f0183a829014696e16ca81e6bdf4 | conradylx/Python_Course | /10.03.2021/Podsumowujace/exc8.py | 1,401 | 3.515625 | 4 | # Napisz program, który będzie sprawdzał, czy nasz samochód kwalifikuje się do zarejestrowania jako zabytek.
# Program zacznie ze stworzonym słownikiem o trzech kluczach:
# marka (str)
# model (str)
# rocznik (int)
# Wypisze ten słownik na ekran (bez żadnego formatowania)
# Sprawdzi, czy samochód ma minimum 25 lat. Jeśli tak, wypisze komunikat:
# “Gratulacje! Twój samochód (tutaj_marka) może być zarejestrowany jako zabytek.”
# Jeśli nie spełnia powyższego warunku, wypisze komunikat:
# “Twój samochód (tutaj_marka) jest jeszcze zbyt młody.”
# Gdy program będzie poprawnie działał, pozmieniaj wartości słownika (ale nie klucze!),
# aby zobaczyć, czy progam również zmienia swoje zachowanie.
import datetime
def check_if_car_is_antique(data: dict):
print(data)
actual_year = datetime.datetime.now()
car_age = 0
if data['year'] > actual_year.year:
print("Nieprawidłowy rocznik samochodu.")
else:
car_age = actual_year.year - data['year']
if car_age >= 25:
print(f'Gratulacje! Twój samochód {data["mark"]} może być zarejestrowany jako zabytek.')
else:
print(f'Twój samochód {data["mark"]} jest jeszcze zbyt młody.')
car_details = {"mark": "Opel", "model": "Astra", "year": 1990}
check_if_car_is_antique(car_details)
|
ed889bd716ca8b4148dbbe91ecc50a58414a2bc8 | AlekseyOgorodnikov/python-algortims | /main_reversed_array.py | 1,036 | 4.09375 | 4 | def inverse_array(arr: list, n: int):
""""
Обращение массива (задом - наперед)
в рамках индекса от 0 до n-1
"""
for i in range(n//2):
arr[i], arr[n - 1 - i] = arr[n - 1 - i], arr[i]
return arr
# arr.reverse()
# return arr
# a = arr
# first = 0
# last = n - 1
# while first < last:
# holder = a[first]
# a[first] = a[last]
# a[last] = holder
# first += 1
# last -= 1
# return a
def test_inverse_array():
arr1 = [1, 2, 3, 4, 5]
print(arr1)
inverse_array(arr1, 5)
print(arr1)
if arr1 == [5, 4, 3, 2, 1]:
print('test1 - ok')
else:
print('test1 - fail')
arr2 = [0, 0, 0, 0, 0, 0, 0, 10]
print(arr2)
inverse_array(arr2, 8)
print(arr2)
if arr2 == [10, 0, 0, 0, 0, 0, 0, 0]:
print('test2- ok')
else:
print('test2 - fail')
test_inverse_array()
inverse_array([22,45,12,324,2342,123124,54535,123,3242,23423],10) |
9842d91525ccd044f9dfb59aaef5bda8cc93aa03 | chapman-cpsc-230/hw2-Jake-Adams | /Cooling.py | 355 | 3.953125 | 4 | import math
t_tea = float(input("Temperature of the Tea: "))
t_air = float(input("Temperature of the Air: "))
t_min = float(input("Number of Minutes: "))
print("Minute Temperature")
print(" 0 ", t_tea)
time = 1
while time < t_min:
t_tea = t_tea - .055* (t_tea-t_air)
print(" ", time ," ", "%.1f" % t_tea)
time = time + 1
|
ecc1e51f73d5063187d7eb1da163df733749a631 | wyattyhh/Little-Simulated-System | /Database.py | 1,321 | 3.546875 | 4 | import sqlite3, random
# Randomly generate 6 characters from given characters
def generateID():
characters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789@_#*-&"
results = ""
for n in range(6):
x = random.choice(characters)
results += x
return(results)
# Genertate random real value from 0 to 100
def generateArrival():
x = random.uniform(0,100)
return(x)
# Genertate exponential distribution of parameter 1 and round up
def generateDuration():
x = random.expovariate(1)
return(int(round(x + .5)))
# create class
class Simulation:
def __init__(self, id, arrival, duration):
self.id = id
self.arrival = arrival
self.duration = duration
conn = sqlite3.connect('database.db')
c = conn.cursor()
# create table
c.execute("""CREATE TABLE simulations (
id text,
arrival real,
duration integer
)""")
# define a function to add data into table
def insert_sim(sim):
with conn:
c.execute("INSERT INTO simulations VALUES(:id, :arrival, :duration)",
{'id': sim.id, 'arrival': sim.arrival, 'duration': sim.duration})
# Simulate 100 data
for n in range(100):
x = Simulation(generateID(), generateArrival(), generateDuration())
insert_sim(x)
conn.close()
|
6621d7c5f20858b70e21dbd542a48695a5150a90 | JorgeHernandezRamirez/PythonLearning | /generator.py | 1,283 | 3.640625 | 4 | import unittest
class GeneratorTest(unittest.TestCase):
def test_shouldIterateFromGeneratorFunction(self):
generator = self.getIteratorNumericValues();
self.assertEqual(next(generator), 0)
self.assertEqual(next(generator), 1)
self.assertEqual(next(generator), 2)
self.assertEqual(next(generator), 3)
self.assertEqual(next(generator), 4)
self.assertRaises(StopIteration, next, generator)
def test_shouldIterateFromGeneratorFunctionLoop(self):
counter = 0
for value in self.getIteratorNumericValues():
self.assertEqual(value, counter)
counter = counter + 1
def test_shouldIterateString(self):
iterator = iter("Jorge")
self.assertEqual(next(iterator), "J")
self.assertEqual(next(iterator), "o")
self.assertEqual(next(iterator), "r")
self.assertEqual(next(iterator), "g")
self.assertEqual(next(iterator), "e")
def test_shouldIterateList(self):
iterator = iter(list(["1", "2"]))
self.assertEqual(next(iterator), "1")
self.assertEqual(next(iterator), "2")
def getIteratorNumericValues(self):
for value in range(5):
yield value
if __name__ == "__main__":
unittest.main() |
497275871ae0913a2097e41b2bca3396e1518eba | JeonJe/Algorithm | /4.programmers/프로그래머스_jungle/프로그래머스_햄버거 만들기.py | 581 | 3.59375 | 4 | def solution(ingredient):
answer = 0
stack = []
for i in range(len(ingredient)):
if ingredient[i] != 1 :
stack.append(ingredient[i])
else:
#스택의 마지막 4개가 빵야채고기빵 순서이면
if len(stack) >= 3 and ''.join(map(str,stack[-3:])) == "123":
answer += 1
for _ in range(3):
stack.pop()
else:
stack.append(ingredient[i])
return answer
ingredient = [1, 3, 2, 1, 2, 1, 3, 1, 2]
print(solution(ingredient)) |
017f44d46e148a8bc1f1a523f9e1bc18b64314ad | kta95/CS50-Python | /pset7/houses/import.py | 1,012 | 4.03125 | 4 | # TODO
import csv
from sys import argv
import sqlite3
con = sqlite3.connect("students.db") # connect to database
cur = con.cursor()
if len(argv) != 2: # check if the number of command-line arguments is correct
print('Usage: python import.py characters.csv')
exit(0)
file_name = argv[1]
with open(file_name, "r") as file: # read the csv file from the command-line argument
reader = csv.DictReader(file)
# insert data from csv file to students table in database
for row in reader:
name = row['name'].split(' ')
if len(name) == 3:
cur.execute("INSERT INTO students (first,middle,last,house,birth) VALUES(?,?,?,?,?);",
(name[0], name[1], name[2], row['house'], row['birth']))
elif len(name) == 2:
cur.execute("INSERT INTO students (first,last,house,birth) VALUES(?,?,?,?);",
(name[0], name[1], row['house'], row['birth']))
con.commit()
con.close() # close the database connection
|
40b5c9f42adb1fc3f0493115334422b6d4823252 | marcosValle/ML | /CS229/week1/gradientDescent.py | 1,535 | 3.625 | 4 | import math
import matplotlib.pyplot as plt
import numpy as np
def h(x, t0, t1):
return t1+t0*x
def J(data, t0, t1):
j = 0
for d in data:
j += math.pow((h(d[0], t0, t1) - d[1]), 2)
return j/(2*len(data))
#gradientFunction
def gradientJ(data,t0,t1):
t0_grad = 0
t1_grad = 1
m = len(data)
for d in data:
t0_grad += d[0]*(h(d[0], t0, t1) - d[1])
t1_grad += (h(d[0], t0, t1) - d[1])
return t0_grad/m, t1_grad/m
#plot the given learning data
def plotData(data):
plt.scatter(*zip(*data), marker='o')
#plot a line h(x)=t0+t1*x
def plotLine(t0, t1, x_range, color):
x = np.array(x_range)
y = h(x, t0, t1)
return plt.plot(x, y, color=color)
#finds t0 and t1 for a certain number of iterations
def findParams(iterations, t0, t1):
for i in range(iterations):
t0_grad, t1_grad = gradientJ(data, t0, t1)
t0 = t0 - alpha * t0_grad
t1 = t1 - alpha * t1_grad
print(t0, t1, J(data, t0, t1))
return t0, t1
data = [(0,0),(1,5),(2,4), (7,9), (22,13)]
#data = [(3,2),(1,2),(0,1),(4,3)]
alpha = 0.0001
maxIter = 999
t0 = 2
t1 = 3
for iteration in range(10, maxIter):
t0Res, t1Res = findParams(iteration, t0,t1)
#plot the params according to the number of iterations
# plt.scatter(iteration, t0Res)
# plt.scatter(iteration, t1Res)
#plot h for this t0 and t1
# plotLine(t0Res,t1Res,range(0,25), 'blue')
#plot final regression line
plotLine(t0Res, t1Res, range(0,25), 'red')
plotData(data)
plt.show()
|
0e25ef9c33f0bc08c8cdd2780470728ea6c8e38b | iniej/camelcase_with_unittest | /test_camelcase.py | 468 | 3.671875 | 4 | import camelcase
from unittest import TestCase
class TestCamelCase(TestCase):
def test_camelcase_sentence(self):
self.assertEqual('helloWorld', camelcase.camel_case('Hello World'))
self.assertEqual('', camelcase.camel_case(''))
self.assertEqual('helloWorld', camelcase.camel_case(' Hello World '))
self.assertEqual('$$$$$@@', camelcase.camel_case('$$$$$ @@'))
self.assertEqual('roof', camelcase.camel_case('ROOF'))
|
8c010946744d3d3c1d1e2857f99858bf98edbc3a | jeffscott2/ceiling-zero | /week_2_code/csv_helper.py | 383 | 3.5 | 4 |
import csv
class CsvHelper:
def __init__(self, filename):
self.filename = filename
def get_rows_exclude_header(self):
csv_file = open(self.filename)
csv_row_reader = csv.reader(csv_file, delimiter=',' )
csv_row_reader.__next__()
rows = []
for csv_row in csv_row_reader:
rows.append(csv_row)
return rows |
263a3eb803c4f30c79a52c58631393f3a6b87fc7 | CrunchyPancake/Unruly-Knife | /male_female_distribution.py | 1,670 | 3.78125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv("database.csv-", low_memory=False)
def get_age_interval(start, end, gender):
return gender[(gender['ALDER'] > start) & (gender['ALDER'] < end)]
def make_plottable(dataset):
out_dict = {}
for entry in dataset:
out_dict.update({int(entry.head(1)['AAR']) : sum(entry['PERSONER'])})
return zip(*sorted(out_dict.items()))
def distribute_by_year(dataset):
return [dataset[dataset['AAR'] == year] for year in range(1992, 2015)]
def plot_dataslice(dataslice, label):
ds_x, ds_y = make_plottable(dataslice)
ax.plot(ds_x, ds_y, label=label)
## Seperate Men and Women
men, women = [data[data['KOEN'] == sex] for sex in [1, 2]]
## Divide Men and Women into young and old
young_men, young_women = [get_age_interval(17, 30, sex) for sex in [men, women]]
old_men, old_women = [get_age_interval(50, 99, sex) for sex in [men, women]]
#¤ Divide datasets into dictionary with Year as Key, and amount of people from the category living in the city that year
men_dist, women_dist, old_men_dist, old_women_dist = [distribute_by_year(cat) for cat in [young_men, young_women, old_men, old_women]]
## Finally Prepare the plot and show it
fig, ax = plt.subplots()
plot_dataslice(men_dist, "Males, 18-30")
plot_dataslice(women_dist, "Females, 18-30")
plot_dataslice(old_men_dist, "Males, 50+")
plot_dataslice(old_women_dist, "Females, 50+")
legend = ax.legend(loc='upper center', shadow=False)
frame = legend.get_frame()
plt.xlabel('Year', fontsize=16)
plt.ylabel('Count', fontsize=16)
plt.title('Fordeling af indbyggere i København og Omegn')
plt.show()
|
e273fc320d6c81c8ce7aa2d91a2ae4bd61c9ec6b | JackoQm/Daily_Practices | /LeetCode/AC/283*.py | 926 | 3.84375 | 4 | '''
From: LeetCode - 283. Move Zeroes
Level: Easy
Source: https://leetcode.com/problems/move-zeroes/description/
Status: AC
Solution: Using two pointer
'''
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
f, s = 0, 0
length = len(nums)
while s < length:
if nums[s] != 0:
if f != s:
nums[f] = nums[s]
f += 1
s += 1
while f < length:
nums[f] = 0
f += 1
# times o(n)
# space o(1)
'''
Most Optimal Answer:
class Solution:
def moveZeroes(self, nums):
last = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[last] = nums[last], nums[i]
last += 1
# times o(n)
# space o(1)
''' |
62e687779c000a167efcc1e5c9097fa6404bfe7b | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Attempts/0109_Convert_Sorted_List_to_Binary_Search_Tree.py | 698 | 3.5625 | 4 | """ 109. Convert Sorted List to BST
Question:
Given a singly linked list where elements are sorted in ascending order,
convert it to a height balanced BST.
"""
class Solution:
def sortedLinkedListToBST(self, head):
if not head or not head.next
return head
slow, fast = head, head.next
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# slow is at prev to mid node.
head2 = slow.next
slow.next = None
curr = TreeNode(head2.val)
curr.left = self.sortedLinkedListToBST(head)
curr.right = self.sortedLinkedListToBST(head2.next)
return curr
|
32691a8cdde211e0ae842f3a18ec91eaecf2ebbb | aliseas/ProgrammingLab | /WEEK8/model&plot.py | 2,188 | 3.734375 | 4 | """
Estendere la classe CSVFile che avete creato la scorsa lezione, aggiungendo
i seguenti metodi
"""
class CSVFile():
def __init__(self,name):
self.name = name;
def get_data(self,name,start,end):
if start>end:
raise Exception('Start value cannot be > end value')
my_file = open(name,'r')
with open(name, "r") as file:
my_file = file.readlines()[start:end]
lista = []
for line in my_file:
print('Riga: {}'.format(line))
elementi_riga = line.split(',')
if elementi_riga[1] != "Sales\n":
lista.append(float(elementi_riga[1]))
print('Lista di elementi: {}'.format(lista))
diff_data = [];
for i in range(len(lista)-1):
diff_data.append(abs(lista[i+1]-lista[i]))
file.close()
return lista,diff_data
def get_date_vendite(self,name):
from datetime import datetime
my_file = open(name,'r')
lista_date = []
for line in my_file:
elementi_riga = line.split(',')
if elementi_riga[0] != "Date":
my_date = datetime.strptime(elementi_riga[0],'%d-%m-%Y')
lista_date.append(my_date.strftime('%d−%m−%Y'))
print('Lista di elementi: {}'.format(lista_date))
my_file.close()
def __str__(self,name):
my_file = open(name,'r')
for line in my_file:
elementi_riga = line.split(',')
if elementi_riga[0] == "Date":
print('Intestazione file: {}'.format(line))
break
my_file.close()
class Model():
def __init__(self,name):
self.name = name
def fit(self):
raise NotImplementedError('This model does not have a fit')
def predict(self,prev_months):
file = CSVFile(self.name)
data,differences = file.get_data(self.name,0,prev_months)
prediction = (sum(differences)/len(differences))+data[-1]
return prediction
file = CSVFile('WEEK7/shampoo_sales.csv')
print(file.name)
lista_dati,lista_diff = file.get_data('WEEK7/shampoo_sales.csv',0,30)
print('\nLista dati: {}'.format(lista_dati))
print('\nLista differenze: {}'.format(lista_diff))
modello_shampoo = Model(file.name)
prediction = modello_shampoo.predict(20)
print(prediction)
#Visualising the data
from matplotlib import pyplot
pyplot.plot(lista_dati,color="tab:blue")
pyplot.plot(lista_dati + [prediction],color="tab:red")
pyplot.show() |
ed10eabc51b51465f957f48f81f5759803d6d949 | say2sankalp/pythonproj | /handling except.py | 168 | 3.765625 | 4 | while True:
try:
x=int(raw_input("Please enter a number :"))
break
except Valueerr:
print "Oops! that was no valid number. Try again.."
|
6781a0ce90b76fe5afe0c0ca500c5e30cc8c3a5e | AlienWu2019/Alien-s-Code | /oj系统刷题/递推求值.py | 150 | 3.53125 | 4 | n=int(input())
def F(n,a):
if a==1:
return F(n-1,2)+2*F(n-3,1)+5
elif a==2:
return F(n-1,1)+3*F(n-3,1)+2*F(n-3,2)+3
F(n,1)
|
e542e10d3b77eb570f7044c0c78b745e982100f4 | Xfan0225/python-BasicPrograming | /五一思维训练/因子数之和.py | 790 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 1 16:16:28 2019
@author: xie
"""
import math
#import time
#start=time.perf_counter()
def make(n): #计算因子数的函数
ans = 0
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 2
else:
for i in range(1, math.ceil(n**0.5)):
if n % i == 0: #假如可以被整除,则肯定有其和其对应的因子,因子数+2
ans += 2
if n**0.5 == math.floor(n**0.5):
ans += 1 #假如是平方数,则因子数为平方项+1
return ans
n = int(input())
ans = 0
for i in range(1, n+1):
ans += make(i)
print(ans)
#end=time.perf_counter()
#print(end-start)
|
fd0614ff6abe278f4c63b62a988f4efebe2cdf12 | c940606/leetcode | /test1.py | 2,215 | 4 | 4 | from collections import defaultdict
# This class represents a directed graph
# using adjacency list representation
class Graph:
def __init__(self, vertices):
# No. of vertices
self.V = vertices
self.userPath = []
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
'''A recursive function to print all paths from 'u' to 'd'.
visited[] keeps track of vertices in current path.
path[] stores actual vertices and path_index is current
index in path[]'''
def printAllPathsUtil(self, u, d, visited, path):
# Mark the current node as visited and store in path
visited[u] = True
path.append(u)
# If current vertex is same as destination, then print
# current path[]
if u == d:
print(id(path))
self.userPath.append(path[:])
#print(path)
else:
# If current vertex is not destination
# Recur for all the vertices adjacent to this vertex
for i in self.graph[u]:
if visited[i] == False:
self.printAllPathsUtil(i, d, visited, path)
# Remove current vertex from path[] and mark it as unvisited
path.pop()
visited[u] = False
# Prints all paths from 's' to 'd'
def printAllPaths(self, s, d):
# Mark all the vertices as not visited
visited = [False] * (self.V)
# Create an array to store paths
#self.path = []
# Call the recursive helper function to print all paths
#print("path_id",id(path))
self.printAllPathsUtil(s, d, visited,[])
return self.userPath
userFriendsMatrix = {0: [1, 2, 3], 2: [0, 1], 1: [3]}
graph = Graph(4)
for userId in userFriendsMatrix:
userFriendsList = userFriendsMatrix[userId]
for friend in userFriendsList:
graph.addEdge(userId, friend)
print(graph)
s = 2
d = 3
userPath = graph.printAllPaths(s, d)
print(userPath)
# Graph.userPath
# print(Graph.userPath)
# print(graph.userPath)
# print(graph.graph)
# print(userPath)
|
b83d7216748e58b73d8b344a8f29f3b1ff39ac82 | vtphan/Graph | /example.py | 872 | 4.25 | 4 | from graph import Graph, DGraph
print("Example of unweighted undirected graph")
G = Graph()
G.add(2,3) # add edge (2,3); (3,2) is automatically addeded.
G.add(3,5) # add edge (3,5); (5,3) is automatically addeded.
G.add(3,10) # add edge (3,10); (10,3) is automatically addeded.
print( (3,5) in G ) # True
print( (5,3) in G ) # True
print( (10,5) in G ) # False
for v in G.Vertices:
print("vertex", v)
for e in G.Edges:
print("edge", e)
print("Neighbors of vertex 3:")
for v in G.Neighbors[3]:
print("\t", v)
print("\nExample of weighted directed graph")
D = DGraph()
D.add(2,3,10)
D.add(2,5,20)
D.add(3,5,30)
for e in D.Edges:
print("Edge", e, "has weight", D[e])
print("Vertices that vertex 3 points to")
for v in D.Out[3]:
print("\t", v)
print("Vertices that point to vertex 5.")
for v in D.In[5]:
print("\t", v)
|
b698a07ad051636bd545ba4f7426d46877d2dfda | fireflyso/DevNote | /Algorithms/sort/base/base.py | 1,516 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Base:
sort_arr = [23,5,8,122,32,45,72,342,2,89,12,34,11,9,77]
sort_model = [23,5,8,122,32,45,72,342,2,89,12,34,11,9,77]
action_times = 0
def __init__(self,name = "玄学"):
self.name = name
print(" --- 开始进行 {} 排序 ---".format(self.name))
print("排序前的数组为: {}\n".format(self.sort_model))
def less(self,a,b):
self.action_times += 1
return self.sort_arr[a] < self.sort_arr[b]
def biger(self,a,b):
self.action_times += 1
return self.sort_arr[a] > self.sort_arr[b]
def swap(self,a,b):
self.action_times += 1
temp = self.sort_arr[a]
self.sort_arr[a] = self.sort_arr[b]
self.sort_arr[b] = temp
def sort_aes(self):
print("排列顺序:升序排列")
self.aes()
self.show_res()
def sort_des(self):
print("排列顺序:降序排列")
self.des()
self.show_res()
def aes(self):
print("{}排序的升序排序方法还未实现".format(self.name))
pass
def des(self):
print("{}排序的降序排序方法还未实现".format(self.name))
pass
def show_res(self):
print("本次操作的时间复杂度为: {}".format(self.action_times))
print("排序后的数组为: {}\n".format(self.sort_arr))
# 重置sort_arr到排序前的状态,且保持arr和model的内存独立
self.sort_arr = self.sort_model[:]
|
5f569cd6a9065de64cc4c3d933e2975e7adc1a97 | souza-pedro/Scripts_GPI | /Anexar_Ordem_SAP2.py | 7,063 | 3.53125 | 4 | import sys
import easygui as g
import os
import pandas as pd
# Escolha da pasta de Destino
def main():
#Escolhe a pasta padrão
escolher_pasta(c_origem, c_destino)
#Extrai Nº das Ordens
Lista_Ordens(c_origem)
#Anexa arquivos
anexa_SAP(c_origem)
#Renomeia arquivos e coloca em pasta destino
renomeia(c_origem, c_destino)
main()
def escolher_pasta(c_origem, c_destino):
c_pasta_origem = r"V:\COMPARTILHADO_CSC-SSE_NSIF\NP-2\GPI\4 - Apoio Administrativo\4.4 - Monte " \
r"Albuquerque\Desenvolvimento\Pedro\Pycharm\Anexar_Ordem_SAP\A Transferir"
while 1:
msg = "Escolha a Pasta de Origem dos arquivos. Gostaria de Selecionar a pasta ou usar a pasta padrão?" \
r" Pasta Padrão: " + c_pasta_origem
title = "Escolha Pasta Origem"
choices = ["Usar Padrão", "Escolher"]
choice = g.choicebox(msg, title, choices)
# note that we convert choice to string, in case
# the user cancelled the choice, and we got None.
if choice == "Escolher":
choice = g.diropenbox()
c_pasta_origem = choice
#g.msgbox("Você escolheu: " + str(c_pasta_origem), "Resultado Escolha")
msg = "Gostaria de Continuar? Você escolheu: " + str(c_pasta_origem)
title = "Please Confirm"
if g.ccbox(msg, title): # show a Continue/Cancel dialog
pass # user chose Continue
break
else:
choice = "" # user chose cancel
# user chose Cancel
#Escolha da pasta de Saída
c_pasta_destino = r"V:\COMPARTILHADO_CSC-SSE_NSIF\NP-2\GPI\4 - Apoio Administrativo\4.4 - Monte " \
r"Albuquerque\Desenvolvimento\Pedro\Pycharm\Anexar_Ordem_SAP\OK"
while 1:
msg = "Escolha a Pasta de Destino. Gostaria de Selecionar a pasta ou usar a pasta padrão?" \
r" Pasta Padrão: " + c_pasta_destino
title = "Escolha Pasta Destino"
choices = ["Usar Padrão", "Escolher"]
choice = g.choicebox(msg, title, choices)
# note that we convert choice to string, in case
# the user cancelled the choice, and we got None.
if choice == "Escolher":
choice = g.diropenbox()
c_pasta_destino = choice
#g.msgbox("Você escolheu: " + str(c_pasta_destino), "Resultado Escolha")
msg = "Gostaria de Continuar? Você escolheu: " + str(c_pasta_destino)
title = "Please Confirm"
if g.ccbox(msg, title): # show a Continue/Cancel dialog
pass # user chose Continue
break
else:
choice = "" # user chose cancel
return c_pasta_origem, c_pasta_destino
escolher_pasta()
def Lista_Ordens(c_origem):
#Transformando Nomes dos aquivos em lista de Ordens.
#Nome do arquivo deve estar no formato XXXXXXXXXX_xx-xx-xx_OPER-XX_C (Nº Ordem_dia-mes_ano_OPER-Nº Oper_C)
a = os.listdir(c_pasta_origem)
c = list(range(len(a)))
for f in range(0, len(a)):
#low = str.find(a[f], " - ") + 3
low = 0
upper = str.find(a[f], "_")
b = a[f]
c[f] = b[low:upper]
#print(c, low, upper)
#Ordens = c
ordens = pd.DataFrame(c)
ordens.to_clipboard(index=False, header=False)
print("FIM ")
print("Pasta Origem " + c_pasta_origem)
print("Pasta Destino " + c_pasta_destino)
print(ordens)
#-Begin-----------------------------------------------------------------
#-Includes--------------------------------------------------------------
import sys, win32com.client
#-Sub Main--------------------------------------------------------------
def Anexar_SAP():
try:
SapGuiAuto = win32com.client.GetObject("SAPGUI")
if not type(SapGuiAuto) == win32com.client.CDispatch:
return
application = SapGuiAuto.GetScriptingEngine
if not type(application) == win32com.client.CDispatch:
SapGuiAuto = None
return
connection = application.Children(0)
if not type(connection) == win32com.client.CDispatch:
application = None
SapGuiAuto = None
return
session = connection.Children(0)
if not type(session) == win32com.client.CDispatch:
connection = None
application = None
SapGuiAuto = None
return
#>Insert your SAP GUI Scripting code here<
session.findById("wnd[0]/tbar[0]/okcd").text = "iw38"
session.findById("wnd[0]").sendVKey(0)
session.findById("wnd[0]/usr/chkDY_MAB").selected = -1
session.findById("wnd[0]/usr/chkDY_MAB").setFocus()
session.findById("wnd[0]/usr/btn%_AUFNR_%_APP_%-VALU_PUSH").press()
session.findById("wnd[0]/usr/ctxtAUART-LOW").text = "*"
session.findById("wnd[0]/usr/ctxtAUART-LOW").caretPosition = 1
session.findById("wnd[0]").sendVKey(0)
session.findById("wnd[0]/usr/ctxtIWERK-LOW").text = "0105"
session.findById("wnd[0]/usr/ctxtIWERK-LOW").caretPosition = 4
session.findById("wnd[0]").sendVKey(0)
session.findById("wnd[0]/usr/ctxtINGPR-LOW").text = "*"
session.findById("wnd[0]/usr/ctxtINGPR-LOW").caretPosition = 1
session.findById("wnd[0]").sendVKey(0)
session.findById("wnd[1]/tbar[0]/btn[24]").press()
session.findById("wnd[1]/tbar[0]/btn[8]").press()
session.findById("wnd[0]/usr/ctxtVARIANT").text = "/ordem"
session.findById("wnd[0]/usr/ctxtVARIANT").setFocus()
session.findById("wnd[0]/usr/ctxtVARIANT").caretPosition = 6
session.findById("wnd[0]").sendVKey(0)
session.findById("wnd[0]/tbar[1]/btn[8]").press()
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").setCurrentCell(-1, "")
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectAll()
session.findById("wnd[0]/tbar[1]/btn[42]").press()
session.findById("wnd[0]/titl/shellcont/shell").pressButton("%GOS_TOOLBOX")
session.findById("wnd[0]/shellcont/shell").pressContextButton("CREATE_ATTA")
session.findById("wnd[0]/shellcont/shell").selectContextMenuItem("PCATTA_CREA")
session.findById("wnd[1]").sendVKey(4)
session.findById(
"wnd[2]/usr/ctxtDY_PATH").text = "V:\COMPARTILHADO_CSC-SSE_NSIF\NP-2\GPI\4 - Apoio Administrativo\4.4 - Monte Albuquerque\Desenvolvimento\Pedro\Pycharm\Anexar_Ordem_SAP\A Transferir"
session.findById("wnd[2]/usr/ctxtDY_FILENAME").text = "2018283469_12-11-19_OPER-10_C.jpg"
session.findById("wnd[2]/usr/ctxtDY_FILENAME").caretPosition = 33
session.findById("wnd[2]").sendVKey(0)
session.findById("wnd[1]/tbar[0]/btn[0]").press()
session.findById("wnd[0]/tbar[0]/btn[11]").press()
session.findById("wnd[1]/usr/btnSPOP-OPTION2").press()
session.findById("wnd[0]/tbar[0]/btn[15]").press()
session.findById("wnd[1]/usr/btnSPOP-VAROPTION2").press()
except:
print(sys.exc_info()[0])
finally:
session = None
connection = None
application = None
SapGuiAuto = None
#-Anexar_SAP------------------------------------------------------------------
Anexar_SAP()
#-End-------------------------------------------------------------------
|
df7b45feb94ff1e42b8121997a0124c9f1524687 | ongsuwannoo/Pre-Pro-Onsite | /The Bridge.py | 726 | 3.90625 | 4 | """ The Bridge """
def main():
""" input """
country = ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', \
'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', \
'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', \
'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'United Kingdom']
num = int(input())
bridge = []
for _ in range(num):
bridge.append([input().title(), input().title(), input().title()])
bridge.sort()
for i in range(num):
if bridge[i][2] in country:
print(bridge[i][0], "in", bridge[i][1]+",", bridge[i][2])
main()
|
0fcbda0c1dfe2058d6b86d6fa266dc0db75914c7 | fiolj/biblio-py | /yapbib/bibdb.py | 3,146 | 3.65625 | 4 | import sqlite3 as sq
from . import helper
DB_TBLNM = 'biblio'
def create_dbconnection(db_file):
"""create a database connection to the SQLite database
specified by the db_file
Parameters
----------
db_file : file-like (string or handle or Path)
Filename of the database
Returns
-------
Sqlite3 connection object or None
"""
conn = None
try:
conn = sq.connect(db_file)
except sq.Error as e:
print(e)
return conn
def parsefile(fname):
"""Parses a bibliography database file
Parameters
----------
fname : file-like or string
Filename to parse
Returns
-------
dict: A dictionary of dictionaries with the items
"""
con = create_dbconnection(fname)
if con is None:
print(f"Can't open database {fname}")
return None
tbname, cols = get_dbcolnames(con)
cur = con.cursor()
if tbname != DB_TBLNM:
print(f"Warning: Table name in database different from {DB_TBLNM}")
rows = cur.execute(f"SELECT * FROM {tbname};") #
entries = {}
for row in rows:
entry = parseentry(row, cols)
if entry:
entries[entry['_code']] = entry
return entries
def parseentry(row, cols):
"""Parse a sqlite database row from a string into a bibliography item
Parameters
----------
row : tuple
cols: list-like of strings
names of the columns in the row
Returns
-------
dict: bibliography entry
"""
entry = {}
for c, r in zip(cols, row):
if r:
if c in helper.namefields:
a = [k.split(',') for k in r.split(";")]
if a:
entry[c] = a
pass
else:
entry[c] = r
return entry
def get_dbtablename(con):
"""Get table name from connected database.
Parameters
----------
con : sqlite3 connection
Returns
-------
table name or empty string if not table present
Notes
-----
If more than a table is present returns only the first
"""
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
tbns = cur.fetchone()
try:
return tbns[0]
except TypeError:
return ''
def get_dbcolnames(con):
"""
Read column names from first table of connected database
Parameters
----------
con : sqlite3 connection
Returns
-------
list: names of colunns (fields)
Notes
-----
Assume that only one table is present, or uses the first
"""
tabnm = get_dbtablename(con) # Get table name
c = con.cursor()
cols = []
for row in c.execute(f"SELECT name FROM PRAGMA_TABLE_INFO('{tabnm}');"):
cols.append(row[0])
return tabnm, cols
def create_dbbib(conn, fields, tablename=DB_TBLNM):
"""Create a table with its columns to store the biblist bibliography
Parameters
----------
conn : sqlite3 Connection object
fields : list
Columns to use
"""
cols = fields[:]
cols.remove('_code')
strcols = "_code text NOT NULL PRIMARY KEY, \n "
# strcols = ""
strcols += ",\n ".join([f"{f.replace('-','_')} text" for f in cols])
try:
c = conn.cursor()
c.execute(f"CREATE TABLE IF NOT EXISTS {tablename} (\n {strcols}\n);")
conn.commit()
except sq.Error as e:
print(e)
|
6055155008c55cf55031cf0e7f3f3ecb44cd3255 | mike1806/python | /udemy_function_3.py | 218 | 4 | 4 | # find out if the word "dog" is in a string
def dog_check(mystring):
if 'dog' in mystring.lower():
return True
else:
return False
dog_check('dog ran away')
'dog' in 'dog ran away'
|
f465d9176ddd21092f6f0a249d1de57df453a5da | JanikThePanic/bricks-on-walls | /main.py | 1,010 | 3.703125 | 4 | import actions, rooms, var, art, monsters
#Imports other files
#The main loop used to start the game, and will be called again for replay
def start_game():
#ASCII Art for title
art.title()
#Confirms that the user wants to play
userIN = input("\nType 'Enter' to begin the adventure.\n").lower()
#Will not accept anything but 'enter'
while userIN != "enter":
print('\033[0;31;48m')#Sets text color to red
userIN = input("\nI didn't get that. Please type 'Enter' to begin.\n").lower()
print('\033[0;37;48m')#Default Color
#Will ask for class, name and then will start the first room
actions.getClass()
actions.getUserName()
#Game Intro
print("\nWell, "+var.userName +", you awaken in a cold and moist cobble dungeon. You do not remember living beforehand, and now you see it as your sole purpose to escape the maze of dungeons and see the surface once again.")
#First room of the dungeon
rooms.room_of_bricks()
#Will set preGame loot for chest
var.chestLootPre()
#Starts game
start_game() |
ae5a41a6c857b81d0a6f95b929abca95d8285e6a | bMedarski/SoftUni | /Python/Fundamentals/Functions and Debugging/08. Multiply Evens by Odds -2.py | 353 | 3.78125 | 4 | def sum_even(a):
rez = 0
for j in a:
if int(j) & 1 == 0:
rez += int(j)
return (rez)
def sum_odd(a):
rez = 0
for j in a:
if int(j) & 1 == 1:
rez += int(j)
return (rez)
n = input()
if n[0] == "-":
line = n[1:]
else:
line = n
result = sum_odd(line) * sum_even(line)
print(result) |
61975ee33a7eea859baf812d3548804b0f88442a | Sujan-Kandeepan/Exercism | /exercism/python/bob/bob.py | 523 | 3.890625 | 4 | def hey(question):
hasletters = False
for i in question:
if not i.isalpha() and i not in ['1','2','3','4','5','6','7','8','9','0', "?"]:
question = question.replace(i, " ")
if i.isalpha(): hasletters = True
question = question.strip()
print(question, question.upper(), hasletters)
if question == "": return "Fine. Be that way!"
if question == question.upper() and hasletters: return "Whoa, chill out!"
if question.endswith("?"): return "Sure."
return "Whatever."
|
9b3dbfe6337ff989ed16e87cfd8e26a73bc8a7a9 | DimonAgon/math-one | /test/test_simplified_formula_is_same_as_long_one_case_30.py | 679 | 3.53125 | 4 |
def compute_simplified_formula(A, B, C):
b_diff_c = B - C
a_intersect_b_diff_c = A & b_diff_c
return a_intersect_b_diff_c
def set_difference(X, Y):
"""# True \ False = True
# True \ True = False
# False \ True = False
# False \ False = False
That is z must be in X and must not be in Y
"""
return X and not Y
def initial_formula(A, B, C):
return not C and set_difference(A, C) and set_difference(B, C) and (not C or B)
def test_initial_formula_is_equal_to_simplified():
for A in (True, False):
for B in (True, False):
for C in (True, False):
assert initial_formula(A, B, C) == (A and set_difference(B, C)) |
908513286b729825bb62349d8cf491dd3d62ad7e | YohannesGetu/RSA-Factoring-Challenge | /rsa | 1,075 | 4.34375 | 4 | #!/usr/bin/python3
from sys import argv
import math
"""gets the first two factors of any number"""
def is_prime(num):
"""checks if a number is prime"""
i = 3
if num % 2 == 0:
return False
while i * i <= num:
if num % i == 0:
return False
i += 2
return True
def factory(num):
"""This factor function gets the factors of a number & prints them out"""
if num % 2 == 0:
i = 2
print("{}={}*{}".format(num, int(num/i), i))
else:
sq = math.sqrt(num)
if sq % 1 == 0:
print("{}={}*{}".format(num, sq, int(num/sq)))
return
sq = int(sq) + 1
for i in range(3, sq, +2):
if num % i == 0:
if is_prime(i):
print("{}={}*{}".format(num, int(num/i), i))
return
def factors(filename):
"""read_file"""
with open(filename, encoding="utf-8") as my_file:
for i in my_file.readlines():
n = int(i)
result = factory(n)
if __name__ == "__main__":
|
8fdff07d65e604520f234dc6cea9132135606874 | daniel-reich/turbo-robot | /FATFWknwgmyc7vDcf_2.py | 2,369 | 3.984375 | 4 | """
My friend required some help with an assignment in school and I thought this
would be a nice addition to be added as a challenge here as well.
Create a function that takes a sentence and returns a modified sentence abided
by these rules:
* If you encounter a **date** within the sentence, **in the format DD/MM/YY** or **DD.MM.YY** , you have to change it over to **DD/MM/YYYY** or **DD.MM.YYYY** (same separator char).
* If you encounter a **date** within the sentence, **in the format MonthName, DD. YY.** you have to change it over to **MonthName, DD. YYYY.**
* If you encounter an **invalid MonthName** then leave it as is.
* **For this challenge there is an arbitrary rule that if YY is less than 25 the year-prefix will be 20, otherwise, the year-prefix will be 19**.
* Meaning 08/11/20 -> 08/11/2020 or 02/11/95 -> 02/11/1995
### Examples
small_favor("I was born on 11/02/98")
➞ "I was born on 11/02/1998"
small_favor("I was born on 11/02/98 and what about you?")
➞ "I was born on 11/02/1998 and what about you?"
small_favor("I was born on 02.11.19")
➞ "I was born on 02.11.2019"
small_favor("I was born on February, 02. 98.")
➞ "I was born on February, 02. 1998."
small_favor("I was born on January, 01. 15. and today is October, 08. 20.")
➞ "I was born on January, 01. 2015. and today is October, 08. 2020."
small_favor("I was born on Fakemonthy, 01. 15. dont change invalid dates")
➞ "I was born on Fakemonthy, 01. 15. dont change invalid dates"
### Notes
Don't forget to apply the arbitrary year-prefix rule defined above.
* DD/MM/YY -> DD/MM/YYYY
* DD.MM.YY -> DD.MM.YYYY
* Month, DD. YY. -> Month, DD. YYYY.
* DD|MM|YY -> DD|MM|YY ( **invalid separator** , means it remains unchanged)
"""
import re
months = {'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'}
def small_favor(sentence):
def rep(m):
s = m.group()
if len(s) == 8:
return s[:6] + ('20' if int(s[6:]) < 25 else '19') + s[6:]
if s[:s.index(',')] in months:
return s[:-3] + ('20' if int(s[-3:-1]) < 25 else '19') + s[-3:]
return s
res = re.sub(r'(\b\w{3,9}, \d\d. \d\d.)|((\d\d[/.]){2}\d\d)', rep, sentence)
return res
|
1b0610210c66486c27d67ecd6742e8b5137190c3 | cikent/Python-Projects | /Automate-The-Boring-Stuff-With-Python/Section_06_Lists/Lesson_16_Similarities_Between_Lists_&_Strings/SequenceDataTypes.py | 860 | 4.125 | 4 | """
Sequence Data Types
-------------------------
Description: Lists aren’t the only data types that represent ordered sequences of values. For example, strings and lists are actually similar if you consider a string to be a “list” of single text characters. The Python sequence data types include lists, strings, range objects returned by range(), and tuples (explained in the “The Tuple Data Type” on page 96). Many of the things you can do with lists can also be done with strings and other values of sequence types: indexing; slicing; and using them with for loops, with len(), and with the in and not in operators.
Source: https://automatetheboringstuff.com/2e/chapter4/#calibre_link-175
"""
# Declare a String variable
name = 'Inciter'
# Print to Console: Each index within the List passed
for i in name:
print('* * * ' + i + ' * * *')
|
3f95078c5c5c6901c6383b9a71b9e48141776a7e | vicentedr96/Fundamentos-de-python | /Estructuras de datos/ListaEnlazada_Simple/Listas_Enlazadas.py | 2,133 | 3.671875 | 4 |
from Nodo import Nodo
class Listas_Enlazadas():
#constructor
def __init__(self):
self.__primero=None
self.__size=0
def get_size(self):
return self.__size
def visualizar(self):
tmp=self.__primero
while(tmp!=None):
print(tmp.get_datos())
tmp=tmp.get_enlace();
def insertar_inicio(self,datos):
if (self.__primero is None):
self.__primero=Nodo(datos)
else:
tmp=self.__primero
nuevo=Nodo(datos)
nuevo.set_enlace(tmp)
self.__primero=nuevo
self.__size+=1
def insetar_final(self,datos):
if(self.__primero is None):
self.__primero=Nodo(datos)
else:
nuevo=Nodo(datos)
tmpF=self.__primero
while(tmpF.get_enlace()!=None):
tmpF=tmpF.get_enlace()
tmpF.set_enlace(nuevo)
self.__size+=1
def esta_vacio(self):
if(self.__primero==None):
return True
else:
return False
def eliminar_primero(self):
if(self.esta_vacio()!=True):
self.__primero= self.__primero.get_enlace()
self.__size-=1
def eliminar_ultimo(self):
if(self.esta_vacio()!=True):
tmp=self.__primero
while(tmp.get_enlace().get_enlace()!=None):
tmp=tmp.get_enlace()
tmp.set_enlace(None)
self.__size-=1
def editar_por_posicion(self,posicion,datos):
if(posicion>=0 and posicion<self.__size):
if(posicion==0):
self.__primero.set_datos(datos)
else:
tmp=self.__primero
i=0
while(i<posicion):
tmp=tmp.get_enlace()
i+=1
tmp.set_datos(datos)
lista = Listas_Enlazadas()
lista.insertar_inicio(1)
lista.insertar_inicio(10)
lista.insetar_final(3)
lista.insetar_final(2)
lista.eliminar_ultimo()
lista.eliminar_primero()
lista.editar_por_posicion(0,100)
lista.visualizar() |
bd7d21e6c48490b6e513423be546d53dd6ef878e | IsmailTitas1815/Data-Structure | /codeforces/Catalan number.py | 203 | 3.5 | 4 | def catalan(li,n):
for i in range(2,n+1):
for j in range(0,i):
li[i] += li[j]*li[i-j-1]
return li[n]
n = int(input())
li = [0]*(n+2)
li[0] = 1
li[1] = 1
print(catalan(li,n))
|
7b3be06c7f53af4fd4ac56f1d37090041211a1d0 | akshala/Data-Structures-and-Algorithms | /graph/partyMe.py | 1,018 | 3.59375 | 4 | class Graph:
def __init__(self, n):
self.vertices=n
self.graph={}
self.incomingGraph={}
def addEdge(self, u, v):
# outgoing edges
if u in self.graph.keys() and v not in self.graph.values():
self.graph[u].append(v)
else:
self.graph[u]=[v]
def remainingEdge(self):
for vertex in range(0, self.vertices):
if vertex not in self.graph:
self.graph[vertex]=[]
def party(self, src, visited, distance):
q = []
visited[src] = True
distance[src] = 1
q.append(src)
while(len(q) > 0):
u = q.pop()
for neighbour in self.graph[u]:
visited[neighbour] = True
q.append(neighbour)
if(distance[src]+1 > distance[i]):
distance[i] = distance[src]+1
n = int(input())
g = Graph(n+1)
for i in range(0, n):
p = int(input())
if p!= -1:
g.addEdge(p, i-1)
g.remainingEdge()
visited = []
distance = []
for i in range(0, n):
visited.append(False)
distance.append(0)
for i in range(0,n):
if(not visited[i]):
g.party(i, visited, distance)
ans = max(distance)
print(ans)
|
e21b0b1c3b908a2c47df9b91e6eae03337572c2b | AlkaffAhamed/fip_powerx_mini_projects | /mp_calc/app/serverlibrary.py | 6,630 | 3.8125 | 4 |
def mergesort(arr, key):
if len(arr) < 2:
return arr
mid = len(arr) // 2
print(arr)
left = arr[:mid]
right = arr[mid:]
mergesort(left, key)
mergesort(right, key)
i = j = k = 0
while i < len(left) and j < len(right):
if key(left[i]) < key(right[j]):
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
class Stack:
def __init__(self):
self.__items = []
def push(self, item):
self.__items.append(item)
pass
def pop(self):
if not self.is_empty:
return self.__items.pop()
pass
def peek(self):
if not self.is_empty:
return self.__items[-1]
pass
@property
def is_empty(self):
return self.__items == []
pass
@property
def size(self):
return len(self.__items)
class EvaluateExpression:
valid_char = '0123456789+-*/() '
operator = '+-*/()'
def __init__(self, string=""):
self._expression = string
@property
def expression(self):
return self._expression
@expression.setter
def expression(self,expr):
for char in self._expression:
if char not in EvaluateExpression.valid_char:
self._expression = ""
else:
self._expression = expr
pass
def insert_space(self):
self._expression = " ".join(self._expression)
list1 = self._expression.split()
for i in range(len(list1)):
if list1[i] in EvaluateExpression.operator:
new_length =len(list1[i]) + 2
list1[i] = list1[i].center(new_length)
self._expression = "".join(list1)
pass
def process_operator(self, operand_stack, operator_stack):
op1= operand_stack.pop()
op2= operand_stack.pop()
if operator_stack.peek() == "+":
operator_stack.pop()
return operand_stack.push(op2 + op1)
elif operator_stack.peek() == "-":
operator_stack.pop()
return operand_stack.push(op2 - op1)
elif operator_stack.peek() == "*":
operator_stack.pop()
return operand_stack.push(op2 * op1)
elif operator_stack.peek() == "/":
operator_stack.pop()
return operand_stack.push(op2 // op1)
else: return 0
class EvaluateExpression:
# copy the other definitions
# from the previous parts
valid_char = '0123456789+-*/() '
def __init__(self, string=""):
self.expression = string
@property
def expression(self):
return self._expr
@expression.setter
def expression(self, new_expr):
if isinstance(new_expr, str):
x = ''.join([i for i in new_expr if i in self.valid_char])
if x == new_expr:
self._expr = x
else:
self._expr = ""
def insert_space(self):
e = "+-*/()"
r = list(map(lambda x: ' '+x+' ' if x in e else x, self.expression))
return ''.join(r)
def process_operator(self, operand_stack, operator_stack):
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items}")
opr = operator_stack.pop()
#print(f"opr={opr}")
if opr == "(":
return
op1 = operand_stack.pop()
op2 = operand_stack.pop()
#print(f"{op1} {opr} {op2}")
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items}")
if opr == "+":
operand_stack.push(op2 + op1)
elif opr == "-":
operand_stack.push(op2 - op1)
elif opr == "*":
operand_stack.push(op2 * op1)
elif opr == "/":
operand_stack.push(op2 // op1)
def evaluate(self):
operand_stack = Stack()
operator_stack = Stack()
expression = self.insert_space()
tokens = expression.split()
#print(f"{tokens} | {expression}")
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items}")
for i in tokens:
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items} for {i}")
if i in "0123456789":
#print("number")
operand_stack.push(int(i))
if i in "+-":
#print("+-")
while not operator_stack.is_empty and operator_stack.peek() not in ['(', ')', None]:
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items} for {i} +- while")
#print(f"{operator_stack.is_empty} | {operand_stack.peek()} for {i} +- while")
self.process_operator(operand_stack, operator_stack)
operator_stack.push(i)
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items} for {i} +-")
if i in "*/":
#print("*/")
op = operator_stack.peek()
#print(f"op={op}")
while op in ['*', '/'] and op != "(" and op != None:
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items} for {i} */ while")
self.process_operator(operand_stack, operator_stack)
op = operator_stack.peek()
#print(f"op={op} while")
operator_stack.push(i)
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items} for {i} */ aft while")
if i == '(':
#print("(")
operator_stack.push(i)
if i == ')':
#print(")")
while operator_stack.peek() not in ['(', None] or not operator_stack.is_empty:
#print(f"{operator_stack._Stack__items} | {operand_stack._Stack__items} for {i} ) while")
#print(f"{operator_stack.peek()} | {not operator_stack.is_empty} || {operator_stack.peek() != '(' or not operator_stack.is_empty}")
self.process_operator(operand_stack, operator_stack)
operator_stack.pop()
while not operator_stack.is_empty:
self.process_operator(operand_stack, operator_stack)
return operand_stack.pop()
def get_smallest_three(challenge):
records = challenge.records
times = [r for r in records]
mergesort(times, lambda x: x.elapsed_time)
return times[:100]
|
a34251fab9e9a497d5baf8fc8934c7b4f809748f | bullethammer07/python_code_tutorial_repository | /python_concepts_and_basics/python_list_comprehensions.py | 3,549 | 4.8125 | 5 | #-------------------------------
# Python List Comprehension
#-------------------------------
# NOTE : List Comprehensions use : []
# List comprehension is an elegant way to define and create lists based on existing lists.
#-----------------------------------------------------------------------------------------------------
# Example 1 : Simple Example
# lets see first how we can iterate through a string using for loop
str_letters = []
for val in 'jayant':
#print(val)
str_letters.append(val)
print(str_letters)
# However, Python has an easier way to solve this issue using List Comprehension.
# Let’s see how the above program can be written using list comprehensions.
#-----------------------------------------------------------------------------------------------------
# Example 2 : Iterting through a string using List Comprehension
# here we have capitalized each element of the list 'str_letters' and stored it in 'str_letters2'
str_letters2 = [x.upper() for x in str_letters] # example of using List Comprehensions.
print(str_letters2)
# Synatx of List Comprehension
# [expression for item in list]
# replicating Example 1 using List Comprehensions
var1 = [x for x in 'deadpool']
print(var1)
# NOTE : 'deadpool' is a string, not a list. This is the power of list comprehension.
# It can identify when it receives a string or a tuple and work on it like a list.
#-----------------------------------------------------------------------------------------------------
# Example 3 : List Comprehensions using Lambda Functions.
# List comprehensions aren’t the only way to work on lists. Various built-in functions and lambda functions can create and modify lists in less lines of code.
str_letters3 = list(map(lambda x: x, 'Jayant Yadav'))
print(str_letters3)
# NOTE : However, list comprehensions are usually more human readable than lambda functions.
# It is easier to understand what the programmer was trying to accomplish when list comprehensions are used.
#-----------------------------------------------------------------------------------------------------
# Example 3 : Conditionals in List Comprehension
#--------------------------------------
# ** Using if with List Comprehension :
num_list = [var for var in range(20) if var % 2 == 0] # makes a list of all even numbers
print(num_list)
#---------------------------------------
# ** Nested If with List Comprehension :
num_list2 = [var for var in range(200) if var % 2 == 0 if var % 5 == 0] # makes a list of all even numbers divisible by 5
print(num_list2)
#--------------------------------------
# ** If-Else with list comprehensions :
obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(obj)
#-----------------------------------------
# ** Nested Loops in List Comprehensions :
# Suppose, we need to compute the transpose of a matrix that requires nested for loop. Let’s see how it is done using normal for loop first.
transposed = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]
for i in range(len(matrix[0])):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
# The above code use two for loops to find transpose of the matrix.
# We can also perform nested iteration inside a list comprehension.
# In this section, we will find transpose of a matrix using nested loop inside list comprehension.
matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose = [[row[i] for row in matrix] for i in range(2)]
print (transpose) |
423de51be9be32af209fe28ab348d8c74825a5c0 | CodingProgrammer/Algorithm | /每日一题/35搜索插入的位置.py | 2,639 | 3.921875 | 4 | '''
Descripttion: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素
version: 1
Author: Jason
Date: 2020-12-02 16:12:58
LastEditors: Jason
LastEditTime: 2020-12-02 16:55:47
'''
import random
from typing import List
def GenerateRandomList(number, size):
temp = list()
random_legth = random.randint(0, size)
current_length = 0
while current_length < random_legth:
temp.append(random.randint(1, number))
current_length += 1
return temp
class Solution:
def searchInsert(self, nums: List[int], target: int):
length = len(nums)
# 如果数组为空或者target比第一个数小
if length < 1 or target <= nums[0]:
return 0
left = 0
right = length - 1
# 如果target比最后一个数大
if target > nums[right]:
return length
# 二分法查找
while left <= right:
mid = left + ((right - left) >> 1)
# 中间的数比target大,说明要找的target在mid的左侧
if nums[mid] > target:
right = mid - 1
# 中间的数比target小,说明要找的target在mid的右侧
elif nums[mid] < target:
left = mid + 1
else:
return mid
if left > right:
return left
def searchInsert2(self, nums: List[int], target: int):
length = len(nums)
# 如果数组为空或者target比第一个数小
if length < 1 or target < nums[0]:
return 0
left = 0
right = length - 1
# 如果target比最后一个数大
if target > nums[right]:
return length
try:
return nums.index(target)
except Exception as e:
for i in range(length):
if i > 0:
if nums[i - 1] < target and nums[i] > target:
return i
s = Solution()
# nums = [1, 2, 3, 5, 6, 8, 9, 11, 13, 14, 15, 17, 19]
# target = 1
# print(s.searchInsert(nums, target))
for _ in range(100):
nums = list(set(GenerateRandomList(200, 200)))
nums.sort()
position = random.randint(0, len(nums) - 1)
target = nums[position]
res = s.searchInsert(nums, target)
res_stand = s.searchInsert2(nums, target)
if res != res_stand:
print(nums)
print(target)
print("Done")
|
21f4264de16bf8189f86c16796242519b1e34635 | moussadiene/Algo_td1 | /algo_td1_python/Exercice_22.py | 1,254 | 3.703125 | 4 | #coding:utf-8
"""
Exercice 22 :
On se propose de saisir N entiers différents entre 1 et 100 (N étant un entier naturel
compris entre 10 et 50) puis afficher la plus longue séquence croissante tout en précisant la
position du premier nombre de cette séquence.
Exemple : Pour N=15
1 2 3. 1 2 3 4 5 6 7 8 . 2 3 4 5
Le programme affiche :
La plus longue séquence est 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 *
qui débute à la position 4 et elle est de longueur 7
"""
print("------------------- Sequence croissante --------------------------\n")
N = 0
while(N <= 0 or N >50):
N =int(input("Donner le nombre de cellule du tableau ::"))
tab = []
for i in range(N):
val = 0
while(val <= 0 or val >100):
val = int(input("Cellule "+str(i)+" ::"))
tab.append(val)
posD = 0
taille = 1
maxlong = 1
i = 0
while (i < N-1):
if(tab[i] < tab[i+1]):
taille += 1
if(maxlong < taille ) :
maxlong = taille
posD = i - (taille+2
else:
taille = 1
i = i + 1
taille = maxlong + posD
print("La plus longue séquence est :: \n")
i = posD
while(i < taille):
print(tab[i] , " * ",end="")
i += 1
print("\nElle debute a la position ",posD, " et elle a une longueur de ",maxlong," cellule .")
|
9159cd59da3bd0178d4595099cba3fa7a653889c | Mafyou/HackerRank | /nonDivisibleSubset/main.py | 436 | 3.59375 | 4 | import itertools
#https://www.hackerrank.com/challenges/non-divisible-subset/problem
def nonDivisibleSubset(k, S):
n = len(S)
while n > 1:
sets = itertools.combinations(S, n)
for set_ in sets:
if all((u+v) % k for (u, v) in itertools.combinations(set_, 2)) != 0:
return n
n -= 1
return 0
nonDivisibleSubset(4,[19,10,12,10,24,25,22])
"""
all = intersection
any = union
""" |
eb2829e3df3d2d0334a21b9cf58806409c71cc40 | chl218/leetcode | /python/stuff/0203-remove-linked-list-elements.py | 981 | 3.875 | 4 | """
Given the head of a linked list and an integer val, remove all the nodes of the
linked list that has Node.val == val, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
The number of nodes in the list is in the range [0, 104].
1 <= Node.val <= 50
0 <= val <= 50
"""
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
while head and head.val == val:
head = head.next
prev = head
while prev:
if prev.next and prev.next.val == val:
prev.next = prev.next.next
prev = prev.next
return head |
043fb3e49294181627eb4cedeb73dadedffddcb1 | oilneck/comphys | /sources/answer07.py | 486 | 3.578125 | 4 | import matplotlib.pyplot as plt
def fibo(n):
if n==0:
f_p = 0
elif n==1:
f_p = 1
else:
f_p_2 = 0
f_p_1 = 1
for p in range(2, n+1):
f_p = f_p_1 + f_p_2
f_p_2 = f_p_1
f_p_1 = f_p
return f_p
x_list = range(1, 101)
y_list = []
for n in x_list:
f_n = fibo(n)
f_nn = fibo(n+1)
ratio = f_nn / f_n
y_list.append(ratio)
plt.plot(x_list, y_list)
plt.show()
|
511443217f8ceb8232c99e69ff53d3eec166c722 | stellakaniaru/practice_solutions | /century_year.py | 603 | 4.28125 | 4 | '''
Create a program that asks the user to enter their name and age.
Print out a message addressed to them that tells them the year
they will turn a 100 yrs old.
'''
import datetime
#prompt user to enter name and age
name = input('Enter name: ')
age = int(input('Enter age: '))
#get the current year
year = datetime.datetime.now().year
#find the users birth year
birth_year = year - age
#find year the user turns a 100 yrs
century_year = birth_year + 100
#tell user the year they turn a 100 years
print ('{}, you will turn a 100yrs in the year {}'.format(name, century_year))
# help('datetime')
|
7118a1977ca37e00caa400685de7533426d928ce | allisondsharpe/dpwp | /Dynamic Site/dynamic-site/data.py | 3,882 | 4 | 4 | '''
Name: Allison Sharpe
Date: 10-17-15
Class: Design Patterns for Web Programming
Assignment: Dynamic Site
'''
class Data(object): #Data() class created to contain objects and attributes created within those objects for DataObject() class
def __init__(self):
home = DataObject() #Home object instantiated in Data() class for DataObject() class - Attributes for header_img, header, the_body, footer, and current_year have been created for this object
home.header_img = ''
home.header = "Welcome to the Home Page of Sharpe's Inc."
home.the_body = "We appreciate your interest at Sharpe's Inc. To get started, try browsing our navigational items above."
home.footer = "Copyright Sharpe's Inc."
home.current_year = 2015
about = DataObject() #About object instantiated in Data() class for DataObject() class - Attributes for header_img, header, the_body, footer, and current_year have been created for this object
about.header_img = ''
about.header = "About Sharpe's Inc."
about.the_body = "Sharpe's Inc has been around for more than 20 years for assisting clients with their financial instabilities as well as granting individuals with the ability to work in a safe and drug-free environment. "
about.footer = "Copyright Sharpe's Inc."
about.current_year = 2015
careers = DataObject() #Careers object instantiated in Data() class for DataObject() class - Attributes for header_img, header, the_body, footer, and current_year have been created for this object
careers.header_img = ''
careers.header = "Join Our Team"
careers.the_body = "We are currently hiring now. If you would like to join our team please submit your email in the contact section above and we'll get in touch with you as soon as possible."
careers.footer = "Copyright Sharpe's Inc."
careers.current_year = 2015
faq = DataObject() #FAQ object instantiated in Data() class for DataObject() class - Attributes for header_img, header, the_body, footer, and current_year have been created for this object
faq.header_img = ''
faq.header = "Welcome to Our FAQ's Page"
faq.the_body = "Q: <strong>What are the responsibilities of Sharpe's Inc?</strong> </br> A: We aide our clients with their financial situation and we ensure that everyone gets treated equally and receives the assistance that they deserve. </br></br> Q: <strong>What should I expect when working for this company?</strong> </br> A: A great atmosphere surrounded by co-workers who enjoy their job and are willing to serve their clients by meeting their needs."
faq.footer = "Copyright Sharpe's Inc."
faq.current_year = 2015
contact = DataObject() #Contact object instantiated in Data() class for DataObject() class - Attributes for header_img, header, the_body, footer, current_year, and input have been created for this object
contact.header_img = ''
contact.header = "Want to Contact Us?"
contact.the_body = 'Submit your email below and a representative will be in touch with you soon.'
contact.footer = "Copyright Sharpe's Inc."
contact.current_year = 2015
contact.input = '<form><input type="text" id="input"/><input type="button" value="Submit" id="form_btn"/></form>'
self.objects = [home, about, careers, faq, contact] #Array for 'objects' created to contain each object created within the Data() class
class DataObject(object): #DataObject() class created to contain declarations of attributes created within the Data() class
def __init__(self):
#Declaring attributes used in Data() class for objects of DataObject()
self.header_img = ''
self.header = ''
self.the_body = ''
self.footer = ''
self.current_year = 0
self.input = ''
|
c966430836ea6a7d5c7ec22a1900ba3a1e7dc064 | leopra/NLPExercises | /exercise16-4.py | 1,181 | 3.609375 | 4 | import nltk
nltk.download('wordnet')
nltk.download('stopwords')
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.tag import pos_tag
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
strings = "Radio is the technology of signaling and communicating using radio waves. \
Radio waves are used to carry information across space from a transmitter to a receiver, by modulating the radio signal. \
The artificial generation and use of radio waves is strictly regulated by law. \
The purpose of most transmitters is radio communication of information. \
The amplitude of the carrier signal is varied with the amplitude of the modulating signal. \
State-enforced laws can be made by a group legislature. \
The creation of laws themselves may be influenced by a constitution. \
The constitution has supremacy over ordinary statutory law. \
Records are information produced consciously or as by-products."
def process_text(text):
tokens = word_tokenize(text.lower())
stopWords = set(stopwords.words('english'))
return [x for x in tokens if x not in stopWords]
xx = process_text(strings)
dictio = dict([(x, dict()) for x in set(xx)])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.