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
8ad60557a87d3fbfaf882bb098de3831def574bb
Bcdirito/algorithm_problems
/array_manipulation/vowel_counter/while_loop.py
389
3.96875
4
def vowel_counter(string): total_vowels = 0 vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] i = 0 while i < len(string): if string[i] in vowels: total_vowels += 1 i += 1 return total_vowels print(vowel_counter("Girls Who Code")) print(vowel_counter("Edi...
fdc3c8706d76e7572fda6bd702a708775d619a38
CiarraMatthews/Simple-Projects
/Affordability_Calculator/functionality.py
2,176
4.03125
4
#The app without the GUI #Constants DEFAULT = 33 BAD_VAL = "Please enter a valid number" def by_net_income(): #Fix the taxes! income = int(input("Please enter your income here: ")) print("You can afford : $", income * 0.33, "/mo, with a net income of ", income) def by_gross_income(): #Fix the loop. Implement try...
c1dcc287c6cd8655da1c90167abb40f7754aa301
martin-ivanov-IT/Python_Team
/26.05.2021/Circle/Circle.py
207
3.953125
4
from math import pi class Circle: def __init__(self, r): self.r = r def area(self): area = pi*self.r*self.r print(f"area: {area}") return area c = Circle(3) c.area()
6837b4c62cb08e49540c1450867702934c660bd4
anmolsaxena10/stanford-ml-python
/ex1/gradientDescent.py
927
3.625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt def computeCost(X, y, theta, m): #print(X.shape, y.shape, theta.shape, m) return (np.sum(np.square(np.matmul(theta, X) - y))/(2*m)) def gradientDescent(X, y, theta, alpha, num_iter, m): J_history = np.matrix(np.zeros((num_iter+1, 1))) ...
c222489968812c65d58847cbe1b7780f9f620b4c
elormcent/centlorm
/conditional.py
542
4.21875
4
i = 6 if(i % 2 == 0): print ("Even Number") else: print ("Odd Number") def even(): number = int(input("Enter a whole number :- ")) if (number > 0 % 2 == 0): print("It\'s an even number, nice work") elif (number > 0 % 2 == 1): print("it\'s an odd number, good job") elif (number ...
c592c5ecc93bdbdc9a27151f2e236de21a3937ba
tgamblin/coursera-sat-smt
/sudoku.py
1,616
3.828125
4
#!/usr/bin/env python3 # Sudoku solver. from z3 import * s = Solver() # f represents positions on the board [int, int] -> int # and maps them to their values f = Function("f", IntSort(), IntSort(), IntSort()) # every cell value is in 1..9 for i in range(1, 10): for j in range(1, 10): s.add(And(f(i, j) ...
b3e68e6ab2789c2a3e57f6d76591ad604c5fc45a
aleksaa01/algorithms-and-data-structures
/algorithms/Sorting/insertion_sort.py
908
3.8125
4
def insertion_sort(array): for i in range(len(array)): temp = array[i] j = i while j > 0 and temp < array[j - 1]: array[j] = array[j - 1] j -= 1 array[j] = temp if __name__ == '__main__': import time import random def test1(): import ran...
9d4e53c50e11882fb8d91c2e1e5e6e670acfa2e1
aleksaa01/algorithms-and-data-structures
/algorithms/Sorting/bubble_sort.py
1,833
3.984375
4
def bubble_sort(array): for x in range(len(array) - 1): for j in range(len(array) - x - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] def bubble_sort_improved(array): x = 0 n = len(array) swapped = True while x < n - 1 and swappe...
38d86807ddb7555a6dcc472086e519c210662e7e
aleksaa01/algorithms-and-data-structures
/data-structures/Python/Graphs/adjacency_map.py
4,035
3.65625
4
from queue import Queue class MappedGraph(object): def __init__(self, graph_dict=None): self._graph_dict = graph_dict if graph_dict else {} self.num_edges = graph_dict.num_edges if graph_dict else 0 def add_vertex(self, vertex): if vertex not in self._graph_dict: self._gr...
7dd14227acdb05570087b9fae73ffcdc1449b04f
aleksaa01/algorithms-and-data-structures
/algorithms/Sorting/shellsort.py
1,906
3.640625
4
def shellsort(array): gap = len(array) // 2 while gap > 0: for start in range(gap): gap_insertion_sort(array, start, gap) gap //= 2 def shellsort_improved(array): gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for start in range(gap): gap_inse...
a54dd98c77853459dd414990b23ad1e3875d40a3
Aultraminum/Secure-subject
/Jacob.py
1,960
3.890625
4
import math import random def Fermat(a,N): if a >= 2 and a <= N-1 : if a**(N - 1) % N != 1 % N : print("N is composite") else: print("N is Prime") else: print("Nope!") def Jacob(m,n): if m == 1 : return 1 elif m % 2 == 0 : ...
e1c096798f3ba0ca7374fe2311b017708ed46e64
cholman17/EscapeyPet
/Other/Avatar.py
2,204
3.625
4
#Avatar Code Kimberly Winter 10/24/16 import sys, pygame pygame.init() black= (0,0,0) #initializes the color black size = width, height = 500,500 #size of the screen screen = pygame.display.set_mode(size) #initializes the screen size floor= 0 #x-coordinate of the floor class Avatar(pygame.sprite.Sprite): def ...
a97025850246a1a6e2a630565d20da91579e84fe
olivianauman/programming_for_informatics
/value_return.py
392
4.15625
4
def multiply3to9(input_number): sum = 0 for to_multiply_with in range(3, 10, 2): product = input_number * to_multiply_with print(' {} * {} = {:.2f}'.format(input_number, to_multiply_with, product)) sum += product return sum sum1 = multiply3to9(-2.5) sum2 = multiply3to9(21) ...
e40b81ba5afa39fdfe0b6384a5802695f53b1662
olivianauman/programming_for_informatics
/untitled-2.py
995
4.40625
4
# turtle trys import turtle # set window size turtle.setup(800,600) # get reference to turtle window window = turtle.Screen() # set window title bar window.title("making a shape") # set background color window.bgcolor('purple') the_turtle = turtle.getturtle() # default turtle # 3 attributes: positioning...
92e64115913451196a6146b826af0d0f735861d1
olivianauman/programming_for_informatics
/Homework7.py
3,791
4.40625
4
#Olivia Nauman #Homework 7 #import the string library so we can use it later import string #this function reads in the file contents of the dictionary def read_dictionary_file(filename): #encode to latin-1 because spanish dict has more words than english #open for reading f = open(filename,'r',...
998496eb9b980bf3c0757b11a412d62e36d423a7
dreamchaserkr/python
/Study/ds_str_methods.py
524
4.0625
4
# This is a string object name = 'Swaroop' if name.startswith('Swa'): print "Yes, the string starts with 'Swa' " if 'a' in name : print "\nYes, it contains the string 'a' " if name.find('war') != -1: print "\nYes, it contains the string 'war'" print "\n find : ", name.find('war') if name.find('Swaa...
c3e9f1b2a68ee376068f230167162d8cf5299550
textpipe/pattern
/examples/01-web/09-wikia.py
1,817
3.53125
4
# -*- coding: utf-8 *-* from __future__ import print_function from __future__ import unicode_literals from builtins import str, bytes, dict, int import os import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) from pattern.web import Wikia # This example retrieves articled from Wikia (h...
ececce51877a38c4d482a8efd720f77b54a37794
Venom207/tabula_rasa-team-no.5
/class_homework_1504.py
1,259
3.734375
4
import warnings class Rectangle: def __init__(self, top_left_x, top_left_y, length, height): self.abs = top_left_x self.ord = top_left_y self.l = length self.h = height def set_new_length(self, length_n): if length_n < 0: warnings.warn('One of the p...
a4c327eb87a6b535eeb6a6750f86279eedf0b16b
peterlulu666/CourseraStartingWithPython
/Assignment 4.6.py
1,064
4.4375
4
# 4.6 Write a program to prompt the user for # hours and rate per hour using input to # compute gross pay. Pay should be the # normal rate for hours up to 40 and time-and-a-half # for the hourly rate for all hours worked above 40 hours. # Put the logic to do the computation of pay in a function # called computepay() an...
2d8bc64ac752f3ecd0823fdf943d3c1a4e403af7
ad780hv/Belajar-Python1
/P14-Class hewan.py
942
3.546875
4
class hewan: def __init__(self): self.suara = 'suara' self.bulu = 'bulu' print(self.suara) print(self.bulu) class kucing(hewan): def __init__(self): print('==============') print('kucing') print('==============') def suara(self): self.suara = input('masukkan suara:') d...
65c594e41221e98d1c6ed2e6e0ec4e10150a9900
Ninpo/techdegree-project-2
/league_builder.py
3,023
3.78125
4
import csv CSVFILE = "soccer_players.csv" TEAMS = ["Sharks", "Dragons", "Raptors"] TEAMFILE = "teams.txt" LETTER_TEMPLATE = """Dear {}, I am delighted to inform you that {} has been selected to play for the {} team in the upcoming season. First practice is at 19:00 on November 5th 2018 at Old Trafford. See you ther...
4770888e88605c78bd1c23beb8a869f9cc7e68f5
guptaharshnavin/Hackerrank_Problem_Solving_Soln
/Climbing_The_Leaderboard.py
1,654
3.875
4
#!/bin/python3 import math import os import random import re import sys # Complete the climbingLeaderboard function below. def climbingLeaderboard(scores, alice): sorted(scores,reverse = True) #print(f'Scores : {scores}') #print(f"Alice's Scores : {alice}") alice_ranks = [] rank_coun...
cd28aa8b0f37ed41ce12a48059dfa04ab90cb057
guptaharshnavin/Hackerrank_Problem_Solving_Soln
/Minimum_Distances.py
887
3.59375
4
#!/bin/python3 import math import os import random import re import sys # Complete the minimumDistances function below. def minimumDistances(a): print(f'A : {a}') i = 0 dist_list = [] while i < len(a)-1: j = i + 1 dist = len(a) while j < len(a): if(...
fd9839e79f7acf6fcdd405e19a67cdfa4ff4fd9b
mosayam96/problemsolve
/maximum_prizes.py
502
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[12]: import sys import math def optimal_summands(n): summands = [] if n == 1: return[1] j = 2*int(math.sqrt(n))+1 for i in range(1,j): if n>2*i: summands.append(i) n=n-i summands.append(n) return summands if ...
ebb462d4bc30a90b5ded1cfb9e7d41e45209000c
willidert/HR_solutions
/HackerRank/problemSolving/Starcaise.py
376
4.0625
4
def staircase(n): l=1 caracter='#' c=1 floyd = '' lista=[' ']*n for l in range(1, n+1): for c in range(1,l+1): floyd += caracter # dá um espaço entre os números floyd=floyd.rstrip() print(floyd.rjust(n)) floyd = '' if __name__ == ...
b52af2f4265f6e46c19f60087d4f50a32b4dcea0
willidert/HR_solutions
/HackerRank/problemSolving/Strong Password.py
680
3.703125
4
import string def minimumNumber(n, password): cont = 0 conj = set(password) conja = set(string.ascii_lowercase) conjA = set(string.ascii_uppercase) conjN = set(string.digits) conjS = set(list("!@#$%^&*()-+")) if conj.isdisjoint(conja): cont += 1 if conj.isdisj...
88d5c78e170fbbcb4c154744dd65db937273f355
willidert/HR_solutions
/HackerRank/problemSolving/Closest Numbers.py
531
3.59375
4
def closestNumbers(arr): arr.sort() res = [] dif = arr[1] - arr[0] for i in range(len(arr)-1): if (arr[i+1] - arr[i]) < dif: dif = arr[i+1] - arr[i] for i in range(len(arr)-1): if (arr[i+1] - arr[i]) == dif: print(arr[i], arr[i+1]) res.a...
596b6d147d2569e901306a89eeb038b7263bad98
willidert/HR_solutions
/HackerRank/Super Reduced String.py
355
3.78125
4
def superReducedString(s): conj = sorted(set(s)) res = '' for i in conj: cont = s.count(i) if cont % 2 != 0: res += i if len(res) > 0: return res else: return 'Empty String' if __name__ == '__main__': s = input() result = superRedu...
3784f7e8a406089173e8bbd8b14e9e079a039bfd
willidert/HR_solutions
/HackerRank/problemSolving/Viral Advertising.py
363
3.59375
4
import math def viralAdvertising(n): shared = 5 liked = math.floor(shared/2) cont = liked for i in range(1, n): shared = liked * 3 liked = math.floor(shared/2) cont += liked return cont if __name__ == '__main__': n = int(input()) result =...
92a1116e684aa08c324f20bad31398f054b0af03
willidert/HR_solutions
/HackerRank/lang_prof_python/set.symmetric_difference() Operation.py
238
3.671875
4
nI = int(input()) english = set(map(int, input().split())) nF = int(input()) french = set(map(int, input().split())) students_english_or_french = english.symmetric_difference(french) print(len(students_english_or_french))
b12616ea29fdfff7b78b1fc13e08f76ea6eaf5be
willidert/HR_solutions
/HackerRank/lang_prof_python/Nested Lists.py
388
3.765625
4
if __name__ == '__main__': n = int(input()) estudantes = {} for i in range(n): aluno = input() nota = float(input()) estudantes[nota] = aluno sorted(estudantes.keys()) notas = list(estudantes.keys()) menor = notas[0] for j in estudantes.keys(): if j...
852c894bbd8b7176612019e9079e63aa8b7c46f0
willidert/HR_solutions
/HackerRank/HackerRank in a String.py
973
3.78125
4
def hackerrankInString(s): Hr = list('hackerrank') res = [] for i in range(10): if s.find(Hr[i]) != -1: if Hr[i] not in list('akr'): res.append(list(s).index(Hr[i])) else: try: while list(s).index(Hr[i]) < list(s).i...
43141dce566e017494468bec1d4ff2d904f45477
RekidiangData-S/SQLite-Project
/sqlite_App/app.py
751
4.15625
4
import database #database.create_db() def main(): print(""" WELCOME TO STUDENTS DATABASE ############################ Select Operation : (1) for create Table (2) for Add Record (3) for Show Records (4) for Delete Records (5) for Records Selection """) operation = input("Enter your ...
434f8f4ef4fbfab04deba211ae593173881a1a08
vivekagarwal5592/cs4660-fall-2017-vivekagarwal5592
/cs4660/graph/utils.py
4,604
3.75
4
from . import graph class Tile(object): """Node represents basic unit of graph""" def __init__(self, x, y, symbol): self.x = x self.y = y self.symbol = symbol def __str__(self): return 'Tile(x: {}, y: {}, symbol: {})'.format(self.x, self.y, self.symbol) def __repr__(sel...
b3a9d2f726c9b105807985602c628cb717b4d596
thaije/Robot-v1
/proximity_sensors/sonar/code_graveyard/ussContinuous.py
1,377
3.609375
4
import RPi.GPIO as GPIO #Import GPIO library import time #Import time library #GPIO.setmode(GPIO.BOARD) #Set GPIO pin numbering # BCM 26 = pin 37 # BCM 16 = pin 36 # GPIO.setmode(GPIO.BOARD) # TRIG = 37 # ECHO = 36 GPIO.setmode(GPIO.BCM) TRIG = 2...
b44ea4d919f4786512bc4b3e1f442cacffb1d42b
JDesignEra/dstra_assignment
/Sierpinski_Carpet.py
2,115
3.890625
4
import turtle def draw(coordinates, color, turtle): turtle.fillcolor(color) turtle.up() turtle.goto(coordinates[3][0], coordinates[3][1]) turtle.down() turtle.begin_fill() for i in range(len(coordinates)): print(i) turtle.goto((coordinates[i][0], coordinates[i][1])) turtl...
f5a05e18deaf2f6b876d3c38c514e628fa034bae
sanjeevsagar787/python-voice-assistance
/Voice Assistant.py
5,143
3.78125
4
import pyttsx3 # pyttsx3 is a text-to-speech conversion library in Python # Speech recognition allows the machine to turn the speech signal into text import speech_recognition as sr import datetime import wikipedia # pip install wikipedia import webbrowser import os import smtplib # for sending mail import w...
a6a3e99eeb35296f6b7fd14d3d6d1ce3140bdf14
mutta-satyanarayana/Student-Details-Management-System
/Student Details Management System/db_setup.py
1,094
3.609375
4
# db_setup.py # for create table to import required # methods from sqlalchemy module from sqlalchemy import String from sqlalchemy import Integer,Column # To create columns to one block to # using "declarative_base" from sqlalchemy.ext.declarative import \ declarative_base # Store table structure in...
038ddb0b0bcd2f7ba84ad96b5033012bded157b1
mottola/python-basics
/numpy_basic_statistics.py
1,364
4
4
# BASIC STATISTICS # DATA ANALYSIS # _______________ # GET TO KNOW YOUR DATA # LITTLE DATA -> SIMPLY LOOK AT IT # BIG DATA -> ??? # NUMPY HAS FRIENDLY STATISTICAL FUNCTIONS SUCH AS: # _________________________________________________ # np.mean(), np.median(), np.corrcoef() to check for correlations # np.std() for sta...
d13dcf6e579b458d12f013700eb760936d9f2e4c
cubicova17/Python_scripts
/fib.py
936
4.21875
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: FibNumbers # # Author: Dvoiak # # Created: 07.10.2014 # Copyright: (c) Dvoiak 2014 # Licence: <your licence> #-------------------------------------------------------------------------------...
dadff267639dd0b8b1d38981202e61dd547f2558
guibiaoguo/pydemo
/do_iter.py
914
3.890625
4
d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key) for value in d.values(): print(value) for ch in 'ABC': print(ch) from collections.abc import Iterable print(isinstance("abc", Iterable)) print(isinstance([1,2,3],Iterable)) print(isinstance(123,Iterable)) for i, value in enumerate(['A','B','C']): ...
7cfa7fac6f164f01fec87f1979dd510f6eb91925
guibiaoguo/pydemo
/async_hello.py
317
3.625
4
import asyncio # python3.4 @asyncio.coroutine async def hello(): print("Hello world!") # 异步调用asyncio.sleep(1): # yield from r = await asyncio.sleep(1) print("Hello again!") # 获取EventLoop: loop = asyncio.get_event_loop() # 执行coroutine loop.run_until_complete(hello()) loop.close()
5bb9a5e4a9d623b105e0457df8e4ebf4a13b7349
guibiaoguo/pydemo
/the_set.py
365
4.03125
4
s =set([1,2,3]) print(s) s = set([1,1,2,2,3,3]) print(s) s.add(4) print(s) s.add(4) print(s) s.remove(4) print(s) s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) print(f"s1和s2的交集{s1 & s2}") print(f"s1和s2的并集{s1 | s2}") a = ['c', 'b', 'a'] print("未执行a.sort() %s" %a) a.sort() print(f"执行a.sort()后 {a}") a = "abc" print(a) print(a.r...
4672ba085830848fa127a191b78900da1a743ff3
LumiaO-N9/python-demo
/demoJson.py
214
3.578125
4
import json as j with open("students.json", encoding="utf-8") as f: for i in range(8): json1 = j.loads(f.readline()) print(json1["id"]) print(json1["name"]) print(json1["age"])
4bafec98048914b7e53189b1a9301b88fec0e465
Anisha7/Python-Algorithms
/lesson7/hw7.py
7,649
3.75
4
################################################# # Hw2 ################################################# import cs112_f17_week7_linter import math import time ################################################# # Helper functions ################################################# def swap(a, i, j): (a[i], a[j]) = ...
6235aaee295351b52a9cc9965664fc98bd9cf0ab
Anisha7/Python-Algorithms
/lesson3/Extensive Week 3 Review.py
3,265
3.859375
4
#Extensive Previous Week Review #Week 3 #split vs splitlines splitlines = split("\n") #returns a list for word in words.split(","): #do stuff # strip() ==> whitespace (leading and trailing) strip("\n") # %d ==> ints age = 3 birthyear = 1996 string = "Abhi is" + str(age) + "years old" #ugly string = "Abhi is %...
4b1d3dc2f8c4774e0d1373f0733152e728b07796
Anisha7/Python-Algorithms
/lesson5/lab/Tkinter Team Tree House/Tkinter Notes TeamTreeHouse.py
5,689
3.515625
4
#tkinter notes from TeamTreeHouse Vids import tkinter def funcTry(): # creates a root window/app # Tk() for library root = tkinter.Tk() hi_there = tkinter.Label ( # what does this label belong to root, text = "Hi there!", bg = "red", fg = "w...
b882a6c8f38065b75d2fdeff2c640cc84ac731f4
kimchison/HardWay
/ex30.py
424
4.125
4
people = 20 cars = 40 buses = 50 if cars > people: print "We should take the cars..." elif cars < people: print "We should not take the cars..." else: print "We can't decide." if buses > cars: print "Thats too many buses" elif buses < cars: print "Maybe we could take the buses" else: print "We still can't deci...
678d563e857ead4ca4d562d78a40f5270eb0f72e
kimchison/HardWay
/ex40.py
613
3.671875
4
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]) bulls_on_parade = Song(["They rally around the family", "With pockets f...
278e24327efec9725f6985c73379e9052043a48a
40309/Functions
/Class Exercises/Revision/Task 1.py
308
3.796875
4
def user(): character = input("Enter character: ") number = int(input("INput number: ")) return character, number def loop(character, number): print(character) print(number) for count in range(number): print(character) def main(): de = user() loop(de)
27f1328336cc35ac94248067964a3078a81d83b1
HoldenGs/AirBnB_clone
/tests/test_models/test_engine/test_file_storage.py
1,697
3.609375
4
#!/usr/bin/python3 """ The credit of json testing goes to http://stackoverflow.com/questions/29637076/python-unittest-for-method-returning-json-string and Swati Gupta: https://raw.githubusercontent.com/guptaNswati/AirBnB_clone/master/models/engine/file_storage.py This is FileStorage class unittest module. This class...
c3c134a4545e81f7e58310ca473b00904ea1f55a
Lakshmishaks88/Python
/choose_other.py
108
3.53125
4
def choose_other(p1): if p1 == 'X': p2 = 'O' elif p1 == 'O': p2 = 'X' return p2
95d138b6f62c62ba8ca0c2f22a2d0798f413abeb
Lakshmishaks88/Python
/choose_player.py
305
4.0625
4
def choose_player(): choice = True while choice not in ['O','X']: choice = input('Player 1 Choose O or X').upper() if choice not in ['O','X']: print('Invalid input, please enter X or O') if choice == "X": return ('X','O') else: return ('O','X')
576672d0fdacac1002b6d96deed88c7ada514fd4
mschruf/python
/division_without_divide_operation.py
1,493
4.3125
4
def divide(numerator, denominator, num_decimal_places): """Divides one integer by another without directly using division. Args: numerator: integer value of numerator denominator: integer value of denominator num_decimal_places: number of decimal places desired in result Returns: ...
cde8e56188d0edabdc4c26f8d94519660a9e6ad7
alanjm15/Python
/binSearch.py
702
3.96875
4
import sys def binarySearch(a, x): low = 0 count = 0 mid = 0 high = 0 high = len(a) - 1 print("\nSearching for: ", x, "\n") while(low <= high): mid = (low + high) // 2 if(a[mid] == x): print("\nFound:", a[mid], "at index position:", mid, "\n") ...
e366ffbd98c7cf6e860489e91b1f07457695b5ab
KishenSharma6/SF-Airbnb-Listings-Analysis
/Project_Codes/03_Processing/Missing_Stats.py
1,102
4.15625
4
import pandas as pd import numpy as np def missing_calculator(df,data_type = None): """ The following function takes a data frame and returns a dataframe with the following statistics: data_type takes a string or list of strings referenceing data type missing_count: Number of missing values per...
dc3d63ec393d37920c1b0d3bb98041bfb8d0be13
muralimandula/cspp1-assignments
/m11/p4/assignment4.py
957
3.984375
4
"""#Exercise: Assignment-4 #We are now ready to begin writing the code that interacts with the player. We'll be implementing the playHand function. This function allows the user to play out a single hand. First, though, you'll need to implement the helper calculateHandlen function, which can be done in under five lines...
320c5067f7607baedb6009db27bca5f99e60b74e
muralimandula/cspp1-assignments
/m7/p3/Functions - Assignment-3/assignment3.py
1,521
4.125
4
""" A program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months using bi-section method """ def payingdebt_offinayear(balance, annual_interestrate): """ A function to calculate the lowest payment""" def bal_d(balance, pay, annual_interestrate): ...
dcab6b855834bb5e06bc93b7a8e8697d72acf68b
muralimandula/cspp1-assignments
/m4/p1/vowels_counter.py
433
3.953125
4
"""#Assume s is a string of lower case characters. #Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: #Number of vowels: 5""" S_S = input() # the input string is in s # remove pa...
b41f2346308de42ff5e15e35ad5cbf3cb7b66f6f
pvergara242/semana2-ejercicio2-python-a
/ejercicio2.py
386
4.0625
4
def numeros(): numeros = 1 #1 while numeros <= 100: #100 numeros = numeros + 1 #1 if numeros % 3 == 0 and numeros % 5 == 0: #1 print("Fizz Buzz") #1 elif numeros%3==0: #1 print("Fizz") #1 elif numeros%5==0: #1 print("Buzz") #1 else: ...
b2eeb5e5272214d1157badd9754f93993d8a07cc
deepa0597/MAQ_Workbook
/Algorithms Course/Course 1/Week 2/prog.py
1,023
3.578125
4
#input file input_file = "IntegerArray.txt.txt" #open the file in read mode ifile = open(input_file,'r') #separating the numbers and storing it in an array. Readlines to read entire file at once with ifile as f: num = [int(number.strip()) for number in f.readlines()] #print(num) count = 0 def count_i...
e2128f7e321ea63887559db8f98808f6280b6c88
mbaaba/co2_thermo_meter
/src/temperature.py
1,033
3.546875
4
import urllib.request TEMP_URL = 'https://data.giss.nasa.gov/gistemp/graphs_v4/graph_data/Monthly_Mean_Global_Surface_Temperature/graph.csv' MEAN_TEMPERATURE_PARIS = 0 MEAN_TEMPERATURE_2DEGREE = 2 def fetch_current_mean_temperature(): data = [] with urllib.request.urlopen(TEMP_URL) as response: html ...
bf2fbb6aa6c1d13126adede544c898c5450fc054
BackupTheBerlios/skunkweb-svn
/sandbox/smulloni/skunk4/src/skunk/templating/stml/codeStream.py
2,632
3.609375
4
from cStringIO import StringIO class PythonCodeOutputStream(object): """ an output stream with indent() and dedent() methods that cause lines to be indented and dedented depending on the state of the stream. The number of tabs can be accessed or directly changed in self.indent_level. Normally, yo...
91b62a3ae3aa5e46345a990a353eae5c488041c8
Vedaang-Chopra/Python_Codes_Practiced
/f-12.py
490
3.546875
4
def leaderarr(n): d=[] for i in range(0, len(n)): flag=True for j in range(i+1,len(n)): #print(n[i],n[j],flag) if n[i]>=n[j]: flag=True else: flag=False break if flag==True: d.append(n[i]) ...
db9cb334ca1e7502b06fac5edfdc3fb24c47fc64
jleko75/Python_SQLite
/sqlite_demo.py
2,147
4.15625
4
import sqlite3 from employee import Employee # conn = sqlite3.connect(':memory:') conn = sqlite3.connect('employee.db') c = conn.cursor() # budući baza podataka već postoji ovo nam ne treba # c.execute("""CREATE TABLE employees ( # first text, # last text, # pay integer # ...
6d58fb56af6588709c50a33762982de5e7a98cb5
vaibhavkamble460/21-DAYS-PROGRAMMING-CHALLENGE
/day10/colorgame.py
1,378
3.828125
4
import tkinter import random colours = ['Red','Blue','Orange','Green','White','Pink','Black','Yellow','Purple','Brown'] score =0 timeleft=60 def startgame(event): if timeleft == 60: countdown() nextcolour() def nextcolour(): global score global timeleft if timeleft>...
11b628e26806a79f33d2dbb2e69d91cad9ee2e51
DixitTrivedi/Find-Sentiments-Title-Summary
/find_summary_sentiments_title.py
2,110
3.609375
4
from gensim.summarization import summarize import nltk from textblob import TextBlob # nltk.download() para = '''Dr. APJ Abdul Kalam was indeed one of the most humble, intelligent, wise, selfless, loving, and lovable leaders ever born. He was born on 15 October 1931 in Rameswaram, Tamil Nadu. He was the 11th...
5a5f4058a0787ad39b0cc91aad561127f9fc94c9
ak-felix/Hackerrank-Python
/ginortS.py
463
3.734375
4
def sortt(s): l=[] u=[] o=[] e=[] for char in s: if char.islower(): l.append(char) elif char.isupper(): u.append(char) elif char.isdigit(): if int(char)%2==0: e.append(char) else: o....
49dc362d97ec0feb3ef0e85d60df45e05c63e145
eliza-wollinger/freecodecamp-exercises
/data-analysis-with-python/boilerplate-sea-level-predictor/sea_level_predictor.py
1,418
3.734375
4
import pandas as pd import matplotlib.pyplot as plt from scipy.stats import linregress def draw_plot(): # Read data from file df = pd.read_csv("epa-sea-level.csv") # Create scatter plot fig, ax = plt.subplots(figsize = (10,5)) x = df["Year"] y = df["CSIRO Adjusted Sea Level"] plt.scatter(x...
66ed2c2b2b82b516a5d7e2a69b619943642b465d
chunyang-wen/code-practice
/Python/key_value_sum.py
6,157
3.515625
4
#!/bin/env python # sum values according to key import sys import os IS_DEBUG=False key_value_dict = {} value_total = {} class Config: def __init__(self,file): ######### CONFIGS ############### # eg # VALUE_KEY = [1,3,5] # relative to VALUE_KEY # VALUE_TOTLA_KEY = [0,1] # VALUE_ITEMS = [2,6] #self.VA...
4a3b63cff2af916eaf8656c3896dce496805c2e9
xjwhhh/Probability-Theory
/ruantong/1.py
878
3.625
4
# -*- coding:utf-8 -*- ''' log api example: log('output is: ' + str(output)) ''' class Solution(): # def solve(self, A): # list=[0,0,0,0,0,0,0,0,0,0] # for numberstr in A: # number = int(numberstr) # while (number > 0): # a = int(number % 10) # ...
746a282ebc6466725ddcaf80be63ad1a0c93fdf5
xjwhhh/Probability-Theory
/ruantong/Rock-paper-scissors.py
2,022
3.703125
4
''' Rock-paper-scissors is a hand game played by two or more people where players choose to sign either rock, paper or scissors with their hands. For your statistics class project, you want to evaluate whether players choose between these three options randomly, or if certain options are favoured above others. You ask ...
3310f56b5bfd01213c8948b7a214efdc17a36369
watty62/abdn_air_quality
/MrParsy.py
1,530
3.59375
4
import os, argparse, csv, json, glob #from pathlib import Path aparser = argparse.ArgumentParser(description='convert csv to json') aparser.add_argument( '-f', '--file', dest='fname', action='store', help='file name for csv to be parsed') aparser.add_argument( '-d', '--dir', dest='dname', action='store', ...
6267f281b52392b9b30a8f382e2cf8c6a1280558
prolo09/pari_2020
/part1/ex4/ex4.py
452
3.671875
4
maximun_number=100 def isPerfect(value): num=value soma=0 for c in range(1, num): if num % c==0: soma=soma+c if soma==num: return True else: return False def main(): print("Starting to compute perfect number up to " + str(maximun_number)) for i in range...
93935575d78e5f875f0e115c18fedc29f96edbce
prolo09/pari_2020
/part2/ex2/ex2.py
407
3.53125
4
maximun_number=100 from my_fuc import isPerfect # ou import mu_fuc # depois possos por my_fuc as mf (e assim posso escrever na frente do codigo so escrevendo mf ) def main(): print("Starting to compute perfect number up to " + str(maximun_number)) for i in range(0, maximun_number): if isPerfect(i):...
c932c4c2f767b0ecdcff3ff82b37a729f61a095d
jamesangie/Software-Design-Assignments
/A2/partner/DCapALst.py
1,932
3.765625
4
## @file DCapALst.py # @author janzej2 # @brief A module which defines the abstract data type for various departments # @date 02/10/19 # from StdntAllocTypes import * ## @brief This class represents an abstract data type of department capacities. # @details Initialising this object creates a new tuple used to st...
96d096cd5dd39bc1849c784afa03344480dea892
ThiagoKS-7/Python-OO
/alura/examples/examples.py
628
3.734375
4
def cria_conta(numero,titular,saldo,limite): conta = { "numero": numero, "titular": titular, "saldo":saldo, "limite":limite } return conta def deposita(conta,valor): conta["saldo"] += valor return True def saca(conta,valor): conta["saldo"] -= valor return True def extrato(co...
5870cbe5b7460108d9c1e6d60c2c6dfdd0a457a4
Juice930/Pythonoso
/Animation.py
549
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 15 13:39:18 2016 @author: Guillermo1 """ import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as matan def f(t): return t**2 t=np.linspace(0,10,100) fig=plt.figure() ax=plt.subplot(111) ax.set_xlim(0,10) ax.set_ylim(0,100) linea,=ax.plot([...
1556d4dc77222c6a7889315262c3de01e2d60f1c
mmicromegas/RANDOM
/ajty35_sutaz_with_comments.py
961
3.96875
4
# Author: Miroslav Mocak # Date: 21/FEB/2018 # Email: miroslav.mocak@ness.com # Description: A single function accum: # accum(“Python“) # Výstup: “P-Yy-Ttt-Hhhh-Ooooo-Nnnnnn“ # accum(“IS“) # Výstup: “I-Ss“ # accum(“cOmInG“) # Výstup: “C-Oo-Mmm-Iiii-Nnnnn-Gggggg“ def accum(input): char = list(input) # conve...
7d25fca29ef23d397b784da8567293279cf4d0ca
alvinuy1110/python-tutorial
/oop/basic.py
867
4.40625
4
##### # This is the OOP tutorial ##### title = "OOP Tutorial" print(title) # Basic class print("\nBasic Class\n") # class definition class A(): # constructor def __init__(self): print("classA initialized") # constructor def __init__(self, name=None): print("classA initialized") ...
2aaad3f3fe4b0a57e481f2b752266a7dc636a6e3
alvinuy1110/python-tutorial
/loop/loop.py
809
4.4375
4
##### # This is the Looping tutorial ##### title = "Looping Tutorial" print(title) # Looping print("\n\nLooping\n\n") myMap = {"key1": "value1", "key2": 1234} print(myMap) # print the entries print("\nKey-Value\n") for k, v in myMap.items(): print(k, v) # loop with the index print("\nIndex-Value\n") for (i, v) i...
f9cf1703c0ef53c675f66995ed0a5ad16e4c747a
keionbis/SmartMouse_2018
/docs/ipynb_gen_py/DC Motor Simulation.py
5,417
3.796875
4
# coding: utf-8 # # DC Motor Simulation # Look at the dynamics_model.pdf for the explanation behind this code. # In[1]: import numpy as np import matplotlib.pyplot as plt # In[2]: def simulate(V, J, C, K, R, L, theta_dot=0, i=0): # simulate T seconds T = 5 dt = 0.01 ts = np.arange(0, T, dt) ...
c115a55e98a112cbd4f2170590cfbbb219c9720a
cal1log/python
/tuples.py
243
4.125
4
#!/usr/bin/env python3 '''creating a tuple''' tup = (10, 20, 30, 40) '''getting a tuple index value''' print(tup[2]) '''impossible to change values in a tuple''' try: tup[2] = 60 except: print("a tuple can not changes your values")
8215d0c26b80a0713d31c1c809c8151b2e89f648
L0UARN/boring-dungeon
/source/traits/mobile.py
3,798
3.6875
4
""" Classes: - Mobile """ from source.core.tools import Position, Direction class Mobile: """ A mobile entity is an entity which can move inside a graph. """ def __init__(self, position: Position, direction: Direction, graph: dict[Position, list[Position]]) -> None: """ :param pos...
3e48f9a43a606598b1fd815f8dd180a1cec9c502
L0UARN/boring-dungeon
/source/traits/fighter.py
2,045
3.671875
4
""" Classes: - Fighter """ from __future__ import annotations from time import time from source.traits.living import Living from source.inventory import Inventory class Fighter(Living): """ A fighter is a living entity that can fight. It has an inventory. """ def __init__(self, max_health: int, s...
99b125911877fcfda38750b135cb0ecc1a9dd040
Natspy/caviar
/src/interface/gui/colors.py
679
3.625
4
import typing Color = typing.Tuple[int, int, int] class Colors: WHITE = (255, 255, 255) BLACK = (0, 0, 0) # (232, 168, 32) DARK = (67, 67, 78) LIGHT = (212, 212, 212) # (255, 255, 255) GREEN = (27, 176, 66) # (246, 104, 185) RED = (255, 105, 97) # (34, 193, 248) PURPLE = (150, 111, 21...
90ab3fffb920d6aa662350ce8a84837d6b946c79
Natspy/caviar
/src/simulator/road/speedcontroller_test.py
2,468
3.578125
4
import unittest from simulator.road.speedcontroller import SpeedController class SpeedControllerTestCase(unittest.TestCase): def test_getMaxSpeed(self): # Default max speed. controller = SpeedController() speed = controller.getMaxSpeed(position=(10, 0), width=1) self.assertEqual(s...
3d153c9038e0ddee857366c0692915f251152952
Natspy/caviar
/src/simulator/statistics/averageresult.py
1,020
3.78125
4
import typing class AverageResult: value: int count: int def __init__(self, value, count): self.value = value self.count = count def __eq__(self, other: 'AverageResult') -> bool: return self.value == other.value and self.count == other.count def __add__(self, other: 'Ave...
4e81aabafc55a0005355d47e700ab0c6084c208d
Natspy/caviar
/src/simulator/dispatcher/dispatcher.py
1,170
3.671875
4
import random from simulator.position import Position from simulator.road.road import Road from simulator.vehicle.vehicle import Vehicle from util.rand import shuffled class Dispatcher: road: Road count: int remaining: int length: int def __init__(self, road: Road, count: int, length: int = 1): ...
0f38003fbfb650fbe867eec42c4296ca31c8be07
ageorge/Path-Tracer
/PathFinderBFS.py
3,439
4.0625
4
from copy import deepcopy class PathFinder: '''This class traces the path from source to destination''' # Constructor to initialize the class def __init__(self): self.tree = {} self.matrix = [] self.__size = 0 self.__start = 0 self.__end = 0 self.obstacles = ...
19140dfa94bf9a7427409d6342bcf8deb2d0bce2
james-gloudemans/cffi_list
/linkedlist.py
5,752
3.84375
4
"""linkedlist.py: circular doubly linked list.""" # standard library from collections.abc import MutableSequence from typing import Any, Generic, Iterable, Iterator, Optional, TypeVar, Union # third party libraries # local libraries T = TypeVar("T") class LinkedList(Generic[T], MutableSequence): """A circular...
5395b42cd640d44f0e97f8d26196142cff346089
ptarau/PyPL
/pyobs.py
1,091
4.03125
4
import turtle # Set the background color turtle.bgcolor("orange") # Create a turle t = turtle.Turtle() t.width(2) t.speed(1) t.color("red") class point: def __init__(self, x, y): self.x = x self.y = y def color(self, color): t.dot(10, color) def __repr__(self): return ...
6b657614323541b09a31fb7c1a0f7c80e54e56c6
ptarau/PyPL
/sk.py
2,003
3.734375
4
import functools # s,k combinators, lambdas and more # s f g x = (f x)(g x) = f x (g x) # k x y = x s = lambda f: lambda g: lambda x: (f)(x)((g)(x)) k = lambda x: lambda y: x i = lambda x : (s)(k)(k) # s k k x = (k x) (k x) ==> k x (k x) = x # i = lambda x : x # Rosser's x combinator in terms of s,k x = lambda f: (...
0cae12c947be2abdc6963e4bb779957ad4f93b41
ptarau/PyPL
/2021/knuthLayoutTurtleTree.py
2,170
3.609375
4
import turtle import time # lambda term with de Bruijn indices as leaves # t = ('a',l,r) or ('l',t) or i where l,r are subtrees and i is an int de Bruijn index # tree with x,y annotations # t = ('a',x,y,l,r) or ('l',x,y,t) or (i,x,y) # compute x,y annotations for each node, derived from Knuth's basic layout def knuth...
e626372e9dfca23bd1e41a29d947fe8ea7519782
sudhanvalalit/Koonin-Problems
/Koonin/Chapter2/Exercises/Ex2.py
2,576
3.78125
4
''' Exercise 2: Apply the Adams-Bashforth two and four step algorithms to the example defined by eq (2.7) using Euler's method (2.6) to generate the values of y needed to start the recursion relation. Investigate the accuracy of y(x) for various values of h by comparing with the analytical results and by applying the ...
69b832863c278164de52ef419b82d3c4d5bee86d
sudhanvalalit/Koonin-Problems
/Koonin/Chapter1/Exercises/Ex5.py
1,427
4.1875
4
""" Exercise 1.5: Write programs to solve for the positive root of x^2-5 using the Newton-Raphson and secant methods. Investigate the behavior of the latter with changes in the initial guesses for the root. """ import numpy as np from scipy.misc import derivative tolx = 1e-6 def f(x): return x**2 - 5.0 def Ne...
84be8ce106db4d9c3d97cc7d07ea06734f0f8f04
sudhanvalalit/Koonin-Problems
/Koonin/Chapter1/Exercises/chap1c.py
669
3.78125
4
""" The following FORTRAN program finds the positive root of the function ..math:: f(x) = x^2 - 5, x_0 = 5^{1/2} = 2.236068 to a tolerance of 10^{-6} using x = 1 as an initial guess and an initial step size of 0.5: """ import numpy as np # tolerance tolx = 1e-6 def func(x): return x*x - 5.0 def mai...
0888cefd4941486e16597cfbd53b81d5215a5e8b
AminFadaee/task
/tasks/abstract.py
1,127
3.65625
4
from abc import ABC, abstractmethod from typing import List class Task(ABC): def __init__(self, name: str): self.name = name self.done = False def finish(self): self.done = True def undo(self): self.done = False def __eq__(self, other): return self.name == ot...
e4f78d1b223ef743380d89bedcf1524c5cd3b52a
jdrinoca/Finite-Element
/element.py
822
3.5
4
# element instance # Joseph Rudick # Edited: 8/28/2020 # node1 - 1st connected node (node instance) # node2 - 2nd connected node (node instance) # A - element cross-section area (float) # E - element modulus of elasticity (float) # I - element area moment of inertia (float) # color - element color (matplotlib color ...
6a808e3a738ceee689388f45fc3206544a6654cd
voodrew/Exercism
/python/largest-series-product/largest_series_product.py
461
3.71875
4
def product(numbers): total = 1 for n in numbers: total *= n return total def slice(sequence,length): return (sequence[i:i+length] for i in range(len(sequence) - length+1)) def largest_product(series, substring_length): if substring_length < 0: raise ValueError('substring length mu...