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
574823b6552a9833a89d00014107a9befffa14a8
Ranc58/18_price_format
/format_price.py
935
3.578125
4
import argparse import locale def format_price(input_price): locale.setlocale(locale.LC_ALL, '') numbers_after_comma = 2 try: if isinstance(input_price, str): input_price = float(input_price.replace(',', '.')) output_price = "{:n}".format(round(input_price, numbers_after_comma)...
432345fd78673b5229337ce0bf738444e8ea4a7d
weicunheng/gulu
/3.数据类型之字典/2.有序字典.py
441
3.515625
4
# -*- coding:utf-8 _*- """ 有序字典 精确控制JSON编码后字段的顺序,可以使用 OrderedDict 先构建数据,然后在序列化。 注意: 一个 OrderedDict 的大小是一个普通字典的两倍,因为它内部维护着另外一个链表。 """ import json from collections import OrderedDict if __name__ == '__main__': map = OrderedDict() map["a"] = 1 map["b"] = 2 print(json.dumps(map))
11a3f538ffdd1fbb65d89ac3983cd3db328be3f6
weicunheng/gulu
/4.日期和时间/5.返回月份所有的日期.py
522
3.8125
4
# -*- coding:utf-8 _*- import calendar from datetime import datetime, date, timedelta def get_date_range(start_date=None): if not start_date: start_date = date.today().replace(day=1) week, days = calendar.monthrange(start_date.year, start_date.month) end_date = start_date + timedelta(days=days) ...
e8d40a8eb6fae3d59777f34cad15f62eef64a7e7
kushalkokje/Social-Media-Mining
/Wikipedia-Vandalism-Detection/Wiki-main.py
9,817
3.65625
4
"""Assignment 5: Vandalism Detection Please add your code where indicated by "YOUR CODE HERE". You may conduct a superficial test of your code by executing this file in a python interpreter. This assignment asks you to predict the class membership of a Wikipedia edit. The edit is either vandalism or an edit mad...
441c71e81abab77af672338ffa8d70605bd4f815
navodathathsara/NIBM_Network_program
/re -built_xxd.py
1,918
3.671875
4
from sys import argv text_list=[] #define a new list #file=str(input("xxd ")) #input file name script, file=argv fo=open(file,"r") #open the file textin=fo.read() #read the file fo.close() ...
88f00080fb2908cf61aa947f0ec3f5e0853078a8
StephanieVazquez/Hamiltonian-Circuits
/matriz.py
206
3.625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 30 13:03:58 2016 @author: Stephanie """ matriz = [] for i in range(3): matriz.append([]) for j in range(3): matriz[i].append(None)
a95f7ffc4cd3f77fe17b2dd35f328ab2d60a4bf4
rkpop/twitter-bot
/kpopbot/db.py
1,034
3.578125
4
import sqlite3 class Database: def __init__(self, file_name, table_name): self.db = sqlite3.connect(file_name) self.table_name = table_name def check_table(self, key): cursor = self.db.cursor() query = """SELECT count(*) FROM {table} WHERE ID=?""".format( table=sel...
4775f84be458ac5db8bf9db84ad355d6bf140dd8
gonczor/AISD
/ham-eul/hamilton.py
1,276
3.546875
4
from utils import timer path = [] found_path = False @timer def find_all_paths_start(graph): find_all_paths(graph) def find_all_paths(graph, current_vertex=0): global path, found_path number_of_vertices = len(graph) neighbours = graph[current_vertex] path.append(current_vertex) for neighbo...
b97a4b51a74fbd91554663a941c839773e4ef510
gonczor/AISD
/Struktury/structures/avl.py
10,328
3.6875
4
from . import StructureHandler class Node: def __init__(self, key): self.key = key self.left = None self.right = None class AVLHandler(StructureHandler): def __init__(self): self.node = None self.height = -1 self.balance = 0 def get_height(self): ...
db2aca2e7320343f235a57adc54d869662f2f1f4
aster-isk/Quick-Programs
/color_functions.py
1,685
3.671875
4
import math #Takes a list of RGB integer decimal values (in that order) and returns a #hexadecimal string in the form of "#RRGGXBB" def hexstring(color): hexcode = "#" for dec in color: rgb = hex(dec) hex_dig = rgb[2:] if len(hex_dig)==1: hex_dig = '0' + hex_d...
fbd421dc8e8edc5cc16a3d1857c53a0a6bf00dfc
Veterun/Interview-1
/language/python/note.py
3,407
4.34375
4
#comparison chaining testing whether a number is the largest of three: a < x > b a == b < c actually means a == b and b < c in python! ****************** str.join(iterable) #Return a string which is the concatenation of the strings in the iterable iterable ex : ["->".join(["22","33","11"])] ['22->33->11'] ********...
eb64b2e0a8d5323ea1d864e703e170b72f36a725
AlanFermat/leetcode
/dfs + tree/637 averageLevelBinTree.py
902
3.9375
4
from binaryTree import Node node = Node(3) node.left=Node(9) node.right= Node(20) node.left.left = Node(3) node.left.left.right = Node(34) node.left.left.left = Node(13) node.right.left = Node(15) node.right.right =Node(7) # do a BFS so that we can do average def height(t): """ input: root node output: height of...
597368b52b65f2cf0b6a61a78ec076f6ff925432
AlanFermat/leetcode
/linkedList/707 designList.py
2,691
4.53125
5
""" Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked...
e590d1eb728c5cd02e6b4db9c85ea0581d69e1ed
AlanFermat/leetcode
/recursion + DP/385 miniParse.py
946
3.671875
4
def parse(s): """ :type s: str :rtype: NestedInteger """ # s = "[123,[456,[789]]]" st = [] i = 0 while i < len(s): ch = s[i] if ch == "[": st.append("[") i += 1 elif ch.isdigit() or ch == '-': sign = 1 if ch == '-': ...
621f89478f6343737be7e239329c4e5e24aedec1
AlanFermat/leetcode
/dfs + tree/102 levelTraverseTree.py
1,140
3.90625
4
# this is equivalent to the BFS of Tree # from binaryTree import Node # def height(t): # """ # input: root node # output: height of the tree # """ # if t == None: # return 0 # hl = height(t.left) # hr = height(t.right) # return max(hl,hr) + 1 # def levelConcat(t,d): # if t == None: # return [] # if d =...
62ad6dfea3d0aaa54c2c4e52baeda1ed56a5fba7
AlanFermat/leetcode
/searchAlgo/smallestSecondSmallest.py
453
3.953125
4
#http://www.geeksforgeeks.org/to-find-smallest-and-second-smallest-element-in-an-array/ import sys def smallestAndSecondSmallest(seq): """ Find smallest and Second Smallest element in an array O(n) """ first = second = sys.maxint for element in seq: if element < first: second = first first = element eli...
5620370d047cb1394979259a4ac8d055ce5c7bae
AlanFermat/leetcode
/google/patienceSort.py
404
3.703125
4
# from bisect import bisect_left def sol(heights): piles = [] def binarySearch(a, x, lo, hi): while lo < hi: mid = (lo+hi)//2 if a[mid][0] <= x: lo = mid+1 else: hi = mid return lo for num in heights: i = binarySearch(piles, num, 0, len(piles)) if i != len(piles): piles[i].insert(0,num) els...
1d32b762a1d7b214ec7254c2489f2e3c9db8f651
AlanFermat/leetcode
/backtracking/211 AddSearchWord.py
1,028
3.875
4
from collections import defaultdict as dd class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.child = dd(WordDictionary) self.isleaf = False def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ ...
14706f52232d15df2e38e0aa3e84d1122012125b
AlanFermat/leetcode
/twoPointer/15 3Sum.py
788
3.5625
4
# Given an array S of n integers, are there elements a, b, c in S # such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. def threesum(arr): result = [] n = len(arr) if n < 3: return [] elif n == 3: if sum(arr) == 0: return [arr] else: return [] else: arr.so...
d511872c877df0f5e684226a8438dfcc03878cfa
AlanFermat/leetcode
/array + Design/681 NextClosestTime.py
650
3.53125
4
def nextClosestTime(time): """ :type time: str :rtype: str """ time_str = time.split(":") minute, hour = int(time_str[1]), int(time_str[0]) a = set(time) while True: minute += 1 if minute == 60: minute =0 ...
0f1a18c76908cb6e90c89a6780de0698a89b81d9
AlanFermat/leetcode
/recursion + DP/665 nonDecreasing_arr.py
360
3.78125
4
def isNon(arr): for i in xrange(len(arr)-1): if arr[i] > arr[i+1]: return False return True def ifNonDecreasing(arr): n = len(arr) seq1 = arr[:] seq2 = arr[:] for i in range(n-1): if arr[i] > arr[i+1]: seq1[i] = seq1[i+1] seq2[i+1] = seq2[i] return isNon(seq1) or isNon(seq2) return True arr = ...
fe46fef1dbac4b4b6fb957c196071f99fb059d8e
AlanFermat/leetcode
/array + Design/license.py
388
3.53125
4
def licenseKeyFormatting(S, K): """ :type S: str :type K: int :rtype: str """ string = S.split('-') string = "".join(string) string = string.upper() s = list(string) ans = [] print s while s: temp = "" for i in range(K): if s: temp = s.pop() + temp else: break ans.insert(0,temp) return ...
ae9fddb2d17a2470b6deb9561c8248f1715bdf9f
AlanFermat/leetcode
/dfs + tree/binTreeToBSTree.py
591
3.765625
4
from binaryTree import Node from treeTraverse import * node = Node(3) node.left=Node(20) node.right= Node(9) node.left.left = Node(7) node.left.right =Node(15) node_list = preorderTraverse(node) node_list.sort() n = len(node_list) print (node_list) def arrToBST(arr,root): """ just apply sorted array to BST """ ...
da7787b68df9d4c12d63d9adc4c05585c0dea677
AlanFermat/leetcode
/searchAlgo/binarySearch/4 medianTwoSortedList.py
996
3.546875
4
def findMedian(seq): if len(seq) % 2 == 0: return (seq[len(seq)/2] + seq[len(seq)/2-1])/2.0 return seq[len(seq)/2] def simpleMedian(seq1,seq2): s = seq1 + seq2 s.sort() return findMedian(s) def medianTwoSortedList(seq1, seq2): n = len(seq1) # this is for the case when two sequences are of the same length...
ef39ed2643adaa985f0314273ce19a95c3dea2fc
AlanFermat/leetcode
/Facebook/jump.py
432
3.765625
4
def jump(nums): """ :type nums: List[int] :rtype: int """ if not nums or len(nums) == 1: return 0 n = len(nums) start, end, step = 0, 0, 0 while end < n-1: step += 1 maxGet = end for pos in range(start, end+1): maxGet = max(maxGet, pos + nums[p...
6e61b662a1ec0a82a0630abe83d40732c16038f5
AlanFermat/leetcode
/Facebook/basicCalculatorII.py
633
3.53125
4
def cal(s): if not s: return 0 n = len(s) idx = 0 num = 0 stack = [] sign = "+" while idx < n: c = s[idx] if c.isdigit(): num = int(c) + 10 * num if (not c.isspace() and not c.isdigit()) or idx == n - 1: if sign == "+": stack.append(num) elif sign == "-": stack.append(-num) elif sign...
24ee8fbaebd1636cfcc1a7c7f1d41d6467022d2d
AlanFermat/leetcode
/google/longestABSpath.py
811
3.703125
4
def longestPath(input): paths = input.split('\n') counter, max_length = 0, 0 s = [] for p in paths: idx = p.rfind('\t') if idx == -1: depth = 1 if idx != -1: depth = idx + 2 p = p[idx+1:] # we store the counter for recyling # so that we can count the number of words for # the length of next wo...
efac1bd7950e79bc1250618d463b4fde1a198d3b
AlanFermat/leetcode
/dfs + tree/invertBinTree.py
377
3.640625
4
from binaryTree import Node def invertTree(root): if root == None: return None tl = invertTree(root.left) tr = invertTree(root.right) root.right = tl root.left = tr return root node = Node(3) node.left=Node(9) node.right= Node(20) node.right.left = Node(15) node.right.left.right =Node(7) node.right.left.lef...
1d5e0c7efb3b5d7366a16323060cd7f73cb7c7e3
AlanFermat/leetcode
/searchAlgo/linearSearch.py
157
3.953125
4
def linearSearch(arr, num): for i in range(len(arr)): if arr[i] == num: return i return -1 arr = [1,2,34,5] num = [2] print linearSearch(arr, num)
cc28251a47b8755af683495a1a0f580d8ef2d72f
AlanFermat/leetcode
/backtracking/90 powerSetII.py
172
3.640625
4
def powerSets(s): res = [[]] nums = sorted(nums) for num in nums: for j in range(len(res)): if [num] + res[j] not in res: res.append([num] + res[j]) return res
43efd03682fe03f8f88f666fba52b78c84ec0b66
AlanFermat/leetcode
/dfs + tree/Stack.py
536
3.828125
4
class Stack: """docstring for Stack Last in First Out """ def __init__(self): self.items = [] def __len__(self): return len(self.items) def __str__(self): s = '' for i in self.items: s += str(i) return s def push(self,item): return self.items.append(item) def pop(self): return self.items.pop...
c2e7e1c216a500cae60ea10801caa46d1a5fd76e
AlanFermat/leetcode
/contest/93/binary.py
666
3.734375
4
def binaryGap(N): """ :type N: int :rtype: int """ binary = bin(N) longest, temp = 0, 0 stack = [] idx = 0 n = len(binary) print (binary) while idx < n: if binary[idx] == '1': while stack: if stack[-1] != '1': stack.pop(...
dcde21722a7a1ffac43bede4f9ebefefeca4a668
AlanFermat/leetcode
/PYTHONNOTE/arg.py
632
4.28125
4
# *args is used to send a non-keyworded variable length argument list to the function def test_var_args(f_arg, *argv): print("first normal arg:", f_arg) for arg in argv: print("another arg through *argv:", arg) test_var_args('yasoob', 'python', 'eggs', 'test') def greet_me(**kwargs): for key, value in kwargs.it...
bc9905bd86583d7a6a5d0c3c4d0c2e18ab2c98e2
eirikwha/camserver
/tpk4128/camera_opencv.py
895
3.515625
4
import numpy as np import cv2 as cv class Camera(object): def __init__(self): # Implement this constructor that opens a webcam and stores it in self._camera self._camera = cv.VideoCapture(0) # Prepare the camera... print("Camera warming up ...") def capture(self): # Im...
93c0068df17e1e1babb2e1179fcc51baba5f1ae2
posttraumaticjess/formal-dinner-seating
/formal dinner seating stage 2.py
5,068
4.09375
4
#formal dinner stage 2.py #1/4/20 #Jess Yang CompSci #done with kenzie and kenzie's mom #must "import random" to be able to use random.sample to assign random values for seating assignments import random #declare list vars #add new lists kitchen = [] waiter = [] waiter_option = [] to_be_seated_option = [] kitchen_op...
a36f77b02a29ff1db4776656f4f02ecf91e8bd34
tysiote/spacedefinition
/src/graphics.py
497
3.609375
4
from tkinter import Tk, Canvas class GraphicController(object): root = None canvas = None app = None def __init__(self, app): self.app = app self.root = Tk() self.root.resizable(width=False, height=False) self.root.geometry('{}x{}'.format(720, 480)) self.root.t...
e5a8790e2ccf19449c19b95e46b2c63c6c5bece9
tskillian/Programming-Challenges
/wonky coins.py
686
3.921875
4
# Catsylvanian money is a strange thing: they have a coin for every # denomination (including zero!). A wonky change machine in # Catsylvania takes any coin of value N and returns 3 new coins, # valued at N/2, N/3 and N/4 (rounding down). # # Write a method `wonky_coins(n)` that returns the number of coins you # are le...
8f967f1220a5b1dbf211c5360d99c479fb522383
tskillian/Programming-Challenges
/N-divisible digits.py
939
4.21875
4
#Write a program that takes two integers, N and M, #and find the largest integer composed of N-digits #that is evenly divisible by M. N will always be 1 #or greater, with M being 2 or greater. Note that #some combinations of N and M will not have a solution. #Example: if you are given an N of 3 and M of 2, t...
56696f55f098f7fa22c6d334d613387f605cae09
hditano/Calculator
/Registration/FileHelper.py
1,906
3.5625
4
from Registration import Information class Filehelper: def __init__(self, user, password): self._user = user self._password = password def totalRecords(self): count = 0 with open(self.path(self._user), 'r+') as file: totalRecords = file.readlines() for...
3ab39c0164d2f87d6e46b09d409fb88d8890b47b
hditano/Calculator
/Guess Number/Guess_Number.py
391
3.890625
4
import random init = 0 result = 0 while init != 3: init = init + 1 print(f"init es {init}") value = int(input("Eliga un numero que quiera: ")) result = random.randint(1, 100) if result == value: print(f"Gano, el numero era {result}: ") break else: value = int(input("Elig...
e11663be8d0f2642325dc04a663ca2b87a5997a4
amaravindmenon/recipe
/recipe.py
2,029
4.03125
4
def get_recipe(a): if (a == 1): print("Tea") print("Coffee") print("Sweet Lemon") elif (a == 2): print("Salty Lemon") elif (a == 3): print("Milk Shake") print("Tea") print("coffee") elif (a == 4): print("Michelade") print("Bloddy Ma...
1d2f9cb894bf72d921debb9e4849036ff6348e5b
alfonsochie/week-6
/nmber 3.py
114
3.8125
4
dictionary = {'boston':1,'new york':2,'new orleans':3} for my_dict,val in dictionary.items(): print(my_dict)
81829252b33bc343b90a7ceb9ea248e9ea49ecc6
Loafly/hanghae99-algorithm
/BaekJoon/2021-03-17/2920.py
326
3.546875
4
import sys scales = list(map(int, sys.stdin.readline().split())) asc = True desc = True for i in range(len(scales)): if scales[i] != i + 1: asc = False if scales[len(scales) - i - 1] != i + 1: desc = False if asc: print('ascending') elif desc: print('descending') else: print('mix...
71c37f6a4f64aafe88250dfde0ed890b598a5cb5
Loafly/hanghae99-algorithm
/BaekJoon/2021-03-16/9663.py
728
3.5
4
import sys N = int(sys.stdin.readline()) def is_available(candidate, current_col): current_row = len(candidate) for queen_row in range(current_row): if candidate[queen_row] == current_col or abs(candidate[queen_row] - current_col) == current_row - queen_row: return False return Tru...
0169cba9cbea815474ef416d2b51cff7ac6d435a
Loafly/hanghae99-algorithm
/BaekJoon/2021-03-06/1157.py
1,024
3.53125
4
#변수를 입력받는 방법 text = input() alphabat_count = [] overlap_check = False overlap_count_check = 0 for i in range(0, 26): alphabat_count.append(0) for i in range(0, len(text)): # text_ascii = ord(text[i]) # index = 0 # #대문자 # if text_ascii >= 65 and text_ascii <= 90: # index = text_ascii - 65 ...
aacc473fa8d000d1f6d0bb451936b1ea3a665fde
Loafly/hanghae99-algorithm
/BaekJoon/2021-03-13/1010.py
318
3.625
4
import sys import math length = int(sys.stdin.readline()) def factorial(num): result = 1 for i in range(1,num + 1): result *= i return result for i in range(length): left,right = map(int, sys.stdin.readline().split()) print(factorial(right) // factorial(left) // factorial(right - left))
31ea83e4382f736cecefe8e4441f51e1e05cb925
Loafly/hanghae99-algorithm
/BaekJoon/2021-03-06/2941.py
211
3.53125
4
#변수를 입력받는 방법 text = input() exception_text = ['c=','c-','dz=','d-','lj','nj','s=','z='] for i in range(0, len(exception_text)): text = text.replace(exception_text[i],"0") print(len(text))
123e8bb58660e3df891d51ffc19c0d8826418aa7
Vaishnavi7279/HackerRank-Solutions
/Python/findthepercentage.py
238
3.796875
4
#HackerRank Problem #Finding the percentage num=int(input()) diction={} for i in range(0,num): marks=[] key=input() #for j in range(0,3): marks=list(input()) value=marks diction.update({key: value}) print(diction)
8ecfe55d0b16605b0f8fae9a85c35fa7f1391d66
gavin-manji/voiceChanger
/voiceChanger.py
2,214
3.625
4
# importing the SpeechRecognition library in python import speech_recognition as sr # importing gTTS to use the google text to speech service from gtts import gTTS # importing OS to run smoothly import os # To easily play audio and record audio, through python import pyaudio """ Briefing: This is a voice ch...
f7cb566fdfed2bf03597dacc5d40e60f7e73233f
Park-Kwanwoo/Python
/Python01/com.test03/rand02.py
213
3.671875
4
import random as r # 1 ~ 45, 중복되지 않는 7개 숫자 def lotto(): res = set() for i in range(0, 7): res.add(r.randint(1, 45)) print(res, end=' ') if __name__=='__main__': lotto()
16460488d668398e2761ec1dffe67d13211ff019
Park-Kwanwoo/Python
/Python01/com.test01/fibo01.py
173
3.859375
4
n = input('input n : ') # fibonaci 수열 : 앞 두개 더해서 다음 숫자 i = 1 a, b = 0, 1 while i <= int(n): print(a, end=' ') a, b = b, a + b i = i + 1
f6e9d273f22cfdca1501d52fe12ff09e6cc15182
Jenghongkong/Flipping-coin-2.py
/flipping coins 2.py
338
3.875
4
import random x = 1 while x > 0: b = float(input("What kind of bias do your coins have?: ")) for number in str(x): if random.random()*1 >b: print("coins flip %s has a value of head: True"%number) else: print("coins flip %s has a value of head: False"%number)...
d02456321853b7ea2b7a0bd80678647c6c0d8c21
karakazeviewview/PythonTraining
/20210201/listlesson.py
453
4.125
4
list1=[] #からのリスト list2=list() #からのリスト list1.append(3) print(list1) list1.append(5) print(list1[0]) list2.append(10) list2.append(20) print(list2) list3=list1+list2 print(list3) list4=list3*3 print(list4) print(len(list4)) #12 print(sum(list4)) #合計114 del list4[0] print(list4) list4.remove(5) #見つけた最初の要素 print(lis...
5554fd458fa3e279d784c97a019dc6f7d1047e61
karakazeviewview/PythonTraining
/20210201/day0202/Ex4_4.py
87
3.625
4
for i in range(1,10): for j in range( 1,10): if i*j%2==0: continue print(i*j)
dbba0f0634fe1cb7040e5d936d0076caf6afa28d
karakazeviewview/PythonTraining
/day0129/code1_22.py
215
3.765625
4
name='松田公太' age=23 height=175.6 #print('私の名前は{}で、年齢は{}で、身長は{}です'.format(name,age,height)) print(f'私の名前は{name}で、年齢は{age}で、信長は{height}cmです')
861d964bba63fe1f2e5b8a313b4d7218ace9cb48
karakazeviewview/PythonTraining
/20210201/Code4_4.py
202
3.703125
4
is_awake=True count=0 while is_awake==True: count+=1 print('羊が{}匹'.format(count)) key=input('もう眠りそうですか?(y/n)>>') if key=='y': is_awake=False print('おやすみなさい')
a8007e2877526049a4d65a69c43bbbf7c46e5f97
karakazeviewview/PythonTraining
/20210201/isLeapyear.py
292
3.984375
4
def is_leapyear(year): if year%400==0: return True if year%4==0 and year%100!=0: return True return False year=int(input('西暦>>')) if is_leapyear(year): print('西暦{}年は、閏年です'.format(year)) else: print('西暦{}年は、閏年ではありません'.format(year))
36afc6b3e8e23d7c5f19bc28c1e025531449368a
karakazeviewview/PythonTraining
/day0204/bingo.py
292
3.765625
4
import random table=[[random.randint(0,9) for j in range(3)] for i in range(3)] for row in table: print(row) vertical=[[table[j][i] for j in range(3)] for i in range(3)] for row in vertical: print(row) cross=[[table[j][j] if i==0 else table[j][2-j] for j in range(3)] for i in range(2)]
4dc952580ff282acc9bf6637b7ca66d043cf77ec
karakazeviewview/PythonTraining
/day0210/mult.py
252
3.625
4
def sum_of4(n):#再帰処理、コールスタック if n<=1: return n else: return n*sum_of4(n-1) num = input("正の整数を入力してください。") ans=sum_of4(int(num)) print('1から',num,"までの積は", ans, "です。".strip())
f7aa36e48c29b8ee8753e7148e72190a1143e7d2
coderlzy/python-
/第三章 控制结构与异常处理/判断素数.py
577
3.734375
4
#对输入的每一个数,判断是否为素数 n=int(input("请输入一个大于0的自然数:")) m=0 #计数 while(n>0): for i in range(2,n): ##这里我之前写的 range(2,n-1) 错了,n-1 只能取到n-2 if(n%i==0): print(n,"不是素数") break else: m+=1 if(m==(n-2)): #全都无法被整除 print(n,"是素数") break else: ...
2fae9b4da5d5c8cae7958a7b528e425eb23a3e6e
coderlzy/python-
/海伦公式求面积加强版.py
957
3.6875
4
from math import * isTriangle = False while not isTriangle: print("请按提示输入三角形三边长") a = float(input("第一个边长:")) b = float(input("第二个边长:")) c = float(input("第三个边长:")) if a == max(a, b, c): if a < b + c: isTriangle = True else: isTriangle = False print...
12a07d0144c004969ae430fcbeeeddf229732945
coderlzy/python-
/比赛训练7天/day1字符串/回文字符串.py
176
3.734375
4
#给出一个长度不超过1000的字符串,判断它是不是回文 str1=input("请输入一个字符串:") if str1[::-1]==str1: print("Yes!") else: print("No!")
ea96f8e8e0c7a7e1bde8a01c47098036d10799f2
usmanmalik6364/PythonTextAnalysisFundamentals
/ReadWriteTextFiles.py
1,111
4.5
4
# python has a built in function called open which can be used to open files. myfile = open('test.txt') content = myfile.read() # this function will read the file. # resets the cursor back to beginning of text file so we can read it again. myfile.seek(0) print(content) content = myfile.readlines() myfile.seek(0) fo...
385ddd7d50fcb78e79d99dfa234194f240c603a1
usmanmalik6364/PythonTextAnalysisFundamentals
/PythonTextBasics.py
454
3.5625
4
# Text Formatting basics using f string literal. from datetime import datetime library = [('Author', 'Topic', 'Pages'), ('Twain', 'Rafting', 601), ('Feynman', 'Physics', 95), ('Hamilton', 'Mythology', 144)] for author, topic, pages in library: # tuple unpacking # text formatting for output; output padd...
2aba30e5cf5d36f2b178000d4f2a2a50ea68be2b
jan920/Hive
/board/player.py
1,329
3.65625
4
from board.globals import QUEEN, SPIDER, GRASSHOPPER, BEETLE, ANT from board.stones import Spider, Beetle, Grasshopper, Ant, Queen class Player: """Class representing player in game Hive""" def __init__(self, colour, choice_of_stones=(QUEEN, SPIDER, GRASSHOPPER, BEETLE, ANT)): self.colour = colour ...
4292e0b85295dba0bd7a242a64ada271e5ee3136
patbman/Password-Generator
/password generator.py
847
3.59375
4
import random import string from random import randint import pickle import uuid a = eval(input("how long do you want the password to be: ")) filename="" r = input("would you like to name the file or just generate a random name?(use either name or generate to answer): ") if r == "name": filename=input("what would...
986860756c2839412c20de0ae0f302a6c8f261a9
vipulsnp/Computer-Society
/Basic/Calculate Factorial of A Number/SolutionByManas.py
194
4.1875
4
#Solution by Manas def fact(n): if n == 1: return 1 else: return n*fact(n-1) n = int(input("Input a number whose factorial is to be calculated:")) x = fact(n) print(x)
7eb28860de09cca32e55a66d2266675e8ec75fc7
viniciusvilarads/codigos-p1
/Lista 1 - FIP/Ex002.py
413
3.75
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 1 Patos - PB | 2020 2 - Sabendo que a cotação atual do dólar americano é R$ 4,47, receba um valor em reais do usuário e converta para dólares. Exemplo de saída: $ 1.00 """ real = float(input("Informe o valor em reais R$")) realDolar = real / 4.47 print("Cotaç...
e71897d5fc81f0635871a81173e186ae09d1c18f
viniciusvilarads/codigos-p1
/Lista 4 - FIP/Lista 4 - Ex008.py
877
4.09375
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 4 Estrutura de Decisão Patos - PB | 2020 8 - Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida. """ dia = int(input("Informe o dia: (DD) ")) mes = int(input("Informe o mês: (MM) ")) ano = int(input("Informe o ano: ...
26d1023d423f31e9ddaccfcedaae9c82896dbe89
viniciusvilarads/codigos-p1
/Lista 3 - FIP/Lista 3 - Ex008.py
816
4.3125
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 3 Estrutura de Decisão Patos - PB | 2020 8 - Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato. """ prod1 = float(input("Informe o preço do produto 1: ")) prod2 = flo...
7f2ab64632cbed0280942876ddbee9e92827375b
viniciusvilarads/codigos-p1
/Lista 4 - FIP/Lista 4 - Ex003.py
649
4.1875
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 4 Estrutura de Decisão Patos - PB | 2020 3 - Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido. """ numero = int(input("Informe um número inteiro: ")) i...
edf634bd1b571c4de8f527e14d3fef587604ecca
viniciusvilarads/codigos-p1
/URI Lista 2 - FIP/1046 - Tempo de Jogo.py
549
3.71875
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 2 URI Patos - PB | 2020 Leia a hora inicial e a hora final de um jogo. A seguir calcule a duração do jogo, sabendo que o mesmo pode começar em um dia e terminar em outro, tendo uma duração mínima de 1 hora e máxima de 24 horas. Link: https://www.urionlinejudg...
88c326721fa9168e13369628d163a165147d8ba3
viniciusvilarads/codigos-p1
/URI Lista 1 - FIP/Ex005 - Média 1.py
570
3.53125
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 1 URI Patos - PB | 2020 Leia 2 valores de ponto flutuante de dupla precisão A e B, que correspondem a 2 notas de um aluno. A seguir, calcule a média do aluno, sabendo que a nota A tem peso 3.5 e a nota B tem peso 7.5 (A soma dos pesos portanto é 11). Assuma q...
a6f2285e1c256b1e0c64597cc9a950f391e2576e
viniciusvilarads/codigos-p1
/Lista 1 - FIP/Ex010.py
291
4.0625
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 1 Patos - PB | 2020 10 - Escreva um programa que converta valores de centímetros em polegadas. """ centi = float(input("Informe o valor em centímetros: ")) pol = centi / 2.54 print("{}cm em polegadas é {:.1f}pol".format(centi, pol))
46c5367bc68272d3ad3933a166ba6743443ee730
viniciusvilarads/codigos-p1
/URI Lista 1 - FIP/Ex016 - Distância.py
634
3.765625
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 1 URI Patos - PB | 2020 Dois carros (X e Y) partem em uma mesma direção. O carro X sai com velocidade constante de 60 Km/h e o carro Y sai com velocidade constante de 90 Km/h. Em uma hora (60 minutos) o carro Y consegue se distanciar 30 quilômetros do carro X...
7aee8c54e1197604d582d1aa67cf0838f4fa8273
viniciusvilarads/codigos-p1
/URI Lista 1 - FIP/Ex011 - Esfera.py
636
3.609375
4
""" Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 1 URI Patos - PB | 2020 Faça um programa que calcule e mostre o volume de uma esfera sendo fornecido o valor de seu raio (R). A fórmula para calcular o volume é: (4/3) * pi * R3. Considere (atribua) para pi o valor 3.14159. Dica: Ao utilizar a fórmula, procur...
c3b0d4ec5fbe5c582b6e5aabb747f1b1354fe58a
kensworth/adv-py
/optimal_alignment.py
639
3.703125
4
string = 'I am a big fan of rats' min_cost = float('inf') def align_text(L, string, cost_so_far): global min_cost string = string.strip() if L >= len(string): cost_so_far += (L - len(string)) ** 3 if cost_so_far < min_cost: min_cost = cost_so_far return word_ends = [...
bc08a6e529936e5a5d58782626376aba3615f560
kensworth/adv-py
/num_islands.py
1,047
3.6875
4
def num_islands(map): visited = set() count = 0 for i in xrange(len(map)): for j in xrange(len(map[0])): if map[i][j] and (i, j) not in visited: explore_island(map, (i, j), visited) count += 1 return count def explore_island(map, start_node, visited):...
6c5a1f96b381b9366f6a4cdc8fb33836145208f1
marcinlaskowski/szkolenieZDDATA
/Zadania3/funkcja_lambda_zad1.py
241
4.03125
4
""" Napisz funkcję lambda, która sprawdzi czy liczba jest parzysta czy nie """ def is_even(number): return number % 2 == 0 print(is_even(10)) print(is_even(3)) is_even2 = lambda x: x % 2 == 0 print(is_even2(10)) print(is_even2(3))
9db3f54a8b24211e05e7062e2479fc4ff37a6f3c
marcinlaskowski/szkolenieZDDATA
/Notatki/petla_while.py
328
3.71875
4
if __name__ == "__main__": # while <warunek>: # blok instrukcji pętli i = 0 while i <= 3: # 3<=3 True 4<=3 False print(i) i = i + 1 # i += 1 print("Hello") i = 10 while i > 0: print(i) i = i - 1 # while i: # print(i) # i ...
e9b22c9d86e48ec24249c6de6012155014a7a6c6
marcinlaskowski/szkolenieZDDATA
/Notatki2/funkcje.py
1,112
3.96875
4
""" ARGS """ # def my_sum(param1, param2, *args): # param1 =1, param2=2, args = (3,4) # print(args) # # for arg in args: # print(arg) # # print(sum(args)) # # my_sum(1,2) # # def my_sum(*args): # print(args) # # for arg in args: # print(arg) # # print(sum(args)) # # my_sum() "...
9d2b79e92b1441856c645e3a34eb9a062dd6a5cd
marcinlaskowski/szkolenieZDDATA
/Zadania2/obiektowo_zad4.py
2,153
4.40625
4
""" Stwórz klasę Pojazd z atrybutami: kolor, cena. Klasę Samochód i Rower, obie dziedziczące po klasie Pojazd. Stwórz kilka obiektów klasy Samochód i Rower. Stwórz listę pojazdy, w której znajdą się stworzone obiekty. Wśród wszystkich pojazdów znajdź najdroższy pojazd, wypisz średnią cenę samochodu. """ class Vehic...
97a63701ff08071fea3e96d3ebd5e6bf64f91c76
marcinlaskowski/szkolenieZDDATA
/Zadania/zad9.py
326
3.8125
4
""" 9. Pętle.Wygeneruj ciąg liczb od 0 do 10 pętlą while, następnie próbuj wygenerować od 10 do 0 również pętlą while. """ if __name__ == "__main__": number = 0 while number <= 10: print(number) number += 1 number = 10 while number >= 0: print(number) number -= 1
45445fc27b2a6015a09b00687adfc14d2555d0c4
marcinlaskowski/szkolenieZDDATA
/Zadania/zad8_2.py
354
4.03125
4
""" 8. Pętle. Napisz program, który dla 10 kolejnych liczb naturalnych wyświetli ich ich wartość do sześcianu. Spróbuj zrobić to pętla for, następnie pętla while. """ if __name__ == "__main__": for number in range(1, 11): print(number ** 3) number = 1 while number <= 10: print(number ** ...
8065455fd0ec08853685831d31a7ab657a5c1ac8
lushep/azg-ds-python
/1_Python_Essentials/answers/ex-fizzbuzz.py
156
3.859375
4
if n % 2 == 0 and n % 5 == 0: print('FizzBuzz') elif n % 2 == 0: print('Fizz') elif n % 5 == 0: print('Buzz') else: print('No Fizz or Buzz')
e5a771e56213f2c03d89fd381fbaaa52e1d2e8d1
HectorMedina124/EjemplosAG
/Ejemplo 4.py
669
3.640625
4
import numpy as np import matplotlib.pyplot as plt def f1(x): return x*x*x*x def f1_dev1(x): return 4*x*x*x def f1_dev2(x): return 12*x*x def f1_dev2_0(x): return 0; x= np.linspace(-4,4,11) i=0 #para moverme entre las posiciones desc=0; asc=0; for x_ in x: if(f1_dev1(x_)<0 and asc==0): ...
3ca890436a27d029d167ee1a74cdf18a3bfd4253
lvraikkonen/GoodCode
/leetcode/168_excel_sheet_column_title.py
253
3.65625
4
class Solution: # @return a string def convertToTitle(self, num): title = '' while num > 0: num -= 1 mod = num % 26 num /= 26 title += chr(ord('A') + mod) return title[::-1]
745672e96a8d12e6f20f7d696c675c90f06761eb
lvraikkonen/GoodCode
/leetcode/232_implement_queue_using_stacks.py
1,989
4.40625
4
# Stack implementation by list class MyStack: """ 栈的说明 栈是一个线性的数据结构 栈遵循LIFO的原则,Last In First Out , 即后进先出 栈顶为top,栈底为base """ def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) ...
40473836505e92c684bbcdf0b9e80749c86e6d65
lvraikkonen/GoodCode
/leetcode/53_maximum_subarray.py
418
3.78125
4
def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ if nums == None or len(nums) == 0: return 0 maximum, sum = nums[0], 0 for i in range(len(nums)): if sum < 0: sum = 0 sum += nums[i] maximum = max(maximum, sum) return ma...
4debaa35db87471485806279bd2b0371ba6b03cb
lvraikkonen/GoodCode
/leetcode/101_symmetric_tree.py
2,435
3.90625
4
# 递归解法 """ 左右两个节点的大小是否相同. 左节点的左孩子是否和右节点的右孩子相同. 左节点的右孩子是否和右节点的左孩子相同. """ # 非递归解法 """ 层级遍历 """ from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isS...
70387825f1b1998cf882aa234f2d5388f7e88fc3
lvraikkonen/GoodCode
/leetcode/581_shortest_unsorted_continuous_subarray.py
1,532
3.5625
4
from __future__ import print_function class Solution(object): def findUnsortedSubarray_sortedMethod(self, nums): """ :type nums: List[int] :rtype: int """ # O(nlogn) nums_sorted = sorted(nums) s = e = -1 for i in range(len(nums)): # find m...
d7fbe209a0c6768588da12aa3e54e90d7ccc79fe
lvraikkonen/GoodCode
/leetcode/147_insertion_sort_list.py
786
3.90625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if not head: return head fh = ListNode(0) fh.ne...
9cfe9572f4087944c86d8945f01ccfe5e69db154
lvraikkonen/GoodCode
/leetcode/20_valid_parentheses.py
451
3.875
4
def isValid(s): push_set = ['(','{','['] pop_set = [')','}',']'] pair = dict(zip(push_set,pop_set)) stack = [] for element in s: if element in push_set: stack.append(pair[element]) elif element in pop_set: if not stack or element != stack.pop(): ...
b80d46b0861850f5db06298453f74089f336f580
lvraikkonen/GoodCode
/leetcode/104_maximum_depth_of_binary_tree.py
1,242
4
4
from __future__ import print_function from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepth_recursive(self, root): """ :type ...
b229337436c8677128f2b4ceea92dc0b5e5516d3
lvraikkonen/GoodCode
/leetcode/654_maximum_binary_tree.py
780
3.890625
4
from __future__ import print_function # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] ...
b7de63953717dccc7b3018ebd0fb544aaa8ed666
lvraikkonen/GoodCode
/leetcode/414_third_maximum_number.py
458
4.03125
4
def thirdMax(nums): """ :type nums: List[int] :rtype: int """ first = second = third = None for n in nums: if n > first: first, second, third = n, first, second elif first > n > second: second, third = n, second elif second > n > third: ...
809217b8a7c69d925265cfd53fb7434ac63dd17c
lvraikkonen/GoodCode
/leetcode/125_valid_palindrome.py
398
3.765625
4
# two pointer solution def isPalindrome(self, s): i, j = 0, len(s) - 1 while i < j: # only char and digit left while i < j and not (s[i].isdigit() or s[i].isalpha()): i += 1 while i < j and not (s[j].isdigit() or s[j].isalpha()): j -= 1 if s[i].lower() != ...
ee6331abd1efa2bc890c757698f56e62863fa1a3
lvraikkonen/GoodCode
/leetcode/26_remove_duplicates_from_sorted_array.py
324
3.765625
4
# @param a list of integers # @return an integer def removeDuplicates(A): if len(A)==0: return 0 i, j=0, 1 for j in range(i, len(A)): if A[i] != A[j]: i += 1 A[i]=A[j] return i + 1 if __name__ == "__main__": result = removeDuplicates([1,1,2,3,3]) print re...
17605ffb06b4163a1673bf96fa165cc41ec8f337
nikhilpanchal/courseracharts
/basiccharts/basics.py
2,830
3.796875
4
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pands as pd from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure def draw_axes(): """ Draws a graph with a pair of axes and a single point :return: """ fig = Figure() ...
e434c6ddc84cfab9e842ed6841393ff8ac27b1f8
Priya-dharshini-r/LeetCode
/matrix_diagona_sum.py
625
3.546875
4
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: n = len(mat) primary_diagonal = [] secondary_diagonal = [] for i in range(n): primary_diagonal.append(mat[i][i]) for i in range(n): secondary_diagonal.append(mat[i][n-i-1]) fin...