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
d6f13bb8f1d2ac82e169ebe22b81a26acf40edb2
digitallyayush/Collection
/CalculatorTkinter/calculator.py
2,909
3.9375
4
from tkinter import * from tkinter import ttk # function which executes on clicking Add Button def get_sum(*args): try: num_1_val = float(num_1.get()) num_2_val = float(num_2.get()) solution.set(num_1_val + num_2_val) except ValueError: pass # function which executes on clic...
16722d2b09a41fe2cc0d93c352f70b978fd15de9
Vlop01/Exercicios-Python-2
/Desafio_38.py
532
3.90625
4
#Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: #-O primeiro valor é maior #-O segundo valor é maior #-Não existe valor maior, os dois são iguais num1 = int(input('Informe o primeiro número: ')) num2 = int(input('Informe o segundo número: ')) if num1 > num2: ...
18047a5fdf5c188444fd83f21946098c2a79945c
Vlop01/Exercicios-Python-2
/Desafio_51.py
319
3.890625
4
#Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos #dessa progressão first = int(input('Informe o primeiro termo da PA: ')) rate = int(input('Informe a razão da PA: ')) print(first) for i in range(0, 9): first = first + rate print(first)
29e0c4f9290740a84e9f4125d8afec22aab9b3fa
Vlop01/Exercicios-Python-2
/Desafio_65.py
981
4.25
4
#Crie um programa que leia vários números inteiros pelo teclado. No final de cada execução, mostre a média entre #todos os valores e qual foi o maior e menor valor lido. O programa deve perguntar ao usuário se ele quer ou não #continuar a digitar valores continuar = 'sim' count = 0 sum = 0 while continuar == ...
96d99c285a6d8abc264d80d8f76a3e2d3b7c1ab2
Vlop01/Exercicios-Python-2
/Desafio_44.py
720
3.859375
4
#Elabore um programa que calculeo valor a ser pago por um produto considerando seu preço normal e condição de pagamento #À vista dinheiro/cheque: 10% de desconto #À vista no cartão: 5% de desconto #Em até 2X no cartão: proço normal #3X ou mais no cartão: 20% de juros price = float(input('Informe o preço do produ...
51f1482babb00e1a73d7c277affddda562707bab
vaishakik/College
/Python_Assignments/P4-Bisection_method.py
2,579
4.0625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 10:45:03 2019 @author: vaishak """ #Bisection method to find the roots of the quadratic equation of the form ax^2+bx+c=0. #Here x is the value of the variable x in the equation ax^2+bx+c=0. #function(x,a,b,c) returns the value of the function at the value x...
ea1c1e8634b6054ac04e714d831ce9af4cc32791
vaishakik/College
/Python_Assignments/P2c-Addition_of_matrices.py
1,148
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 20 13:02:27 2019 @author: vaishak """ #Addition of matrices import numpy as np print('Enter the sizes of the matrices: ') print('Enter the size of the first matrix: ') m1=int(input('Enter the number of rows of the first matrix: ')) n1=int(input('Enter the...
d045089f2b27d5e9f10c4b0d3f9440f8cb612b0a
AkThao/battleship
/battleship_text.py
13,165
4.28125
4
#!/usr/bin/env python3 import time from random import randint, choice class Ship(): """Ship properties: Size ID Starting position List of positions it occupies Ship methods: pick_random_point – give the ship starting coordinates that are not already occupied place_on_board – give the...
b414af7e9b56c5a64659054f70ad982db68a01f8
c0ns0le/Pythonista
/sort/sort/MergeSort.py
1,370
3.828125
4
''' Created on May 25, 2013 @author: Giacomo ''' def mergeSort(L): recursiveMergeSort(L, 0, len(L) - 1) def recursiveMergeSort(L, left, right): if left >= right: return mid = int((left + right) / 2) recursiveMergeSort(L, left, mid) recursiveMergeSort(L, mid + 1, right) ...
008f41a9d1c389c586481a4497d76a3f16eb832e
c0ns0le/Pythonista
/keychain/keychainsetup.py
1,183
3.828125
4
# coding: utf-8 # https://gist.github.com/mlgill/8310754 import keychain def set_get_user_pass(service): # store username and password in keychain if not found if not service in [x[0] for x in keychain.get_services()]: print 'Keychain does not contain %s username and password.' % service username = raw_input...
b671176f30d60b159c8e2a7d37c7916a95344392
c0ns0le/Pythonista
/games/flashcard-master/Flashcard_UI.py
13,341
3.546875
4
# coding: utf-8 """ Flashcard Program written by Steven K. Pollack July 18, 2014 modified August 15, 2014 This script is designed to display a set of image and/or their descriptions from files organized in a set of folders (chapters) The program will display a set of selectors for the chapter...
88b8ff45446bfee318b181f3ac574141b86ebdfe
c0ns0le/Pythonista
/omz/Examples/Convert Markdown/Convert Markdown.py
914
3.859375
4
'''This script demonstrates how you can convert Markdown documents to HTML and view the results in the built-in browser.''' import os, tempfile, codecs import urllib, urlparse import console, clipboard, webbrowser from markdown2 import markdown def main(): choice = console.alert('Markdown Conversion', 'What would yo...
c5dc0a81dd091aa975a59f416be1a354484df906
c0ns0le/Pythonista
/VisualExamples/mandelbrot.py
988
3.828125
4
from __future__ import division from visual.graph import * # Bruce Sherwood, Jan. 1, 2008 # Use points object to make a pixel-like plot of a fractal XMIN = -2 XMAX = 0.5 YMIN = -1 YMAX = 1 g = gdisplay(width=750, height=600, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX) pixels = gdots(shape='square', size=2) # Scale fa...
1ab9f6d87b6d0460bd823d40b9791b1cf12e4627
c0ns0le/Pythonista
/parse/CopyWebpageTitle.py
400
3.5
4
# @viticci # Copy a URL's page title and return title + link format. Example: Tweetbot for Mac Review http://www.macstories.net/news/tweetbot-for-mac-review/ import urllib import clipboard import bs4 import webbrowser import console link = clipboard.get() soup = bs4.BeautifulSoup(urllib.urlopen(link)) clipboard.set(...
2329edbd95987612173698c865b2d212281e7c38
c0ns0le/Pythonista
/games/maze-cv-master/App/SolutionView.py
1,908
3.640625
4
'''This view will compute the shortest path and then display it in a pretty format''' import ui import photos import sys; sys.path.append('..') from pathfinding import imageInput, dijkstra class SolutionView(ui.View): def __init__(self, image, start, goal): self.image = image.convert('RGB') self.load = self.ima...
ccd1387c6ce1c7db690a6ebb5efa308472231a01
tschoi6712/crawlingScraping_ML_DL
/ch5/5-13.Pandas_test.py
1,357
3.609375
4
# 5-13.Pandas_test import pandas as pd # 데이터프레임(2차원 리스트) df = pd.DataFrame([ [10,20,30], [40,50,60], [70,80,90] ]) print(df) print(type(a)) # 시리즈(1차원 리스트) s = pd.Series([1.0, 3.0, 5.0, 7.0, 9.0]) print(s) print(type(s)) ## 키, 몸무게, 성별 데이터프레임 생성하기 df1 = pd.DataFrame({ "weight": [ 80.0, 70.4, 65.5, 4...
7313bba9eb53d6d5c63890757f81899839a4c006
pumbaacave/atcoder
/Leetcode/414.third-maximum-number.py
1,045
3.53125
4
# # @lc app=leetcode id=414 lang=python3 # # [414] Third Maximum Number # # @lc code=start class Solution: def thirdMax(self, nums: List[int]) -> int: # sortedset? # many great edge cases :) if len(nums) < 3: return max(nums) m1, m2, m3 = list(reversed(sorted(nums[:3])...
1df6fc45e8f9b8a79895ef21fd9c4cf5eeabb0a9
pumbaacave/atcoder
/interviewBit/RearrangeArray.py
754
3.875
4
""" Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space. Solution want to put info (ori_data, target_data) in one cell set INFO = ori_data * N + target_data can retrieve info using oridata, target_data = divmod(INFO, N) if val > N that is an INFO edge case: ori_data = 0 so INFO = INOF' + N ...
62c147c1b626a6e39f10cf3f1b16788c837b30f8
pumbaacave/atcoder
/adventOfCode/day9.py
1,393
3.703125
4
from loguru import logger """ return: the highest score of elves """ def cal_highest(num_player, last_marble_mark): scores = [0 for i in range(num_player)] marbles = [0, 1] L = 2 # length of marbles list, updated dynamically current = 1 # current operation index for i in range(2, last_marble_mark+1...
6b3c77a64efae2b7765f37c1b39f540257258230
pumbaacave/atcoder
/Algo/BST.py
1,826
3.640625
4
from collections import deque import random import pdb class Node(): def __init__(self, val): self.val = val self.left = None self.right = None class BST(): def __init__(self, nums): self.create_bst(nums) def __contains__(self, val): pass def __getitem__(self...
97d27012c3abacd2e5dc6945dcf393ec2d4987f0
pumbaacave/atcoder
/interviewBit/GridUniquePath.py
859
3.59375
4
""" https://www.interviewbit.com/problems/grid-unique-paths/ dynamic programming """ class Solution: # @param A : integer # @param B : integer # @return an integer def init_dis(self, h, w): dis = [] for i in range(h): dis.append([]) for _ in range(w): ...
0caebb51533a758773bc47f4298dc4f8a8079f41
pumbaacave/atcoder
/ABC126/B.py
376
3.5625
4
import sys stdin = sys.stdin def ls(): return stdin.readline() S = ls() first, second = int(S[:2]), int(S[2:]) def is_my(f, s): return 0 < f < 13 def is_ym(f, s): return 0 < s < 13 ym, my = is_ym(first,second), is_my(first, second) if ym and my: print("AMBIGUOUS") elif ym and not my: print("YYMM") elif...
114efadd3171e28d5db9afff83197143ea779733
pumbaacave/atcoder
/Leetcode/PredictWinnder.py
2,002
3.515625
4
class Solution: def PredictTheWinner(self, nums: 'List[int]') -> 'bool': first_score = 0 second_score = 0 while nums: print(nums) maximum, nums = self.get_rival_min_gain(nums) first_score += maximum print(f'first choose {maximum}') ...
ed04a805e4164bfcca7eed6cdd319ec6886e1958
pumbaacave/atcoder
/Leetcode/MostCommonWord.py
1,149
3.65625
4
from collections import Counter from typing import * class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: p = paragraph.lower() cnt = Counter() l = 0 for r in range(len(p)): if not p[r].isalpha(): if not r: ...
29750d8b3b8395688bae3d96c94da14d03a8cdb3
pumbaacave/atcoder
/Leetcode/Medium/NestedIterator.py
3,148
4.15625
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rt...
ef25c5b5c3bf8cf4753f06f30f9e1734c2fb46b9
pumbaacave/atcoder
/Leetcode/NextGreaterElem.py
1,935
3.984375
4
from collections import deque, defaultdict from typing import * class Solution1: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: """ using a stack to build next_greater_num mapping the stack is used 1. to watermark the state, only find next greater num ...
4de6633af7d909263ba094e4c635ee7e073309f5
pumbaacave/atcoder
/Leetcode/538.convert-bst-to-greater-tree.py
1,028
3.703125
4
# # @lc app=leetcode id=538 lang=python3 # # [538] Convert BST to Greater Tree # # @lc code=start # 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 convertBST(...
c97de84513f8f46cf63006157aac29f2193a6f47
pumbaacave/atcoder
/Leetcode/isBipartie.py
984
3.609375
4
class Solution: def isBipartite(self, graph): """ :type graph: List[List[int]] :rtype: bool """ num_vec = len(graph) # init node i to group i parent = [i for i in range(num_vec)] self.parent = parent for i, v_list in enumerate(graph): ...
4f9bb8ff54cedfdaa9bbf7c1e4c7bdb3c2d544a3
pumbaacave/atcoder
/ABC118/C.py
619
3.515625
4
import sys stdin = sys.stdin def li(): return map(int, stdin.readline().split()) N = li() A = list(li()) def gcd(A, B): # normal gcd logic while B not in (1, 0): A, B = (A, B) if A > B else (B, A) _, mod = divmod(A, B) A, B = B, mod if B == 0: return A elif B == 1: ...
480ec3acb4986e4592e9450a5ead6ac1d2166a89
pumbaacave/atcoder
/Leetcode/438.find-all-anagrams-in-a-string.py
696
3.546875
4
# # @lc app=leetcode id=438 lang=python3 # # [438] Find All Anagrams in a String # # @lc code=start from collections import Counter class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: target = Counter(p) ret = [] len_p = len(p) if len(s) < len_p: retur...
a1b8878a4ed4a267f9604ce46dd1fa6039f79e6e
pumbaacave/atcoder
/Leetcode/235.lowest-common-ancestor-of-a-binary-search-tree.py
1,101
3.71875
4
# # @lc app=leetcode id=235 lang=python3 # # [235] Lowest Common Ancestor of a Binary Search Tree # # @lc code=start # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: de...
c1d8997d5fe31c5dda44c87cbbb1fd54512b74f0
alecmchiu/DailyProgrammer
/e3.py
820
4.125
4
#!/Users/Alec/anaconda/bin/python # Challenge E3 # https://www.reddit.com/r/dailyprogrammer/comments/pkw2m/2112012_challenge_3_easy/ def encrypt(text): characters = list(text) #new_chars = [chr(((ord(x)+824)%95)+32) for x in characters] new_chars = [] for each in characters: new = ord(each)+22 if (new < 127):...
73493eee59d22ed269c74688091c714fa669ba92
fogcitymarathoner/Tic-Tac-Toe
/player/models.py
3,860
3.5625
4
__author__ = 'marc' from config.settings import * class Player(object): """A tic tact toe player""" def __init__(self, board_value, *args, **kwargs): """ board_value should be a single character to display such as X or O. """ # the value which will represent the player behind...
1f4a718e65b8d593f81e31bc5647f62baadfc8fe
kzth4/mdvlboo-kzth4-PYTHON
/Python/Project/Input Data User/Input.py
656
3.609375
4
# data selalu str xumbra = input("input user = ") print("xumbra = ",xumbra, ",type = ", type(xumbra)) #casting int zumbra = int(input("scr number = ")) print("zumbra = ", zumbra, ",type = ", type(zumbra)) #casting float kumbra = float(input("scr number = ")) print("zumbra = ", kumbra, ",type = ", type(kum...
ceb203d2505872457606b09e85bcf93395d6dd39
krutarth-t18/Code-in-Plcae-2021
/Programming_with_Karel/Extension(optional)/Karel's_heart.py
5,605
4.0625
4
from karel.stanfordkarel import * """ File: ExtensionKarel.py ----------------------- This file is for optional extension programs. """ def main(): """ I have written a code, which shows the heart of karel in the Checkerboard world. Here first I used the code of previous problem(the Midpoint) ...
1b73506a202035de0e82b762fa1f8c343805b995
alonn24/learnings
/python/exercises/binary_search_tree/binary_tree_test.py
358
3.703125
4
from binary_tree import insert, height def test_height(): root = insert(None, 15) assert height(root) == 1 insert(root, 10) assert height(root) == 2 insert(root, 25) assert height(root) == 2 insert(root, 6) assert height(root) == 3 insert(root, 14) insert(root, 20) insert(r...
cf1117dd3776f07ef1e8ac772a8f315d7969a3f1
senghuot/Algorithms
/Python/spiralGrid.py
1,103
3.859375
4
''' Premise: given a two dimensional array, you need to print the array in a spiral format as follow. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 ''' def spiralGrid(grid): top_index = 0 bot_index = len(grid)-1 l...
11357e97c21e3e5b00d83a576959ca9fd32d9142
DtjiSoftwareDeveloper/Python-Recursion-Tutorial
/recursive_fibonacci.py
405
4.28125
4
""" This file contains implementation of recursively calculating the nth Fibonacci number. Author: DtjiSoftwareDeveloper """ def fibonacci(n: int) -> int: if n == 0 or n == 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(2)) # 1 print(fibonacci(3))...
d767eaf48d687d720d10450e2ea6580da7ad68ef
hendersj5018/distance-traveled
/m2hw1_DistanceTraveled_Henderson.py
333
4.09375
4
#CTI_110 #H2HW1 - Distance Traveled #Jasper Henderson #10Sep2017 # #Distance=speed*time speed=70 time=6 distance=speed*time print('the distance after 6hours is', distance) time=10 distance=speed*10 print('the distance after 10hours is', distance) time=15 print('the distance after 15hours is', distance) 'input( ...
ecb768b15755c92cbf1e14a2d7773d36ed60ff5c
kmerfeld/village_generator
/birther.py
3,717
3.609375
4
#!/usr/bin/env python3 import random from person import * from family import * #read in file def make_person(): g = random.randint(0,1) fname = "" mname = "" lname = "" if g == 1: gender = "male" lname = random.choice(l_names) mname = random.choice(male_m_names) ...
0ec2955d3d50aac5bd9c660169d5a55b7eef4d19
ajose-equinix/python-para-zumbis
/Lista.2/ex007.py
243
3.6875
4
metros = int(input('Tamanho da área a ser pintada(m²): ')) if metros % 54 == 0: latas = metros / 54 else: latas = int(metros / 54) + 1 valor = latas * 80 print(f""" Total de latas de tinta: {latas} Preço total: R${valor:.2f}""")
21b5ea6bf5dd53928be22f1949197248d66f52c5
USA-Citizen/Basic-Computer-of-Liberal-Art
/购票.py
1,321
3.8125
4
# Import from tkinter import * # Root root = Tk() root.title('Purchasing Tickets') root.geometry('560x560') # Func def wrt(): dic = {1: 150, 2: 49, 3: 78} price = dic.get(varrb.get()) if etr.get() != '': num = int(etr.get()) if num >= 50: result = 0.8*price*num ...
32a302cf2d82f921de081ed10fff19f058b7c32b
USA-Citizen/Basic-Computer-of-Liberal-Art
/解二元一次方程.py
446
3.53125
4
print('本程序计算ax^2+bx+c=0的实数根') a = float(input('a=')) b = float(input('b=')) c = float(input('c=')) print('方程%.2fx^2+%.2fx+%.2f=0'%(a,b,c),end='') delta = b**2-4*a*c if delta > 0: x1 = (-b-delta**0.5)/(2*a) x2 = (-b+delta**0.5)/(2*a) print('有两个实数根:\n','x1=%.2f x2=%.2f'%(x1,x2)) elif delta == 0: x = -b/(2*...
0a30498fc787ba7d6a166843c9e032e47d06e3a1
USA-Citizen/Basic-Computer-of-Liberal-Art
/三个数从小到大.py
202
3.828125
4
x = float(input('x=')) y = float(input('y=')) z = float(input('z=')) LIST = [] LIST.append(x) LIST.append(y) LIST.append(z) LIST.sort(reverse=False) print(LIST[0],'<',LIST[1],'<',LIST[2],sep='')
c763646a619a9dc26579538133accefcb0ee3977
USA-Citizen/Basic-Computer-of-Liberal-Art
/抓吧按顺序 copy.py
943
3.53125
4
import urllib.request import re def getHttp(url): h = urllib.request.urlopen(url) html = h.read() return html # url[5:-1]部分必须是一个可以打开的图片网址! def downloadImg(html): reg = r'src="https.*?\.jpg"' imgre = re.compile(reg) urls = imgre.findall(html) for url in urls: urllib.re...
47a49812c72efb2544c3592a53c48388c3f7e9b0
USA-Citizen/Basic-Computer-of-Liberal-Art
/判断完全、丰沛、不足数.py
404
3.75
4
while 1: integer = int(input('请输入一个整数:')) total=0 for i in range(2,integer): if integer % i == 0 : total += i if total == integer : print('{0}为完全数。'.format(integer)) elif total > integer : print('{0}为丰沛数。'.format(integer)) elif total < integer : ...
231d905f24fa551c060748793eee07c9ce563edd
deepaparangi80/Github_pycode
/sum_numb.py
254
4.21875
4
# program to print sum of 1 to n n = int(input('Enter n value')) print('entered value',n) sum = 0 for i in range(1,n+1): '''print(i)''' sum = sum + i print('total sum of 1 to {} is {}'.format(n,sum)) '''print (range(1,n))'''
029bea05d6179da3db8c9153c988a93055eda363
yy2lyx/Thread-Multiprocess
/Threading/threading_tutorial_1.py
869
3.78125
4
import threading import time def thread_job_1(): print("Thread_1 start\n") for i in range(10): time.sleep(0.1) print("Thread_1 end\n") def thread_job_2(): print("Thread_2 start\n") print("Thread_2 end\n") def main(): print(threading.enumerate()) print(threading.active_count()) ...
9d0b8e5abf4b41a62125e6dd7996a9f8de42a2d1
Scribble86/Drone-Landing
/precision_drone_landing/__main__.py
992
3.546875
4
"""The entry point of the program. This file contains the main loop.""" import asyncio from typing import Callable, Awaitable from config import SECONDS_PER_FRAME from target_finder import TargetFinder async def main_loop(body: Callable[[], Awaitable]): """The main loop of the program. This loop starts eac...
1e4cbf985e298c52b54b644c3a0153cf89885c1e
th0masb/misc
/daily-coding-problem/strings/2-2.py
2,108
4.09375
4
''' If two words have same length parity then we only need to check one ordered tuple, if they have different parity do we need to check both ways? This way works but the complexity isn't much better than brute force, they used a clever prefix/suffix trick with dictionaries in the book. ''' def palindrome_pairs(wor...
592910ee54b51989b35c13622b7dd2f6f034578e
akfunes/studyProblems
/flatten_a_multilevel_doubly_linked_list.py
848
3.8125
4
""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten_dfs(self, prev, curr): """ return the tail of the flatten list """ if not curr:...
909c42c369f9306b4694f66a400eab4ff2f3ad9f
akfunes/studyProblems
/climbing_stairs.py
309
3.625
4
# https://leetcode.com/problems/climbing-stairs/ class Solution: def climbStairs(self, n: int) -> int: if n == 1: return 1 numWays = [1 for x in range(n+1)] for i in range(2,n+1): numWays[i] = numWays[i-1] + numWays[i-2] return numWays[n]
3fd73d8e6877a6b0685f7f60cb29aaa39c106027
akfunes/studyProblems
/word_ladder.py
1,171
3.625
4
# https://leetcode.com/problems/word-ladder/ import queue class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: comboDict = {} for word in wordList: for i in range(len(word)): newWord = word[:i] + "*" + word[i+1:] ...
464f6f9562589352d77c4b36783280f3f0b95f57
Alihassan8096/AI_LAB_2
/H Task 1.py
102
3.515625
4
#creating a tuple of different data types myTuple = ("tuple", False, 3.2, 1) print (type(myTuple))
d778b446a64b2a12c3cd521aa611ca71937d2381
JYDP02/DSA_Notebook
/Searching/python/breadth_first_search.py
1,263
4.40625
4
# Python3 Program to print BFS traversal from collections import defaultdict class Graph: # Constructor def __init__(self): self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def BFS(self, s): # Mark all the vertices as not visited vis...
9edbcb198f6b82211e2b7800f6b8068d789c1418
JYDP02/DSA_Notebook
/Sorting/python/merge_sort.py
1,107
4.0625
4
def merge_sort(arr): if len(arr) >1: mid = len(arr)//2 left_arr = arr[:mid] right_arr = arr[mid:] merge_sort(left_arr) merge_sort(right_arr) left_iter = right_iter = merge_iter = 0 while left_iter < len(left_arr) and right_iter < len(right_arr): ...
a937750f6105e173443dca6ad173a52be6ec7e49
ATelders/learn-python
/hello/calories.py
406
3.875
4
print("Date du jour") date = str(input()) print("Calories au petit déjeuner ?") calories_petitdej = int(input()) print("Calories au déjeuner ?") calories_dejeuner = int(input()) print("Calories au goûter ?") calories_gouter = int(input()) calories_total = calories_petitdej + calories_dejeuner + calories_gouter print("L...
0ec0b700d360e2041e98367531fecbec7310712f
yuyangoops/learn_python
/06.py
427
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- _len = 0 my_list = [1,2,-1,64,2,3,5,65,55,3241,2,3,4,5] for element in my_list: _len += 1 print 'mysql list len is %d' % _len _max = 0 _min = None for element in my_list: if element > _max: _max = element print 'my list max is %d' % _max for element in my...
8bf11d623899a8640bd99dc352518a2c562c9e87
lingaraj281/Lingaraj_task2
/q3.py
317
4.15625
4
print("Enter a text") a=str(input()) letter = input("Enter a letter\n") letter_count = 0 for x in a: if x == letter: letter_count = letter_count + 1 num_of_letters = 0 for x in a: if(x != " "): num_of_letters = num_of_letters + 1 frequency = (letter_count/num_of_letters)*100 print(frequency)
b36c4d9119e7de69f3c5a322e8a47ef9b0f7aa55
Gamain/WorksApplication2014ProgrammingExamination
/test/gen_distance_matrix.py
555
3.78125
4
import random def print_matrix(width, height): matrix = [] for _ in range(height): row = [0] * width matrix.append(row) # fill matrix. for x in range(width): for y in range(height): if x >= y: continue distance = random.randint(1, 100) ...
946109656fc4292b3ab1b2f47e3e297f7aefb39f
ShreyasDaBoss7/python_classses
/Week 7/Session.py
1,171
3.765625
4
#hello = ('Hello Python World!!!') #print(hello[1:5]) #a = ('Python Programming') #b = (' Hello World') #c = (a+b) #print (c) #JusticeLeague_list = ['Batman','Superman','Wonder Woman','Flash','Cyborg'] #if 'Wonder Woman' in JusticeLeague_list: # print('Wonder Woman, present') #else: # print('Wonder Woman died'...
2e7266efc9d0d28413d9b28053d49830f6c85834
JatinR05/Python-3-basics-series
/17. appending to a file.py
864
4.40625
4
''' Alright, so now we get to appending a file in python. I will just state again that writing will clear the file and write to it just the data you specify in the write operation. Appending will simply take what was already there, and add to it. That said, when you actually go to add to the file, you will still use ....
832116d9d321018bcd4a616b96fa69dd669f9058
JatinR05/Python-3-basics-series
/42. cx_Freeze/reandurllib.py
1,570
3.53125
4
''' Identifiers: \d = any number \D = anything but a number \s = space \S = anything but a space \w = any letter \W = anything but a letter . = any character, except for a new line \b = space around whole words \. = period. must use backslash, because . normally means any character. Modifiers: {1,3} = for digits, u exp...
a429e619657d092618f27c24cd0a30abfbda9e3c
JatinR05/Python-3-basics-series
/9. if elif else.py
972
4.34375
4
''' What is going on everyone welcome to my if elif else tutorial video. The idea of this is to add yet another layer of logic to the pre-existing if else statement. See with our typical if else statment, the if will be checked for sure, and the else will only run if the if fails... but then what if you want to chec...
4ea711632c6a2bab41d0810384552a220d35eb7a
joe-bollinger/python-projects
/tip_calculator/tip_calculator.py
1,703
4.25
4
print('Tip Calculator') print() # TODO: Get the cost of the meal and print the results get_cost = input('How much did your meal cost? (i.e. 45.67) ') # Convert the input string to a float get_cost = float(get_cost) print(f"Food Cost: ${format(get_cost, '.2f')}") # TODO: Calculate 10% sales tax for the bill and print...
51369fe1595abbe3874a57edc3e02051d0b56fba
JonasProg/ProjectEuler
/Problem_2.py
332
3.640625
4
def fibonacci(maximum): Sum=0 letzte_zahl=2 vorletzte_zahl=1 while letzte_zahl<=maximum: nachste_zahl=letzte_zahl+vorletzte_zahl vorletzte_zahl=letzte_zahl letzte_zahl=nachste_zahl if vorletzte_zahl%2 == 0: Sum=Sum+vorletzte_zahl return Sum print(fibonacci...
60f7a48a4e3e6c0b5287a59ad7264d32551cd89c
JonasProg/ProjectEuler
/Problem_11.py
2,113
3.8125
4
def txt_reader(): file = open('C:\\Users\\Jonas\\Desktop\\Python_Matrix.txt') liste = file.readlines() liste2 = [] final_liste=[] for x in range(0, len(liste)): liste2 = liste[x].split() liste2 = [int(i) for i in liste2] final_liste.append(liste2) return final_liste def ...
07d09a3cce445e0a34eb1a16c5c654727af76bab
KEYURRATANGHAYRA/python_morsels_solutions
/2018_09_10_parse_ranges/parse_ranges.py
723
3.96875
4
"""Parse a string representation of several numeric ranges Returns a generator >>> nums = parse_ranges('1-3, 8, 18->exit') >>> next(nums) 1 >>> next(nums) 2 >>> next(nums) 3 >>> next(nums) 8 >>> next(nums) 18 """ def parse_ranges(range_str): ranges_and_numbers = range_str.split(',') for item in ranges_and_n...
0762a98d1841cb449422c2bbcf57fdc58c9831e4
KEYURRATANGHAYRA/python_morsels_solutions
/2018_08_27_interleave/interleave_alt.py
250
4.09375
4
"""Alternate solution to interleave exercise 08/30/2018 """ def interleave(iterable1, iterable2): """Interleave the elements of two iterables and return an iterator""" for x, y in zip(iterable1, iterable2): yield x yield y
d1fe2853db3c4706e64457efe81790c6c5529437
KEYURRATANGHAYRA/python_morsels_solutions
/2018_10_15_float_range/float_range_initial.py
849
3.859375
4
def float_range(*args): if not args: raise TypeError("Must provide stop argument") elif len(args) == 1: start, stop, step = 0.0, args[0], 1.0 elif len(args) == 2: start, stop, step = args[0], args[1], 1.0 elif len(args) == 3: start, stop, step = args[0], args[1], args[2] ...
b90589bc271b9b85f36995144b00923797d74cec
KEYURRATANGHAYRA/python_morsels_solutions
/2018_09_17_window/window_initial.py
505
3.828125
4
from collections import deque def window(iterable, n): """Return tuples of n consecutive elements in iterable as a generator. >>> tups = window([1, 2, 3, 4], 2) >>> next(tups) (1, 2) >>> next(tups) (2, 3) >>> next(tups) (3, 4) """ q = deque() it = iter(iterable) while ...
1b039d81ef2d63373606fcf4bedc405822b83dbc
KEYURRATANGHAYRA/python_morsels_solutions
/2018_09_17_window/window.py
564
3.734375
4
""" Revised solution to window exercise that gets rid of if statement to check length of queue within body of loop """ from collections import deque from itertools import islice def window(iterable, n): """Return tuples of n consecutive elements in iterable as a generator. >>> tups = window([1, 2, 3, 4], 2)...
ac16c1747a2794bbfc8a6d00beefffd0e097fc9b
KEYURRATANGHAYRA/python_morsels_solutions
/2018_06_11_matrix_from_string/matrix_initial_try.py
339
3.90625
4
def matrix_from_string(mat_str): """Takes a string representing a matrix where rows are delimited by newline characters and returns a list of lists """ matrix = [] for col_str in mat_str.split("\n"): col = [float(x) for x in col_str.split()] if col: matrix.append(col)...
15b7ee2b8ab897d81af763c835b47b0f070e0b34
Teifion/ultimate_ox
/lib/actions.py
1,323
3.546875
4
from . import rules def perform_move(the_game, square): player_number = rules.current_player_number(the_game.turn) mutable_board = list(the_game.current_state) mutable_board[square] = str(player_number) the_game.current_state = "".join(mutable_board) def set_active_board(the_game, square): b,...
f6717518f0fc59f794607f32ae3b2c33f8f88356
sohel2178/Crawler
/file_test.py
1,983
4.15625
4
# f= open('test.txt','r') # print(f.mode) # f.close() # Context Manager # with open('test.txt','r') as f: # Read all the Content # f_content = f.read() # There is another method to read a file line by line # f_content = f.readlines() # print(f_content) # Another way to read All of the Li...
b2b7f682880b2154e2b60a646766190fd00e7301
devSoyoung/jump-to-python-examples
/zip_string.py
723
3.890625
4
mystr = input('문자열을 입력하세요: ') before_char = '' current_char_cnt = 0 result = '' for char in mystr: # 문자가 서로 다를 경우 if(before_char != char): # cnt가 1보다 큰 경우 > 유의미한 값 > 저장, 초기화 if(current_char_cnt > 1): result += str(current_char_cnt) # result에 새로운 단어 저장하고 카운트 증가 curr...
b90fc117e086c236bfaa3777f04e92316ccd17d7
galinapivovarnik/university-python
/L13/draft_1/main.py
2,994
3.890625
4
def is_balanced(text): """ >>> is_balanced('(())()') True >>> is_balanced('(()()') False """ level = 0 for character in text: if character == '(': level += 1 elif character == ')': level -= 1 return level == 0 def intersection(a1, b1, c1, a2,...
42772f58e2c23afba54f974a36a41594f075c845
hsneto/ifes-redes-neurais
/neural_networks/multilayer_perceptron.py
3,642
3.78125
4
import numpy as np from mlp_layer import Layer class MultiLayerPerceptron(object): '''Neural Network: MultiLayer Perceptron ''' def __init__(self): self.n_layers = 0 self.layer = {} self.weights = {} def add_layer(self, units, rate, activation):#adicionar error_max ...
d05f46251c0c3550dd70cda5948587aaf72d4901
Kjeldgaard/ProjectEuler
/src/multiple_3_5.py
1,326
4.15625
4
#!/user/bin/env python3 -tt """ Multiples of 3 and 5 https://projecteuler.net/problem=1 """ # Imports import sys import argparse def sum_of_multiples(number :int, divisor :int) -> int: max_multiple = int((number - 1) / divisor) times_multiple = float((max_multiple + 1) / 2) * max_multiple sum_of_multiple...
dca2d9c0bd0340d8d1bbe12c81818399830dd694
mirjambe/python12.11
/zad_7.py
398
3.609375
4
""" 7. Ispiši vrijednost broja Pi na 4 decimalna mjesta, kvadriraj taj broj te ga podijeli s racionalnim brojem odabranim od strane korisnika (input funkcija) i ispiši rezultat. """ import math pi = math.pi pi4 = float(f"{pi:.4f}") print(pi) print(pi4) kvatrat = math.pow(pi4,2) nekiBroj = float(input("Unesi neki ...
5a703b7c15376d707b6b35b9d7d201f7d0ebe11d
jaskirat1208/turtlebot-polaris
/src/polaris_follower/utils.py
211
3.59375
4
class Point: """ A point in a cartesan plane """ def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return str.format("({}, {})", self.x, self.y)
962a9e8550354762ef40fa81abb57bbbe7ff788b
Lewi23/multiplication-turing-machine
/MultMachine.py
3,806
3.859375
4
# -*- coding: utf-8 -*- import time # Constant for tab TAB = "\t" # Tape settings tape = "" # Get input for n * m try: n = int(input("Please input n : ")) m = int(input("Please input m : ")) except ValueError: print("Oops! That was not a valid number") raise print() # Location the TM is looking at in...
1b1a99edebb03c45ed2fa0339347221b9abb5860
jc2brown/Plink
/src/camera.py
1,467
3.53125
4
from convenience import * from transform import * from mover import * # The Camera class represents the "eyes" of the scene. Image data is # collected here and displayed using an instance of the View class # position: a point in 3-space # rotation: a vector in 3-space # objects: the set of objects...
8d396407944ea4bbd208e78374a07066eb0b0d7f
Gembelton/kyprianovLabs
/lab_4/lab_4.py
5,146
3.875
4
# Создать программу, выполняющую следующие действия. # 1.Создание массива случайных чисел в диапазоне от -100 до 100, размер которого вводится с клавиатуры. # 2. Сортировка созданного массива по возрастанию и подсчет количества операций перестановки. # 3. Выполнение задания в соответствии с вариантом с помощью л...
5ba664e7226324b9001fb113223aedef370290fc
Richie010/uplift-python-resources
/List Problems/complist.py
167
3.9375
4
name = ["Sagnik", "Mitra"] newlist = [] for x in name: if "Sagnik" in name: newlist.append(x) print(newlist) newlist2 = [x for x in name if "Sagnik" in x]
df130b73e0c47f96a9624d0db5b87c05b51ae54d
Richie010/uplift-python-resources
/List Problems/printevenandoddinlist.py
413
3.90625
4
ourList = [] for i in range(0, 7): ourList.append(int(input())) print(ourList) evenList = [] oddList = [] size = len(ourList) for i in range(0, size): if(ourList[i] % 2 == 0): evenList.append(ourList[i]) else: oddList.append(ourList[i]) print(evenList) print(oddList) print(f"There were {len(...
1bece5bb15bcfc928d9f766671512c1881880ad5
fabioktazo/C-digo-POO-3-Bim-1
/Entregador.py
661
3.625
4
class Entregador (Pessoa): def __init__(self, conducao, placa, nome, contato, id, estrelas): super().__init__(nome, contato, id, estrelas) self.conducao = conducao self.placa = placa def relatar_problema_entrega (self): print("PROBLEMA RELATADO COM SUCESSO. AGUARDE O CONTAT...
f7f83ae4a45bf1896a6c7d9608f9f560e8bf904f
ishan5886/Python-Learning
/OOPS Concepts/OOPS-Class Variables.py
2,480
4.15625
4
# class Employee: # def __init__(self, first, last, pay): # self.first = first # self.last = last # self.pay = pay # # def fullname(self): # return '{} {}'.format(self.first, self.last) # # def appraise(self): #Without using class variable # self.pay = int(self.pay ...
79e38192f0cf9da84f170c21c5781eac2eeb8d7b
ishan5886/Python-Learning
/OOPS Concepts/OOPS- Class Methods and Static Methods.py
1,244
3.828125
4
class Employee: emp_no = 0 raise_amt = 2.50 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay Employee.emp_no += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def appraise(self): self.pay...
8a5a3eff7f13f1b444054ad2c39c14e972a37590
ishan5886/Python-Learning
/SQLite Database Programming/SQLLite1.py
2,112
4.09375
4
import sqlite3 from employee import Employee #Import another class # # conn = sqlite3.connect(':memory:') #to create an in memory database # conn = sqlite3.connect('employee.db') # use file # # c = conn.cursor() #create Cursor to execute SQL commands # # # # c.execute("""CREATE TABLE employees( # # first...
5b45bd9c80e50eade21ee398a53d6fff32f75759
ishan5886/Python-Learning
/Conditional Statements and Loops.py
647
3.84375
4
X = 10 Y = 20 # IF/ELSE/ELIF - Conditional Statements # Indentation important to signify that piece of code belongs to if/else/elif loop """ if(X<Y): print('X is greater than Y') else: print('Bhag ja') """ # WHILE LOOP - Looping Statements """ while(X<=Y): print("X is ", X) X+=1 """ # FOR LOO...
80e00f4c0f308f8c361a884b08c56b60f3e6d4b3
ishan5886/Python-Learning
/Decorators.py
1,020
4.21875
4
#Decorators - Function that takes function as an argument, performs some functionality and returns another function # def outer_function(msg): # def inner_function(): # print(msg) # return inner_function # def decorator_function(original_function): # def wrapper_function(): # return or...
bb7f5bbd3a5fb5c9d89c1d6d3d23283cb958b09a
ka1be/qqq
/euler1.py
79
3.703125
4
d=0 for i in range(1,1000,1): if (i%3==0) or (i%5==0): d+=i; print (d);
f71daaceeb85a8fce4291900096cf596f5182e93
jtorquetti/PythonChallenges
/Challenges/desafio15.py
162
3.5625
4
a = int(input('Quantos dias alugados? ')) q = float(input('Quantos Km Rodados? ')) d = (a * 60) + (q * 0.15) print('O total a pagar e de R${:.2f}'.format(d))
28ca5f1cab993b0e65cd4d42e64573b162ea531c
jtorquetti/PythonChallenges
/Challenges/Desafio8.py
313
3.5625
4
m = float(input('Quantos Metros?')) cm = m * 100 mm = m * 1000 dm = m * 10 dam = m / 10 hm = m / 100 km = m / 1000 print('Kilometros = {:.0f}km\nHectometro = {:.0f}hm\nDecametro = {:.0f}dam\nMetro = {:.0f}m\nDecimetro = {:.0f}dm\nCentimetro = {:.0f}cm\nMilimetro = {:.0f}mm'.format(km,hm,dam,m,dm,cm,mm))
64ebe368cdb224650ddcd053605e4058fab76bcf
jtorquetti/PythonChallenges
/Challenges/desafio7.py
164
3.625
4
a = float(input('Semestre 1 ')) b = float(input('Semestre 2 ')) t = (a + b) / 2 print('Semestre 1 = {} / Semestre 2 = {} / Nota Media = {}'.format(a, b, t))
67eecb0959d0b1663bf807f40a1f32a0cdade3db
jtorquetti/PythonChallenges
/Challenges/desafio38.py
240
4.03125
4
a = float(input('Primeiro numero: ')) b = float(input('Segundo numero: ')) if a > b: print('O primeiro valor e maior') elif a < b: print('O segundo valor e maior') else: print('Nao existe valor maior, os dois sao iguais')
26e5cc14a2bc3fb8a887ce5cfeb94e8f435806e9
jtorquetti/PythonChallenges
/Challenges/desafio45.py
1,062
3.8125
4
import random itens = ('Pedra', 'Papel', 'Tesoura') print('='*13) print('JOKENPO GAME!') print('='*13) print('Escolha uma das opcoes!') print('''[0]Pedra [1]Papel [2]Tesoura''') user = int(input('Voce escolhe? ')) print('''JO KEN PO!''') computador = random.randint(0, 2) print('O Computador jogou {}'.form...
22d08eb472d5f1e3e3a841c67cf10dec3d28b000
apustovitin/sea-battle
/read_file.py
664
3.5
4
import os class ReadFile: def __init__(self, file_name): if os.path.isfile(file_name): self.file_name = file_name else: raise ValueError(f"Can not open {file_name}.") def get_content(self): content = [] with open(self.file_name, encoding='utf-8') as fil...
ce482934842c4846f1cef3d4157920b49ddf8a09
ManolisNikolakakis/gusbuzzgames
/gusbuzz/actors/actor.py
532
3.984375
4
from abc import ABC from abc import abstractmethod class actor(ABC): """ Abstract class that all elements should implement """ @abstractmethod def render(self): """ Renders the actor on the screen """ pass @abstractmethod def get_position(self): ""...