blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
59e910d6b0fd95ddd3da22bcff86fec7fe92f076 | luhralive/python | /ailurus1991/0004/main.py | 343 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'jinyang'
def calcWords(path):
file = open(path, 'r')
inputStr = file.read()
wordsNum = 0
for i in inputStr:
if i == ' ' or i == '\n':
wordsNum += 1
file.close()
print wordsNum + 1
if __name__ == '__main__':
... |
59d383fce09fddcab3808941b2f1061bf3e596ab | luhralive/python | /BrambleXu/play1/play1.py | 558 | 3.59375 | 4 | # -*- coding:utf-8 -*-
#**第 0001 题:**做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
import random, string
def random_str(num, length = 7):
f = open("Running_result.txt", 'wb')
for i in range(num):
chars = string.letters + string.digits
s = [random.choice(... |
33e9b3d3209477a2e24421803b26c9697b374d44 | star10919/Keras_ | /02_keras2/keras66_gradient1.py | 312 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
f = lambda x: x**2 - 4*x + 6
x = np.linspace(-1, 6, 100) # -1부터 6까지 100개의 데이터
# print(x)
y = f(x)
# 그리자!!
plt.plot(x, y, 'k-')
plt.plot(2, 2, 'sk') # 최솟점에 점 찍힘
plt.grid()
plt.xlabel('x')
plt.ylabel('y')
plt.show() |
d6a908a27dd70295ba986d4aed8dde9c20dfc03b | bryangreener/School | /Spring 2018/Python/Assignments/Assignment#6/hw#6PartI_BryanGreener.py | 597 | 3.5 | 4 | # Name: Bryan Greener
# Date: 2018-04-11
# Homework : #6 Part 1
import csv
def csvopen(file):
with open(file, "r") as entries:
for entry in csv.reader(entries):
yield entry
rownum = 0 #iterator for row number
for i in csvopen('people.csv'):
if rownum != 0: # If 0, skip header row
... |
f454e3872e516ac64bb105063071ab7a23f119a6 | bryangreener/School | /Spring 2018/Python/Assignments/Assignment#4/hw#4Greener.py | 7,932 | 4.09375 | 4 | #Name: Bryan Greener
#Date: 2018-02-23
#Homework: 4
class Customer:
def __init__(self):
self.first_name = ""
self.last_name = ""
self.phone = 0
self.email = ""
self.date = ""
self.history = []
def __str__(self):
output = ""
output = (("\n%s, %s - ... |
231490f1ba7aa8be510830ec4a16568b5e4b2adb | THUEishin/Exercies-from-Hard-Way-Python | /exercise15/ex15.py | 503 | 4.21875 | 4 | '''
This exercise is to read from .txt file
Pay attention to the operations to a file
Namely, close, read, readline, truncate, write(" "), seek(0)
'''
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here is your file {filename}")
#readline() is to read a line from the file
#strip(*) is to ... |
d7bb8090a4e4af1cc2443a2cf81bbb22885b6c95 | Hugo-Oh/study_DataStructure | /9012, 실버4, 괄호, DFS/AAA.py | 326 | 3.53125 | 4 | import sys
sys.stdin=open("input.txt", "rt")
N = int(input())
for _ in range(N):
a = input()
stack = []
#stack
for i in a:
if stack and stack[-1] == "(" and i == ")":
stack.pop()
else:
stack.append(i)
if stack:
print("NO")
else:
print("Y... |
b429ecbee6d9567020821e24134937bdb17100d9 | Hugo-Oh/study_DataStructure | /캐치 파이썬스터디/배달, sUMMER/WINTER.py | 912 | 3.546875 | 4 | from collections import deque
road = [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]]
N = 5
K = 3
# 양방향
que = deque()
dis = [21470000 for _ in range(N)]
graph = [[0 for _ in range(N)] for _ in range(N)]
que.append(0) #1번부터 시작
dis[0] = 0
for y, x, cost in road:
if graph[y-1][x-1] == 0:
graph[y-1][x-1] = co... |
16e30b0ff9c0b0dee4ddd0c9d075491b9de9f44b | Hugo-Oh/study_DataStructure | /1260, DFS_BFS, S2, BFS_DFS/AA.py | 14,096 | 3.71875 | 4 | """price = [13, 15, 20, 100]
cost = [13, 15, 15, 0]
def solution(price, cost):
price_maxx = 0
sales_maxx = 0
for price in prices:
sales = sum([price-y for x, y in zip(prices, costs) if (x >= price) and (price > y)])
if sales_maxx < sales:
sales_maxx = sales
price_... |
50bfbf2caca5ce37fc342346e801519f1e4fa6e6 | traffaillac/traf-kattis | /kafkaesque.py | 124 | 3.515625 | 4 | last = 0
rounds = 1
for _ in range(int(input())):
clerk = int(input())
rounds += clerk < last
last = clerk
print(rounds)
|
350090f3b735d4c317e9160eef06298a7ebece31 | traffaillac/traf-kattis | /flagquiz.py | 312 | 3.59375 | 4 | input()
ans = [input().split(", ") for _ in range(int(input()))]
def dist(a:list, b:list):
return sum(i != j for i, j in zip(a, b))
def incongruousity(a:list):
return max(dist(a, b) for b in ans if b != a)
i = min(incongruousity(a) for a in ans)
for a in ans:
if incongruousity(a) == i:
print(", ".join(a))
|
3a3218a2c96e4d4d9c959b912f5bdcfa61d70995 | traffaillac/traf-kattis | /windows.py | 2,974 | 3.5625 | 4 | class Window:
def __init__(self, x, y, X, Y):
self.x = x
self.y = y
self.X = X
self.Y = Y
def __repr__(self):
return f'{self.x} {self.y} {self.X-self.x} {self.Y-self.y}'
def intersects(self, x, y, X, Y):
return self.x<X and self.X>x and self.y<Y and self.Y>y
xmax, ymax = (int(i) for i in input().split(... |
e26fc6f5f156320565aeae808b77a7a4dc187a81 | traffaillac/traf-kattis | /greedilyincreasing.py | 189 | 3.546875 | 4 | N = int(input())
A = [int(i) for i in input().split()]
gis = [A[0]]
largest = A[0]
for a in A:
if a > largest:
gis.append(a)
largest = a
print(len(gis))
print(' '.join(map(str, gis)))
|
d7163d8f0103969ae0bde1b5a78eec2de69ae2b9 | traffaillac/traf-kattis | /fractalarea.py | 181 | 3.640625 | 4 | from math import pi
for _ in range(int(input())):
r, n = map(int, input().split())
area = pi * r * r
inc = area
for _ in range(1, n):
area += inc
inc *= 3 / 4
print(area)
|
2528414bb4d275a06a005c6916a34fb14d1044a8 | traffaillac/traf-kattis | /estimatingtheareaofacircle.py | 145 | 3.65625 | 4 | from math import pi
while True:
r, m, c = input().split()
if r==m==c=='0': break
print(pi*float(r)**2, (float(r)*2)**2*int(c)/int(m)) |
6f6ee1e51869b660295e04630614abfc191d5ce3 | traffaillac/traf-kattis | /stararrangements.py | 132 | 3.71875 | 4 | S = int(input())
print(f"{S}:")
for l in range(S-1, 1, -1):
q, r = divmod(S, l)
if r==0 or r==(l+1)//2:
print(f"{q+(r>0)},{q}")
|
7609faa9ce11e3c51897a1bf3f6af1d4555df6a6 | traffaillac/traf-kattis | /hidden.py | 228 | 3.625 | 4 | password, string = input().split()
pos = 0
for i, c in enumerate(string):
idx = password.find(c, pos)
if idx == pos:
pos += 1
elif idx > pos:
print("FAIL")
break
else:
print("PASS" if pos == len(password) else "FAIL")
|
51e46ec32799eaabb5f3d4c38b7e42e8c25700a1 | traffaillac/traf-kattis | /calculatingdartscores.py | 502 | 3.515625 | 4 | def valid(d):
return 0<d<21 or d%2==0 and 0<d<41 or d%3==0 and 0<d<61
def output(*args):
for d in args:
if d%3 == 0:
print("triple", d//3)
elif d%2 == 0:
print("double", d//2)
else:
print("single", d)
exit()
n = int(input())
for d in range(1, min(n+1, 61)):
if not valid(d):
continue
if d == n:
... |
f7e2f32b81397a04b68ba2f99421eb69e695198b | traffaillac/traf-kattis | /justaminute.py | 152 | 3.53125 | 4 | N = int(input())
m,s = 0,0
for _ in range(N):
M,S = (int(i) for i in input().split())
m += M
s += S
print(s/m/60 if s/m>60 else "measurement error")
|
bfaff6249a671404ff2d7e6b70805617128a3ff2 | traffaillac/traf-kattis | /warehouse.py | 338 | 3.578125 | 4 | from operator import itemgetter
for t in range(int(input())):
toys = {}
for n in range(int(input())):
name, num = input().split()
toys[name] = toys.setdefault(name, 0) + int(num)
items = sorted(toys.items(), key=lambda t: t[0])
items.sort(key=lambda t: t[1], reverse=True)
print(len(items))
for i in items:
... |
b1a178f88369e1944b141b40708c4c674ca81a4c | lakshman-battini/Examples-from-Spark-The-Definitive-Guide | /code/Ch6-Working_with_Different_Types_of_Data-I.py | 8,588 | 3.65625 | 4 | # Databricks notebook source
# This notebook covers building expressions, which are the bread and butter of Spark’s structured operations.
# We also review working with a variety of different kinds of data, including the following:
# Booleans
# Numbers
# Strings
# Dates and timestamps
# Handling null
# Complex types
... |
1fbae5b6f69ff34a7849e3d0d1a227a5ffac2a81 | ekim0188/theGrind2 | /cleanDBaccess3.py | 1,237 | 3.515625 | 4 | #!/usr/bin/env python3
"""
Created on Sun Oct 14 22:57:31 2018
@author: Mike Blake
Script to interact with the database itself
"""
#
import pymysql
def readDB(msg = []):
print(msg)
##READ INFO FROM A DATABASE###
db = pymysql.connect('localhost', 'root', '[removed for security]', 'thegrind')
cursor =... |
6a4f8c8732b5e384c0da3a6f8c36f90d57a982fc | ElManous/PythonStuff | /PythonStuff/MinaTawfik_omis30_project_s2019/scraping2.py | 5,171 | 3.515625 | 4 | from lxml import html
import requests
import re
import json
# Call the link I want to scrape
club_page = requests.get('https://www.premierleague.com/clubs')
tree = html.fromstring(club_page.content)
linkLocation = tree.cssselect('.indexItem')
#Create an empty list for us to send each team's link to
teamLinks = []
... |
5cfafd423c1d2d315dadc17c6796ec3cc860dad4 | aav789/pengyifan-leetcode | /src/main/python/pyleetcode/keyboard_row.py | 1,302 | 4.4375 | 4 | """
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American
keyboard like the image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You ... |
98ca0cf6d09b777507091ea494f28f756f6ca1e1 | aav789/pengyifan-leetcode | /src/main/python/pyleetcode/Reverse_Words_in_a_String_III.py | 682 | 4.40625 | 4 | """
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not... |
ec00fc0c7a2c9628d55ca08364653a356ce4bfe4 | aav789/pengyifan-leetcode | /src/main/python/pyleetcode/string-to-interger-atoi.py | 3,195 | 4.34375 | 4 | """
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and inte... |
91e826ad0ea139bf3abe1a4889c86338f833edfa | Sandy134/FourthSem_Material | /Python_Lab/Termwork1b.py | 1,068 | 4.1875 | 4 | #11/5/2021
MAX = 3
def add(q, item):
if len(q) == MAX:
print("\nQueue Overflow")
else:
q.append(item)
def delete(q):
if len(q) == 0:
return '#'
else:
return q.pop(0)
def disp(q):
if len(q) == 0:
print("\nQueue is empty")
re... |
7efd406c8661629efec66a1d88ccc1bb565941be | naijopkr/tic-tac-toe | /functions.py | 1,795 | 3.78125 | 4 | from sys import exit, platform
from os import system
def clear():
if platform == 'win32':
system('cls')
else:
system('clear')
def choose_name(player):
return input(f'Hello, enter the name for player {player}: ')
def enter_position(player, board_size):
while True:
try:
... |
2f839536c9011ef074e49ddd72e96d420e7b2099 | Bl41r/code-katas | /forbes.py | 1,542 | 3.921875 | 4 | """Forbes top 40.
This savory chunk of code takes a provided json file, namely
forbes_billionaires.json, and returns the oldest dude on the list under
the age of 80, and the youngest member of the list. There are a few
'errors' in the json file, so only valid ages are considered.
"""
import json
def oldrich_and_yo... |
4ccf01874b1265abcb901ee7a0d6d23dfb64ed3f | Bl41r/code-katas | /credit-card-issuer-checking.py | 573 | 3.640625 | 4 | """Code Wars Kata.
https://www.codewars.com/kata/credit-card-issuer-checking
"""
def get_issuer(number):
cc = str(number)
if cc[0] == '4' and (len(cc) == 13 or len(cc) == 16) :
return 'VISA'
elif cc[0:4] == '6011' and len(cc) == 16:
return 'Discover'
elif (cc[0:2] == '34' or cc[0:2] =... |
cbc03484b8f7179e775dff6c594d4aa28a177522 | Bl41r/code-katas | /get-all-possible-anagrams-from-a-hash.py | 619 | 3.9375 | 4 | """Code Wars Kata.
https://www.codewars.com/kata/get-all-possible-anagrams-from-a-hash
"""
def anagrams(word):
if len(word) < 2:
yield word
else:
for i, letter in enumerate(word):
if letter not in word[:i]:
for j in anagrams(word[:i] + word[i + 1:]):
... |
699e447a4545dd42bf8d7ac835608dd7aa978e57 | erziebart/pykiddou | /src/value.py | 1,350 | 4.0625 | 4 | from abc import ABC, abstractmethod
from dataclasses import dataclass
class Value(ABC):
"""A value in the kiddou language."""
@abstractmethod
def type_name(self) -> str:
return self.__class__.__name__
@abstractmethod
def stringify(self) -> str:
return str(self)
class Undef(Value):
"... |
78e972f58f05adb457b4348172c000b7e46d7462 | AI-Inspire/Code-for-Workshops-Spring-2018-PL | /Stastistics.py | 519 | 3.96875 | 4 | #STATISTICS
number_of_laptops = [30, 40, 50, 60, 311, 23, 13]
num_points = len(number_of_laptops) #number of data points, length
largest_value = max(number_of_laptops) #largest value
#sorting values
sorted_values = sorted(number_of_laptops)
smallest_value = sorted_values[0]
second_smallest_value = sorted_values[... |
6520ca71378dbafd74eece20d613404d647d2d6a | moredhel/project_dolly | /src/server/user.py | 439 | 3.828125 | 4 | import database
class User:
db = database
def __init__(self, name, email):
self.name = name
self.email = email
self.computers = get_computers
def user_creation(self, db):
"""user creation returns error string if unsuccessful"""
if ((db.query("select '%s' from db") % (self.name)) != self.name):
db.upd... |
1af36f5047e5ed15218cdc84f3b2bc9ea77bc57c | faridmaamri/PythonLearning | /PCAP_Lab Palindromes_method2.py | 1,052 | 4.34375 | 4 | """
EDUB_PCAP path: LAB 5.1.11.7 Plaindromes
Do you know what a palindrome is?
It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not.
Your task is to write a program which:
asks the user for some text;
checks whether the entered text is a ... |
23658a3a61c3d99202f05925b331cb5e3e62cffc | fmsilver89/IN_5400 | /Project1/dnn/main.py | 23,095 | 3.578125 | 4 | #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::#
# #
# Part of mandatory assignment 1 in #
# IN5400 - Machine Learning for Image analysis ... |
3bfc4eee9efa7d88b031271d9f474e3dc4c5d5f4 | b64-vishal/python-lab | /aphabets_count.py | 353 | 3.96875 | 4 | ch=input("enter the string")
alphabet=digit=special=space=0
for i in range(len(ch)):
if(ch[i].isalpha()):
alphabet+=1
elif(ch[i].isdigit()):
digit+=1
else:
special+=1
print("total number of aphabet :" ,alphabet)
print("totsl number of digit :", digit)
print("total number o... |
99b26d6675d16b87d6eb0295ffb1ac8b1507b958 | mikeleppane/Advent_of_Code | /2018/Day_5/solution_part1.py | 1,182 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from collections import deque
INPUT_FILE = "input.txt"
def scan_polymer(polymer: str):
while True:
indices_to_be_removed = set()
found = False
for index in range(len(polymer) - 1):
if (polymer[index].isupper() and poly... |
0723dc096c41ef7f503e45b99c848d7293abad5e | mikeleppane/Advent_of_Code | /2018/Day_15/solution_part1.py | 9,326 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from dataclasses import dataclass
from enum import IntEnum, Enum
import sys
from collections import Counter
from itertools import product
from typing import NamedTuple, Dict, Tuple, Union
from copy import deepcopy
from pprint import PrettyPrinter
INPUT_FILE = "input.tx... |
f0290af4261bdb25a9c093e1041d550d09a4664c | mikeleppane/Advent_of_Code | /2021/Solutions/Day-12/solution_p2.py | 2,513 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import Counter
import sys
from pprint import PrettyPrinter
from typing import List, Set, Tuple
custom_printer = PrettyPrinter(
indent=4,
width=100,
depth=2,
compact=True,
sort_dicts=False,
underscore_numbers=True,
)
INPUT_FILE = ... |
373762827d80124fd528f21e1e67261addaff6ab | mikeleppane/Advent_of_Code | /2019/Day_1/solution_part1.py | 481 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import math
INPUT_FILE = "input.txt"
inputs = []
def read_inputs():
with open(INPUT_FILE, "r") as f_handle:
for line in f_handle:
inputs.append(int(line.strip()))
def calculate_total_fuel_consumption():
return sum(math.floor(mas... |
7b08e1891542f11851fb78919915c7ed7e80d4ea | mikeleppane/Advent_of_Code | /2019/Day_1/solution_part2.py | 803 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import math
INPUT_FILE = "input.txt"
inputs = []
def read_inputs():
with open(INPUT_FILE, "r") as f_handle:
for line in f_handle:
inputs.append(int(line.strip()))
def calculate_total_fuel_required_for_module(module_mass):
total_... |
46c7dc2ae604d10cd4849834b6b1f087f54b7978 | mikeleppane/Advent_of_Code | /2020/Day_12/solution_part1.py | 6,940 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from dataclasses import dataclass
from enum import Enum
from itertools import cycle
import re
import sys
from typing import List
INPUT_FILE = "input.txt"
class Direction(Enum):
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W"
LEFT = "L"
RIGHT = "R... |
bf28365b1f0dd24a1801e9c35c19febeef8bd8f1 | mikeleppane/Advent_of_Code | /2020/Day_5/solution_part2.py | 2,499 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from dataclasses import dataclass
import math
import sys
from typing import List, Set, Optional
INPUT_FILE = "input.txt"
UPPER_ROW_HALF, LOWER_ROW_HALF = ("B", "F")
UPPER_COLUMN_HALF, LOWER_COLUMN_HALF = ("R", "L")
@dataclass(frozen=True, eq=True)
class BoardingPass:... |
bc99f279e82adaead3c0900f07dc16607da095ba | mikeleppane/Advent_of_Code | /2019/Day_6/solution_part2.py | 4,094 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from collections import deque
from typing import Deque, List, NamedTuple
INPUT_FILE = "input.txt"
class OrbitObject:
def __init__(self, name, orbits_around):
self.name = name
self.orbits_around = orbits_around
def __str__(self):
... |
534f0bcba402ade07b132cc23e8974748438593d | AGCapdeville/Data-Mining-Labs | /Lab3.py | 3,842 | 4.34375 | 4 |
'''
Lab 3
'''
print ("Lab 3")
##########Part 1 ###########
'''
1) Write a python function to find the frequency of the charchters in a sentence
Hint : Use a dictionary
e.g.: "hello"
{"h":1, "e":1, "l":2, "o":1}
'''
# YOUR CODE GOES HERE
import pandas as pd
######### Part 2 ###########
'''
... |
6f8df55732c84ebe46f917494b0b4aba0c6b33b9 | AGCapdeville/Data-Mining-Labs | /lab1.py | 4,415 | 4.53125 | 5 | '''
Lab 1
'''
print ("Lab 1")
##########Part 0 ###########
'''
1) Create a variable, x, and set its value to 5
Create a variable, y, and set its value to 3 more than x's value
Exponentiate x by half of y, and store the result in x (hint: **=)
'''
# YOUR CODE GOES HERE
print()
print("= = = = = = = = = = ... |
a99405e7e2fddce640e8925494eb32a53a94b4d5 | mallius/CppPrimer | /CorePythonProg/ch06/0609ex.py | 128 | 3.53125 | 4 | #!/usr/bin/env python
str = raw_input('Enter a string like 03:30 >')
hm = str.split(":", 1)
print int(hm[0])*60 + int(hm[1])
|
ecfbcab263b54fed0c927844370a752a6efa1363 | mallius/CppPrimer | /CorePythonProg/ch07/0703ex.py | 109 | 3.78125 | 4 | #!/usr/bin/env python
d = {'a':1, 'c':2, 'b':3, 'd':4}
s = sorted(d.items())
for x in s:
print x[0], x[1]
|
1b7c1dc4a3cfe1aa34b2972bca53e80ea1201244 | mallius/CppPrimer | /CorePythonProg/ch11/1113ex.py | 154 | 3.578125 | 4 | #!/usr/bin/env python
def mult(x, y):
return x*y
ret = reduce(mult, range(1,4,1))
print ret
ret = reduce((lambda x,y: x*y), range(1, 4, 1))
print ret
|
f50848bcf18dcb9ab437b73f7ca595b7bdb12106 | mallius/CppPrimer | /CorePythonProg/ch06/0602ex.py | 573 | 3.65625 | 4 | #!usr/bin/env python
import string
import keyword
alphas = list(string.letters + '_')
nums = list(string.digits)
key = keyword.kwlist
kw = alphas + nums + key
print 'Welcome to the Identifier Checker v1.1'
print 'Testees must be at least 1 chars long'
myInput = (raw_input('Identifier to test: ')).split()
print m... |
f930faad4a19494e55d7666cf6f4db2bd1df0e41 | mallius/CppPrimer | /CorePythonProg/ch13/p376_1305anylter.py | 384 | 3.515625 | 4 | #!/usr/bin/env python
class AnyIter(object):
def __init__(self, data, safe=False):
self.safe = safe
self.iter = iter(data)
def __iter__(self):
return self
def next(self, howmany=1):
retval = []
for eachIter in range(howmany):
try:
retval.append(self.iter.next())
except StopIteration:
... |
b4944285e06ae6c8f26feeb861afe4754fc97af5 | mallius/CppPrimer | /CorePythonProg/ch13/p374_1303time60.py | 683 | 4.09375 | 4 | #!/usr/bin/env python
class Time60(object):
'Time60 - track hours and minutes'
def __init__(self, hr, min):
'Time60 constructor - takes hours and minutes'
self.hr = hr
self.min = min
def __str__(self):
'Time60 - string representation'
return '%d:%d' % (self.hr, self.min)
__repr__ = __str__
def __... |
c7cf28ba610285a09fa49d7e01760d9700e41310 | mallius/CppPrimer | /CorePythonProg/ch11/p289.py | 175 | 3.5625 | 4 | #!/usr/bin/env python
from random import randint
def odd(n):
return n % 2
allNums = []
for eachNum in range(9):
allNums.append(randint(1,99))
print filter(odd, allNums)
|
d1c21863de80c80b30f6afe24696fc4dc18ebe31 | binary-com/gce-manager | /lib/terminaltables.py | 11,513 | 4.15625 | 4 | """Generate simple tables in terminals from a nested list of strings.
Example:
>>> from terminaltables import AsciiTable
>>> table = AsciiTable([['Name', 'Type'], ['Apple', 'fruit'], ['Carrot', 'vegetable']])
>>> print table.table
+--------+-----------+
| Name | Type |
+--------+-----------+
| Apple | fruit ... |
a00233fcb03e5dd33ff8d39575f520a5bf5f8bf0 | webpagedemo/python101-my | /skrypty/trzyLiczby.py | 238 | 3.515625 | 4 | op = "t"
while op == "t":
a, b, c = input("Podaj trzy liczby oddzielone spacjami: ").split(" ")
liczby = [a, b, c]
print("Wprowadzono liczby:", a, b, c)
print("\nNajmnijsza: ")
liczby.sort()
print(liczby[0])
|
d9395f8dd710f4555f66febe8bb575799b52e181 | hannahTao/2021-Coding-Club-Biweekly-Challenges | /challenge3.py | 4,052 | 4.21875 | 4 | import math
def calculator_functions(userInput):
if userInput in ["add", "multiply", "divide"]:
numOfNumbers = int(input("How many numbers do you want to " + userInput + "? "))
for i in range(numOfNumbers):
if i == 0:
value = float(input("Input a number: "))
else:
if userInput == ... |
fabf3690168c58868a8de655cbb3b522dab2e0fc | martika810/superbeginner | /test.py | 468 | 3.84375 | 4 | class Palindrome:
def __init__(self, phrase):
self.phrase = phrase.replace(' ','').lower()
def is_position_palindrome(self, index):
return self.phrase[index] == self.phrase[-index-1]
def is_palindrome(self):
for index in range(int(len(self.phrase)/2)):
if not self.is_po... |
fa578313a53ff90e3a1733cba0dd6248ca4f5771 | katsuragawaa/japanese-flash-card | /Flash Card.py | 2,952 | 3.609375 | 4 | from tkinter import *
import pandas
from random import randint
from csv import writer, reader
data = pandas.read_csv("data/japanese.csv")
# -----------------
FONT = "Bahnschrift"
BACKGROUND_COLOR = "#B1DDC6"
class Card:
def front(self):
card.itemconfig(card_image, image=image_front)
card.itemco... |
7a7e4c2393928ca31e584f184f4a6c51689a42c5 | DominiqueGregoire/cp1404practicals | /prac_04/quick_picks.py | 1,351 | 4.4375 | 4 | """asks the user how many "quick picks" they wish to generate. The program then generates that
many lines of output. Each line consists of 6 random numbers between 1 and 45.
pseudocode
get number of quick picks
create a list to hold each quick pick line
generate a random no x 6 to make the line
print the line
repeat th... |
8ce539f39c64ec427b153f83dd925b6f06dae087 | DominiqueGregoire/cp1404practicals | /prac_02/capitalist_conrad.py | 3,853 | 4.28125 | 4 | """
CP1404/CP5632 - Practical
Capitalist Conrad wants a stock price simulator for a volatile stock.
The price starts off at $10.00, and, at the end of every day there is
a 50% chance it increases by 0 to 10%, and
a 50% chance that it decreases by 0 to 5%.
If the price rises above $1000, or falls below $0.01, the progra... |
5675306e73bfd33b8371343e45af5c8ec1c50499 | SherwinRF/olympics-data-analysis | /code.py | 3,260 | 3.5625 | 4 | # --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
#Code starts here
# Data Loading
data = pd.read_csv(path)
data.rename( columns = {'Total':'Total_Medals'}, inplace = True )
data.head(10)
# Summer or Winte... |
032b23fefe460e8a624bf0885d4b85c6d2166837 | nickcorin/nbx | /users/errors.py | 927 | 3.5 | 4 | class UsersError(Exception):
"""Base class for exceptions in this module."""
pass
class DuplicateEmail(UsersError):
"""Returned when registering a user with an email that already exists."""
def __init__(self):
self.status_code = 400
def __str__(self):
return "email already exists... |
966fdbc0aef9bb5ea720d4234f2bcb7d68b3eec1 | nickcorin/nbx | /users/db/util.py | 221 | 3.984375 | 4 | import re
def valid_email(email: str) -> bool:
"""Validates an email format using regex."""
regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
return True if re.search(regex, email) is not None else False |
76ad563b5afe7a6657cf7c62d4c450cfd022da37 | gperaza/ISLR-Python-Exercises | /Chapter11/02-discrete-distributions/discrete-dist.py | 685 | 3.640625 | 4 | from random import random
import matplotlib.pyplot as plt
from collections import Counter
def plot_prob_mass_funct(sample):
""" Plots a probability mass function from a sample of discrete random
variables. """
bars = sorted(Counter(sample).items())
heights = [x[1]/len(sample) for x in bars]
ticks ... |
d96ac503bf0327c03984ad0e0bb26247d335926f | vbnguyen165/Ted-Talks-Database | /command-line_utility.py | 2,661 | 3.859375 | 4 | # importing the requests library
import requests
import csv
URL = 'http://127.0.0.1:5000/'
def get(object):
request = input('Do you want to see all records (Yes/No) ')
while request.lower() != 'yes' and request.lower() != 'no':
print('Please enter Yes or No.')
request = input('Do you want to see a... |
13e9c29eed2b024c271fa1984cc5e90c86b23683 | jasmintey/pythonLab6 | /labsheet/lab7/Lab7 practice.py | 1,640 | 3.734375 | 4 | #Q2
# f = open("demofile.txt", "r")
# print(f.read())
# f.close()
#Q3
# print(f.read(5))
# f.close()
#Q4
# print(f.readline())
#Q5
# print(f.readline())
# print(f.readline())
#Q6
# for x in f:
# print(x)
#Q7
# f = open("demofile.txt", "a")
# f.write("Now the file has more content!")
# f.close()
#
# f = open("d... |
b78ec391ca8bbc6943de24f6b4862c8793e3cc14 | cat-holic/Python-Bigdata | /03_Data Science/2.Analysis/3.Database/2.db_insert_rows.py | 1,218 | 4.375 | 4 | # 목적 : 테이블에 새 레코드셋 삽입하기
import csv
import sqlite3
# Path to and name of a CSV input file
input_file = "csv_files/supplier_data.csv"
con = sqlite3.connect('Suppliers.db')
c = con.cursor()
create_table = """CREATE TABLE IF NOT EXISTS Suppliers(
Supplier_Name VARCHAR(20),
Invoic... |
1e8d40ea899ea7a2913c0fd03325bb4d2f14c2e9 | cat-holic/Python-Bigdata | /01_jumptopy/Jump_to_Python/chap04/20180509(수)/sandwich.py | 751 | 3.515625 | 4 | def make_sandwich(order_list):
print("샌드위치를 만들겠습니다.")
for i in order_list:
print("%s 추가합니다"%i)
print("\n여기 주문하신 샌드위치 만들었습니다. 맛있게 드세요.")
def input_ingredient(message):
if message == 1:
order_list = []
while True:
order = input("안녕하세요. 원하시는 재료를 입력하세요: ")
i... |
44d5f96ed08732ddc8b79b07f05846dc91ff51af | cat-holic/Python-Bigdata | /01_jumptopy/Jump_to_Python/chap03/Rhombus-v3.py | 1,305 | 3.75 | 4 | #coding: cp949
print(" α v3")
while True:
floor = int(input("ִ غ ũ⸦ Էϼ.(, Ȧ Է. 0 Է½ ) : "))
if floor == 0:break
maxFloorline = int((floor+1)/2)
maxBorderline = floor+4
i=0
print(" ",end="")
while i!=maxBorderline-3:
print("-",end="")
i+=1
print()
i=0
while i!=... |
bea0678a341e3fc8bc10aeaa0f3f3ff5cce2eb43 | akash3927/python- | /list.py | 1,454 | 4.375 | 4 | #lists
companies=["mahindra","swarajya","rucha","papl"]
#1
print(companies)
#2
print(companies[0])
#3
print(companies[1])
#4
print(companies[1].title())
#replacing
companies[0]="force"
print(companies)
#adding or appending
companies.append("mahindra")
print(companies)
#removing
del companies[0]
print(... |
e90cd19052685e2143da03934d17bcfc3daa2140 | OmkarShidore/FacialRecognitionAttendance | /Facial Recognition (GUI and Server)/tktest.py | 1,473 | 3.828125 | 4 | from tkinter import *
#main
window= Tk()
#
def click():
entered_text=textentry.get()#this will collect the text from textentry box
if (len(entered_text))==0:
pass
else:
output.delete(0.0,END)
try:
defination=my_compdictionary[entered_text]
except:
def... |
43757f10da1a76545a1fe22bdecc6fbfcaf80cfa | apriantoa917/Python-Latihan-DTS-2019 | /LIST/list - find number.py | 263 | 3.875 | 4 | # 3.1.6.8 Lists - more details
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
toFind = 5
found = False
for i in range(len(myList)):
found = myList[i] == toFind
if found:
break
if found:
print("Element found at index", i)
else:
print("absent") |
ac26196e5daed22f4972565f957dff6f6c087525 | apriantoa917/Python-Latihan-DTS-2019 | /OOP/OOP - import class object/class - stack.py | 476 | 3.828125 | 4 | # 6.1.2.4 A short journey from procedural to object approach
class Stack: # defining the Stack class
def __init__(self): # defining the constructor function, constructor diawali dengan __init__()
print("Hi!")
stackObject = Stack() # instantiating the object
# 6.1.2.5 A short journey from procedu... |
edcc3cce2a1f416279ee73c73b15f596d7e850a7 | apriantoa917/Python-Latihan-DTS-2019 | /EXCEPTIONS/try except - example 4.py | 1,305 | 3.8125 | 4 | # 5.1.5.2 The anatomy of exceptions
# source image : https://edube.org/uploads/media/default/0001/01/0ee75473d85349d36925771423976c94c08ddbf1.png
# ZeroDivisionError berada di dalam ArithmethicError, jika exceptions menggunkan class yang lebih general maka cakupan lebih banyak
# lihat hasil di bawah
print('percobaan... |
13712aa9ee6581cdc87c817cb630001117e159b7 | apriantoa917/Python-Latihan-DTS-2019 | /LOOPS/loops - for examples.py | 415 | 4.15625 | 4 | #3.1.2.5 Loops in Python | for
# for range 1 parameter -> jumlah perulangan
for i in range(10) :
print("perulangan ke",i)
print()
# for range 2 parameter -> angka awal perulangan, angka akhir perulangan
a = 1
for i in range(3,10) :
print(i," = perulangan ke",a)
a+=1
print()
# for range 3 parameter ->... |
2de1d64d9050ce148da40aec103d0eac7dabfe20 | apriantoa917/Python-Latihan-DTS-2019 | /OOP/OOP - Methods/examples 2.py | 849 | 3.84375 | 4 | # 6.1.4.3 OOP: Methods
class Classy:
def __init__(self, value):
self.var = value
obj1 = Classy("object")
print(obj1.var)
# constructor :
#tidak dapat mengembalikan nilai, karena ini dirancang untuk mengembalikan objek yang baru dibuat dan tidak ada yang lain;
# # tidak dapat dipanggil secara langsung b... |
e84ee8da19f091260bef637a5d7104b383f981a5 | apriantoa917/Python-Latihan-DTS-2019 | /LOOPS/loops - pyramid block.py | 366 | 4.28125 | 4 | # 3.1.2.14 LAB: Essentials of the while loop
blocks = int(input("Enter the number of blocks: "))
height = 0
layer = 1
while layer <= blocks:
blocks = blocks - layer #jumlah blok yang disusun pada setiap layer , 1,2,3...
height += 1 #bertambah sesuai pertambahan layer
layer += 1
... |
a0eb44d5616b3d273426c5a7397c773a4a558c46 | apriantoa917/Python-Latihan-DTS-2019 | /TUPLES/tuples - example.py | 691 | 4.21875 | 4 | # 4.1.6.1 Tuples and dictionaries
# tuple memiliki konsep sama dengan list, perbedaan mendasar tuple dengan list adalah :
# Tuples
# - tuple menggunakan (), list menggunakan []
# - isi dari tuple tidak dapat dimodifikasi setelah di inisialisasi, tidak dapat ditambah (append) atau hapus (delete)
# - yang dapat dilakuka... |
d78e0d79180c505e8d77b77aef43b5fbf14b8c64 | apriantoa917/Python-Latihan-DTS-2019 | /LIST/list - hat list.py | 241 | 3.890625 | 4 | # 3.1.4.6 LAB: The basics of lists
hatList = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat.
indices = int(input("enter a new number : "))
hatList[2] = indices
del hatList[4]
print(len(hatList))
print(hatList) |
0568e98654b7e85c3856519194c5f9b50f376f21 | apriantoa917/Python-Latihan-DTS-2019 | /nature of string/string sequence.py | 291 | 4.03125 | 4 | # 5.1.8.6 The nature of strings in Python
# indexing : memerankan string sebagai elemen index yang dapat diakses
str1 = 'sebuah kata'
for i in range(len(str1)):
print(str1[i],end=' ')
print()
#iterating : memanggil string berdasarkan urutannya
for str2 in str1:
print(str2,end=' ') |
02fc00ec75f78c552b47cf4376c8d655b1012cc6 | apriantoa917/Python-Latihan-DTS-2019 | /LOOPS/loops - the ugly vowel eater.py | 282 | 4.21875 | 4 | # 3.1.2.10 LAB: The continue statement - the Ugly Vowel Eater
userWord = input("Enter the word : ")
userWord = userWord.upper()
for letter in userWord :
if (letter == "A" or letter == "I" or letter == "U" or letter == "E" or letter == "O"):
continue
print(letter) |
b4816f6cf26d87c58b12a15fc379748e0c167db9 | hyunsooryu/Algorithm | /GCD_3_WAYS_BRUTEFORCE_RECURSIVE_ITERATIVE_in_python.py | 402 | 3.609375 | 4 | def GCD_R(A, B):
if not(B):
return A
return GCD_R(int(B), int(A % B))
def GCD_BRUTE_FORCE(A, B):
g_c_d = 1
for i in range(2, min(A, B) + 1):
if A % i == 0 and B % i == 0:
g_c_d = i
return g_c_d
def GCD_I(A, B):
while B > 0:
tmp = A
A = B
B = int(tmp % A)
return A
prin... |
a177c5db9ef4c8144c44298ca08aaf365169577c | hyunsooryu/Algorithm | /2_HowToSolveArrayProblem_TwoNumsNegative.py | 322 | 3.6875 | 4 |
def maxTwoDiff(nums):
MAX = nums[0]
MIN = nums[0]
for i in nums:
if i > MAX:
MAX = i
if i < MIN:
MIN = i
return MAX - MIN
def main():
print(maxTwoDiff([2, 8, 19, 37, 4, 5, 12, 50, 1, 34, 23])) # should return 49
if __name__ == "__main__":
main(... |
7eede1c69baa25dc60fa9127efa24817b627ddac | SharmaManav/CMPS101 | /hw2.py | 5,388 | 3.75 | 4 | # -*- coding: utf-8 -*-
# Manav Sharma msharma7
# Jeffrey Chan jchan40
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import timeit
import matplotlib.pyplot as plt
import scipy
def selectionsort(A):
for i in range (len(A)):
minIndex = i #set the minimum index i
... |
70320362f2dcf8277c59efd3a1b104fca0c0b784 | 100ballovby/6V_Lesson | /IV_term/05_lesson_2505/01_star_functions.py | 1,387 | 4.3125 | 4 | '''
Чтобы передать функции неограниченное количество элементов,
необходимо использовать звездочки.
*args - список аргументов
**kwargs - список именованных аргументов
На примере задачи. Дан список чисел, длина списка неизвестна,
сложите все числа в списке между собой. Верните сумму.
'''
from random import randint
n =... |
3091db7ad4567ec16d070bb42bece1340cec2cf3 | 100ballovby/6V_Lesson | /lesson_0902/03_list_sorting.py | 532 | 4.0625 | 4 | '''
Сортировка списка.
Метод .sort() располагает элементы списка
от меньшего к большему.
'''
cars = ['toyota', 'skoda', 'mercedes', 'seat', 'audi']
print('Список ДО сортировки', cars)
cars.sort() # обычная сортировка
print('Список ПОСЛЕ сортировки', cars)
cars.sort(reverse=True) # сортировка в обратном порядке
print(... |
2225f0786213292a5106ca625af0a65885d2ebbb | 100ballovby/6V_Lesson | /IV_term/02_lesson_2704/00_hw_solution.py | 512 | 3.859375 | 4 | # simple
message1 = input('Input smth: ')
num1 = []
for letter in message1:
if letter.isnumeric():
num1.append(letter)
print(num1)
# middle
message2 = input('Input smth: ')
num2 = []
for letter in message2:
try:
num2.append(int(letter))
except:
pass
print(num1)
# hard
import strin... |
c73e20200d1fe03e2746432dc925cc63361fd5a4 | 100ballovby/6V_Lesson | /lesson_2601/task0.py | 753 | 4.3125 | 4 | '''
Task 0.
Систему работы с багажом для аэропорта.
Багаж можно поместить в самолет если:
Его ширина < 90 см;
Его высота < 80 см;
Его глубина < 40 см;
ИЛИ
Ширина + высота + глубина < 160.
'''
w = float(input('Введите ширину багажа: '))
h = float(input('Введите высоту багажа: '))
d = float(input('Введите глубину багаж... |
2d01844b3781a61af499ab1f1be75892f03cdfcf | 100ballovby/6V_Lesson | /lesson_0203/02_bigger_and_smaller.py | 782 | 4 | 4 | '''Самый большой и самый маленький'''
n = [123, 12, 56, 34, 87, 9, 10, 413]
max = n[0] # здесь храню максимум
min = n[0] # здесь храню минимум
for number in n: # перебираю числа в списке
if max < number: # если число из списка больше максимума
max = number # переназначить максимум
if min > number: ... |
a57cba9867327db26740cb194168c8c33de8e329 | 100ballovby/6V_Lesson | /lesson_2601/bool_condition.py | 204 | 3.609375 | 4 | '''
a = True # 1
b = False # 0
print(a > b) # True
'''
ex1 = True
ex2 = True
ex3 = True
ex4 = True
mid = 4.5
if (ex1 and ex2 and ex3 and ex4) and (mid > 4):
print('OK')
else:
print('Ne ok')
|
fd09482d05ff8e7a0eebed43f3159153792a5834 | 100ballovby/6V_Lesson | /IV_term/03_lesson_0405/shapes.py | 1,192 | 4.34375 | 4 | '''
Параметры:
1. Черепашка
2. Длина стороны
3. координата х
4. координата у
5. Цвет
'''
def square(t, length, x, y, color='black'):
"""Функция рисования квадрата"""
t.goto(x, y) # переместить черепашку в x, y
t.down() # опустить перо (начать рисовать)
t.color(color) # задать черепашке цвет через п... |
0cf3ed5712c6fddad0759d449d56f434cc1ff3aa | hibruna/Sistemas01 | /Exercício c.py | 500 | 3.796875 | 4 | #Desejo que minha função receba 2 valores e retorne sucesso caso seja possível fazer a divisão Objetivo do teste:
#Verificar se a divisão entre 2 valores numéricos retorna sucesso
#d. Caso
from unittest import TestCase
def divisao(valor1, valor2):
return valor1 / valor2
class validadivisao(TestCase):
def tes... |
3822fece34f2135dfc9392c03b14a44bf93b374c | thepr0blem/spaceAI | /game_classes.py | 11,949 | 3.78125 | 4 | """
Game classes:
- SpaceShip
- Obstacle
- Population - collection of Spaceships
- Pilot - "brain" of SpaceShip, decides on what movement should be done by SpaceShip when in non-human player mode
"""
import random as rd
import arcade
import numpy as np
from settings import *
from ext_functions import... |
44238507b6d8b885054912b93cbdd799ddf73b46 | burtr/reu-cfs | /reu-cfs-2018/svn/cipher/crack-shift.py | 1,721 | 3.59375 | 4 | import string
import sys
import os
import argparse
import numpy as np
#
# crack-shift.py
#
# author:
# date:
# last update:
#
args_g = 0 # args are global
def frequencycount(s):
"""
input:
string of lowercase letters
return:
an integer array of length 26, where index i has the count of occurances of the i-t... |
8735cfbd69ed580c6740fe9fc608c7328782f896 | ealmuina/fuzzy-logic-evaluator | /fuzzy/defuzzifiers.py | 1,609 | 4.03125 | 4 | def centroid(func, step=0.1):
"""
Determine the center of gravity (centroid) of a function's curve
:param func: Function object
:param step: Distance between domain's values
:return: Numeric value representing the domain's value which approximately corresponds to the centroid
"""
points = fu... |
9227bf5285617689daf3ed5dd9507780c63bcc84 | christoforuswidodo/Hacker-Rank | /NumberTheory/SherlockDivisor/SherlockDivisor.py | 213 | 3.828125 | 4 |
def count_divisor_div_2(n):
if (n <= 1):
return 0;
else:
i = 2;
while (i <= n):
if (n % i == 0):
return 1 +
t = int(input())
for case in range(t):
n = int(input())
print(count_divisor_div_2(n)) |
6612f0794f4af6fc91a783f7a90ff5ba60bf57f6 | christoforuswidodo/Hacker-Rank | /Warmup/TaumBday/TaumBday.py | 931 | 3.609375 | 4 |
def minPrice(black, white, b_price, w_price, shift_price):
if b_price == w_price:
return black*b_price + white*w_price
else:
min_price = min(b_price, w_price)
if (min_price == b_price):
sp_or_wp = min(b_price + shift_price, w_price)
if sp_or_wp == (b_price + shift_price):
init_price = black*b_price +... |
cdbb2662d61edbf9a01005cebf4b926b4df003b5 | deividasskiparis/calculator-1 | /nershcalculator/nershcalculator.py | 3,480 | 4.46875 | 4 | class Calculator:
"""Calculator class object whose methods do addition, subtraction, multiplication, division,
takes n root of a number and resets the stored memory to the initial value.
"""
def __init__(self, number=0):
"""Accepts a number as initial value and if none is specified, default is ... |
267c852b0d5c87ea91bdfabb2c29485717f0dd7d | rahulsangwn/DS-Algo-CTCI | /python/removeAdjacentDuplicates.py | 633 | 3.65625 | 4 | def remove(str):
string = list(str)
flag = 1
while flag == 1:
i = 0
j = 1
flag = 0
flag2 = 0
while j < len(string):
while j < len(string) and string[i] == string[j]:
flag = 1
flag2 = 1
temp = string.pop(j)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.