blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
daaed12a62090bde0adc57ffd294c881a8e89685
soomark/Level_0_Chanllenges
/Task_0.7.py
631
4.3125
4
# Function to convert Celsius to Fahrenheit def celc(c): fahrenheit = 9/5 * c + 32 # Formula to convert Celsius to Fahrenheit return fahrenheit # Function to convert Fahrenheit to Celsius def fahr(f): celsius = (f - 32) * 5/9 # Formula to convert Celsius to Fahrenheit return celsius #...
9839b329fd5f3336a701e28fc0177d3965b1f1f7
joefrank03/UsaCovid2020-2021
/data_analysis/covid_compare_gender.py
2,337
3.515625
4
""" __author__ = 'Joseph Fernandez' Data Source: https://data.cdc.gov/NCHS/Provisional-COVID-19-Deaths-by-Sex-and-Age/9bhg-hcku/data """ import pandas as pd from matplotlib import pyplot as plt import os from datetime import datetime PLOTS_DATA_PATH = '../plots' if not os.path.exists(PLOTS_DATA_PATH): os.mkdir(PL...
b90782fd1fb60c011939818b7b112a274b64441b
adamkaragoshi/adamKaragoshi
/FizzBuzz.py
819
4.25
4
def fizz_buzz(number): while True: if "help" in number: print(""" You can check if your number is divisible by 3 and 5 (returns FizzBuzz), only 3 (returns Buzz), only 5 (returns Fizz) or by none (returns your starting number). """) ...
2b7c42e9e47ff9d96a4db4141e3975984c243480
manasikattel/computergraphics
/dda.py
2,088
3.578125
4
from tkinter import * import tkinter as tk def ROUND(a): return int(a + 0.5) def drawDDA(x1,y1,x2,y2): x,y = x1,y1 length = (x2-x1) if (x2-x1) > (y2-y1) else (y2-y1) dx = (x2-x1)/float(length) dy = (y2-y1)/float(length) print ('x = %s, y = %s' % (((ROUND(x),ROUND(y))))) for i in range(length): ...
dbf25f0908530b0a4e663274fd85bd37e3c7b1a1
MiJooJeong/birdview
/birdview/practice.py
728
3.765625
4
def print_star_tree(n): for i in range(1, n + 1): if i <= (n + 1) // 2: print((' ' * (-i + ((n + 1) // 2))) + ('*' * ((2 * i) - 1))) elif i > (n + 1) // 2: print((' ' * (i - ((n + 1) // 2))) + ('*' * (((2 * n) + 1) - (2 * i)))) def print_triangle(n): for i in range(1, n...
612bddc37a398ed3e014b666ed61f88be3dbfe8e
woo-nny/project_python
/KJW/Intermediate/8.Tree/이진탐색.py
586
3.578125
4
class Tree: def __init__(self,N): self.list = [0]*(N+1) #공간 형성 self.N = N self.cnt = 1 #노드의 수 self.numbering(1) #1번부터 넘버링 def numbering(self,num): if num <= N: self.numbering(num*2) self.list[num] = self.cnt self.cnt += 1 s...
73df24518c0d555a26686d00bf983c052eea579f
kranthy09/pythonpraccodes
/classes_objects.py
1,742
3.90625
4
class Human(object): def __init__(self, age = 0, nationality = "no nationality", locality = "no locality", *args, **kwargs): self.age = age self.nationality = nationality self.locality = locality def speak(self): print("Hello, my name is :", self.name) def set_location(self...
e362a0de8f1a4915519a4411e5a55b79f51b3f93
anvesh620/tutorial_tasks
/dict_kap_task.py
2,466
4
4
dict_a = {'A':'Hello', 'B': 'World', 'C': 'Buddy'} dict_b = {'A':'Hello', 'C': 'Buddy', 'D': 'Welcome'} expression = input() if (expression == "A and B"): # concate A and B c = ('A' in dict_a) and ('B' in dict_a) if (c): print(dict_a["A"],dict_a["B"]) elif (expression == "A and C")...
efea8782264529267f209e85793bf3dd2b8bfc18
Offstavo/python_hellomars
/oop.py
517
4.25
4
class Person(): def __init__(self, age, name):#self refers to the object itself self.f_name = name self.my_age = age person_one = Person(15,"John") person_two = Person(25,"Mary") person_three = Person(30,"Kate") print(f"The first person is called {person_one.f_name} and is aged {perso...
3ecb9e5c0134a6908390486a18f7be441e69becb
mochy-NRS/mochy-python
/main.py
408
3.5625
4
# coding: utf-8 #時間の入力 hours = [] #分の入力 minutes = [] def calc(): i = 0 day = 0 total_minute = 0 total_hour = 0 calc_minute = 0 a = int(len(minutes)) for i in range(a): total_minute += minutes[i] total_hour += hours[i] day += 1 calc_minute = total_minute / 60 total_hour += calc_minute ...
8831210a1bef86ff4f17f0257c68b735b125fbff
dchen3121/COptimism
/buttons.py
1,908
3.671875
4
''' Check button ''' from tkinter import Tk, Label, Button class Check: def __init__(self, master): self.master = master master.title("CHECK") self.label = Label(master, text="CHECK!", font="Helvetica, 20") self.label.pack(padx=5, pady=10) self.close_button = Button(mast...
be2e7d66b72d737eb0940f83b2be16dd7398b3d3
ebaek/Data-Structures-Algorithms
/LeetCode/reverse_polish_notation.py
1,078
3.578125
4
# 150: Evaluate Reverse Polish Notation class Solution: def evalRPN(self, tokens: List[str]) -> int: def eval(operations): operation = operations.pop() second = operations.pop() first = operations.pop() if operation == "+": return int(first...
a21bd632b4381465921ac33e813adc8ec947658f
ebaek/Data-Structures-Algorithms
/LeetCode/ugly_number.py
987
4.15625
4
# 263: Ugly Number # Write a program to check whether a given number is an ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # Example 1: # Input: 6 # Output: true # Explanation: 6 = 2 × 3 # Example 2: # Input: 8 # Output: true # Explanation: 8 = 2 × 2 × 2 # Example 3: # Inp...
14ce0d541635e89eaea075697e0dde9663de1052
ebaek/Data-Structures-Algorithms
/LeetCode/queue_using_stacks.py
659
3.953125
4
# 232: Implement Queue using Stacks class MyQueue: def __init__(self): self.stack = [] self.stackQueue = [] def push(self, x: int) -> None: self.stack.push(x) def pop(self) -> int: while len(self.stack) > 0: self.stackQueue.append(self.stack.pop()) ...
9ed190777e99ab52701ff4ced673b72358765acc
ebaek/Data-Structures-Algorithms
/LeetCode/move_zeroes.py
744
4.03125
4
# 283: Move Zeroes # Given an array nums, write a function to move all 0's to the end of it # while maintaining the relative order of the non-zero elements. # You must do this in-place without making a copy of the array. # Minimize the total number of operations. # Example: # Input: [0,1,0,3,12] # Output: [1,3,12,...
7f0285ca799ec4953ac69ebff1d761b92b591906
ebaek/Data-Structures-Algorithms
/LeetCode/word_break.py
1,406
3.8125
4
# 139: Word Break # Recursive Approach: # BASE CASE # if s is an empty string, return True # RECURSIVE STEP # convert wordDict into set for O(1) look up time # check if word exists in the set starts at 0 -> idx, if exists than recursively call wordBreak # with a string from s[idx:] # -> if this returns True, ret...
46cd0350ab354b3f712cbf0dfa25cd577f23febc
ebaek/Data-Structures-Algorithms
/LeetCode/filing_bookshelves.py
1,386
3.5625
4
#1105: Filling Bookcase Shelves class Solution: def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int: def dfs(book_idx, shelf_height, shelf_remaining): if shelf_remaining < 0: return float('inf') if book_idx == len(books): return shelf_height b...
7eecc24408faccb3ede351e73c53c481495ae86b
ebaek/Data-Structures-Algorithms
/Mocks/9-21-19.py
4,223
4.09375
4
# Given two lists of strings as input, for example # a: List[str] = ['hello', 'dad', 'orange', ...] # b: List[str] = ['jeff', ...] # write a function that determines if the intersection # of these two lists is the empty set, i.e. there are no # words in common # find the list with the most words in it # iterate thr...
b9cab4180739fe5d5f01f647e62c54d473c7df8e
ebaek/Data-Structures-Algorithms
/LeetCode/reverse_linked_list_ii.py
706
3.9375
4
# 92: Reverse Linked List II # Approach: very similar to reversed linked list 1 but keep track of start, end, prev, curr class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: dummy = ListNode(0) dummy.next = head start = dummy for _ in rang...
95a751e6ae45f13bc054804d7e50facba1aaa410
ebaek/Data-Structures-Algorithms
/LeetCode/maximum_subarray.py
808
3.890625
4
# 53: Maximum Subarray # Given an integer array nums, find the contiguous subarray # (containing at least one number) which has the largest sum # and return its sum. # Example: # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. # Follow up: # If you have figured out t...
7651f625b254536b0b3b4f49e0617f176d71be58
Bumskee/Week-5-Assignment
/Problem5.py
426
4.375
4
#Write a Python program to create Fibonacci series upto n using Lambda def fibseq(count): if count <= 0: sequence = "nothing" elif count == 1: sequence = [0] else: sequence = [0, 1] any(map(lambda _: sequence.append(sum(sequence[-2:])), range(2, count))) return sequence...
23f81d0bbe82051d7d321c6ce4710954004de6ac
ramonaghilea/Graph-Algorithms
/Project Graph Algorithms/MaximumCliqueBronKebosch.py
2,866
3.59375
4
from Graph import Graph def BronKebosch(graph, temporaryResult, candidates, excludedSet, maximumClique): ''' Finds the clique of maximum size in the graph. input: - undirected graph - lists temporaryResult, candidates, excludedSet, maximumClique output: - ''' if len(can...
ff95f127b15ed14061e39e280bc71a7e07bee230
franckboudraa/harvard-cs50
/pset6/mario/less/mario.py
570
4.34375
4
# https://docs.cs50.net/2019/x/psets/6/sentimental/mario/less/mario.html # Implement a program that prints out a half-pyramid of a specified height. import cs50 # initializing var for user input height = "" # prompt the user for number between 1 and 8 while height.isdigit() == False or int(height) < 1 or int(height)...
d66543c128716a41321e6917af2d92aa1d810528
arian-picco/automation-training-python
/Class 2 - 2 assigment/assigment2.py
504
3.6875
4
clientes = int(input('ingrese el numero de clientes ')) for i in range(clientes): print(i) edad = 0 while edad <=1 and edad <=120: edad = int(input('Digame su edad ')) if edad<18: condicionEdad = 'menor' print(condicionEdad) elif edad>18: conficionEdad = 'mayor' ...
77f7fe694cec267e77e8280a08c77b7862d7a818
owari-taro/concurrency_in_python
/mastering_concurrency/ch16/ex2.py
1,575
3.859375
4
import threading import time class LockedCounter: def __init__(self): self.value = 0 self.lock = threading.Lock() def increment(self, x): with self.lock: new_value = self.value+x time.sleep(0.01) self.value = new_value def get_value(self): ...
866f158f6d24a54cc2e0c3eecd64f671b4a5e18e
owari-taro/concurrency_in_python
/concurrency_with_asyncio/ch8/strem_read_write.py
933
3.53125
4
import asyncio from asyncio import StreamReader from typing import AsyncGenerator async def read_until_empty(stream_reader:StreamReader)->AsyncGenerator: count=0 while response:=await stream_reader.readline(): count+=1 print(count) yield response.decode() async def main(): host="ww...
a422ee6e0118c263e9b7d39ff53208607908c09d
SpencerOs/AStarFrogger
/toolbox.py
2,432
3.625
4
# toolbox.py # Author: Spencer Ollila # Where the tools are kept import heapq # This class was based off of the priority queue # found in the util.py file we received in our homeworks class priority_queue: def __init__(self): self.heap = [] self.count = 0 def __len__(self): return...
1a667a32555a86328a66c6218644830ade3ce709
anisov/python_simple_scripts
/threading_scripts/thread.py
704
3.609375
4
from tkinter import * import threading root = Tk() root.title("Многопоточная программа") e = Entry(root, width=17) e.grid(row=1, column=1, padx=(1, 1)) def writer(filename, n): with open(filename, "w") as file: for i in range(n): file.write(str(e.get()) + "\n") def run_tread(): t1 = th...
939de59a0a5bb0cdc60a7751282f05a3d18fad55
ATLS1300/pc02-graffiti-12-wilson-seet
/PC02_Graffiti_SEET.py
1,254
3.703125
4
#!/usr/bin/env python # coding: utf-8 ''' Turtle starter code ATLS 1300 Author: Dr. Z Author: Wilson Seet September 4, 2020 ''' from turtle import * #import the library of commands that you'd like to use colormode(255) # Create a panel to draw on. panel = Screen() w = 750 # width of panel h = 750 # height of pane...
e227d680444102d24cccedd0d29611a2b088ffaf
nikunjbadjatya/design_patterns
/strategy/strategy.py
651
3.5
4
class Fly(object): def fly(self): raise NotImplementedError class CantFly(Fly): def fly(self): print("Cant fly") class ItFlys(Fly): def fly(self): print("Flying high") class Animal(object): def set_flying_ability(self, fly_type): self.flying_type = fly_type def try_to_fly(self): self....
50bf7191c9aa8716e1ef0f67fb835702068c14ed
pratik-chaudhari-883/problem-statments-on-python
/prog4.py
279
4.09375
4
#Accept one number from user and print that number of * on screen. def PrintStar(iNo): while iNo!=0: print("*") iNo=iNo-1 def main(): print("Enter any Number...") iValue=int(input()) PrintStar(iValue) if __name__=="__main__": main()
a43ba8e74d51fe156ef5c799a3dd662297508db0
pratik-chaudhari-883/problem-statments-on-python
/prog9.py
452
4.0625
4
#Accept number from user and check whether number is even or #odd. def CheckEvenOdd(iNo): if iNo<0: #Updater iNo=-iNo A=True if (iNo%2==0): return A else: A=False return A def main(): print("Enter any Number...") iValue=int(input()) bRet=True bRet=...
5d3b3739cc485adc0fd38545f110351efc09d2ad
lizasolomyannik/NLPpractice_2
/p2.py
3,429
3.640625
4
import nltk # Python library for NLP from nltk.corpus import twitter_samples # sample Twitter dataset from NLTK import matplotlib.pyplot as plt # visualization library import numpy as np # library for scientific computing and matrix operations # download the stopwo...
b376e4e51fd791928961dc7f0eb52c0703321f5d
DanDHirst/Coding-challenges
/collatz.py
540
3.890625
4
import time start = time.time() length = 0 longestNum = 0 longestlength = 0 for tempnum in range(1,1000001): length = 0 i=tempnum while i != 1: if(i % 2==0): i =i/2 length +=1 elif(i%2!=0): i = (i*3) +1 length +=1 if lengt...
5a322c7e7a2174c446056ace2aae4301e0553e6d
kaveen27/kalyan_project-
/calculator.py
422
4.1875
4
#def add(a,b): # print(a+b) while True: a=int(input("enter the no :")) b=int(input("enter the no :")) c=input("enter the values for calculation ,+,-,*,/: ") if c=="+": print(a+b) elif c=="-": print(a-b) elif c=="/": print(a/b) eli...
612f7f8eeaae7cfe9d2515c82724ad50e87ac527
TraductoresSeccion1/clase1
/primera_clase.py
335
3.953125
4
opc = 's' while opc == 's': num1 = input('ingrese num1: ') num2 = input('ingrese num2: ') operacion = raw_input('1: suma, 2: resta ') if operacion == '1': print num1 + num2 elif operacion == '2': print num1 - num2 else: print "opcion invalida" opc = raw_input('volver...
906baa28d18ec1b57d8e91629c1d943494d43118
mocan2000/Final-Year-Project
/FinalYearProject/Twitter_Stream.py
3,016
3.828125
4
import tweepy import json import sqlite3 import apiConfig # Twitter authentication stuff global api # API keys are stored in a separate file access_token = apiConfig.access_token access_token_secret = apiConfig.access_token_secret consumer_key = apiConfig.consumer_key consumer_secret = apiConfig.consumer_se...
2dbf17eff0baacf1917e576ec9abf6526ff3da18
AkinJimoh/pythonBasics
/100daysofcode/days/day-1.py
1,689
4.59375
5
#100DaysOfCode #Day-1 #Write a program that prints the following #Day 1 - Python Print Function #The function is declared like this: #print('what to print') # print("""Day 1 - Python Print Function # The function is declared like this: # print('what to print')""") # print("Day 1 - Python Print Function") # print("Th...
78f79c54ed6324692023c5fea641f534bd6a5dda
adnandossaji/interview_app
/active_interview.py
1,682
3.8125
4
import question import answer import interview # an object that consists of an Interview object and a dictionary consisting of key value pair's, (QuestionNumber,Question) # object can store and return a list of Answers, Answers can be stored one at a time with putAnswer() # a list of questions may be submitt...
b2f5e8c17ff37eed01a508322456e5165c4ce19d
BenLehmann12/Final
/FinalGame.py
2,772
4
4
import tkinter as tk import random ''' Author: Ben Lehmann Project: Rock Paper Scissors - We have multiple methods - computer_selection(self): this will return a random value, from the list of rock, paper, scissors - def test(self,input): this will return whether you have beaten the computer or have ti...
f05a9855057a62fb2f4633c0d76b811dfedd9e40
mukhamedzarifovakf/mukhamedzarifova
/Prac13/matrix.py
3,153
3.671875
4
class Matrix: def __init__(self, m, n = None): if isinstance(m, int): if not isinstance(n, int): raise ValueError() if n <= 0 or m <= 0: raise ValueError() self.m = m self.n = n self.matrix = [[0] * n for i in range(...
da7713fc14eec7de60779e55a6e86bd6ef22d5e3
mukhamedzarifovakf/mukhamedzarifova
/Prac16/calculator.py
859
3.546875
4
import argparse import sys parser = argparse.ArgumentParser( description = 'Calculator' ) parser.add_argument( 'values', metavar = 'VALUES', type = float, nargs = 2, help = 'input values' ) parser.add_argument( '-a', '--action', metavar = 'ACTION', required = 'True', action = 'store', help = 'action ...
1014f4648eeca0dbcacc099ebcc3027652221f3b
frankShih/TimeSeriesVectorization
/vectorization/dataTransformation.py
8,865
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed May 27 16:53:12 2015 @author: shih """ #import csv import numpy, math, time import matplotlib.pyplot as plt #--------transform x-y series to series of x_speed, y_speed, speed--------- def movingaverage(series, window_size): window = numpy.ones(int(wind...
d341556b26c37005821981468c3d79217468583a
meysam81/small-library-project
/small-library.py
5,934
3.90625
4
class books: def __init__(self): self.bookList = {} def readBooks(self, fileLocation): bookFile = 0 try: bookFile = open(fileLocation) except: print("Can't open file") return False for i in bookFile: j = i.strip("\r\n").stri...
14441355aaca36b4c6c772c2fb52dea7fbc9e0fc
ekta1007/Hello-world
/Quick_hacks.py
771
3.8125
4
#Reading an array backward using list comprehension [num-(i+1) for i in range(0,num)] # Initializing a list of alphabets from string import ascii_letters ascii_letters #Alternative methods to initize an array of chars map(chr, range(97, 123)) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', '...
e9d4d944765a8be418e8b99927f2fe29457be161
MatheusOliveiraIII/exercicios-python
/estrutura-sequencial/ex9.py
144
3.84375
4
tc = float(input('Informe a temperatura em ºC: ')) tf = ((tc*(9/5))+32) print('A temperatura de {} ºC corresponde a {} ºF!'.format(tc, tf))
634926732636e14be5268961fd96ffbbf005c94f
bo-yang/robotics_exercises
/diff_drive.py
1,165
3.5
4
import numpy as np def diffdrive(x, y, theta, v_l, v_r, t, l): """ Implement the forward kinematics for the differential drive. x, y, theta is the pose of the robot. v_l and v_r are the speed of the left and right wheels. t is the driving time. l is the distance between the wheels....
7390cc3933e9ebb451ddf55a4eeac985324a4ef5
bowenkj/Python_DataStruc-Algo
/Google OA/StoreAndHouse.py
1,372
3.9375
4
""" Given two arrays of integers representing the location of stores&houses, output the nearest store for all the houses. If two stores share the nearest distance, choose the left one. For example: stores = [3,5] houses = [6,2,4] stores = [1,4,6,8,10] houses = [2,5,8,9,12] """ class Solution(object): def nearest...
f4fce1b9e61886cd3004779c78848d0d47e7b053
bowenkj/Python_DataStruc-Algo
/SearchinRotatedSortedArray/search_in_rotated_sorted_array.py
1,548
3.6875
4
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not len(nums): return -1 start, end = 0, len(nums) - 1 while start + 1 < end: # make sure that there are at least three ...
5a5295467168b19e6ec3f4270978d9c3ad3f24e5
bowenkj/Python_DataStruc-Algo
/ConnectingGraph/connecting_graph_iii.py
916
3.546875
4
class ConnectingGraph3: """ @param a: An integer @param b: An integer @return: nothing """ def __init__(self, n): self.father = {} self.setNum = n for i in range(1, n + 1): self.father[i] = i def connect(self, a, b): bigBroa = self.findBigbro(a) ...
7e6dd47d1687e0b77de4959c07a43e65fd1c1a25
uca-00121117/Analisis_numerico
/Guia/Newton Ejercicio#7.py
438
3.765625
4
from math import * def f(z): return z**3 -2*z + 2 def df(z): return 3*z**2 - 2 def newton(p0, TOL, Nmax): for i in range(0, Nmax): p = p0 - f(p0)/df(p0) print(str(i) + " \n " + str(p0) + " \n " + str(p) + " \n " + str(abs(p-p0))) ...
e78ee5d816cba6204b1858ceb1bf4bf542fc9259
JaydevSR/numeric-matrix-processor
/matrix-processor/menu.py
1,497
4.0625
4
from matrix import Matrix def menu(): print("""Choices: 1. Add matrices 2. Multiply matrix by a constant 3. Multiply matrices 4. Transpose matrix 5. Calculate a determinant 6. Inverse matrix 0. Exit""") choice = input("Your cho...
c337cd88f281cb9c96b8cdc9230a179bde6eeccf
MasMat2/Games
/Algorithms/minimax.py
3,761
3.796875
4
import time, copy board = [[" " for j in range(3)] for i in range(3)] def draw_board(board): print(' 1 2 3') for line in range(3): if line != 0: print('----------') for value in range(3): if value == 0: print(line+1, end=' ') print(boar...
56fc56712e5738346cd58201901aa4a9f573f3a4
iamsathishsatz/feature_engineering_project
/q03_skewness_log/build.py
693
3.5625
4
from scipy.stats import skew import pandas as pd import numpy as np data = pd.read_csv('data/train.csv') # Write code here: def skewness_log(df) : skewGr1 = skew(df['GrLivArea']) # print df['GrLivArea'] # print('Before :',skewGr1) df_trans=df.copy() df_trans['GrLivArea'] = np.log(df_trans['GrLiv...
924be26c818d531ec4d55561901d1edeef2a0e43
Augmented-Library/Augmented-Library
/21_Spring/AStarNewVersions/a_star.py
14,903
3.796875
4
import copy # Nodes represent a location class Node: def __init__(self, name,x,y): self.name = name self.child_array = [] self.x = x self.y = y def __eq__(self, other): return self.name == other.get_name() def get_coord(self): return (self.x , self.y) ...
b53075a1f9f8827a4b4564b2fe0a9151f88a753f
Tomasz-Kluczkowski/Coding_exercises
/Quadratic-Generator/quadratic_gen.py
707
3.953125
4
def quadratic_gen(a, b, c, start=0, step=1): """Yields result of a quadratic equation y = ax^2 + bx + c. Starting point for calculation is start and the interval is step. Parameters ---------- a : float Parameter of the equation. b : float Parameter of the equation. c :...
ce2544cc917c87bf75dfa4d127485e4a85f27171
Tomasz-Kluczkowski/Coding_exercises
/Give-me-a-diamond/diamond.py
697
3.828125
4
def diamond(n): """Display a diamond made of *. Args: n: (int) Amount of *s in the middle row. Returns: Diamond shaped text. None if input n is invalid. """ if n <= 0 or n % 2 == 0: return None offset = int((n - 1)/2) # for i in range(offset + 1): # shap...
773d5078fcadf58f54b4690c114626c25fa736b2
Tomasz-Kluczkowski/Coding_exercises
/Arithmetic-Progression-Missing-Item/find_missing_item.py
371
4.3125
4
def find_missing(ar_prog): """Finds missing item in the arithmetic progression.""" # The sum of terms of arithmetic progression is: # S = n*(a1 + an)/2 # where in our case since 1 item is missing n = len(ar_prog) +1 sum_complete = (len(ar_prog) + 1)*(ar_prog[0] + ar_prog[-1])/2 sum_current = s...
0078e69b9ad4c35a04b0f389a2637ed3b6911cab
wenlarry/VisualizationPython
/world_pop.py
3,696
3.921875
4
# Mapping global Data Sets: JSON Format # Download the file 'population_data.json' from # http://data.okfn.org # Import json to load the data properly and store # the data in pop_data # The json.load() function converts the data into # a format that Python can work with. # Loop through each item in pop...
b4f98885fcb49bdf29a1111cc32baa4a2080bedc
wenlarry/VisualizationPython
/dice_visual.py
1,094
3.640625
4
# Rolling Two Dice # Calculate the sum of 2 dice or each roll; the largest possible # result(12), that we store in max_result # When we analyze the results, we count the number of results for # each value btw 2 and max_result # This code simulate rolling a pair of dice with any number of # sides imp...
93c0600588edb58ff5fdd204a059ad306e913b8b
Kamil-Ru/Coffee_Machine-OOP
/main.py
650
3.515625
4
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine money_machine = MoneyMachine() machine = CoffeeMaker() menu_coffee = Menu() while True: user_choice = input(f"What would you like? {menu_coffee.get_items()}: ") if user_choice == "q": break ...
8743269cc79ff5e708be01eb8da6213e01664541
TylerJGabb/MATH475A
/Homework/SEM1/05/source/cubicSplines.py
3,422
3.765625
4
''' Program cubicSplines.py Author: Tyler Gabb MATH475A This program takes in a .dat or .csv file as input, parses the data points and generates a cubic spline between them. This is then output as a .png file ''' import sys import os import numpy as np from numpy.linalg import inv from numpy import dot import matplotl...
24b2becc1bfa7abdad9d15df41a9672b715f546b
TylerJGabb/MATH475A
/Homework/SEM1/02/source/problem1.py
2,129
4.21875
4
import matplotlib.pyplot as plt import math as M import sys #VAL = int(sys.argv[1]); ITERS = 200#int(sys.argv[2]); def main(): """ The main Function """ if len(sys.argv) < 3: print("Usage: python3 problem1.py POWER ITERATIONS") exit(1) x = plt.figure(1) plt.plot(algo1(VAL),'r-...
cc32d86098c2ea60bc3c670381f2308010b64330
dmrhmt/Some-of-Scikit-learn-Algorithms
/Bölüm 2/Class-Fonk-ListeYapisi.py
221
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 29 16:34:01 2020 @author: demir """ class insan: boy = 160 def kosmak(self, b): return b+10 ali = insan(); print(ali.boy) print(ali.kosmak(50)) l = [1,2,3]
ef889298c22b6221ce7f025f768b00262ca2e26e
beratbora/algo_visualize
/src/Insertion_sort.py
634
4.09375
4
my_list = [6, 4, 2, 3, 5] def insertion_sort(my_list): every_pos = [] n = len(my_list) for i in range(1,n): cvalue = my_list[i] position = i while position > 0 and my_list[position-1] > cvalue: my_list[position] = my_list[position-1] position -= 1 ...
db776a350d75964422cddcfb74d470bb8aed579e
BoaTheCrafter/Python-lernen
/Spam.py
498
3.578125
4
from random import shuffle liste = "amazing exciting gorgeous blazing stunning biggest tremendous greatest best fantastic \ phenomenal delightful ambitious outstanding massive incredible spectacular magical".upper().split() shuffle(liste) for Strophe in range(5): for n in range(2): for i in r...
f3b3c706d0b4a32d0dd61a690431679f73af6fdb
cole-k/advent-of-code-2017
/24.py
1,191
3.71875
4
import sys def part_one(connecting_value, ports): valid_ports = (port for port in ports if connecting_value in port) max_length = 0 for a, b in valid_ports: next_value = None if a == connecting_value: next_value = b else: next_value = a next_len...
bbbe3eab528e66dbaf7db8f640923072d2c159e6
hanabeast/CIT590-homework
/HW4/movie_trivia.py
22,147
3.953125
4
#movie_trivia.py #Xu He, Yilun Fu import csv def create_actors_DB(actor_file): '''Create a dictionary keyed on actors from a text file''' f = open(actor_file) movieInfo = {} for line in f: line = line.rstrip().lstrip() actorAndMovies = line.split(',') actor = actorAndMovies[0] ...
8f7f98179709ac6f2a4029e69444af0f1bbc3998
ReadMyCourseOfficial/PythonForBeginnersStudyMaterials
/codes/Day7/tuple_example.py
176
3.796875
4
list_example=[1,2,3,4] list_example[2]=5 print(list_example) tuple_example=(1,2,3,4,3) #tuple_example[2]=5 print(tuple_example.count(3)) print(tuple_example.index(3))
cfe05e3f617f881ba5a60f31d92d263eafa4a526
ReadMyCourseOfficial/PythonForBeginnersStudyMaterials
/codes/Day3/string_example.py
665
3.921875
4
# #stores messages,texts # name="ReadMyCourse" # print(name) # print(type(name)) # #addition or concatination of two strings # first_name="Anand" # last_name="Kumar" # name=first_name+last_name # print(name) # name=first_name+" "+last_name # print(name) # name=2 # name="Anand" # print(name) #strin...
15fe842d8c321b8f2749e1e0ec593c37d06b5ce2
siketh/udacity-logs-analysis-project
/psql_db.py
2,620
3.921875
4
#!/usr/bin/env python3 """This module simplifies access to a PostgreSQL database.""" import psycopg2 from logs_analysis_exceptions import PrintException, PsqlDbException from psycopg2.extras import DictCursor class PsqlDb: """PsqlDb provides convenient wrapper functions for psycopg2. Upon instantiation, a da...
81bd7cb5410ecab82f1f481ded6fe524c0344836
archanasreekumar/greedy_dynamic_algo
/huffman_greedy.py
1,419
4.03125
4
#command to run the program #python2 filename.py from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): """Huffman encode the given dict mapping symbols to weights/frequency""" heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] #print heap heapi...
5aabec94f4df81af8ba362e88a4af99ef425ba16
xypisces/Example
/python/highfn.py
791
3.65625
4
# __slots__ 用于限制类的属性,但是对继承的子类没有效果 class Student(object): __slots__ = ('name', 'age') # Python内置的@property装饰器就是负责把一个方法变成属性调用的 class Students(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must...
89af09846aec0fa4676852a7c21bacea5f2412c2
TewariSagar/Python
/listMethods.py
1,272
4.28125
4
#max() minimum() functions in a list list = ["cisco", "HP", 10,10.5,-11] print min(list) print max(list) #python always considers strings to be maximum than numbers print max(1,"a") #add the element to the end of the list list.append(100) print list #del function removes the index at the specified index del list...
502bdf8d8e1a34c155b4520b8aa2ef8fcc84b2c0
TewariSagar/Python
/exception.py
764
4.15625
4
#this doc is about exception handling #we have a try block with 1 level of inendation where we put code we believe cam raise an error #except block is like the catch block in JAVA. if our except code is not the correct way to handle exception, out code wont work for i in range(10): try: print i / 0 except ZeroDiv...
c621529a4652c823842ab42727d7526da792f493
outrageousaman/Python_study_marerial
/Emp.py
1,714
4.15625
4
class Employee(object): """ base class for all employees """ Empcount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.Empcount +=1 def display_count(self): print("the number of employees is ",Employee.Empcount) def disp...
a0c883636729e955b162a6d16891a48e2c06e3b3
outrageousaman/Python_study_marerial
/pd/df2.py
673
3.59375
4
# df functionality import pandas as pd import numpy as np # Create a Dictionary of series d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']), 'Age':pd.Series([25,26,25,23,30,29,23]), 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])} # Create a DataFrame df = pd.DataFrame(d) print...
cacf462e2a53b366536e441b2ecce9c2a240615a
outrageousaman/Python_study_marerial
/pd/df.py
1,577
4.03125
4
# Dataframe is 2 dimensional data structure stores data in tabular format, i.e Rows and columns import pandas as pd import numpy as np # create dataframe from a list l = ['aman', 'raman', 'kamal'] df1 = pd.DataFrame(data=l, columns=['name']) print(df1) l2 = [22,20,23] df2 = pd.DataFrame(data=zip(l,l2), columns=['nam...
a44adc36994b1926a42d7d25f01c29f21fe82694
outrageousaman/Python_study_marerial
/pd/options.py
1,529
3.78125
4
# pandas options # pandas provides the api to change some aspects of its behaviour # the api is composed of 5 relavent options # get_option # set_option # reset_option # describe_option # option_context # get_option takes a single parameter and returns the value as given in the output below import pandas as pd prin...
5b2b452ffe003fc343c1574199fe7684c415864a
cooneyro/python-basics
/Adventure.py
2,720
4.15625
4
# Adventure game # User moves through rooms by inputting text to indicate # direction they wish to move # Each room has a description and is connected to 1+ other rooms # Game tracks direction user is facing and adjusts information # printed accordingly # Describing room connections in format # [ (Name), North, East, ...
d3ac3248e4f478446697d2c6fc00a1eadbcfd100
joshuaSmith2021/codewars2021
/jaden/12.py
654
4.125
4
#!/usr/bin/env python contraption, speed, unit_distance, _, unit_time = input().split() distance_conv = { "MILES": 5280 / 3.28, "YARDS": 3 / 3.28, "FEET": 1 / 3.28, "INCHES": 1 / 12 / 3.28, "KILOMETERS": 1000, "METERS": 1, "CENTIMETERS": 1 / 100 } time_conv = { "HOUR": 1 / 60 / 60, "MINUTE": 1 / 60, "SECON...
0bec824d29a4de2916888530b9c76dcf5a477616
seok0813/study
/시퀀스.py
630
3.921875
4
# 시퀀스(Sequence) : 문자열, 리스트, 튜플등의 인덱스를 가지는 자료형 string1="Hello World" list=['H','e','l','l','o',' ','w','o','r','l','d'] tuple=['H','e','l','l','o',' ','w','o','r','l','d'] print(string1[0:5]) print(list[0:5]) print(tuple[0:5]) # 반복문 등에서 사용될 수있음 list1=[1,2,3,4,5] print(5 in list1) print(6 in list1) if 3 ...
c8e58f4ba9fa363895644804383c73f21c935413
SeungHyun-Song/TIL
/StartCamp/day_1/lotto.py
390
3.515625
4
# import 문은 스크립트 파일 최상단에 위치한다. import random # 1~45번 숫자 만들어서 저장하기 numbers = range(1, 46) #range를 쓸 때는 범위를 마지막 숫자보다 1 크게 # print(numbers) # numbers에서 6개 숫자 뽑아서 저장하기 lucky_numbers = random.sample(numbers, 6) print(sorted(lucky_numbers)) #sorted : 숫자들을 순서대로 정렬
0bc185dd486406666f8b9489cec265704a137609
fucilazo/Dragunov
/CodeWar/019 6kyu-Build Tower Advanced.py
1,168
4.375
4
"""Build Tower by the following given arguments: number of floors (integer and always greater than 0) block size (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as * Python: return a list; JavaScript: returns an Array; Have fun! for example, a tower of 3 floors with bloc...
197a602f1562698151ffece070346ffcf016be30
fucilazo/Dragunov
/CodeWar/009 Good vs Evil___ 数组相乘, lambda, zip, map, for语句.py
3,168
4.125
4
"""Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil. Different races will certainly be involved. Each race has a certain worth when battling against others. On the side of good we have the following races, with their associated worth: Hobbits: 1 Men: 2 Elves: 3 Dwar...
c846045eaaa09109d2946d5e16400eb11b65241f
fucilazo/Dragunov
/斐波那契数列.py
281
3.625
4
#黄金分割比 def fun(x): if x == 1: return 1 elif x == 2: return 1 else: return fun(x-1)+fun(x-2) x = int(input("请输入斐波那契数列中组数:")) print("该组的值为:%d"%fun(x)) print("分割比为:%f"%((fun(x-1))/(fun(x))))
14111b248d8bfe52c794fd4be38bc5e42811eb0c
baubrun/Grade_Book
/Simple Grade Book/simple_grade_book.py
785
3.859375
4
gradebook = {} def add_student(student): gradebook[student] = [] def add_grade(student, grade): try: gradebook[student].append(grade) except KeyError: return f"'{student}' not enrolled" def get_grade(student): return gradebook.get(student) def grade_average(grade): r...
405105365efd3af8008a612450ffc9dc38811bc6
mbyrd27/python-challenge
/PyBank/main.py
2,152
3.984375
4
#import necessary modules import os import csv #save path to csv file in a variable raw_data = os.path.join("raw_data", "budget_data.csv") #open the csv file and create a reader object with open(raw_data, newline = '') as f: reader = csv.reader(f, delimiter = ',') #iterate the reader once to ignore the csv he...
b6610f20198d9767004d80e489b186545a10ea34
YohansN/CodigoMorse
/codMorse.py
1,465
4.0625
4
#Mensagem em código Morse #Para que o código funcione a posição das letras da lista morse devem corresponder a posição das letras da lista Alfabeto! morse = [".- ","-... ","-,-, ","-.. ",". ","..-. ","--. ",".... ",".. ",".--- ","-.- ",\ ".-.. ","-- ","-. ","--- ",".--. ","--.- ",".-. ","... ","- ","..- ","...- ",...
84e81b3b94d30444e6ba847712c56f1ef0019f95
AbhiniveshP/DP-1
/MinCoins.py
1,602
3.65625
4
class MinCoins(object): ''' Solution: 1. Problem can be solved using recursion and has overlapping subproblems and so use dynamic programming. Recursive step would be based on whether the coin is chosen or not. 2. If coin is not chosen, the value of the cell would be previous row's extract, othe...
71a56b6c541c371527e53bd642f33aeaf96b5736
Rajputsagar/python-programming
/24 armstrong between range.py
241
3.796875
4
a = int(input("enter lower range:")) b = int(input("enter upper range:")) for num in range(a, b+1): temp = num sum = 0 n = temp % 10 sum = sum + n**3 temp = temp // 10 if num == sum: print(num)
031198009cae0b8c4321cab86c8315a78ec4a7aa
Rajputsagar/python-programming
/13 greatest of 3 no.py
244
4.15625
4
a = int(input("first number: ")) b = int(input("second number: ")) c = int(input("third number: ")) if(a>b and a>c): print("a is greater") elif(a<b and b>c): print("b is greater") elif(a<c and b<c): print("c is greater")
a58de0f4717d50a5ca8676000c3fa563f86c45b2
ar95314/codekata_hun
/camel_check.py
70
3.515625
4
s=input() x=s.title() if s==x: print("yes") else: print("no")
e2484f5eb6e1df39326bc1e6f294ec2e8ab22b9e
ar95314/codekata_hun
/palin.py
68
3.65625
4
s=input() x=s[::-1] if s==x: print("YES") else: print("NO")
847c3c16609794b223597be9b94a17357ea15e0c
ascott1043/data_structures
/graph.py
2,106
3.921875
4
class Graph: def __init__(self, edges): self.edges = edges self.graph_dict = {} for start, end in self.edges: if start in self.graph_dict: self.graph_dict[start].append(end) else: self.graph_dict[start] = [end] def get_paths(se...
3d6ac1bb9a614bcbd38ee216bb5c35b41d8a3ff2
ascott1043/data_structures
/binary_tree.py
3,668
3.578125
4
# O(log n) # # class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def add_child(self, data): if data == self.data: return if data < self.data: if self.left: self.left.add_child(da...
934915f4e3b8c344081997d55ec7ca6be6c0c5a8
Stephanievillegas0728/Pyhton-Challenge
/PyBank/Main.py
516
3.640625
4
import os import pandas as pd import numpy as np import csv df = pd.read_csv("budget_data.csv") df print("Final Analysis") count1 = df['Date'].count() sum1 = df['Profit/Losses'].sum() mean1 = df['Profit/Losses'].mean() max1 = df['Profit/Losses'].max() min1 = df['Profit/Losses'].min() print('Total Months: ' + str(co...
772bb77a058d30a7ad49b1bbc2f292459db4ac2d
leliel12/diseno_sci_sfw
/legacy/unidad1/codes/historia.py
325
3.671875
4
def matar(bicho: int, arma: int) -> bool: """Recibe un bicho y un arma, ambos enteros que representan La cantidad de vida del primero, y cuanto daño hace la segunda y retorna True si la cantidad de vida se disminuye 0""" return (bicho - arma) <= 0 matar(bicho=100, arma=100) matar(bicho=100, arma="espad...
f3360560037fd5bdb4b8b5fa55edf16f92bd64a9
MattScheffler/Games
/RockPaperScissors.py
3,331
3.8125
4
import random import time def game_check(player1, player2): # Return 0 if draw, 1 or 2 for which player wins # If computer it will be player 2 winning_moves = {"rock": "scissors", "scissors": "paper", "paper": "rock"} player1 = str(player1).strip...
4f10e79e97234bee6be8a704165f0910ddffad71
Shruthi-Shree/Regex-in-Python
/search string retrieval.py
82
3.5
4
import re txt = "The rain in Covai" x = re.search(r"\bC\w+",txt) print(x.string)