blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7a4f203309d86d6e218b44c879179bbce9f3db38
lingyunyi/PythonSmallProject
/LibrarySystem/Bookadmin.py
9,176
3.546875
4
# 导入自定义的mysql操作数据库 from mysqli import Mysqli # 定义图书修改系统。 class Bookadmin(object): # 初始化函数 def __init__(self): # 开启数据库 self.mysqli = Mysqli() # 查询数据库中所有书籍的函数 def selectAllbook(self): ''' # 查询数据库中所有书籍的函数 :return: ''' # 尝试执行 ...
9efa2743b11d84076f3c0ad44849851188b979ca
JevonsAn/Astar-findpath-algorithm
/shortestpath.py
6,111
3.71875
4
from queue import PriorityQueue from math import sqrt import time def getgraph(filename): graph = [] src = (8, 4) dst = (10, 14) with open(filename) as f: x = 0 for line in f.readlines(): newline = [] y = 0 for word in line.strip().split(" "): ...
b16d9425c71fc6cc7153f886046f3af83d37496d
LeopoldACC/Algorithm
/树/889前序后续构建二叉树.py
837
3.5625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: def dfs(pre,post): if not pre: ...
23d40eedd39906e1d31ee4893cf72bfae9408e78
ChachoPacho/Proyecto_Ajedrez
/chess/clases/movements.py
6,553
3.546875
4
class Movements(): def __init__(self, pos, game): self.row, self.col = pos self.board = game.board self.board_color = game.color[0] self.piece = self.board[self.row][self.col] # Two letters: [0]:color, [1]:piece # Movements validator def __valid_path(self, sr, sc) -...
51907234c7c36c7b2ff62fff9c21fccc54532d9d
cordeliabagley/triangle
/triangle.py
284
4
4
import turtle turtle.speed('slowest') def triangle(side_length, colour): angle = 120 turtle.color(colour, colour) turtle.begin_fill() for side in range(3): turtle.forward(side_length) turtle.right(angle) triangle(60, 'pink') triangle(120, 'green')
a0ac77459d0785b605ef90d980c82e6751b474e2
KETULPADARIYA/Learning-Designing-Pattern-and-Object-Oriented-Programming
/Object_Oriented_Programming/OperatorOverlading/reperAndString.py
1,064
3.84375
4
class adder: def __init__(self,value = 0): self.data = value def __add__(self, other): return adder(self.data + other) x = adder() def printStrAndprintReper(x): print(x) print(repr(x)) printStrAndprintReper(x) class addreper(adder): def __repr__(self): return " addrepe...
62f8c6bfce3d7a0e2d76618f0e16127068010758
apandey300/AmongUs
/AmongUsGame.py
6,598
3.6875
4
## This program is a recreation of the Game of Among Us. ## Author: Akanksha Pandey ##Creates the rooms that crewmates will travel to to complete task class Room: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name def __repr__(self)...
a1e2dd16a8a9168aaf32bbdfa3a93de45436a434
yucdong/courses
/ucb_cs61A/lab/lab08/lab08.py
5,019
3.703125
4
# Q3 def make_advanced_counter_maker(): """Makes a function that makes counters that understands the messages "count", "global-count", "reset", and "global-reset". See the examples below: >>> make_counter = make_advanced_counter_maker() >>> tom_counter = make_counter() >>> tom_counter('count') ...
25773d41014814b074e83b6765086fc79f8893d7
easywaldo/python_basic
/select_group_number.py
612
3.84375
4
def select_group_name(name_list): group_name = set() for name in name_list: group_name.add(name) print(group_name) def select_same_name_group(name_list): length = len(name_list) same_name_list = [] for i in range(0, length - 1): for j in range(i + 1, length): if (n...
ada728a62883f5e22a574ce0d8a4e64bc4e5ce7a
yugenechen/SAMS-Python-24hr-Training
/pygamge_displayText.py
3,267
4
4
# -*- coding: utf-8 -*- """pygame example - font.render() & screen.blit() using "surface" objects Script exploring printing Text to a Graphics Screen. Recognizes keyboard inputs and prints them to the screen. This example detects alphaNumerics and punctuation from the main keyboard but does not accept input from the ...
ac2be91f94dfa3fd3904fa082a2ef03ea6fb3851
xXG4briel/CursoPythonGuanabara
/7 - Operadores Aritméticos/Desafio 010.py
141
3.625
4
dolar=float(input('Quantos voce tem de dinheiro na sua carteira? ')) print('Voce consegue comprar um total de {} dolares'.format(dolar/4,0))
e753ab7cff10ca9fc3701f1f76a684d636149f52
rafaelperazzo/programacao-web
/moodledata/vpl_data/40/usersdata/101/24769/submittedfiles/main.py
395
3.640625
4
# -*- coding: utf-8 -*- from __future__ import division import funcoes #COMECE AQUI m = input('Digite a quantidade de termos que deseja obter no valor de Pi: ') eps = input('Digite o valor de epsilon para que realize-se o cálculo da razão auréa: ') print ('O valor aproximado de pi é: %.15f' %(funcoes.Pi(m)) print (...
9abbd1205181f5d94dbedd1ac2e01ab7a3249aba
zweros/DL_primary
/pytorch_demo/ch01/03autograd.py
3,130
3.703125
4
import torch """ https://pytorch123.com/SecondSection/autograd_automatic_differentiation/ autograd 包是 PyTorch 中所有神经网络的核心。首先让我们简要地介绍它,然后我们将会去训练我们的第一个神经网络。 该 autograd 软件包为 Tensors 上的所有操作提供自动微分。 它是一个由运行定义的框架,这意味着以代码运行方式定义你的后向传播,并且每次迭代都可以不同。我们从 tensor 和 gradients 来举一些例子。 torch.Tensor 是包的核心类。如果将其属性 .requires_grad 设置为 T...
bf9ccec9961d5489677d5ce5629ff6a044cb27c7
turbobin/LeetCode
/二分法/find_min.py
1,257
3.734375
4
# -*- coding: utf-8 -*- """ 153. 寻找旋转排序数组中的最小值 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。 你可以假设数组中不存在重复元素。 (链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array) 示例: 输入: [3,4,5,1,2] 输出: 1 """ class Solution(object): def findMin(...
34fc9e4fca06acf48d14e183722ee6f684dc6dc1
SergeyErmolaev/Al-game
/ex21.py
1,282
4.0625
4
def add(a, b): print(f"ADDING {a} + {b}") return a + b def substract(a, b): print(f"SUBSTRACTING {a} - {b}") return a - b def multiply(a, b): print(f"MULTIPLYING {a} * {b}") return a * b def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b print("Let's do some math with just ...
c1c81a44f6b7fb340ab1766698c3c402b9251343
arunshenoy99/python-assignments
/list9.py
810
4.25
4
# Count occurrences of an element in a list def list_count(my_list, ele): count = 0 for el in my_list: if el == ele: count += 1 return count my_list = [] n = int(input('Enter the length of the list:')) for i in range(0, n): el = input('Enter the {} element of the list:'.format(i)) ...
451f3939a7471aa50e614a470bc26f2d01689c49
samvelarakelyan/Algorithms-and-Data-structures
/Algorithms/Searching_Sorting/Sorting/Python/insertion_sort.py
1,664
4.53125
5
""" |--------------| |Insertion Sort| |--------------| ------------------------ Time complexity --------------- O(n^2) Space complexity ---------------- O(n) worst case time complexity --> O(n^2) and swaps average time complexity --> O(n^2) and swaps best ca...
bfd823b2e32b2d18878eb9aa8ca7ccb5174ebd81
hghayoom/pyseidon
/components/velocity.py
728
3.875
4
import numbers class Velocity: """Contains information on the 1D velocity of an entity""" def __init__(self, velocity: float): self._validate_velocity(velocity) self._velocity = velocity @property def velocity(self): return self._velocity @velocity.setter def velo...
ea0fa9309ff47b96b6d3ca3cd03ee97ded7ad40d
xiaohongxiao/study_tensorflow
/demo/Student.py
648
3.75
4
class Student(object): # def __init__(self, name, age): # self.__name = name # self.__age = age # pass def print_score(self): print(self.__name) def __str__(self): return 'this is (name:%s)' % self.__name def __iter__(self): return self def __next_...
b4d775d5ffaaf64f6523edcbc3c8d2885c0be28a
nicholas-huang/Leetcode
/simple/70_Climbing_stair.py
310
3.640625
4
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n <= 3: return n dip = [0]*n dip[0] = 1 dip[1] = 2 for i in range(2,n): dip[i] = dip[i-1] + dip[i-2] return dip[n-1]
2ee57da372a186079cb49e642a051572c9f5cdcf
prasadbylapudi/PythonProgramming
/Functions/local_variable_scope.py
275
3.859375
4
def print_message(): message = "hello !! I am going to print a message." # the variable message is local to the function itself print(message) print_message() print(message) # this will cause an error since a local variable cannot be accessible here.
eff84253e23fe591315a57e5a73523ccb181ea71
mbaguszulmi/KattisSolutions
/python27_solutions/Difficulty1.5/SymmetricOrder.py
839
3.953125
4
# Program by Muhammad Bagus Zulmi # Url to problem : https://open.kattis.com/problems/symmetricorder # http://www.mbaguszulmi.com def main(): symmetricNames = [] while 1: n = input() if n == 0: break else: firstName = [] secondName = [] fo...
90bc6e45f22c704bd5f17b3531e4d17e662b92fd
ug-kim/lecture-note-python-basics-for-ai
/codes/python/conditionals_and_loops/trapezoid.py
211
3.8125
4
def addtition(x, y): return x + y + 100 def multiply(x, y): return x * y def divided_by_2(x): return x / 2 def main(): print(15 == addtition(10, 5)) if __name__ == "__main__": main()
42a46914a360a1dc4cc63a5a0ea0c035c4ee9e7d
Programmer-Admin/binarysearch-editorials
/Contiguous Intervals.py
598
3.515625
4
""" Contiguous Intervals We iterate over the sorted numbers, each time the present number isn't equal to the past number, we append the interval. Trick so you don't have to deal with edge cases: add big value at end, so you don't need to check if you reached the end, or if the list is at least length 2. """ class So...
27aa83e2d6362fbc86fd3ab7b0576452b719bf5b
Resires/tietopythontraining-basic
/students/uss_tomasz/lesson_06_dictionaries_tuples_sets_args_kwargs/6_1_6_2/fantasy_game_inventory.py
765
3.6875
4
def display_inventory(player_inventory): print('Inventory:') total_items = 0 for k, v in player_inventory.items(): print(v, k) total_items += v print("Print total number of items:", total_items) def add_to_inventory(inventory, added_items): for item in added_items: if item ...
797c12b5ff955658530e4e0e631a7ed6790c479a
namujinju/study-note
/algorithm-study/codewars/largest_pair_sum.py
146
3.5
4
def largest_pair_sum(numbers): numbers.sort(reverse = True) return numbers[0] + numbers[1] print(largest_pair_sum([10,14,2,23,19]))
88fccafce2328be813de6b2a4cc376ae8e5731a9
cleilsonjose/algoritmo
/uri 1071.py
152
3.578125
4
soma = 0 X = int(input()) Y = int(input()) if X>Y: a=Y Y=X X=a for i in range(X+1,Y): if i%2!=0: soma+=i print(soma)
e8ed39177fef1ed4c422f4c245fe20a43a7955da
iqeqsun/python-small-examples
/src/test.py
700
3.890625
4
# class Book(object): # # 定义类的参数 # def __init__(self, book_id, book_name, book_store_count): # self.book_id = book_id # self.book_name = book_name # self.book_store_count = book_store_count # # 定义加法操作 # def __add__(self, book): # return self.book_store_count + b...
582453cf97f427a711faa425f32f12a4fd5c71e8
Artemish/euler
/145.py
271
3.796875
4
def is_reversable(n): if n % 10 == 0: return False r, n0 = 0, n while n > 0: r = (r * 10) + n % 10 n /= 10 n2 = r + n0 while n2 > 0: if (n2 % 10) % 2 == 0: return False n2 /= 10 return True
35a923c33a657d4532d7e2ef2e7386d992caeb4d
bikash-das/pythonprograms
/openCV/loadImage.py
376
3.84375
4
import cv2 print("OpenCV version:") print(cv2.__version__) img = cv2.imread("testimage.jpg") #reading image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #converting to gray scale cv2.imshow("Over the clouds", img) #showing image cv2.imshow("Over the clouds - gray", gray) cv2.imwrite('output.jpg', gray) #writing a ne...
f869886f00d7271c5b1ee102254ab6357d9f0a1d
IUIUN/The-Best-Time-Is-Now
/minmove2.py
1,082
3.953125
4
from collections import deque class Move: def __init__(self, x, y, step): self.x = x self.y = y self.step = step def isInside(x, y, n): return x >= 0 and x < n and y >= 0 and y < n def nextMoves(x, y, n): AVAILABLE_SHIFTS = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1...
4b538357cb87f1f2928feea88869ad14edb89325
Colaplusice/algorithm_and_data_structure
/LeetCode/week_36/15_3sum.py
2,543
3.8125
4
def list_set(a_list): dicts = {} for each in a_list: each = tuple(each) if not dicts.get(each): dicts[each] = 1 else: dicts[each] += 1 return [list(k) for k, v in dicts.items()] class Solution: def threeSum(self, nums): """ 排序整个list ...
6d200a147e2029942055f9467924539cad6e7b4a
spicypurrito/interview-questions
/python/fib-bottom-up.py
418
3.734375
4
# fib iterative bottom up. this is an O(n) algorithm def bottomUpFib(n, memcache={}): sum = 0 for itr in range(0, n+1): if itr == 0: memcache[itr] = 0 continue elif itr == 1: memcache[itr] = 1 sum += 1 continue else: ...
fd3f3e9f1d2148d26fe3cd799167e65ae4c64cc2
YangF0917/ML_Tutorials
/pandas/Dataframes.py
1,499
3.703125
4
import pandas as pd import numpy as np # Dataframes are used to objects to store 2-D data df = pd.DataFrame() # Newline added to separate DataFrames print('{}\n'.format(df)) df = pd.DataFrame([5, 6]) print('{}\n'.format(df)) df = pd.DataFrame([[5,6]]) print('{}\n'.format(df)) df = pd.DataFrame([[5, 6], [1, 3]], ...
ab3ad0cc739a8443dcdc81bdd9e3e0aaca2a7417
mtgjarvis/01_reinforcement_exercises_programming_fundamentals
/exercise.py
536
4.125
4
def grade_calc(): grade_in = int(input('Enter the grade as a percentage: ')) if grade_in == 100: print('You got an A+') elif grade_in >= 95: print('You got an A') elif grade_in >= 90: print('You got an A-') elif grade_in >= 85: print('You got an B+') elif grade_in...
5de48f7b763f3e90cf257858d1921befda546318
skahuria/python101
/multithreadExample.py
660
4.03125
4
from threading import * import time class Demo: def num(self): for i in range(1,6): print("The number is", i) time.sleep(1) def double(self): for i in range(1,6): print("The double of the number is",2*i) time.sleep(1) def square(self): ...
5806b39c5949cfe9c53c908baa694d1bf2a4fce7
RonanLeanardo11/Python-Lectures
/Lectures, Labs & Exams/Lecture Notes/Lect 5 - Classes and Definitions/Lect 5 Example 2.py
704
4.03125
4
# Define class and attributes class rectangle: length = 0 width = 0 # Have to define length and width as numbers and not strings so can do calculations # Define instances of a class instance1 = rectangle() instance2 = rectangle() # Provide values to instance 1 instance1.length = 15.2 instance1.width = 1...
b2b82a190e32371a9b474d1ed7ab6f6fb8102238
Aalekseika/python_hw-2nd
/hw#28.py
1,604
3.640625
4
# Условие: # Создать программу, которая запрашивает у пользователя произвольную строку символов. # Далее программа ее шифрует и выводит на экран в зашифрованном виде. # Шифрование происходит путем замены каждого символа символом, который # находится на 5 позиций правее в предопределенной таблице шифрования. # Таблица ш...
2640d91b1e2b9b407e144b9e1596fd6f0cbfb0f8
Jiezhi/myleetcode
/src/692-TopKFrequentWords.py
1,337
3.609375
4
#!/usr/bin/env python3 """ CREATED AT: 2022-10-19 URL: https://leetcode.com/problems/top-k-frequent-words/ GITHUB: https://github.com/Jiezhi/myleetcode FileName: 692-TopKFrequentWords Difficulty: Medium Desc: Tag: See: """ from tool import * class Solution: def topKFrequent(self, words: List[str], k: i...
06473045aab8f3ca60be45820ce79c351d7a8355
key36ra/m_python
/CheckiO/home/HousePassword.py
1,129
3.765625
4
def checkio(data): re = False #d = [x for x in data.lower()] rstr = ["{}".format(x) for x in range(10)] # boolen must have "True" or "False" red = False for d in data: # data must have number. # "in" adjust to it, but "not in" sequence does nothing. if d in rstr: ...
b928b15672fd91185d021b1c360b7c86273f7121
green-fox-academy/Kucika14
/week-04/day-03/fibonacci.py
192
3.90625
4
class Fibonacci(object): def fibonacci(self, num): if num <= 1: return num else: return self.fibonacci(num -1) + self.fibonacci(num -2)
7ca4871d19e848e41d2cefaaf8401e6a506c3dcf
sannirinne/My-Projects
/PROJECT_Battleship.py
11,271
4.0625
4
#this game was made by Sanni, Nea and Iiris import copy, random def empty_board(board): #creating the empty board board = [] row = [] #first row with the numbers row.append(" ") for i in range(10): row.append(str(i+1)) board.append(row) for j in range(9): #rows 2-9 row = [] ...
6452b8a95d2dee40f219e5618e1c88f98133ddde
DarkAlexWang/leetcode
/Interview/k_distinct_character.py
1,386
3.65625
4
# Given a string s and an int k, return an int representing the number of # substrings (not unique) of s with exactly k distinct characters. If the given # string doesn't have k distinct characters, return 0. # # Example 1: # Input: s = "pqpqs", k = 2 # Output: 7 # Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", ...
00ff1cc4e4e4e4cb7f2b39eb35cbb8c9aa26c4ea
gstarmvp/Various
/ProjectEuler/p059.py
762
3.53125
4
# Here I assume only that space is the most common character. # From there, with no additional knowledge, I derive the key. n = eval('[' + open('p059_cipher.txt', 'r').readlines()[0] + ']') print sum([c ^ k for c, k in zip(n, ([max(n[i::3], key=n[i::3].count) ^ ord(' ') for i in range(3)])*401)]) print (''.join([chr(m...
c0e2f5230cbb0d639760f37aeaaaf67e7c4eb13d
nikolaj808/python-economy-tracker
/testing.py
3,066
3.609375
4
import os import sys import tkinter as tk from tkinter import filedialog, Text from datetime import date date = date.today() ####################################################################### if os.path.exists("expenses.txt") == False: fp = open("expenses.txt", "x") fp.close() if os.path.exists("previou...
f6acb1dc70172a097f20eb07902522bc3651c1c5
apurvalembi007/Python-Smallcodes
/convertBase.py
205
3.515625
4
def conversion(n, base): if n<1: return [0] output = [] while n: output.append(n%base) n = n/base return "".join(map(str,output[::-1])) print conversion(13, 2)
26f1f7497096c60238655e5fd8df51fbb70d756e
mattykay/leetcode
/solutions/1207/main.py
669
3.84375
4
from collections import defaultdict class Solution: def uniqueOccurrences(self, arr: list) -> bool: occurrences = defaultdict(int) # Sort by occurrences for value in arr: occurrences[value] += 1 # If set of occurrences is less than occurrences, it means duplicate value...
7a0d33dbeff3e516adfe8ca93fb58a38feab2916
NikhilMJain/PCCode
/One/minheight.py
672
3.546875
4
import math class Node(): def __init__(self, info = None): self.info = info self.l = self.r = None s = [] s1 = [] head = root = one = Node(1) two = Node(2) three= Node(3) four = Node(4) five = Node(5) one.l = two one.r = four two.l = three two.r = five m = math.inf def height(root, l): global ...
ccbf151eefc804b61a345d4acdae0346d97a547e
jcarnide97/IPRP
/Ficha/cap9.py
1,572
3.75
4
# Capítulo 9 - Recursividade import math # Somatorio de numeros inteiros positivos até N # sem recursividade def somatorio_srec(N): soma = 0 for i in range(1, N+1): soma += i return soma # com recursividade def somatorio_crec(N): if N == 1: return 1 else: ...
ae6ca646dcece9191332693928e1315611dcd746
cowlsdnr77/algorithm
/programmers/Stack&Queue/stock_price(Deque Sol).py
1,079
3.578125
4
from collections import deque prices = [3, 1, 4, 5, 2] # Deque로 푸는 방법 # 시간 복잡도는 O(n^2) def solution(prices): answer = [] prices = deque(prices) while prices: # prices를 모두 탐색해서 [] 되면 stop flag = prices.popleft() # prices의 첫 숫자를 기준점으로 잡고 cnt = 0 for i in prices: # 나머지 숫자 하나씩 다...
3b55dc7593329d27c0731c3a33398334b6b5392e
KRISHNANSHUCODER/Python
/Missing Number.py
304
3.5
4
n = input().split()# take input sepetarely# print(n) b = n[0]#1st element of input# c = n[-1]#last element of input# b = int(b) c = int(c) print(b)#prinr 1st element# print(c)#print 2nd element# for a in range(int(n[-1])): print(n[a]) i = 0 l = [] for i in range(b,c+1): l.append(i) print(l)
0ef4986b97563492306352b1936789370c4c8c5e
rahulgadre/python-files
/hw.py
800
3.84375
4
# Hello World print (' hello world') # Length of a sentence a = 'winter is coming' print (len (a)) # reversing a strong mystring = "rahulgadre" print (mystring[::-1]) # spliting string secstring = "the world is dark" print (secstring.split()) # Using variables show = "GoT" time = 7 print (f'Do not forget to watch ...
176fc8e4fb2105bbce12f17096ba247d3da7a955
ejohnso9/programming
/codeeval/CE/chal_161/ce161.py
1,682
3.859375
4
#!/usr/bin/env python import sys """ TEMPLATE Solution for codeeval challenge #161 (GAME OF LIFE) https://www.codeeval.com/open_challenges/161/ AUTHOR: Erik Johnson DATE: 2016-Sep-30 """ N = 10 # compute number of adjacent neighbors def n_adj(g, r, c): if c > 0 and c < N - 1: # insi...
c900935be551e9c2d75a75770850cb19ac88f00f
diptangsu/Sorting-Algorithms
/Python/BucketSort.py
1,010
4.03125
4
"""Python3 program to sort an array """ def insertion_sort(arr): for i in range(1, len(arr)): up = arr[i] j = i - 1 while j >= 0 and arr[j] > up: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = up return arr def bucket_sort(numbers): arr = [] slot_num ...
7546e3a93f58058ade8ce4878c938be5995976ab
huzaifabaloch/PIAIC-AI-Q1-Python-Assignment-1
/Task 22/pattern_2.py
473
3.828125
4
""" 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 """ def make_pattern(size): # Counter for iteration. counter = 0 # Start number traction. number = 0 # It will add and remove numbers to make the desired pattern. lis = [] while counter < size: lis.append(number+1) print(lis) counter += 1 numbe...
6c6656732e30276aca1d8dbe6b3b7cfdc656722d
Rich43/rog
/albums/3/challenge84_easy/code.py
3,422
4.3125
4
''' Like many people who program, I got started doing this because I wanted to learn how to make video games. As a result, my first ever 'project' was also my first video game. It involved a simple text adventure I called "The adventure of the barren moor" In "The adventure of the barren moor" the player is in the mi...
38f841b23b6ecf45761515da8e0ab3a91fc9e027
sealanguage/april2021refresh
/leap_year/leap_year.py
154
3.84375
4
year = int(input("Input a year: ")) if(year %4 == 0 and year %100 != 0): print("True") elif(year %4 == 0 and year %400 != 0): print("False")
59e1fd3d07639e5d78723b4d89267186455f35a9
JiangHuYiXiao/PythonStudy
/Python基础&并发编程/day1/04用户交互input.py
295
4.0625
4
#-*- coding:utf-8 -*- # 用户交互:获取用户的输入,然后进行输出,使用input() # input输出输出的数据全部是字符串 name = input('请输入你的名字:') age = input('请输入你的年龄:') print('我的名字是:' + name,'我的年龄是:'+ age + '岁')
8cbae9082b15fa8b1e9efdb7af05c8447e53aad1
SJulia/MyStudy
/PhoneBook.py
1,782
3.953125
4
import pickle Data = {} Phonebook = [Data] book_file = 'D:\\book.pb' def read_from_file(path_to_file): try: return pickle.load(open(path_to_file, 'r')) except: pass def dump_to_file(path_to_file, data): try: data_from_file = read_from_file(path_to_file) print data_from_file...
ae3e3eae0621ff5fbebcd8b39f93dc4592382bf7
ParulProgrammingHub/assignment-1-malgamves
/q2.py
130
4.0625
4
#Q2 PI = 3.142 rad = input("Enter the radius of the circle\n") cir = 2 * PI * rad print ("Circumference is %f\n" %cir)
eaca5931cbb9c28d2c6af0c01adb3e1e9993ca9c
wikibook/python36
/1부/7장/7-1-4.py
193
3.5625
4
def divide(a, b): return a / b try: c = divide(5, "af") except TypeError as e: print('에러: ', e.args[0]) except Exception: print('음~ 무슨 에러인지 모르겠어요!!')
07f6867006e9eba23d672d58bf5d9a0729f0d1fa
NenadPantelic/DailyInterviewPro
/20_04_07_non-decreasing_array_with_single_modification.py
1,648
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 8 11:37:50 2020 @author: nenad """ """ Problem description: You are given an array of integers in an arbitrary order. Return whether or not it is possible to make the array non-decreasing by modifying at most 1 element to any value. We def...
ef3fe6dd1f04231973610e627ed5a64b77e66561
feadoor/hackerrank
/practice/algorithms/strings/super_reduced_string.py
490
3.5625
4
#!/usr/local/bin/pypy3 from itertools import groupby from operator import itemgetter def groups(s): return map(''.join, map(itemgetter(1), groupby(s))) def reduce_once(s): return ''.join(group[0] for group in groups(s) if len(group) % 2) def reduce(s): prev_s = None while prev_s != s: prev_s...
7edc13399fc3b1b89564e37131efe33fc3f995eb
Roberta-bsouza/pyscripts
/exe014.py
379
3.9375
4
x = int(input('Informe um número: ')) print('A tabuada de somar de', x, 'é:') print(x ,'+', 0, '=',x+0) print(x ,'+', 1, '=',x+1) print(x ,'+', 2, '=',x+2) print(x ,'+', 3, '=',x+3) print(x ,'+', 4, '=',x+4) print(x ,'+', 5, '=',x+5) print(x ,'+', 6, '=',x+6) print(x ,'+', 7, '=',x+7) print(x ,'+', 8, '=',x+8...
49692aef28c795118b2bb620e63d8bdc53cd1a4c
inallweather/python_learning
/python学习/链表/linked_reverse.py
1,135
4.0625
4
""" @version: 1.0 @author: jack-liu @file: linked_reverse.py @time: 2020/5/12 10:27 """ class Node: def __init__(self, val): self.value = val self.next = None class LinkedListReverse: """ 传入一个链表,反转链表后,并返回第一节点 """ def get_linked_reverse(self, head): """ 传入一个链表,反转链...
80775ade166d10b00024acdb9a2379155995465b
SivasubramanianA/Solved_programs
/pro set 06-52.py
222
3.546875
4
a1,a2=map(int,raw_input().split()) b1,b2=map(int,raw_input().split()) c1,c2=map(int,raw_input().split()) d1,d2=map(int,raw_input().split()) if(a1==b1 and c1==d1 and a2==d2 and b2==c2): print "yes" else: print "no"
cbeb6412c56e10b5e60b2f8b0e23bf79e4599b01
daher7/Python_Pildoras
/11_try_except_2.py
361
4.0625
4
def divide(): try: op1 = (float(input("Introduce un numero: "))) op2 = (float(input("Introduce otro numero: "))) print("La division es {}".format(op1/op2)) except ZeroDivisionError: print("Ha ocurrido un error. No se puede dividir entre 0") finally: ...
f09337a4fb9b29be53c07079d0361fd8a950b58a
wesbasinger/LPTHW
/ex04/practice.py
894
4.5
4
# Using your new knowledge of variables, modify the code # so that it prints what the comments call for. capital_city_of_Texas = # Remember to protect strings with quotes!!! # should print "The capital city of Texas is Austin." print "The capital city of Texas is " + capital_city_of_Texas + "." num_sides_of_a_squ...
a9466c5fcaf9d4df438dddeb47aea87a6909c7ad
Svitanki/2019-AdventOfCode
/day03a.py
2,103
4
4
#!/usr/bin/python3 wire1 = set() wire2 = set() def make_move(current_x, current_y, move, wire): direction = move[0:1] amount = int( move[1:] ) goal = 0 if direction=="R": goal = current_x+amount while (current_x<goal): current_x ...
2ca15595c91f9fd9d33fd594ca61660171c98d38
iCodeIN/LeetCode-12
/MergeIntervals.py
546
3.828125
4
def getKey(element): return element[0] def merge(intervals): intervals.sort(key=getKey) st = intervals[0][0] en = intervals[0][1] n = len(intervals) ans = [] for i in range(1, n): if intervals[i][0] >= en: pair = [st, en] ans.append(pair) st = in...
ae85ed90629a8a70f8bba07d32f3dff276e25f35
ABScripts/auadd
/shelves/shelves/shelf.py
4,425
3.671875
4
#!/usr/bin/env python """ This module provides everything needed for shelves to work and expose all the needed method as well as some agnostic storage Shelves (such as shelf of shelves) A shelve is made of at least a searchable index, and a readable store (indexed by the index). """ class Shelf(dict): """ Thi...
d10a722f52503fe9fd70aff4773dbbaea66b2a5e
hiteshsahu/Python4ML
/src/python/datatype/SetType.py
1,096
4.21875
4
""" Set Data Type(set): - UN INDEXED - Can hold HETEROGENEOUS DATA TYPE - Repetition NOT allowed - SINGLE Dimensional """ # Creating a Multi-Dimensional List from math import pi print(" \n-------CREATE---------- ") multiDSet = {'Hitesh', 'kumar', 'Sahu', 29, "Sahu", pi} mySet = {"0", "1", "2", "3", "4", "5", "6",...
84bf2d426c2880abc8e2a69bf6034d42a7303e87
goswami-rahul/plots-and-visualizations
/show_golden_ratio.py
604
4.25
4
import matplotlib.pyplot as plt def draw_graph(x, y): plt.plot(x, y) plt.xlabel('Numbers') plt.ylabel('Ratio') plt.title('Ratio between consecutive fibonacci numbers') def draw(n): fib = [1, 1] for i in range(2, n+1): # generate fiboncci numbers fib.append(fib[i-1]+fib[i-2]) ratios = ...
06596bd8e6d8d57ed975b42cbcd85e2412fb5423
profnssorg/henriqueJoner1
/exercicio310.py
497
3.703125
4
""" Descrição: Este programa calcula o aumento percentual do salário indicado pelo usuário Autor:Henrique Joner Versão:0.0.1 Data:23/11/2018 """ #Inicialização de variáveis salario = 0 novosalario = 0 aumento = 0 #Entrada de dados salario = float(input("Qual o seu salário atual? ")) aumento = float(input("Qual o...
7aa54df4284514df9298a620a837964e236c336f
xiuxim/store
/day02/三角形.py
534
3.734375
4
num=[] print("请输入第一条边:") a=input() a=int(a) num.append(a) print("请输入第二条边:") b=input() b=int(b) num.append(b) print("请输入第三条边:") c=input() c=int(c) num.append(c) if a==b or a==c or b==c: print(num,"构成等腰三角形!") elif a==b==c: print(num,"构成等边三角形") elif a*a+b*b==c*c or a*a+c*c==b*b or c*c+b*b==a*a: print(num,"构成直...
78430796fea9bc457e93fa91790db6c1171584e6
RaquelFonseca/P1
/Unidade1a3/area_esfera.py
267
3.703125
4
# coding: utf-8 # area da esfera # Raquel Ambrozio print "Cálculo da superfície de uma esfera" print "---" diametro = float(raw_input("Medida do diâmetro? ")) import math area_esfera = 4 * math.pi * ((diametro/2)**2) print "---" print "Àrea calculada: %.2f" % area_esfera
cc290fcbf2b851e0ae283169242c357c66da66c3
DaliahAljutayli/PythonCode
/Python Function to Display Calendar/Function to Display Calendar.py
1,011
4.46875
4
#By Daliah Aljutayli #Python Function to Display Calendar #---------------------------- import calendar import datetime calendar.setfirstweekday(calendar.SUNDAY) #1st day is Sunday def DayName(): #display Weekday name d = datetime.datetime.now() print(d.strftime('%A , %a')) # %A -> Weekday,full v...
20535085fae79be67ba4d6ed9e6a770ef1a89367
Adasumizox/ProgrammingChallenges
/codewars/Python/8 kyu/EvenOrOdd/even_or_odd_test.py
941
3.546875
4
from even_or_odd import even_or_odd import unittest class TestEvenOrOdd(unittest.TestCase): def test(self): self.assertEqual(even_or_odd(2), "Even", 'Basic test even') self.assertEqual(even_or_odd(1), "Odd", 'Basic test odd') self.assertEqual(even_or_odd(0), "Even", 'Edge: zero') ...
22f40c50422b442c0840be92340a65e420e24dea
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/654 Maximum Binary Tree.py
2,187
3.875
4
#!/usr/bin/python3 """ Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constr...
e907ecae5f52334773d65f2923e036c183796e70
S-Nathalia/URI-s
/src/python_C/semana_1/1017.py
102
3.734375
4
time = int(input()) speed = int(input()) dis = 0.0 dis = time*speed dis = dis/12 print("%.3f" % dis)
f7a631f66f138e91ce9ade699408aaa58e5c070a
szabgab/slides
/python/examples/web-client/parse_html.py
1,183
3.53125
4
from bs4 import BeautifulSoup import requests url = 'https://en.wikipedia.org/wiki/Main_Page' res = requests.get(url) if res.status_code != 200: exit(f"Error in getting the page. Status code: {res.status_code}") html = res.content soup = BeautifulSoup(html, features='lxml') print(soup.title.text) for link in sou...
ae3422a09b511a0aa5b3835567aa6d3c14e615de
cozyo/algo-learn
/python/binarysearch/leetcode/first_last_sort_array.py
605
3.578125
4
from typing import List # 在排序数组中查找元素的第一个和最后一个位置 class Solution: # 遍历的方式 def searchRange_1(self, nums: List[int], target: int) -> List[int]: res = [-1, -1] for i in range(len(nums)): if nums[i] == target: if i == 0 or nums[i - 1] != nums[i]: res...
8ad842ab0c5a9c18cc58ab4235cada3248bb653c
mtrinh11/CodingPractice
/HackerRank/rotateArrayLeft.py
237
3.578125
4
# V1 def rotateLeft(d, arr): while d > 0: first = arr.pop(0) arr = arr + [first] d -= 1 return arr # V2: simplified logic and process with splicing def rotateLeftTwo(d, arr): return arr[d:] + arr[0:d]
7168d98d82a9bfc2ccf5234a8ee71bc2f53a5640
LasterSmithKim/Pandas
/pandas入门/5.向DataFrame里增加数据列.py
583
3.828125
4
import numpy as np import pandas as pd df = {'Name': pd.Series(['Jon', 'Aaron', 'Todd'],index=['a', 'b', 'c']), 'Age': pd.Series(['39', '34', '32', '33'],index=['a', 'b', 'c', 'd']), 'Nationality': pd.Series(['US', 'CN', 'US'],index=['a', 'b', 'c']) } print(pd.DataFrame(df)) #重新定义一个Series,把它放入到表中 #...
bbb2fbc4a7dc8b80204555c28a5545c67aeba9cf
eyvitoria/Projetos-python
/jokenpo.py
1,082
3.59375
4
import random vitoria = 0 aux= 1 while aux <=5: jogadaPlayer = input("SUA JOGADA [PEDRA - 0,PAPEL - 1, TESOURA - 2:") jogadaComputador = random.randrange(0,2) jogadas = ["pedra", "papel", "tesoura"] print("Player:", jogadaPlayer) print("Computador:", jogadas[jogadaComputador]) if jogadaPlayer == jogadas[jog...
c008b949344a5eb5e7b53441505ac20a9300c008
atshaya-anand/LeetCode-programs
/Easy/symmetricTree.py
803
4.09375
4
# https://leetcode.com/problems/symmetric-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: ...
125f77ab2ec140e0f337484778c20be4886d1608
fduda/Intro_prog
/Semana 9/ex6/possibility_reduction_final.py
2,289
3.65625
4
def choose_branches(n, picker): # smart choices if picker == "first_player": if n == 1: p1 = 1 p2 = 2 else: if n % 3 == 0: p1 = n+1 p2 = n+1 # elif n % 3 == 1: # p1 = 4 # ...
8076180d97989cf328d7f4bf14a9f30d26d8ac4c
ashishsth7586/algorithms
/arrays/four-number-sum.py
1,331
4
4
""" Given an array of integers, return the four numbers (quadruplets) such that they add up to a specific given target. Each input may have multiple solutions Example: arrayOfNums = [7, 6, 4, -1, 1, 2] Target = 16 Solution: [[7, 6, 4, -1], [7, 6, 1, 2]] """ # Using the Naive solution which is infact # the use of ...
78a968484e112c42f0214a417c3bf424bf1dee07
cs-richardson/fahrenheit-thoang21
/fahrenheit.py
891
4.46875
4
""" This program will ask the user to input a temperature in celcius. Then, it will convert that number into fahrenheit and print back out the fahrenheit value """ # Tung Hoang - 08/16/19 # Asking user to input a number celcius = input("C: ") # Using a while loop to keep asking the user value until it is valid (numer...
16c58dccb1f6c47efb960492b2bae15b39394028
aaakashkumar/competitive_programming
/leetcode/validate-binary-search-tree.py
772
3.828125
4
# Validate Binary Search Tree # https://leetcode.com/problems/validate-binary-search-tree/ # @author Akash Kumar # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solutio...
409d2f7dfa3c8abe00ca1a309c7fe7d8f859b57a
edgarshurtado/pythonBioinformaticsExercises
/TemarioWeb/control_flujo/ejer1.py
241
3.765625
4
# Leer un fichero que contiene una lista de palabras y guardar las palabras en # una lista from sys import argv src = open(argv[1]) palabras = [] for line in src: line = line.strip().split() palabras.extend(line) print(palabras)
6e4545e98271d4c110e6a077c63a9e3ce565bf60
lizzzcai/leetcode
/python/sorting_and_searching/0973_K_Closest_Points_to_Origin.py
3,942
3.84375
4
''' 30/05/2020 973. K Closest Points to Origin - Medium Tag: Divide and Conquer, Heap, Sort We have a list of points on the plane. Find the K closest points to the origin (0, 0). (Here, the distance between two points on a plane is the Euclidean distance.) You may return the answer in any order. The answer is gu...
f903fba3ba11238d20b9c45462fd60b31b2a3eb3
moustafaBadrr/Linear-Regression
/SimpleLinearRegression.py
1,175
3.859375
4
#libraries. import numpy as np import matplotlib.pyplot as plt import pandas as pd from google.colab import files from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression #uploading dataset file uploadFile = files.upload() dataset = pd.read_csv("Salary_Data.cs...
a7329d79e065fd0cce71d588a6c905ab51c3a90c
gutovianna88/learning_python
/ListaDeExercicios/EstruturaDeDecisao/12.py
2,123
3.84375
4
""" Faça um programa para o cálculo de uma folha de pagamento, sabendo que os descontos são do Imposto de Renda, que depende do salário bruto (conforme tabela abaixo) e 3% para o Sindicato e que o FGTS corresponde a 11% do Salário Bruto, mas não é descontado (é a empresa que deposita). O Salário Líquido corresponde ao ...
bc6025f53053e894e6040e174f5737b564ec5c9e
myron-z-zhang/machine_learn
/re_maxmatch.py
4,332
3.5625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import string import random import math import sys def main(): #reload(sys) #sys.setdefaultencoding('utf-8') #sys.setdefaultdecoding('utf-8') #create an list for storage all file'words words = [] newsclass = ['auto','business','sports'] del_estr = string....
6719ca8f4b7f25c24185a9a93c9f024fdbc328b3
srahul1989/PythonInterviews
/OOPsConcepts/inheritance.py
1,485
4.3125
4
__author__ = 'rahul' ''' There are three ways that the parent and child classes can interact: 1. Actions on the child imply an action on the parent. 2. Actions on the child override the action on the parent. 3. Actions on the child alter the action on the parent. ''' # ## Implicit Inheritance:: class Parent(object): ...
33d69e0bd1c2378f7601ae2baa1487041c87a38e
jzeng07/coursera
/algorithem/week4/scc_dsf1.py
1,888
3.796875
4
def make_graph(edges): g = {} for v, w in edges: if not v in g: g[v] = set([]) g[v].add(w) return g def reverse_graph(edges): g = {} for v, w in edges: if not w in g: g[w] = set([]) g[w].add(v) return g def dsf_loop(edges): ...
e9eec5905f4cc88acaaccd3990f3253e842ea677
csumithra/pythonUtils
/guessing_game_args.py
899
4.25
4
from random import randint print("start here") try: lower = int(input("Enter lower bound for guessing game: ")) except ValueError: print("Please enter a number") try: upper = int(input("Enter upper bound for guessing game: ")) if upper < lower: print(f"Enter a number greater than {lower}") ...
31528bebca5bb1ecc8c13091df1f2b247ff5c594
GK-SVG/PYDS-Training
/DAY1/anagrame.py
420
4.03125
4
def anagram(str1, str2): temp_str1 = sorted(str1) temp_str2 = sorted(str2) count = 0 for i in range(len(temp_str1)): if temp_str1[i] == temp_str2[i]: continue else: count += 1 break if count == 0: print('Anagram') else: print('N...
6d480277da83e3db9df3b715792d38a05f6628de
vohuynh1990/odsc
/mlp_mnist_theano.py
10,029
4.125
4
""" This tutorial covers your simplest neural network: a multilayer perceptron (MLP) Also known as feedforward neural network. We will learn to classify MNIST handwritten digit images into their correct label (0-9). """ import cPickle as pickle import gzip from PIL import Image from opendeep.utils.image import tile_ras...