blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8997508dde0407076d1fc2ee84ba66d8517bbd0e
srihariprasad-r/workable-code
/Practice problems/foundation/2D-arrays/wavetraversal.py
592
4.3125
4
""" Wave traversal is first go top to bottom, for next column go from bottom to top and continue [ | 1 | 2 | 3 | 4 | 5 | 6 ] To achieve this, for even columns, we go top to bottom and vice-versa for odd columns """ def wavetraversal(arr1): r1, c1 = len(arr1), len(arr1[0]) for i in range(len(arr1[0])): ...
6c5d26b9e2663817378906ad2ca9d4f56317c046
Anubamagpljecs07/Codekata_Hunter
/Pal_using_stack.py
711
3.640625
4
class Stack: def __init__(self): self.items=[] def push(self,data): return self.items.append(data) def pop(self): return self.items.pop() def is_empty(self): if self.items==[]: return True else: return False def get(self): retur...
08601c461854255623a05ff639ec0b4771972f8e
beidou9313/deeptest
/第一期/上海-Jason/pyLearn/task02/breakAndContinue.py
1,428
3.875
4
# _*_ coding : utf-8 _*_ __author__ = "Jason" ''' break和continue语句及循环中的else子句 break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。 continue语句被 用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。 ''' #for语句的break和continue #break for counter in range(0,10): print("counter值为%d"%counter) if counter == 1: ...
c1426068a73977b07388fbaa02e2250ba3ad0ed0
m-01101101/code_wars
/multiplication_table.py
563
4.25
4
""" Your task, is to create NxN multiplication table, of size provided in parameter. for example, when given size is 3: 1 2 3 2 4 6 3 6 9 """ def multiplication_table(size): meta_list = [] list1 = [] for i in range(size): list1.append(i + 1) meta_list.append(list1) for i in range(size ...
13821533695b84cab42b1daca172891a03a58afb
daniel-reich/ubiquitous-fiesta
/fpJXv7Qn9LCxX8FYq_13.py
161
3.640625
4
def solve(eq): lst = eq.split(' ') if lst[1] == '+': return eval(lst[-1] + '-' + lst[2]) elif lst[1] == '-': return eval(lst[-1] + '+' + lst[2])
58809beb7946fb5b3f896b731f152a9be7052334
h-main81423/main_h_python
/functions.py
642
3.96875
4
def greetings(): print("Hello from the greetings function") # the greetings function just says hello # invoke or call the function greetings() def greetingsWithArgs(msg="a default message"): # print the msg variable print("now we're saying", msg, "from another function.") greetingsWithArgs("eat my fuc...
cfab6dc766951b3a9161cb015c625de3bb55c02d
ruslanvs/Bike
/Bike.py
1,007
4.25
4
class Bike( object ): def __init__( self, price, max_speed, miles = 0 ): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo( self ): print self.price, self.max_speed, self.miles return self def ride( self ): print "Miles before th...
27b711d9e12bb397878fa9c87ec648b15ff9add1
PkYang-2020/-
/ques56.py
624
3.828125
4
num = [[1,2],[2,3],[3,5]] res = [] def quick_sort(num): if len(num) < 2: return p = num[0][0] L = [] M = [] R = [] while len(num) > 0: if p > num[-1][0]: L.append(num.pop()) elif p == num[-1][0]: M.append(num.pop()) else: R.appe...
00df03ae6d38a12bd04675f0a5a415d7f6a052c2
j-kroon/HackerRank
/hacker/function.py
461
4.1875
4
""" The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: The year is also evenly divisible by 400. Then it is a leap year. """ def is_leap(year): leap = False if leap % 4 != 0: return leap elif leap%100 =...
bd4209636cdacc6482ee1e914d5617e350184338
dguan4/HanStory
/src/button.py
1,052
4.0625
4
""" Button class for doing actions """ import pygame class Button: def __init__(self, text, x, y, width, height, action=None): """ Creates a button at a location and some text :param text: text to display :param x: x location :param y: y location :param width: wid...
919e2493e1b46750f22563d27bce479473312340
bsherwood9/cs-module-project-recursive-sorting
/src/searching/searching.py
1,700
4.375
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # Your code here if end >= start: mid = (start + end)//2 if arr[mid] == target: return mid if arr[mid] > target: return binary_search(arr, target, start, mi...
f139032627edeea7b0e6bdeeb4df291d75a6b4dc
iwuch/python_examples
/merge_intervals.py
280
3.765625
4
intervals = [[1,2],[3,4],[5,6],[0,10],[7,12]] def merge(intervals): intervals.sort() results = [] for i in intervals: if not results or results[-1][-1]<i[0]: results.append(i) else: results[-1][-1] = max(results[-1][-1],i[-1]) return results print(merge(intervals))
9679335e7efea656319de208270b1eaf9bd84d49
tjwudi/learn-python
/codewars/character-frequency.py
562
3.984375
4
# return a list of tuples sorted by frequency with # the most frequent letter first. Any letters with the # same frequency are ordered alphabetically dic = {} def inc(c): if 'a' <= c <= 'z': if dic.get(c, 0) == 0: dic[c] = 1 else: dic[c] += 1 def letter_frequency(text): text = t...
fadfe2612478e80ef8615a581bd1826f895e6069
mercado-joshua/Program__Spell-Checker
/pyspellchecker-package/main1.py
186
3.609375
4
from spellchecker import SpellChecker spell = SpellChecker() misspelled = spell.unknown(['pythn', 'is', 'populr', 'languge']) for word in misspelled: print(spell.correction(word))
275c024bc09b30b666f8c6f86e35c77b73a6ab92
SJeliazkova/SoftUni
/Python-Fundamentals/Exercises-and-Labs/data_type_more_exercises/04_decrypting_messages.py
194
3.546875
4
key = int(input()) lines = int(input()) message = "" for l in range(lines): character = input() new_character = chr(ord(character) + key) message += new_character print(message)
8d8afbe790ccfff8d4caa8a3dfce3d23dfb37ccc
Frans-L/Algorithm-Challenge-Heaps
/visualize/misc.py
5,775
3.96875
4
# This is used for the visualization. The function calculates # the positions of the nodes for the tree visualization # Licensed under Creative Commons Attribution-Share Alike # (C) Joel # https://stackoverflow.com/a/29597209/2966723 import networkx as nx import random def hierarchy_pos( G, root=None, width=1.0...
73295b96438c3a148c377eddd639b9e2b52ad2aa
msagar7/collegematch
/processdata.py
1,008
3.78125
4
import csv from collections import defaultdict # Loads the csv file of college data into a dictionary # params: # - filename: name of csv file containing the dataset # return: # - dictionary: # - key: college UNITID defined by DOE # - value: dictionary containing different data # points of each college (eg. ci...
4e49424909f9442207f35e01d14a4af291dc523d
cedricbasuel/flames-with-plot-generator
/flames.py
2,229
3.921875
4
from collections import Counter def remove_common_letters(string1, string2): '''Given two strings, remove common letters. Params ------ string1, string2 : str Returns ------- uniqueDict : dict Dictionary of unique letters in both strings and their counts. ''' # dict1 ...
4b8b1629494a37ba9c2beae07c7a22650b47273d
SebastVR/test
/Data_Science_Python/Introduction_to_Data_Sciencein_Python/Assignment2.py
11,462
4.125
4
'''Assignment 2 - Pandas Introduction All questions are weighted the same in this assignment. Part 1 The following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on All Time Olympic Games Medals, and does some basic data cleaning. The columns are organized as # of Summer g...
4a17e1fdb8f65183e2e7e30e3fa265c76f570c16
AlexanderWeismannn/Pierian-Data-Python-Course
/Methods and Functions Questions/Challenging/spy_game.py
636
3.90625
4
#CHALLENGING PROBLEMS #1 (SPY GAME) #TAKES IN A LIST OF NUMS AN RETURNS TRUE if there exists a [0, 0, 7] in order def spy_game(nums): exists = 0# if the number reaches 3 then the 007 string exists in order for i in range(len(nums)): if(nums[i] == 0 and exists == 0): exists = exists +...
13394710d887a6c7ffb93f28cb294f032d916175
patkhai/LeetCode-Python
/OA/Goldman_Sach/rotateTheString_GoldManSachs.py
1,035
3.953125
4
def rotateTheString(originalString, direction, amount): lengthS = len(originalString) for rotate in amount: for j in range(rotate-1): if direction == 1: #rotate right originalString = originalString[lengthS - 1] + originalString[0:lengthS-1] else: #rotate left ...
679e8559e444aecf44063540bb7f33ad9dbc2668
AirGear02/PyLabs
/Lab1/task1.py
361
3.78125
4
from math import cos, factorial, fabs eps = float(input('Eps = ')) a = float(input('a = ')) x = float(input('b = ')) all_sum = 0 k = 0 while True: curr_sum = cos(a ** k + x ** k) / factorial(k ** 2) k = k + 1 all_sum += curr_sum if fabs(curr_sum) <= eps: print('Sum = ', all_sum) prin...
a44a818c3b1e2920f3370262d140cdca3f7721d9
anti-Alz/leetcode-python
/232. Implement Queue using Stacks.py
2,058
4.21875
4
''' 232. Implement Queue using Stacks Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must use only standard operat...
ba6e56383b9ff760e2403cfd7535e9f09f29ecf9
Aadesh-Shigavan/Python_Daily_Flash
/Day 13/Program2.py
342
4.09375
4
''' Program 2: Write a Program that accepts Two integers from user and prints the series of factorial of all numbers between those two inputs. ''' num1, num2 = [int(i) for i in input("Input : ").split()] for i in range(num1, num2 + 1): fact = 1 for j in range(1, i + 1): fact *= j print("Fact of "...
8af95c151a6feb1af56cb9a2b92d4bddf91d2e5d
nickwu241/coding-problems
/leetcode/235-lowest-common-ancestor-of-a-binary-search-tree.py
549
3.734375
4
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'Tree...
814cb1338a7da04658d43e513ab202534a4317ed
jeffchen/DailyCodingProblem
/problem21/solution.py
1,202
3.671875
4
''' Good morning! Here's your coding interview problem for today. This problem was asked by Snapchat. Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. ''' def...
a34cebfb50f8041f7a6ce3647aa830f0108f957f
jacobabrennan/space-shuttle-sim
/main.py
1,886
3.6875
4
# - Game ---------------------------------------------------------------------- """ This file is the main entry point for the game. Execute this file to play: $ py main.py The game is a 3D spaceship simulation. The user can fly a spaceship around a sparsely populated solar system. The controls are as follows: W+S: ...
5cab90a49611d104b97c0af2d17a9232b856ac36
ervitis/challenges
/leetcode/factorial_trailing_zeroes/main.py
333
4.1875
4
""" Given an integer n, return the number of trailing zeroes in n!. """ def trailing_zeroes(n: int) -> int: c = 0 while n > 0: n //= 5 c += n return c if __name__ == '__main__': print(trailing_zeroes(3)) print(trailing_zeroes(5)) print(trailing_zeroes(0)) print(trailing_...
56bcd22d6c7e02c78e6ebe7edc171d94f2f06388
lyneca/ncss2017
/roman_numerals.py
1,743
3.703125
4
import string class RomanNumeral: def __init__(self, i): if isinstance(i, int) or i[0] in string.digits: self.r = to_roman(int(i)) self.i = int(i) else: self.r = i.upper() self.i = to_decimal(i.upper()) def __add__(self, o): return RomanN...
3d72956e64d1306dee9080bcf33832627215f16b
MrTy13r/geekbrains_python_OkhitinLA
/Урок 3. Функции/Задание 3.1.py
685
4.28125
4
"""3.1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль""" def division(num1, num2): if num2 == 0: print("Делить на ноль нельзя, аллё") else: return int(num1 / num2) ...
e625208e4d8af4cd5fc57564b527260056c63e83
hyc12345hyc/hyc
/py_basic_exercises/chapter2/2-1suoyin.py
650
4.34375
4
#-*-coding:utf-*- #根据给定的数字形式的年月日打印出日期。 months = ['January','February','March','April','May','June','July','August','September','October','November','December'] #以1~31的数字作为结尾的列表。 endings = ['st','nd','rd'] + 17 * ['th']\ + ['st','nd','rd'] + 7 * ['th']\ + ['st'] year = raw_input('Year: ') month = raw_input('Month(1~12...
26bda2145ace52e26f85c701c03dd796851fb847
Thorarinng/prog_01_kaflaverkefni
/timaverkefni/12-5.py
2,019
3.8125
4
#12-5 GAME OF EIGHTS #game_of_eights() function goes here def game_of_eights(i_list): """athugar hvort 8 se lika i saetinu a undan""" is_eight = False # i_list = change_to_ints(nlist) for i in range(len(i_list)): if i_list[i] == 8 and i_list[i-1] == 8: is_eight = True print(i...
c74dad953f8a1435fe6c0c270a9858ef9992c8cc
KShaz/Machine-Learning-Basics
/python code/ANN 2-1 OR-Sigmoid.py
1,007
4
4
import numpy as np def Sigmoid(x): return 1/(1+np.exp(-x)) def Sigmoid_deriv(x): return x*(1-x) # input dataset X = np.array([ [0,0], [0,1], [1,0], [1,1] ]) # output dataset y = np.array([[0],[1],[1],[1]]) # seed random numbers to...
9aca842a286eae90d60176aa46d9261b2a0f2562
sas342/hackerRank
/datastructures/Stacks.py
6,215
3.5625
4
''' Created on Jun 11, 2016 @author: sstimmel ''' class BalancedParen(): def __init__(self): self.balanced = True self.stack1 = [] def nextchar(self, char): if self.balanced == False: return if char == '{' or char == '[' or char == '(': ...
cd7e90e197f912a9fd67d302d59232bd7980f8d9
lokeshkumar9600/python_train
/dct1.py
162
3.8125
4
me = {"name" : "lokesh" , "age" : 18} print(me) print(me["name"] , me["age"]) me["age"]=19 print(me) #updated dict me.pop("name") print(me) me.clear() print(me)
6d50c296b96e8642e28587c53102aae41a9b4469
SeongHyukJang/HackerRank
/Python/Regex and Parsing/Regex Substitution.py
232
3.71875
4
import re string = '' n = int(input()) for i in range(n): line = input() res1 = re.sub(r'(\s)(&&)(?=\s)', ' and',line) res2 = re.sub(r'(\s)(\|\|)(?=\s)', ' or', res1) string += res2 string += '\n' print(string)
0e0db3d5f8e14200b1996aaacac96100b46da261
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4148/codes/1800_2567.py
111
3.921875
4
j = int(input("numero: ")) for i in range(j): print((j-i)*"*" ) for i in range(j): print((i + 1)*'*')
72b220305ffbc210100b8d6f0786784232c02877
Prakort/competitive_programming
/flatten-binary-tree-to-linked-list.py
514
3.65625
4
class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ self.helper(root) def helper(self,root): if not root: return None if not root.right and not root.left: return root left = self.helper(r...
ec0616524fda3c75b55d6e3c35d9ddf2faa17bfb
kakkarotssj/Algorithms
/Greedy/union_find_detect_cycle.py
903
3.90625
4
from collections import defaultdict graph = defaultdict(list) def addedge(node1, node2): graph[node1].append(node2) graph[node2].append(node1) vertices_count = 5 addedge(0, 1) addedge(0, 2) addedge(1, 3) addedge(1, 4) addedge(3, 4) def findparent(parent, node): if parent[node] == -1: return node else: retur...
59a08272be6a31ccdec8d1892d5e893c7afe9892
kaustav1996/networking-
/kaustav networking/networkin.py
571
3.59375
4
print("Enter Bit Sequence: \n") s=raw_input() flag=0 x=list() for i in range(len(s)): x.append(s[i]) if(s[i]=="1"): flag=flag+1 else: flag=0 if(flag==3): x.append("0") flag=0 y="".join(x) print("message sent: "+y) z=list() i=0 while(i<len(y)): z.appe...
8df45c4b31d033e88d3909d662eecd8e6475ca68
jooonyliks/Album-photo-viewer
/PhotoAlbum/media/demand.py
1,786
4.09375
4
# A program that deals with demand # getting cross elasticity of demand def crossElastcityofDemand(): '''This is a program that gets the cross elasticity of two products requires the // change in quantity demanded of product x//the original quantity of product x //change in price of product y//the original price ...
d9d09bba2ad08685272c1c96a4ccb13b1ba851b3
CristofherAndres/Codigos_Python
/ejercicio_propuesto6.py
641
3.953125
4
#Datos de entrada dinero = int(input("Ingrese el dinero: ")) b10 = dinero//10000 dinero = dinero%10000 print("Billetes de 10.000:",b10) b5 = dinero//5000 dinero = dinero%5000 print("Billetes de 5.000:",b5) b1 = dinero//1000 dinero = dinero%1000 print("Billetes de 1.000:",b1) m500 = dinero//500 dinero = dinero%500 p...
66fd6cb1853a18cdf7affdc308bdefcd66500dbf
realbakari/python-program
/Random/Anti-median/test.py
1,491
3.84375
4
# Author: Bakari Mustafa, contact@bakarimustafa.com from main import anti_median_permutation # Test case 1 # There is only one test case with n = 2. # The permutation is given as [1, -1], which means that the first element # is given and the second element is unknown. # There is only one anti-median permutation in t...
faafc54a60b70eccd0334d07eee209e53a386bbc
botaoap/DesenvolvimentoPython_Botao_2020
/Revisao/Exercicio08/ex5.py
176
4
4
# Faça um programa que mostre a tabuada do 8 na tela. # Lembrando que a tabuada é de 0 a 10 for i in range(10): tabuada = 8 * (i+1) print(f"8 X {i+1} = {tabuada}")
979ae11d0a020f4994bce73e2246b1bc54051781
MerlynAllen/JLU-VPN
/vpn.py
1,129
3.53125
4
''' Generate a url to JiLin University VPN ''' import urllib.parse, os key = [0x6f, 0x68, 0xde, 0x3, 0xb8, 0xaf, 0xf7, 0xcf, 0xe1, 0x97, 0x16, 0x33, 0x7, 0xca, 0xbc, 0xaa, 0xc6] meaningless_bullshit = '77726476706e69737468656265737421' def generate(origin: str): info = urllib.parse.urlparse(origin) ...
afbb935c4dd7438adac5784ffc4a0f9ce83a48a9
VillaEdwar/Ciclo_1_MisionTic2022_Python
/Unidad_2/reto_completo_2.py
2,617
4.125
4
#Utilizando python, escriba una función que # reciba como parámetro un diccionario en el cuál # las llaves son los nombres de las variables mencionadas anteriormente. Retorne un nuevo # diccionario con las llaves “banco”, “usuario” y “mensaje” dónde esta última tenga como # valor una variable de tipo “str” que mues...
70f5d24ff721f6d993ad22312a2054a57be2e7e5
Magneet/CodeConnect_2021_Samples
/vmware_horizon.py
264,965
3.59375
4
import json, requests, ssl, urllib from typing import get_args class Connection: """The Connection class is used to handle connections and disconnections to and from the VMware Horizon REST API's""" def __init__(self, username: str, password: str, domain: str, url:str): """"The default object for the c...
9d7b81ee12b841bb27da083f75557d3ab46ee79e
0x90shell/ipwn
/nmapscrape.py
1,690
3.609375
4
#!/usr/bin/env python # # This script simply parses the scans/sS.gnmap and scans/sU.gnmap files # and places any open ports into a text file with the respective IP address # in it. So for example, you should end up with a scans directory # containing files such as 80.txt, 443.txt, 53.tct, etc. ...
c9b1f05f480762fca13773ef228b0b92b90fc1a4
Xancett/RandomPython
/mutable.py
576
3.796875
4
def my_number(something): something += 10 print('Value inside function: ', something) def my_word(something): something += ' rocks' print('Value inside function: ', something) def my_list(list): list.append('four') print('Value inside function: ', list) # Immutable types width ...
1a4daeb46fdb6fe583ff490bbc04f2791b8aa3bb
vezril/IEEEXtreme
/6.0/honey.py
679
3.5625
4
#!/usr/bin/python2.6 coord = raw_input() (x1,y1,x2,y2) = coord.split(" ") x1 = int(x1) x2 = int(x2) y1 = int(y1) y2 = int(y2) total = 0 while(True): x0 = x2 - x1 y0 = y2 - y1 if(x0 == 0): total = total + 2*y0 break elif(y0 == 0): if(y0 == 1): total = total + 2 ...
7f265a5d9d58692a329156c456872eba784683b3
AusBOM/serverless-tile-poc
/colour_map.py
2,793
3.9375
4
"""Functions for generating a custom colour map.""" import numpy as np import spectra def make_colour_map(colours, indexes=None, size=256, gradient=True): """Make a colour map for a list of colours aligned to indexes. Parameters ---------- colours : list of (spectra color objects or strings) ...
fa1a3cd6afed7abee94ce088086531a65fb99d58
Dian82/Assignments
/AdvancedComputerProgramming/ps1/ps1c.py
982
4
4
# Chen Hongzheng 17341015 # chenhzh37@mail2.sysu.edu.cn # Part C: Finding the right amount to save away # Initialization semi_annual_raise = 0.07 return_rate = 0.04 portion_down_payment = 0.25 total_cost = 1000000 downpay_cost = total_cost*portion_down_payment annual_salary = int(input("Enter the starting salary: ")) ...
daa9a2c783a467737d7370edd83947425e8c4214
alex-cres/ConnectFourAI
/TestingBoard.py
1,404
3.546875
4
import ConnectGame as CG class TestingBoard: def __init__(self, number, testMatrix): game = CG.ConnectGame() result = game.initBoard(testMatrix[3]) if game.isGameOver(): if result[0] != testMatrix[0] or result[1] != testMatrix[1] or \ "".join(str(i) for i in resu...
963db3a75f19b6a77f931acf321294ef05beebfd
league-python-student/level0-module1-nanonate32
/_03_if_else/_1_unbirthday/Unbirthday.py
445
3.90625
4
from tkinter import Tk, messagebox, simpledialog if __name__ == '__main__': window = Tk() window.withdraw() birthday = simpledialog.askstring("", "When is your birthday? Respond using the format of month/day") if birthday == "8/17": messagebox.showinfo(title = None, message = "Happy birthday to...
2eab9695831854c707f97784d59f3408787c45cb
SouthDrago/python-work
/basicPrac/functionPractices.py
2,980
4.15625
4
""" function can be defined as mulit arguments with *args """ from math import sqrt from math import pi city_prices = {'Charlotte': 183, 'Tampa': 220, 'Pittsburgh': 222, 'Los Angeles': 475} singleday = 40 def shut_down(s): arg = s.lower() if arg=="yes": return "Shutting down..." elif arg=="no": ...
fd867fa8b204338ff8f7442c5b98e6e120303b44
RichardSibi/friendly-guacamole
/WebscrapingIMDB.py
452
3.59375
4
from bs4 import BeautifulSoup import requests source = requests.get('http://www.imdb.com/search/title?release_date=" + year + “,” + year + “&title_type=feature') soup = BeautifulSoup(source.content,'lxml') i = 0 print("List of most popular movies for October 2021") print() for movie_sec in soup.find_all('div', class_ =...
d4fa9a47a46b4a0190314d8e904fa38aa1e3b20b
JanMagne/GameOfLife
/gol.py
3,173
4.0625
4
""" Python 3.9.6 implementation of Conway's Game of Life, using Pygame to display. The rules of GoL are as follow 1. Any live cell with two or three live neighbours survives. 2. Any dead cell with three live neighbours becomes a live cell. 3. All other live cells die in the next generation. Similarly, all other dea...
a1ea04da42b892a0284152a2920e1ca7f441225b
jklemm/curso-python
/curso-2/exercicio_02.py
179
3.8125
4
# entrada de dados numero_obtido = input('Digite um número: ') # processamento mensagem = 'O número informado foi {}'.format(numero_obtido) # saída de dados print(mensagem)
a7a27230b25565d12f6a35e761af5e320713e26b
sriramb2000/memory
/src/main.py
1,474
4
4
from logic.game import * if __name__ == "__main__": # 2 - 4 for now num_players = int(input("How many players?")) while num_players > 4 or num_players < 2: num_players = int(input("Please enter a number of players between 2 and 4: ")) # Should be even number >= 2*numplayers num_cards = int(...
99649c93efbc6bd77eccb58fcdfa710e12c36ed9
SubhamPanigrahi/Python_Programming
/area_triangle.py
330
4.25
4
# program to find the area of a triangle import math # importing math module def area(x,y,z): s = (x + y + z)/2 ar = math.sqrt(s*(s-x)*(s-y)*(s-z)) # this is the formula to find area return ar a = int(input("Enter a side: ")) b = int(input("Enter a side: ")) c = int(input("Enter a side: ")) print(are...
1ccaa08b9ce85461c71e5684d194b4fbb1278b7b
cu-swe4s-fall-2019/hash-tables-alisoncleonard
/test_hash_functions.py
1,106
3.578125
4
""" Unit test file for hash_functions.py module """ import unittest import hash_functions class TestHashFunctions(unittest.TestCase): def test_ascii_constant_key(self): k = 107 e = 101 y = 121 ascii_total = k + e + y N = 20 self.assertEqual(hash_functions.h_ascii(...
a37efbcded2d121d8fd9429372a618d6933838c5
john-adamsss/my_first_rep
/python_assign_2.py
313
4.03125
4
while True: age = input("Are you a cigarette addict older than 75 years old? (Yes/No) : ") if age == "Yes": age = True break elif age == "No": age = False print(age) break else: print("Please enter Yes/No only!") continue print(age)
2170269fddd261043c676e1131b4e4a1f7556661
bitnahian/info1110_s2_2019
/helpdesk/special_sum2.py
376
3.609375
4
a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) d = int(input("Enter d: ")) e = int(input("Enter e: ")) nums = [a, b, c, d, e] # Set up your counter i = 0 sum_val = 0 while i < len(nums): # Standard idiom for looping over a list # Do something if nums[i] == 7: i +...
21d2db86e29731860258223fac979d42c0a60500
Zahed75/PythonCodePractice
/List_tuples.py
627
4
4
#List are mutable we can create edit list remove item etc import copy L_one=[1,2,3,4,5,6] L_two=[6,47,9,2,3,5,9,10,13,12,15] print(L_one) """ L_one.append("That thing i wanna say im sorry") print(L_one) L_two.sort() print(L_two) """ L_two.pop() print(L_two) #copy function L_three=copy.copy(L_one) print(L_three) ...
d5d778155975f6745e5ad9ff11f4514d93eaf0a3
KayDeVC/Python-CeV
/MUNDO1/Ex011_Tinta.py
286
3.71875
4
print('=====QUANTO DE TINTA?=====') alt = float(input('Qual a altura da parede?')) lar = float(input('Qual a largura da parede?')) area = alt*lar print('A área da parede é de {:.2f}m²!'.format(area)) print('Serão necessários {} litros de tinta para pintar a parede'.format(area/2))
8f176823a4b9f9e79101917c32188ad7cf79d9c0
linhaidong/linux_program
/container_ssl/python_test/pytool-master/datastruct/finding-the-largest-or-smallest-N-items.py
1,005
3.75
4
# coding=utf-8 """ 查找最大或最小的N个元素 当N较小时,使用heapq:`nlargest()` & `nsmallest()` 当N较大时,先排序在切片:sorted(items)[:N] 当N为1时,使用`max()`,`min()` :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '1/4/16' import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] prin...
c496349d47ffe4489e92753343490bd041e5ddca
martijngastkemper/timeflip-client-python
/timed_input.py
1,645
3.984375
4
import asyncio import sys async def timed_input(prompt, timeout=0): """Wait for input from the user Note that user input is not available until the user pressed the enter or return key. Arguments: prompt - text that is used to prompt the users response timeout - the number of seconds ...
7fd318ff20ceff098aec23fd045fa819c540628e
HiDann0207/guess-num
/guess-num.py
489
3.671875
4
import random start = input("請決定隨機數字範圍開始值:") end = input ("請決定隨機數字範圍結束值:") start = int(start) end = int(end) r = random.randint(start, end) count = 0 while True: count += 1 # count = count + 1 number = input('請輸入數字: ') number = int(number) if number == r: print('猜了', count, "次,終於對了!") break elif number > r: ...
0f78db9b2eae11e2009ff4b533ce22fead2bc45e
KEClaytor/Euler
/Euler2.py
559
3.859375
4
# Sum the even values of the Fibonacci sequence # Consider only terms < 4*10^6 # Brute force method if __name__ == "__main__": # fmax = 90 # should give 44 fmax = 4000000 fibsum = 0 # The starting values # Note that the third is always even fa = 1 fb = 1 fc = 2 # print "Even term...
b1ec5ae38fd48986ffa6965e70f95c463db4b6e1
zack4114/Amazon-Questions
/PrintNodesWithNoSibling.py
758
4.09375
4
# Given a Binary Tree, print all nodes that don’t have a sibling (a sibling is a node that has same parent. # In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling. class Tree(object): def __init__(self,x): self.data = x self.left = None self.right = None...
f5c76d332a693a126689b75f36a486c7c719dd54
cianmcateer/Data_Final_CA
/part2.py
465
3.515625
4
from pymongo import MongoClient def extract_json(): try: """Connect to mongod""" client = MongoClient('localhost') except: print("Could not connect to mongo server") """Set database and collection we are going to extract from""" db = client.final_data students = db.students...
33993968f8279b4b433485b0330ac826cca3d24d
gary-hsu/ProA-Python
/ProA Python Exercises and Challenges/Exercise 3 - String concatenation/code.py
586
4.5
4
# In this section, we will combine multiple strings into a single string. From this point on, I will no longer be providing the print statements. example_string_1 = "EE58245" example_string_2 = "EE58310" example_string_3 = "EE58315" # 1. Take all three strings and combine them into a single string, separating e...
7b27cdb941007f198d86360d9d4d223886e442e8
supby/algo_train
/reverseLetter.py
2,106
3.78125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys def reverseWord(arr, start_i, end_i): i = start_i j = end_i while i < j: tmp = arr[i] arr[i] = arr[j] arr[j] = tmp i += 1 j -= 1 def isSpaceArr(arr): for ch in arr: if ch !...
f3f12024b48c74eefcec2a94847639fd8bb391d0
Shivampanwar/algo-ds
/Recursion/Replace Character Recursively.py
314
3.609375
4
import re def replaceChar(inval, old, new): if inval == '': return '' if inval[0] == old: return new + replaceChar(inval[1:], old, new) return inval[0] + replaceChar(inval[1:], old, new) print replaceChar('abac', 'a', 'x') s = "abbac" replaced = re.sub('a', 'x', s) print replaced
f9fd1561f833f6a402b149b40b1d0014c8ad460a
tmwitczak/iad-1
/src/NeuralGasAlgorithm.py
15,789
3.625
4
# /////////////////////////////////////////////////////////////////// Imports # import random import statistics from typing import List, Tuple import math import numpy from matplotlib import pyplot from src.file_reading import ClusteringData, DataMode, Vector, vector_from_list # ////////////////////////////////////...
fb1576aa961d8323fbbcfa1966a7994a49e76e9f
celestiel4562/github_exercise
/python課堂練習/1090608/01.開啟讀取csv檔案.py
875
3.5
4
""" import csv fn= with open("sample.csv",encoding="utf-8 sig") as csvFile: #開啟csv csvReader=csv.reader(csvFile) #讀取csv建立reader物件 listReport=list(csvReader) #將資料轉成list(串列) print(listReport) """ """ #當csv檔案的編碼為UTF-8 import csv fn=r"C:\Users\ASUS\Desktop\PYTHON\課堂練習\1090608\opendata106N0101.csv" #fn="C:\\User...
649619e67d24edb23908dd1763aa751139c766b3
Shree24/acadview
/assignment14.py
822
3.71875
4
# QUESTION 1 f=open("abc","r") a=(f.readlines()) # read lines of a file a.reverse() n=int(input("enter no. of lines")) for i in range(0,n): print(a[i]) f.close # END # QUESTION 2 d="python" f=open("abc","r") # COUNT FREQUENCY OF WORDS IN FILE b=f.read() c=b.split() e=...
d0f39c9b1707d72eef7b939840781558bd15d426
euanstirling/udemy_2021_complete_bootcamp
/my_work_python_2021/section_3_objects_and_data_structures/objects_and_data_structures.py
1,260
4.3125
4
#! OBJECTS AND DATA STRUCTURES # * Assigning a variable name # * use lower case and avoid keywords like list and str (editor will highlight a key word if used) # * You can reasign variables to different data types my_dogs = 2 my_dogs = ["sammy", "frankie"] #! You need to be aware of type() # a = 5 # a = 10 # a = a...
88477493f6568540fef7267ce5eccb0b355e04ef
whsqkaak/CodingTrainingStudy
/stackqueue/printer.py
628
3.734375
4
from collections import deque def solution(priorities, location): answer = 0 deque_priorities = deque(priorities) while len(deque_priorities) > 0: max_priority = max(deque_priorities) j = deque_priorities.popleft() location -= 1 if j < max_priority: ...
94dc9619ebdfb5326d30507b6890964630329da2
terpator/study
/Функции. Часть 1/dop_domashka_2.py
1,132
4.25
4
""" Число-палиндром с обеих сторон (справа налево и слева направо) читается одинаково. Самое большое число-палиндром, полученное умножением двух двузначных чисел: 9009 = 91 × 99. Найдите самый большой палиндром, полученный умножением двух трехзначных чисел. Выведите значение этого палиндрома и то, произведением ка...
84102e5ea4a6f57eb784f964a8d52207d969a126
Bharqgav/Qsamp
/Assignment Python/Even Indexes.py
251
4.09375
4
#Please write a program which accepts a string from #console and print the characters that have even indexes. import sys a = raw_input("Enter a string ") even = a[0] b = 2 for b in range(2,len(a)): if b%2 == 0: even = even+a[b] print even
8c84cbe6ab0ecd8d34d7f9d4459016e3a23678f4
YuliaFeldman/Mathematical-Logic
/predicates/semantics_test.py
4,945
3.71875
4
# (c) This file is part of the course # Mathematical Logic through Programming # by Gonczarowski and Nisan. # File name: predicates/semantics_test.py """Tests for the predicates.semantics module.""" from predicates.syntax import * from predicates.semantics import * def test_evaluate_term(debug=False): model = Mo...
4c1867d3871178ac6f950d47472aad1921d53254
vinaykumar7686/Algorithms
/Algorithms/Searching/Linear_Searching.py
741
3.984375
4
# Time Complexity: O(n) class Linear_Searching: def __init__(self): self.num=0 self.arr=[] def accept(self): n= int (input("Enter the size of array: ")) print('Enter the Array Elements') while n!=0: n-=1 self.arr.append(int(input())) self...
8ea704d521ced6591cc62573dcd8c62161e6f8d1
vicch/leetcode
/0100-0199/0125-valid-palindrome/0125-valid-palindrome-1.py
451
3.578125
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ # Filter out non-alphanumeric characters and lowercase all characters s = "".join(c.lower() for c in s if c.isalnum()) l = len(s) for i in range(l // 2): ...
fd6078e4dd76d3ad954006d545c63a36da1e0963
anirudhRowjee/pyray
/vector.py
3,032
4.28125
4
""" Vector Object Author: Anirudh Rowjee Data: 1. X, Y and Z Co-ordinates 2. Magnitude - square root of (X^2 + Y^2 + Z^2) 3. Normalize/Direction - Unit Vector in Direction of Vector Operations 1. Dot Product with Other Vector 2. Addition with other vector 3. Subtraction with other vectors 4....
df1baaaf7ffdb2bf5de4ac4522a33964ab84d6c9
madhavmurthy93/python-practice
/arrays/quick_sort.py
1,191
3.859375
4
def quicksort(a, left, right): if (left < right): medianof3pivot(a, left, right) pivot = partition(a, left, right - 1) quicksort(a, left, pivot - 1) quicksort(a, pivot + 1, right) def partition(a, left, right): pivot = a[right] i = left j = right - 1 while(i < j): ...
dc3f4e6235ddd4569e5d8eb9e337375d4cafc61a
Sangeethakarthikeyan/CS-2
/dataset_nsw.py
607
4.15625
4
import sys #prompt the user for a file name fname=input('Enter a file name: ') # open the file or print a message if the file doesnt exist try: fhand=open(fname) except: print('File cannot be opened',fname) sys.exit() # Loop for operating on each line of the file total=0 for line in fhand: field=line.split('|') ...
8aad5500d47c2af7c05737958af279bed59ca04c
Agent215/ScraperOnFlask
/testScrape.py
1,400
3.625
4
#Abraham Schultz #This is the test script for a proposed webscraper #The webscraper will try and scrape course requirements for temple CIS # get the request module and name it as uReq for future use from urllib.request import urlopen #get the beautifulSoup module and name as soup from bs4 import BeautifulSoup...
53115dfcd1ebfab20035ccfc14a7ce107dd26c98
bgoonz/UsefulResourceRepo2.0
/GIT-USERS/TOM-Lambda/CSEU3_Architecture_GP/src/day2/04-fileio03.py
1,041
3.53125
4
# lets parse some numbers # argv and argc take in command line args import sys if len(sys.argv) != 2: print("usage: 03-fileio02.py filename") sys.exit(1) try: with open(sys.argv[1]) as f: for line in f: # split line before and after comment symbol comment_split = line.split(...
3d02623057d8eccc316f42239e36b0587767d6a4
Prashant414/python
/qn 43.py
358
4.40625
4
# # Write a program to find the factorial value of any number entered through the keyboard. # def fact (n): # if n==0 or n==1: # return 1 # else: # return n*fact(n-1) # n=int(input("value of n")) # fact(n) # print(fact(n)) # n=3 fact=1 for i in range(n,0,-1): if n==0: fact=fact*1 ...
e0bf75533ca259480827cc08b32f9a12d9383185
sarveswara-rao/Object-oriented-programming-in-python
/first_class.py
395
4.0625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 11 06:49:14 2019 @author: sarveswara rao """ # to create a class, we have to use the class keyword class Dog: # constructer for the class def __init__(self, name, age): self.name = name self.age = age # instantiating the class to create a oz ...
2ef807c0fcb6d13ed4bfc3fbb66f4806beb3d145
onsare/oop
/oop.py
1,791
4.40625
4
#methods class Book(object): """Methods are basically functions within a class. The first definition of a method has to be a reference "self" to the instance of the class """ def __init__(self, name): self.name = name #constructor """ The __init__ keyword acts as a constructor in python Though strictly sp...
b862f7b11e1b928dc7edc00b93fca472dad44d7c
sharmarkara/Data-structure-Programs
/2 Matrix Programs/2 Spiral matrix.py
1,586
4.375
4
def spiralMatrixPrint(row, col, arr): # Defining the boundaries of the matrix. top = 0 bottom = row-1 left = 0 right = col - 1 # Defining the direction in which the array is to be traversed. dir = 0 while (top <= bottom and left <=right): if dir ==0: ...
ce8f97238f56c2460f6c5510f4dea0c1b425d17a
ramtiwary/week_1
/Matplotlib _Piechart.py
1,616
4.09375
4
#1.create a pie chart of the popularity of programming Languages. import matplotlib.pyplot as plt languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++' Popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7] colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"] explode = (0.1,0,0,0,0,0) plt.pie(Popu...
99fe4e60a3b8a73b5abc82e2c77e00219328b88d
tedyeung/Python-
/python_cc/dic.py
476
3.71875
4
# Dictiaries users = { 'first_name': 'Slvko', 'last_name': 'Popovic', 'age': 35, 'city': 'Pompano Beach' } print (users['first_name']) print (users['last_name']) print (users['age']) print (users['city']) print (users) # loop print('************ LOOP ************************************') for k...
c622c7e72d798aac098135f4bfea1ee8b25ec048
shehryarbajwa/Algorithms--Datastructures
/algoexpert/hatchways/adjacency_list.py
4,811
3.65625
4
import unittest class Graph: def __init__(self, vertices, is_directed=False): self.vertices = vertices self.adjacency_list = {} self.is_directed = is_directed for v in vertices: self.adjacency_list[v] = [] def add_edge(self, source, destination): self.adjac...
86f99b22e8c667d88ec683d830bc7d65d4758600
SouzaCadu/guppe
/Secao_10_Expressoes_Lambdas_Funcoes_Integradas/10_66_Sorted.py
2,091
4.4375
4
""" Sorted Não é igual ao atributo sort() que só funciona em listas. Sorted funciona com qualquer iterável. Não altera o elemento original, retorna um novo objeto Exemplos """ numeros = [9, 8, 7, 3, 4, 1, 0, 11, 10, 12, 5, 6, 2] print(numeros) print(sorted(numeros)) print(tuple(sorted(numeros))) print(set(sorte...
4dd3a1016033727b6de1ea9bd2a012cb2ee6f078
Nick-Mason/Combet-Tracker
/LargeCombat.py
1,104
3.609375
4
import random #"Trial change" rollAgain = "n" while 1: if rollAgain == "n": #name = raw_input("Enter Name: ") number = input("Number of Creatures in Attack Group: ") numAtk = input("Enter Number of Attacks per Unit: ") diceNum = input("Enter Number of Dice: ") diceSize =...
579c38a1e78624249eeff446ac9c0d644ffe3220
sidharth14/python
/dict_test3.py
808
3.953125
4
# Exercise 3: Write a program to read through a mail log, build a histogram using a dictionary # to count how many messages have come from each email address, and print the dictionary. inp = input('Enter the file name: ') try: opn = open(inp) except: print(inp,'file not found') exit() dic2=dict() for...
5d1fd37e094f03d635d7d06cf50e78beb73ff594
aromaljosephkm/Smart_Speed_Governor
/ultrasonic.py
506
3.5625
4
import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BOARD) GPIO_TRIGGER = 7 GPIO_ECHO = 12 GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) GPIO.output(GPIO_TRIGGER, True) time.sleep(0.0001) GPIO.output(GPIO_TRIGGER, False) while GPIO.input(GPIO_ECHO) == ...