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 |
|---|---|---|---|---|---|---|
7ab29eadb9da0ac5873909d1dc2f4bbf35b9d5c7 | LINDBURG/Programmers | /스택큐_다리를 지나는 트럭.py | 566 | 3.515625 | 4 | def solution(bridge_length, weight, truck_weights):
answer = 1
wsum = 0
con = []
while(truck_weights or con):
if len(truck_weights) >0:
if wsum + truck_weights[0] <= weight:
truck = truck_weights[0]
truck_weights.remove(truck)
for i in ... |
ed9a2268889fab9a24e6e63ac30127b20210f4d9 | LINDBURG/Programmers | /해시_전화번호 목록.py | 346 | 3.65625 | 4 | def solution(phone_book):
answer = True
phone_book.sort(key= lambda x: len(x))
for i in range(len(phone_book)):
l = len(phone_book[i])
for j in range(i+1, len(phone_book)):
if(phone_book[i] == phone_book[j][:l]):
return False
return answer
solution(["12", "12... |
96e9683a30fc9833159b9e696d36a9f42f2e5ba9 | LINDBURG/Programmers | /연습_최고의 집합.py | 441 | 3.671875 | 4 | class Multiset():
def __init__(self, n, s):
self.n = n
self.s = s
def run(self):
base = self.s//self.n
if base == 0:
return [-1]
plus_len = self.s - base*self.n
return [base for _ in range(self.n-plus_len)] + [base+1 for _ ... |
b2401d0f1cb2a819074670ac4f00532d473d4e78 | LINDBURG/Programmers | /2019_KBR_블록 게임.py | 3,784 | 3.5625 | 4 | class Board:
def __init__(self, board):
self.board = board
self.upper = []
self.cnt = 0
last = [0 for i in range(len(board))]
for i in range(len(board)):
line = []
for j in range(len(board)):
if board[i][j] == 0:
... |
6febc50e7ea26317e7090b8f3e07e51c99960b95 | LINDBURG/Programmers | /연습_N개의 최소공배수.py | 355 | 3.609375 | 4 | from functools import reduce
def lcm(a,b):
base = 1
last = max(a,b)**0.5
q = 2
while q <= last:
if a%q ==0 and b%q == 0:
base *= q
a //= q
b //= q
else:
q += 1
return base * a * b
def solution(arr):
answer = ... |
daeeefabbac2204103ad244ce42b6c3f48758319 | SahilPulikal/Surge-AI-Machine-Learning-Workshop | /Assignments/Assignment 2/2.1 log creator.py | 1,021 | 3.65625 | 4 | # 1. Create a log creator that will accept, following details as a parameter and log the details into the file with the time of logging.
# a. a message
# b. type of the message like INFO, WARNING, ERROR
# 2. Create a command line contact book that wll allow storing contact details of the user including phone no... |
26fb9811a666189f56c17f5b33cfaf829d4a4c62 | kaisprites/python-lecture | /mega4/test.py | 783 | 3.671875 | 4 | print("주민번호입력: ", end='')
num = input()
if num[7] == '1' or num[7] == '3':
print("남자")
else:
print("여자")
print("현재시각입력(24h): ", end='')
time = input()
if int(time[0:2]) < 11:
print("굿모닝")
elif int(time[0:2]) < 15:
print("굿애프터눈")
elif int(time[0:2]) < 20:
print("굿이브닝")
else:
print("굿나잇")
candid... |
2741cf44e71bb41868f14f944230d1705b82ab27 | kaisprites/python-lecture | /mega3/py06.py | 423 | 3.5625 | 4 | class TV:
company = "mega"
color = "red"
size = 50
onoff = "off"
def __init__(self):
print("TV가 만들어졌습니다")
def on(self):
self.onoff = "on"
print("TV켬")
def off(self):
self.onoff = "off"
print("TV끔")
def __str__(self):
return f"{self.comp... |
11f3b60496ec197f71d59938e25e3463b7847791 | VincentVelthuizen/Week-3 | /second_set/exercise_5.py | 590 | 3.75 | 4 | import turtle
screen = turtle.Screen()
tess = turtle.Turtle()
side_length = 50
# equilateral triangle
for _ in range(3):
tess.forward(side_length)
tess.left(120)
# square
for _ in range(4):
tess.forward(side_length)
tess.left(90)
# hexagon
for _ in range(6):
tess.forward(side_length)
tess.l... |
8a862826d164e2f05f18d2ad21c06843abde6264 | VincentVelthuizen/Week-3 | /first_set/exercise_3.py | 229 | 3.625 | 4 | # test using these values
a = 19
b = 6
day = 3
# a
print((a > b) != (a <= b))
# b
print((a >= b) != (a < b))
# c
print((a >= 18 and day == 3) != (a < 18 or day != 3))
# d
print((a >= 18 and day != 3) != (a < 18 or day == 3))
|
d089443bd4dd1defe5db88a6fcf53963c70cb5c3 | VincentVelthuizen/Week-3 | /second_set/exercise_11.py | 515 | 4.0625 | 4 | import turtle
screen = turtle.Screen()
hour_turtle = turtle.Turtle()
hour_turtle.shape("turtle")
# the next line causes my turtle to end in the "wrong" position
# I like it better to start at the top though
hour_turtle.left(90)
hour_turtle.penup()
for hour in range(12):
hour_turtle.forward(200)
hour_turtle.p... |
a5ad8c8a3e2c0a6ac172e08129f092bb638768a5 | ZhangJiaQ/LintCode_and_other_homework | /LintCode/字符串处理/LintCode415.py | 935 | 4.25 | 4 | # 有效回文串
# 给定一个字符串,判断其是否为一个回文串。只包含字母和数字,忽略大小写。
# 样例
# "A man, a plan, a canal: Panama" 是一个回文。
# "race a car" 不是一个回文。
# 解题思路:由于需要忽略标点与空格,只对字母和数字进行回文判定,所以我们需要先对字符串进行处理,遍历字符串并使用
# isalpha()方法与isnumeric()方法取得字母与数字,然后将字母全变为小写,进行回文判定。
class Solution:
# @param {string} s A string
# @return {boolean} Whether the ... |
24abe6f422ab4a59983b9bf0c3f23eadf0a29413 | ZhangJiaQ/LintCode_and_other_homework | /LintCode/字符串处理/LintCode82.py | 476 | 3.640625 | 4 | #落单的数
#给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
#解题思路 使用或运算,求得多出来的那个数字
class Solution:
"""
@param A : an integer array
@return : a integer
"""
def singleNumber(self, A):
# write your code here
if len(A)==0:
return 0
n=A[0]
for i in range(1,len(A)):
... |
9400ba6d818be03daa763aa3cfc55e9370089fc7 | ZhangJiaQ/LintCode_and_other_homework | /LintCode/字符串处理/LintCode158.py | 675 | 3.875 | 4 | # 两个字符串是变位词
# 写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。
# 样例
# 给出 s = "abcd",t="dcab",返回 true.
# 给出 s = "ab", t = "ab", 返回 true.
# 给出 s = "ab", t = "ac", 返回 false.
# 解题思路:将两个字符串进行排序,然后进行比对,相同则返回True
class Solution:
"""
@param s: The first string
@param b: The second string
@return true or f... |
c38b730a42d229bc2907f9ff17fb557f5ddffc7a | ZhangJiaQ/LintCode_and_other_homework | /LintCode/字符串处理/LintCode355.py | 699 | 4.0625 | 4 | '''查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
前2个数是 0 和 1 。
第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...'''
'''
解题思路
1.使用递归方式, Runtime Error,
2.使用非递归方式,将N个数转换为长度为N的数组,取第N个值
'''
class Solution:
"""
@param: : an integer
@return: an ineger f(n)
"""
def fibonacci(self, n):
... |
9e740d910d7a65ee9a295e87c6f5551c9a3ebc65 | ZhangJiaQ/LintCode_and_other_homework | /LintCode/字符串处理/LintCode133.py | 1,243 | 3.984375 | 4 | 最长单词
给一个词典,找出其中所有最长的单词。
样例
在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
解题思路:设置一个数组,将第一个单词加入,并计算第一个单词的长度
计算剩下单词的长度,如果与第一个单词相等加入数组,如果大于第一个单词的长度则清空数组,加入新的单词,重新计算... |
987f2823f2953e65a4289c4e26b6ac1b7f30afd5 | ITliuxiangyu/taobao_mm | /python/test1.py | 38,541 | 4.03125 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python
print ("Hello, Python!");
# if True:
# print ("true");
# print ("hello");
# else:
# print ("false");
# input("\n\nPress the enter key to exit.");
# a = b = c = 1;
# print (a);
# print (b);
# print (c);
#
# a , ... |
2ca07397585bc81164c44b9de399e81171879dd7 | LucasManza/computer-vision_manzanelli-brieu | /src/practice/connected-components/connected-components-ex1.py | 2,909 | 3.84375 | 4 | import cv2
import numpy as np
# todo
# Ejercicios con la cámara, en tiempo real, mostrando siempre en una ventana la imagen de la cámara. Requiere imágenes binarias sin ruido, que se pueden obtener por thresholding y operaciones morfológicas con sus respectivos trackbars.
# 1)Aplicar componentes conectados a la... |
750f7521226713d2b036aeda56cd9129271fef17 | NaveenAKT/DSA | /project.py | 10,485 | 3.78125 | 4 | import random
class Linkedlist:
def __init__(self):
self.head=Listnode()
def random(self):
k=random.randint(1,6)
return k
def insert(self,k):
temp=Listnode()
temp.value=k
temp.next=self.head.next
self.head.next=temp
def skiplist(self):
self.search(1).skip=self.search(10)
self.search(10).sk... |
90e24e9f6c646cae52e14edc986b18c91b2cdfaa | ReniltonRibeiro/capacitacao-ilp-TITAN | /capacitacao-ilp-TITAN-master/exercicio-1.py | 257 | 3.890625 | 4 | #Crie um algoritmo que leia um número e mostre o seu dobro, seu triplo e sua raiz quadrada.
n = int(input("Digite um valor: "))
a=n*2
b=n*3
c=n**(1/2)
print("O dobro de", n,"vale",a)
print("O triplo de", n,"vale",b)
print("a raiz quadrada de", n,"vale",c) |
59bcbcb9289657ab2a3533f9aecc1eabb9fa2aba | tiendunggithub/LearnPython | /ex3.py | 123 | 3.59375 | 4 | n = int(input("Nhập n:"))
s = 0
i = 1
while i <= n:
s += i
i += 1
print("Tổng các số từ 1 đến",n,":",s) |
257abd628ab7faf43f348cced7fbcbb9f399333d | tiendunggithub/LearnPython | /ex9.py | 705 | 3.84375 | 4 | class Student:
def printInfo(self):
print(f"""Thông tin sinh viên:
Họ tên: {self.ten}
Tuổi: {self.tuoi}""")
st1 = Student()
st1.ten = "TienDung"
st1.tuoi = 2
st1.printInfo()
class Info:
def __init__(self, name="", age=18):
self.name = name
self.age = age
def printkq... |
d57e662d520f5ff40408d2d410584cb32942d4aa | elrapha/Lab_Python_01 | /zellers.py | 1,672 | 4.75 | 5 | """
Zeller’s algorithm computes the day of the week on which a given date will fall (or fell). In
this exercise, you will write a program to run Zeller’s algorithm on a specific date. You
will need to create a new file for this program, zellers.py. The program should use the
algorithm outlined below to compute the day ... |
46cffa6e35d41a5256358da57b749771f2ee7e34 | yuri0906/PythonPractice | /chapter5.py | 719 | 3.90625 | 4 | #辞書やリストから特定の値を抜き出す
# coding: UTF-8
agesDictionary = {"歌手A":24, "歌手B":60, "歌手C":19}
songsDictionary = {
"歌手A":["曲1","曲2","曲3"],
"歌手B":["曲1","曲2","曲3","曲4","曲5"],
"歌手C":["曲1","曲2"],
}
def pickUpAges(singerName):
return agesDictionary[singerName]
def pickUpSongs(singerName, number):
return songsDi... |
a8957e1efe8e0575189d370f895155601766f6fe | pquinn/time-sink | /resources/visualization/data_points.py | 1,324 | 3.828125 | 4 | __author__ = 'phil'
#a jump data point is essentially just a time when the player jumped
class JumpDataPoint():
def __init__(self, time):
self.time = time
def __str__(self):
return "Player jumped at time {time}".format(time=self.time)
#a health data point is a player's health value at a time ... |
2e0ddab5df598f0bae089697cb0faffff2d36a76 | Martin20494/Python_PredictionMovieGross | /Python_MovieGrossPrediction/Part 1 - Webscraping.py | 5,042 | 3.921875 | 4 | """Program name: Movie Gross Prediciton.
Student name: Thong Minh Nguyen (Martin)
Student ID: 68623131
Tutor: Liam Laing
Description: This program uses the training data gathered from the past to build
model that helps movie executive producers predict the gross
of the movie with provided g... |
41b43a603d87f2f031056701842b0cbe9f03fc31 | lavi02/algorithms-practice | /acmicpc/2587.py | 172 | 3.609375 | 4 | data = []
avg = 0
try:
while True:
data.append(int(input()))
except:
pass
data.sort()
avg = sum(data) // len(data)
print(avg)
print(data[len(data) // 2]) |
13e195b091369ecdc48928ad52ca84b5108576b8 | BelleBruinsma/Heuristieken1 | /opdracht_a/classes.py | 1,743 | 3.671875 | 4 | import numpy as np # import numpy to create 2d arrays
class Plate:
# initialize with given size and category
def __init__(self, height, width, category):
self.width = width
self.height = height
self.category = category
self.state = np.zeros((height, width), dtype=np.... |
1b02bf677a4c432aa8900f431dc99693c8b62b57 | simpleboss/Python-Honglee | /4MultipleLoop/printF/printF.py | 314 | 4.0625 | 4 | def input():
return raw_input()
def printf(n):
long_line = ''
for i in range(n):
long_line += '*'
print long_line
for i in range(n // 2 - 1):
print '*'
print long_line
for i in range(n // 2):
print '*'
def main():
n = int(input())
printf(n)
main()
|
cfb998da62dc605e2968f2c61f8a475c0a97c712 | simpleboss/Python-Honglee | /4MultipleLoop/zorro/zorro.py | 467 | 3.890625 | 4 | def input():
return raw_input()
def zorro(n):
long_line = ''
for i in range(n):
long_line += '*'
print long_line
middle_line = ''
for i in range(n-2):
for j in range(n - 2 - i):
middle_line += ' '
middle_line += '*'
for j in range(i + 1):
... |
980e8212486e8e1e8be20b8db644d614307da2b4 | simpleboss/Python-Honglee | /parking/parking.py | 275 | 3.6875 | 4 | def parking():
test = input()
location_store = [int(i) for i in raw_input().split(" ")]
min_location = min(location_store)
max_location = max(location_store)
print 2 * (max_location - min_location)
return 2 * (max_location - min_location)
parking()
|
f9309d2979df065c2f1e0a81f3d0cb330e92e66e | simpleboss/Python-Honglee | /3for/cycling/cycling.py | 678 | 3.703125 | 4 | def cycling(n, input_list):
range = 0
result = [0]
left = input_list[0]
for right in input_list:
if right - left > 0:
range += right - left
#print 'add range', range
else:
if range != 0:
result.append(range)
#print 'appe... |
3e6ea7b8f04d70342d5234d7c33912d087802890 | simpleboss/Python-Honglee | /3for/ants/ants.py | 790 | 4.03125 | 4 | def ants(length, number_ants, ants_list):
for i in ants_list:
if i * 2 < length:
shortest_distance.append(i)
else:
shortest_distance.append(length - i)
shortest_distance.sort()
print shortest_distance[-1],
for i in ants_list:
if i * 2 < length:
... |
40497cce7a11efcc3b1cf5e64fe348e28e90a047 | HarshitAroraDroid/Python | /answer1.py | 246 | 4.09375 | 4 | def add_list(list1):
"""
This function is used to return sum of all values present in list.
"""
ans = 0
for ele in list1:
ans += ele
return ans
list1 = [2,3,4,25,43,26,76,89]
answer = add_list(list1)
print(answer) |
bea01d931cd6a66731136384735dc241e2616da8 | Robert-Ma/foal | /src/foal/graph/dijkstra.py | 4,287 | 4.15625 | 4 | """
Dijkstra's Algorithm
Determine the shortest paths from `node v1` to all other vertices in a
weighted, directed graph.
"""
from collections import defaultdict
from .graph_data_structre import DirectedGraph
class Dijkstra:
"""
Dijkstra's Algorithm
Determine the shortest paths from starting node `node... |
194efa21a260ba26898212f0b7023e21cdb19417 | Robert-Ma/foal | /src/foal/linear_algebra/strassen.py | 3,082 | 4.125 | 4 | """
Determine the product of two n-by-n matrices where n is a power of 2.
Because matrix has been converted to np.matrix, its associated addition,
subtraction will be directly added and subtracted, and its multiplication
uses np.matmul().
"""
import numpy as np
POWER = 2
def _determine_dim_of_matrix(mat_left, mat_ri... |
d43903d58c24c90792dbd057a6773f4c08867348 | Robert-Ma/foal | /src/foal/tree/binary_search_tree.py | 8,739 | 4.15625 | 4 | """
Binary Search Tree
This module implements binary search tree algorithm, which contains Node class,
and BinarySearchTree class. This module does not contain many complex methods,
and it just a simple implemention.
"""
class Node:
"""
Node
This class contains value, parent node and children node.
... |
c8c420d56a1f346ceb65cc47c8aeaa2f4c6803f1 | OliverNichols/cotd-solutions | /programs/solution_3.py | 244 | 3.75 | 4 |
def even_digits(a, b):
result = []
for num in range(a, b+1):
for digit in map(int, str(num)):
if digit % 2 != 0:
break
else:
result.append(str(num))
return ",".join(result)
|
5622e0a55650eeb6f2fe511f9fdf40861c8578a4 | zepler2011/leetcode_solution | /zshen/dp/wildcard-matching-lc192.py | 1,212 | 3.875 | 4 | class Solution:
"""
@param s: A string
@param p: A string includes "?" and "*"
@return: is Match?
"""
def isMatch(self, B, A):
# write your code here
n = len(A)
m = len(B)
f = [[False] * (m+1) for _ in range(n+1)]
f[0][0] = True
for i in... |
a2635da7a3b8930a45bd01fff2e03c25005af5de | zepler2011/leetcode_solution | /zshen/dp-dfs/word-break-2.lc582.dfs+memo.py | 1,694 | 3.53125 | 4 | class Solution:
"""
@param: s: A string
@param: wordDict: A set of words.
@return: All possible sentences.
"""
def wordBreak(self, s, wordDict):
# write your code here
memo = {}
return self.dfs(s, wordDict, memo)
def dfs(self, s, dict, memo ):
if s in... |
fc28665d53a8dd96e5b865d4ec5370392abc5e40 | zepler2011/leetcode_solution | /zshen/dp-dfs/word-ladder-2-bfs+dfs.py | 2,072 | 3.53125 | 4 | class Solution:
"""
@param: start: a string
@param: end: a string
@param: dict: a set of string
@return: a list of lists of string
"""
def findLadders(self, start, end, dict):
dict.add(start)
dict.add(end)
K = self.bfs(end, start, dict)
res = []
self... |
416efa3420b079b1a96098bcbb08a7c9cd84c16f | zepler2011/leetcode_solution | /zshen/dfs-combi-permu/sudoku-solver-lc802.py | 1,431 | 3.59375 | 4 | class Solution:
"""
@param board: the sudoku puzzle
@return: nothing
"""
def solveSudoku(self, board):
r = [set() for _ in range(9)]
c = [set() for _ in range(9)]
b = [[set() for _ in range(3)] for _ in range(3)]
cnt = 81
for i in range(9):
for j... |
5bf7dc9b489c207df48822a7a85569d2a5772825 | zepler2011/leetcode_solution | /zshen/dfs-combi-permu/split-string-lc680.py | 864 | 3.84375 | 4 | class Solution:
"""
@param: : a string to be split
@return: all possible split string array
"""
def splitString(self, s):
# write your code here
results = []
self.dfs(s, [], results)
return results
def dfs(self, s, combi, res):
if not s:... |
df54f1e209fa72c1c9fcc2781041d421c3d84542 | Denis-997/repo1 | /homework_8 — копия.py | 3,655 | 3.765625 | 4 | # Задание 1
def multiplication_table(a, b):
numbers = [[x * y for x in range(1, a + 1)] for y in range(1, b + 1)]
table = ''
for line in numbers:
for item in line:
table += f'{item}\t'
table += f'\n'
return table
print(multiplication_table(5, 5))
print(multiplic... |
d50f2c35e58eb483c20e544e42edf8cee4c1df7e | liyujiel/LeetCode | /validParentheses.py | 383 | 3.640625 | 4 | def isValid(self,s):
validDict = {")":"(","]":"[","}":"{"}
stack = []
for breket in s:
if breket in validDict.values():
stack.append(breket)
elif breket in validDict.keys():
if stack == [] or validDict[breket] != stack.pop():
return False
else:... |
1faf7950718cd67c1bd3dc182059763b1c784c5c | JosephLiu04/Wave3 | /PythagTheorem.py | 317 | 4.53125 | 5 | from math import sqrt
Side1 = float(input("Input the length of the shorter first side:"))
Side2 = float(input("Input the length of the shorter second side: "))
def Pythag_theorem():
Side3 = sqrt((Side1 * Side1) + (Side2 * Side2))
return Side3
print("The length of the hypotenuse is", str(Pythag_theorem())) |
2e74b450dcb9cd6696f7f95b3f90f7fb22ea50f5 | Umesh8Joshi/Leetcode_solutions | /easy/palindrome.py | 264 | 3.6875 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
num = str(x)
if num[0] == '-':
return False
elif num == num[::-1]:
return True
return False |
685be9417512353f773fcad3413766d1e2c56bc9 | mrfabroa/ICS3U | /Archives/4_Functions/functions_primer_1.py | 641 | 3.828125 | 4 | __author__ = 'eric'
"""
Filename: functions_primer_1.py
Description: A short program to demonstrate the usage if built-in python functions and the math library
"""
import math
# usage of a built-in function abs()
number_1 = input("Enter a number: ")
abs_value = abs(number_1)
print "The absolute value of", nu... |
9902409c31c852fd0878827aaa3b025099f997af | mrfabroa/ICS3U | /Archives/2_ControlFlow/conditional_loops.py | 1,611 | 4.34375 | 4 | __author__ = 'eric'
def example1():
# initialize the total and number
total = 0
number = input("Enter a number: ")
# the loop condition
while number != -1:
# the loop statements
total = total + number
number = input("Enter a number: ")
print "The sum is", total
def... |
c2e42318e56cf09abd5c1a456a4e3222a80e5226 | mrfabroa/ICS3U | /Archives/3_Lists/3_1_practice.py | 1,341 | 4.1875 | 4 | __author__ = 'eric'
def middleway(list_a, list_b):
"""
Given 2 int lists, list_a and list_b, each length 3,
write a function middle_way(list_a,list_b) that returns
a new list length 2 containing their middle elements.
:param list_a: int[]
:param list_b: int[]
:return: int[]
"""
li... |
d5e37664cc0facc1ecc1104fb1b442fc1f2383ef | D1D1O/python-Redes-Neurais- | /perceptron2.py | 337 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Este é um arquivo de script temporário.
"""
import numpy as np
entradas =np.array([-1,7,5])
pesos = np.array([0.8,0.1,0])
def soma(e,p):
return e.dot(p)#produto escalar
s = soma(entradas,pesos)
def stepFunction(soma):
if(soma>= 1):
return 1
return 0
r = ... |
00f18fbabb03bdd45762b43e769f074532db360a | savstone/C-Demo | /AsyncDemo/Demo/PythonApplication2/PythonApplication2.py | 1,164 | 3.765625 | 4 | #print("hello, world")
#object=input("enter an object")
#print(object,type(object),len(object))
counter = "100"
print(counter)
a = 100
b = 20
if a > b:
print("aaa")
else:
print("bbb")
#name =input("输入名称")
#print('Hi, %s, you have $%d.' % ('Michael', 1000000))
a = 'qwertt'
b = 'e'
if b in a:
print('yes')
... |
d8101fc77f87197e6076a8b55c031ca9e60eefa4 | tianshu-lyu/Sum-Tree | /checker.py | 4,316 | 3.59375 | 4 | from kwayHeap import kwayHeap
from heapq import *
from random import shuffle
"""
There may or may not be code that you need to change, namely
the import up top
heapToString()
get_heap()
add()
remove_min()
get_min()
but it's all just simple one line changes.
... |
747c36536e94bf66f04ff7d6a39df41594df271d | Astrcode/astr-119-session-3 | /data_types.py | 564 | 3.78125 | 4 | import numpy as np #import numpy library
#integers
i = 10 #integer
print(type(i)) #print out the data type of i
a_i = np.zeros(i,dtype=int) #declare an array of ints
print(type(a_i)) #will return ndarray
print(type(a_i[0])) #will return int64 (got int32 instead on Windows)
#floats
x = 119.0 #f... |
51c4f09686dfc3e7b2cf59a1a549ba5ac1fb7806 | shijietopkek/cpy5p1 | /q1_fahrenheit_to_celsius.py | 268 | 4.25 | 4 | # q1_fahrenheit_to_celsius.py
# Fahrenheit to Celsius converter
# get input
Fahrenheit = float(input("Enter Fahrenheit temperature: "))
# convert temperature
celsius = (5/9) * (Fahrenheit - 32)
# output result
print("temperature in celsius is", celsius)
|
adaa02710ee9b147cc4e28fe423a341f228a4882 | Airmagic/Lab-6 | /process_data.py | 1,075 | 3.65625 | 4 | # this is to be used to work with the csv file
import csv
mammoth_data = []
# opening the file so it can be read
with open('pbdb_data.csv', 'r') as csvfile:
# reading the file
reader = csv.reader(csvfile)
# reading the columns in the document
columns = reader.__next__()
# ... |
9e70ddca54a596c8e6e757096066d1c8de21e517 | JaeLinJoo/Python-Team-Notes | /Study/baekjoon/hw/17413.py | 662 | 3.671875 | 4 | # 단어 뒤집기2
def rev_word(s):
a = list(s.split())
res =''
for i in range(len(a)):
if i==0:
res = a[i][::-1]
else:
res += ' '+a[i][::-1]
return res
s = input()
val = s.find('<')
#'<' , '>' 를 포함하지 않은 경우
if val == -1:
print(rev_word(s))
#태그를 포함한 경우
else:
open = [0]
close = [-1]
resul... |
e8559bbdeeabe75830d4998f2fc7c5022e3bdc96 | JaeLinJoo/Python-Team-Notes | /Study/programmers/86491.py | 344 | 3.71875 | 4 | #weekly 8
# 최소 직사각형
def solution(sizes):
answer = 0
max_1, max_2 = 0, 0
for size in sizes:
x, y = sorted(size)
if max_1<x:
max_1 = x
if max_2<y:
max_2 = y
answer = max_1*max_2
return answer
print(solution([[60, 50], [30, 70], [60, 30], ... |
1a09b71ede60a455acb30a51b0be7670d799e307 | jjzcru/student-repository | /grade.py | 4,864 | 3.671875 | 4 | """
Handles everything related to university grades
"""
import os
from pathlib import Path
from typing import List
from enum import Enum
class GetBy(Enum):
# Enum for different ways to search
STUDENT = 1
INSTRUCTOR = 2
COURSE = 3
class Grade:
# Represents grade object
__slots__ = ["stud... |
80082cb77bdaa137b9bc6f35efac848671463b73 | rhondacrespo/EpiProject | /epimodel.py | 3,480 | 3.578125 | 4 | #! /usr/bin/env python3
#rhonda crespo, carlos phillips
#april 25, 2020
#this is a simple epidemiology model using the SIR model developed by
#Kermack & McKendrick in 1927. S stands for Susceptible, I is for
#Infected, and R stands for Removed (either recovered or
#dead). Removed are assumed to not be susceptible to t... |
657c1ebea59dd2b1ba7ab0e9acfb43f6580496f6 | harshmaru7/Steganography-using-Genetic-Algorithm-for-Wirleess-Network-Applications | /Chromosome.py | 2,109 | 3.625 | 4 | from PIL import Image
from numpy import array
from cryptography.fernet import Fernet
# This module is used to handle operations related to a single chromosome
class Chromosome:
# Initializing the attributes of the class Chromosome.
def __init__(self,id=-1,r=-1, g=-1, b=-1, fit=-1, xP=-1, yP=-1, sol=-1):
self.genes... |
cedf844ac92aa2736312ee2a56e5c6e2ada67899 | mihoito/learning_python | /make_dictionary.py | 1,003 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import sys
def modify_line(string):
removing_character_string = "'‘’()<>[]{}&/?=-_:;,.!"
modefied_str =string.lower()
modefied_str = modefied_str.replace('"',' ')
modefied_str = modefied_str.replace('\n','').replace('\t',' ')
for s in removing_character_string:
mod... |
0262acf9c5874dc5d07024f09936e3ec83740707 | ljdursi/make_pattern_rules | /src/merge_and_clean.py | 2,108 | 3.5 | 4 | #!/usr/bin/env python
import argparse
import sys
import os
import pandas
def merge_dataframes(input_dir):
"""
Reads in all CSV files in the provided directory, and converts
'last_modified' column to a datetime, and extracts year
Also removes unused columns, and removes some spurious entries
(zero ... |
7abf73addb280f2f79689f5fa5023c907ce6d562 | JayAgrawalgit/JayAgrawal | /Loops/ques1.py | 241 | 3.734375 | 4 | n=int(input("Enter first digit:")) #for sum of next 10 digit
sm=sum(range(n,n+10))
c=[i for i in range(n,(n+10))]
print("Sum of",c,"is:",sm)
# print("sum of");sm=0
# for i in range(n,(n+10)):
# sm+=i
# print(i)
# print("is=",sm)
|
86c95b6cdf36ebdff7f501640037cf8167af7479 | numpde/aliz | /cocha/ailz_tools/classification/topt.py | 3,543 | 3.578125 | 4 | """
Classification with threshold optimization
"""
# Author: RA
import numpy as np
import pandas as pd
from scipy.optimize import minimize_scalar
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils import validation
VALIDATION_1D... |
c7882e0cd3ce78ccd4ac1e0681ed44c3dd7f8d4f | SoniSiddharth/Data-Structures-and-Algorithms-in-python | /BST_from_preorder.py | 778 | 3.53125 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def constructTree(pre, low, high, size):
global preInd
if( preInd >= size or low > high):
return None
root = TreeNode(pre[preInd])
preInd+=1
if low == high ... |
25d127338941aa863ba5260e12ea3b47b1f4da62 | manhtruong594/vumanhtruong-fundamental-c4e24 | /Fundamental/Session03/homework/SeriousEx1b.py | 196 | 4.1875 | 4 | #Repeats a block of code as long as the user indicates they want it to
print("Type exit to escape")
loop = True
while loop:
n = input("Your input: ")
if n == "exit":
loop = False |
8b505676a08ba224903433f7546e35ae8f441edb | manhtruong594/vumanhtruong-fundamental-c4e24 | /Fundamental/Session04/homework/SeriousEx1.py | 1,313 | 4.125 | 4 | items = ["T-Shirt", "Sweater"]
print("Here is my items: ", sep=" ")
print(*items, sep=", ")
loop = True
while loop:
cmd = input("Welcome to our shop, what do u want (C, R, U, D or exit)? ").upper()
if cmd == "R":
print("Our items: ", *items, sep=", ")
elif cmd == "C":
new = input("Enter new... |
c8dc91a100a42e430110dafb0342595fbdba03e5 | traleig1/MTris | /Tetris.py | 5,277 | 3.5 | 4 | import random
from Board import Board
from BlockQueue import RandomQueue
from TetrisBlock import *
from Data import *
from Enum import Enum
Act = Enum(["Drop","Down","Left","Right","Hold","RotCW","RotCCW"])
class Tetris(object):
"""Represents a player's board, falling block, hold, score, and block queue."""
def _... |
24979e4b645fd55c678190b244fd9ee3436232d7 | sbolla27/python-examples | /class2/calculator_class.py | 748 | 4.125 | 4 | class Calculator(object):
def __init__(self, num1, num2, num3=0):
self.x = num1
self.__y = num2
self.z = num3
def add(self):
return self.x + self.__y + self.z
def sub(self):
return self.x - self.__y
def multi(self):
return self.x * self.__y
def di... |
d22bca1ca374f5d7336077a68c645ddf512411fd | fabiangothman/Python | /oop/4.class_attributes.py | 668 | 3.84375 | 4 | class Person:
number_of_people = 0
GRAVITY = -9.8 # Constant
def __init__(self, name) -> None:
self.name = name
#Person.number_of_people += 1
Person.add_person()
@classmethod
def get_number_of_people(cls):
return cls.number_of_people
@classmethod
def add_p... |
7d34ce21348e849a06da1b04a3c40c611587261a | fabiangothman/Python | /fundamentals/4_strings.py | 811 | 4.21875 | 4 | myStr = "hello_all_world"
#Properties of an object: command "dir"
#print(dir(myStr))
print(myStr.upper())
print(myStr.lower())
print(myStr.swapcase())
print(myStr.capitalize())
print(myStr.replace("hello", "bye").upper()) #Method chaining (Métodos encadenados)
print(myStr.count("l"))
print(type(myStr.count("l")))
... |
86c74cd73d63268fda991badaf4a42c3a43861b7 | fabiangothman/Python | /fundamentals/12_functions.py | 230 | 3.703125 | 4 | def greet(name="none"):
print(f"waving to {name}")
greet("Fabian")
greet()
def sum(num1=0, num2=0):
return num1+num2
print(sum(8, 5))
#Lambda functions (one expression)
res = lambda num1, num2: num1-num2
print(res(8, 5)) |
6c91e86ed574878cf4d9d3a33d6dd24ffab940e8 | ali-mahani/ComputationalPhysics-Fall2020 | /PSet2/P2/serpinski_set.py | 782 | 3.671875 | 4 | #!/usr/bin/env python
"""
Draw the Serpinski Triangle set to the specified level
"""
from matplotlib import pyplot as plt
from serpinski_class import Serpinski
def main():
"""Main body of the program"""
# Initialize the Serpinski set
print("==> Making serpinski set...")
my_serpinski = Serpinski(400, ... |
d7cdfdc944c19f9e2b2e11e99c6a521908cbfb3d | ali-mahani/ComputationalPhysics-Fall2020 | /Final/p4/main.py | 3,634 | 3.515625 | 4 | #!/usr/bin/env python
""" main module """
import time
import numpy as np
from matplotlib import pyplot as plt
from eulers import *
def my_method(x_init, x_dot_func, step, time):
""" euer method """
# finding count
count = int(time / step) + 1
# initialization
x = np.zeros(count)
x_dot = np.... |
7bb5b40e426bd5a6f7bf1733f9591ef31478be3a | ali-mahani/ComputationalPhysics-Fall2020 | /Final/p4/eulers.py | 1,073 | 3.890625 | 4 | #!/usr/bin/env python
""" implementations of the euler and reverse euler methods """
import numpy as np
def euler(x_init, x_dot_func, step, time):
""" euer method """
# finding count
count = int(time / step) + 1
# initialization
x = np.zeros(count)
x_dot = np.zeros(count)
time = np.zero... |
1d95d14087921ed57bfd2007332adf1824e90e81 | ali-mahani/ComputationalPhysics-Fall2020 | /PSet7/ising_example.py | 803 | 3.65625 | 4 | #!/usr/bin/env python
""" Here I make an Ising model and run metropolis 100 times. """
from ising import Ising
from matplotlib import pyplot as plt
def before_after(size, beta, file_name):
""" simulate for size and beta """
ising = Ising(size, beta)
before = ising.data.copy()
# do metropolis 200 tim... |
a0f9a0bee45430c624bf38a300877281f289c541 | ali-mahani/ComputationalPhysics-Fall2020 | /PSet3/p3/colorize.py | 2,517 | 3.625 | 4 | #!/usr/bin/env python
"""
algorithm to find the clusters and colorize them and see if you have
Percolation
"""
import numpy as np
from matplotlib import pyplot as plt
from include.generation import gen_rand_sys
def merge(grid, new, old):
""" Merge the two clusters """
length = grid.shape[0]
for i in ran... |
fc498b7671a519e0390e1b1064ee3d073960e91b | ali-mahani/ComputationalPhysics-Fall2020 | /PSet1/P2/cells.py | 1,078 | 3.75 | 4 | """This module provides the things we need for the evolution of cells"""
import numpy as np
def state(row, i):
"""This function takes in the current row and the index of the item,
and returns its state as and 0 =< integer =< 7 """
length = len(row)
return row[i - 1] * 4 + row[i] * 2 + row[(i + 1) ... |
a100390df12d2a1c091c4283569c98f1b53c4ac1 | JamesJimbo/Genetic-Algorithm-Dissertation | /Backup/SonicAI.py | 7,224 | 3.875 | 4 | import retro
#Allows classic video games to be supported in Gym environments for AI.
import numpy as np
#Works with arrays and matrices.
import cv2
#Displays the game onto the screen.
import neat
#Neuro-Evolution of Augmented Topologies; used to create a neural network.
import pickle
#Used to serialise and deserialise ... |
99ec192ac77df5906950a92b131e73665a76a06a | Cole-Hayson/L1-Python-Tasks | /Names List.py | 1,136 | 4.25 | 4 | names = ["Evi", "Madeleine", "Dan", "Kelsey", "Cayden", "Hayley", "Darian"]
user_name = input("Enter a name")
if user_name in names:
print("That name is already on the list!")
else:
print("The name you chose is not on the list.")
if user_name != names:
replace = input("Would you like to replace one of the n... |
33661d20aa589d10b58440d07d34314b0992aeb6 | judychau/linearsearch_challenge | /test.py | 2,227 | 3.765625 | 4 | import unittest
from linear_function import linear_search
class SearchTest(unittest.TestCase):
def test_linear_search(self):
#ascending
self.assertEqual(linear_search ( [0, 2, 4, 6, 8], 5, -1, 1, "LessThanEquals"), ("NotFound", "X") )
self.assertEqual(linear_search ( [0, 2, 4, 6, 8], 5, 0, 1, "LessT... |
38663dcb6d9b8862a98d075e123cb00be9c3bb22 | andreatrufini/TheReactionGame | /gr04_lab07/Terminal_Interface/TerminalSupport.py | 2,900 | 3.578125 | 4 | #!/usr/bin/python3.6
import sys
import os
#Function to control which serial ports can be used
def availableSerialPort():
import serial.tools.list_ports as port_list
portsList=[]
ports = list(port_list.comports())
for p in ports:
portsList.append((p)[0])
return (portsList)#return a list with all the name of th... |
03ff38d06c7fc4935fb3a4d0e7663a59b126bab1 | arnabdutta2194/NPTEL-DSA-WITH-PYTHON | /assgn7.py | 209 | 3.65625 | 4 | #What is the value of endmsg after executing the following lines?
startmsg = "hello"
endmsg = ""
for i in range(0,len(startmsg)):
endmsg = startmsg[i]+endmsg
print(endmsg)
#OUTPUT--- ollehh |
e87c8a9452a5351013a2c2e2df5397617c391fdb | FuelFighter/Telemetry_2020 | /data_vis/TechWithTimTutorial.py | 2,859 | 4.09375 | 4 | # link to tutorial https://www.youtube.com/watch?v=Vde5SH8e1OQ
# buttons: https://www.youtube.com/watch?v=-2uyzAqefyE&list=PLzMcBGfZo4-lB8MZfHPLTEHO9zJDDLpYj&index=3&t=0s
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
class MyWindow(QMainWindow): # heritag... |
131fd6dac4be5fc1d91ef9befde67a683b593439 | amirafzali/coding-questions | /more/distance-k-node.py | 946 | 3.640625 | 4 | def distanceK(self, root, target, K):
def search(root, parent=None):
if not root: return
root.parent = parent
search(root.left,root)
search(root.right, root)
search(root)
queue = deque()
res = []
queue.append((target,0))
seen = set([target])
... |
36b7c263e1f7f7a019303e8a23005595253f500c | amirafzali/coding-questions | /3Sum Multiple/sol.py | 368 | 3.96875 | 4 | def threeNumberSum(array, targetSum):
array.sort()
results = []
for i in range(len(array)-2):
num = array[i]
j = i+1
k = len(array)-1
while j < k:
total = num+array[j]+array[k]
if total == targetSum:
results.append([num,array[j],array[k]])
j+=1
k-=1
elif total > targetSum:
... |
64024bee6aad9d78d294871922c9da3824634a4d | amirafzali/coding-questions | /LRU Cache/sol.py | 1,869 | 3.625 | 4 | class Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.next = None
self.prev = None
class LRUCache(object):
def __init__(self, capacity):
self.cap = capacity
self.size = 0
self.head = Node... |
7653ec8d0433feb353c66e383d36cfff3e637484 | amirafzali/coding-questions | /Word Break/sol.py | 835 | 3.515625 | 4 | def wordBreak(s, wordDict):
states = set()
words = set(word for word in wordDict)
return self.search(s, words, 0, states)
def search(s, words, pos, states):
if pos >= len(s): return True
for i in range(pos, len(s)):
if s[pos:i+1] in words and i+1 not in states and se... |
ce2f174d889c33c66cf9270e4c3248f7b12ad9be | amirafzali/coding-questions | /Merge Two Arrays (In place)/sol.py | 532 | 3.765625 | 4 | def merge(self, nums1, m, nums2, n):
p1 = m-1
p2 = n-1
track = len(nums1)-1
while p1 >= 0 and p2 >= 0:
if nums1[p1] < nums2[p2]:
nums1[track] = nums2[p2]
p2-=1
else:
nums1[track] = nums1[p1]
p1-=1
track-=1
... |
574c57da4e458972dd07f44f71ee784df05d5f0c | amirafzali/coding-questions | /Lowest Common Ancestor/sol.py | 889 | 3.5625 | 4 | def lowestCommonAncestor(self, root, p, q):
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right: return root
if left: return left
return right
def ... |
9c6e46ed3aea1ff9b2d5dee5db5a9813d5514efc | amirafzali/coding-questions | /Randomized Set/sol.py | 799 | 3.65625 | 4 | class RandomizedSet(object):
def __init__(self):
self.arr = []
self.lookup = {}
def insert(self, val):
if val in self.lookup: return False
self.arr.append(val)
self.lookup[val] = len(self.arr)-1
return True
def remove(self, val):
... |
e85f5e00df6e978a1783c6e94ff25351babdd223 | trentlim/COSC343-Artificial-Intelligence | /Assignment 2/myAgent.py | 5,107 | 3.5 | 4 | import numpy as np
import random
playerName = "myAgent"
nPercepts = 75 # This is the number of percepts
nActions = 5 # This is the number of actions
# Training schedule
trainingSchedule = [("random", 1000), ("self", 0)]
# Creature/agent class
class MyCreature:
def __init__(self):
# Creates a matrix o... |
1d3de1928600f3442c08a0d9cd690ec88044d16b | JonasCoussement/AdventOfCode2017 | /Day1/Day1.py | 1,052 | 3.640625 | 4 | def initial_setup():
row_init = open("Day1.txt").readlines()[0]
return row_init
def check_next(inputlist):
is_double =list()
for i in range(0,len(inputlist)-1):
if inputlist[i] == inputlist[i+1]:
is_double.append(1)
else:
is_double.append(0)
return... |
db2c7fcbe14cd12c46788e1a8d5e3c1980ec45a9 | klepper24/codecademy-datascience | /Machine Learning Unsupervised Learning/ClusteringKMeans.py | 1,215 | 3.53125 | 4 | import codecademylib3_seaborn
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
from sklearn.cluster import KMeans
digits = datasets.load_digits()
print(digits.target[100])
# Figure size (width, height)
#fig = plt.figure(figsize=(6, 6))
# Adjust the subplots
#fig.subplots_adjust(l... |
0af2e371893947ebdeb44ccb345ca2a41fc962bd | klepper24/codecademy-datascience | /Machine Learning Supervised Learning/LogisticRegression.py | 2,035 | 3.734375 | 4 | import codecademylib3_seaborn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Load the passenger data
passengers = pd.read_csv('passengers.c... |
bd64fadca3071891ce36d42ddfdd8b1ddc96901b | PuneetPowar5/Small-Python-Projects | /fibonacciSequence.py | 323 | 4.21875 | 4 | print("Welcome to the Fibonacci Sequence Generator\n")
maxNum = int(input("How many numbers of the sequence do you want to see? \n"))
maxNum = int(maxNum)
a = 0
b = 1
c = 0
print("\n")
for num in range(0, maxNum):
if(num <= 1):
c = num
else:
c = a + b
a = b
b = c
print... |
286e1540c00d2f7e59869dc13e6abccb757742bf | kamaleshanantha/Array-2 | /minMax.py | 415 | 3.546875 | 4 | # Time complexity: O(N)
# Space complexity: O(1)
# Difficulty faced: No
# Not there on leetcode
def minMax(nums):
if len(nums) > 0:
minSofar = nums[0]
maxSoFar = nums[0]
for i in range(1,len(nums) -1):
minSofar = min(minSofar, min(nums[i], nums[i + 1]))
maxSoFar = m... |
b2868a546dd30bd1d4dbf1aba1bcec4a701569c5 | Takkiddie/WereTrainer | /character/engine/moods.py | 1,801 | 3.84375 | 4 |
#Each mood has two parts, high and low
#The value determines which side the mood is on
class wereMood:
def __init__(self,low,high,value):
self.high = high
self.low = low
self.value = value
def __str__(self):
if(self.value > 0):
return self.high
else:
return self.low
def absolute(self):
if(self.val... |
87400935f516df7a3ca89b4bc2ff68d314d3dbdf | JohnyXXX/Python-Quick-Start | /lesson_9_task_3.py | 327 | 4.09375 | 4 | """
Сделать так, чтобы она помнила
отвеченные вопросы
даже переформулированные
"""
from lesson_9_task_3_module import Head
head = Head()
question = ''
while question != 'стоп':
answer = head.think(input('Какой вопрос? '))
print(answer)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.