blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
039ff633d86e9e9d7b805e31e8f1b5543107e651
adgray09/CS-2.1
/Code/sorting_recursive.py
1,353
3.75
4
#!python import random def merge(items1, items2): left_index, right_index = 0, 0 result = [] while left_index < len(items1) and right_index < len(items2): if items1[left_index] < items2[right_index]: result.append(items1[left_index]) left_index += 1 else: ...
552eceac4331e0ea6341028cf3be8dc39dd1e33d
laxminarsaiah786/Python
/Filestolist.py
189
3.546875
4
def file(fname): with open(fname) as f: #text stores in list content_list = f.readlines() print(content_list) file("text.txt")
775ff6a575bc9cb914bcfb80e2dd29c15d1b6b5c
dwalczak84/python-projects
/03-tic_tac_toe_5/tic_tac_toe_5.py
4,802
3.890625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 08 16:31:05 2017 @author: Dariusz """ class TicTacToe: # Tic-Tac-Toe 10-sizer game board initialization. def __init__(self): """Start a new game.""" self._board = [ [' '] * 10 for j in range(10)] self._player = 'X' ...
0335e1075d0d9c46d4fdb056ba17adf596ecd062
aammokt/newProject
/python102/small/8_small.py
196
4.125
4
sentence = input("Please enter a string:") list_sentence = list(sentence) list_sentence.reverse() rev_sentence = "".join(list_sentence) print(f'The reverse of the string above is: {rev_sentence}')
fea6d2630dfc799546ada736ecc78809d0b2d397
aammokt/newProject
/python102/large/game.py
1,556
4.15625
4
#!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Character: def __init__(self, name, health, power): self.name = name self.health = health ...
ab83b18a9344677bbdf00e3c583300794ed29757
aammokt/newProject
/python102/small/6_small.py
235
4.125
4
numbers = [4,-2,55,6,-20,5,-11,8,0,-1] pos_numbers =[] print(numbers) for num in numbers: if num >= 0: pos_numbers.append(num) print("The following are the list of positive numbers from the list above:") print(pos_numbers)
77ddc8a387ecdfca6ec56800dfb9ea48cd6560fc
junwei-h/Learning-Algorithms-with-Leetcode
/0001.py
367
3.546875
4
class Solution: def removeEdgeBT(self, root): def removeEdgeBT(node, seen): if node is None or node in seen: return None seen.add(node) node.left = removeEdgeBT(node.left, seen) node.right = removeEdgeBT(node.right, seen) return n...
15de44dd87ac6cd9b7892ce045d25b6ea3b3a41e
JansenLefever/Ops-401d2
/ops07.py
1,183
3.96875
4
#!/usr/bin/env python3 # Author: Jansen Lefever # Class: 401D2 Ops Challenge 7 # Purpose: from cryptography.fernet import Fernet, os def load_key(): # Load the key from the current directory named `key.key` return open("key.key", "rb").read() def Encrypt_file(): f = Fernet(key) with open(filep...
7f969285be518ac43207e5c20e4456e1188a36d1
IsabelMai/python-ethical-hacking
/network_scanner.py
1,662
3.5
4
#!/usr/bin/env python # Import modules import argparse import scapy.all as scapy # Function to run this script using an argument and option as input to scan for MAC addresses of the input def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--target", dest="ip", help="IP Address...
2fe6171053eb22a913f280c5eaccdbece02e627b
hbk93/password-locker
/password_test.py
1,809
3.953125
4
import unittest from password import User class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviours. Args: unnittest.TestCase: TestCase class that helps in creating test cases ''' def setUp(self): ''' Set up method to run before each test case '...
63327ee8bc66f9d17fb249c7c310fd828ffae587
itsEricmiao/ProgrammingLanguage
/ReadFileWordsFrequency.py
1,360
4.09375
4
# CSE-3342 Spring 2019 # PA03: Read File Words Frequency # Instructor: Nasser Jan # Name: Eric Miao import re def readfile(path): days_file = open(path, 'r') # Input the file mystr = days_file.read() # Read in the file wordList = re.sub("[^\w]", " ", mystr).split() # Split string to the words days_file...
850c820432c4deb8d3517452b256618141758d26
GermanEngineering/RotateImages
/Progress.py
957
3.640625
4
import math def PrintProgress(numberOfProcessedFiles): if numberOfProcessedFiles == 1: print(""" OO OO OOOO OOOO OOO OOO O OO O O O OO OO O O OOO OOO OO OO OO O O OOO O OOOO ...
545167f0e5e3a1f082c1f357992604cb903b867e
dlrandy/PYTHON-SHOOTING
/day9/exception.py
735
4
4
# try: # print(9/0) # except ZeroDivisionError : # print('you can not divide by zero') # # print(8/0)1 # print('Give me two numbers, and i will divide them.') # print('Enter q to quit.') # while True: # first = input('\nFirst num: ') # if first == 'q': # break # second = input('\n Second number') # if...
ac4f7d683c5dfd5692cd2d388b39e606f2944b96
AK607/my-reality
/to_add_2_num_that_are_in_a_period.py
250
4
4
a=int(input("enter the 1st number: ")) b=int(input("enter the 2nd number: ")) if a>=-1000 and a<=1000 and b>=-1000 and b<=1000: sum=a+b print("%d + %d = %d"%(a,b,sum)) else: print("the one/more input number(s) are outside the limits")
f4834bced5e7e1667d6642964e15945ba7f262ad
jasokan/myplayground
/python-examples/jType.py
537
3.65625
4
# # Created by Jagannathan Asokan # # Some examples on Data types intvalue = 10 print(type(intvalue)) floatvalue = 11.9 print(type(floatvalue)) strvalue = 'string' print(type(strvalue)) fint=5 sint=10 complexvalue=complex(fint,sint) print(type(complexvalue)) tuplevalue = ("School", "students", "exam") print(type(t...
9a178fe6e3219a6fba2aef6f0c7f1588e9fa2d14
jasokan/myplayground
/python-examples/jForRangePass.py
171
3.703125
4
# # Created by Jagannathan Asokan # for i in range(1, 10): if (i % 4 == 0): print(str(i) + " is divisible by 4") pass print(str(i) + " is not divisible by 4")
1f4bab4c387d60be7b60415e3f5a293eea248377
rmuraglia/HRC_Trump_NLP_practice
/two_class_sklearn.py
2,713
3.640625
4
# two_class_sklearn.py """ implement a basic text classifier to assign if the speaker of a given sentence was Donald Trump or Hillary Clinton based on: http://scikit-learn.org/stable/auto_examples/text/document_classification_20newsgroups.html#example-text-document-classification-20newsgroups-py http://stackoverflow...
bd597a61599241ae1a04c0ca233612bcae46c326
CenzOh/Python_Exercises
/turtle_exercises/exercise_13.py
1,239
3.96875
4
from random import randint #import statement for the randint fcn counter = 0 #using i in the for loop counts for iterations. Even when using break statements iteration will auto inc #iterations = 0 for i in range(20): #twenty times print() #newline print("iteration: ", i) #print which iteration is bein...
e55979deac8c7ac4b5400c5770b9b32e7c4b085e
CenzOh/Python_Exercises
/notes/series_dataframe.py
6,999
4.5
4
# 3/1/21 class ISI 300 L05 import pandas as pd #importing the pandas library import numpy as np # create a series s = pd.Series([7, 'Paolo', 'ISI', 300]) #this guy comes from Pandas library, that's whay we type "pd." print(s) #prints the series as a list #this is also a good way to check if it is installe...
c1a83e446228bc5f331a8776acab6d540f163bd7
CenzOh/Python_Exercises
/class_exercises/assignment_5_E2.py
1,608
3.953125
4
# ISI 300 Vincenzo Mezzio Assignment 5 Exercise 2 class Student: # no need to use the init_ or i_ for these variables you could if you want def __init__(self, init_name, init_address): self.__name = init_name self.__address = init_address self.__course_names = []#at initialization the...
4a32472c6bdb2a4a0a2dca1debbb78df57b0fdd0
CenzOh/Python_Exercises
/notes/class.py
6,874
4.40625
4
# 3/15/21 ISI 300 3/15/21 # define a class class Person: # constructor, __ is syntax for some hiddent fcns def __init__(self, init_firstname , init_lastname): ## <-- initial values coming from the outside (caller) # Variables to store first and last name of a person self.firstnam...
87f32682ea2d449c0a0fb4b256deabf626c66bef
CenzOh/Python_Exercises
/turtle_exercises/exercise_3.py
257
3.78125
4
import turtle pencil = turtle.Pen() counter = 0 while (counter < 4): #needed to add the fourth so it can make the full square pencil.forward(10) pencil.right(90) counter += 1 #keep window open until click turtle.exitonclick()
d629b399bddcdd709a76f26f9e35b660d448f632
likwoka/old_py_stuffs
/svnutil/svnbox.py
3,995
3.53125
4
#!/usr/bin/env python ''' Usage: svnbox [OPTION] List all subversion sandbox in the file system directories, as specified in the configuration file. The configuration file is looked up in the user home directory. If it is not found and no configuration file is specified on the command line, the program will ask th...
269357411bfffaece175035ded56a5fef891bcee
likwoka/old_py_stuffs
/silverlib/silverlib/dbaccess/generic.py
2,927
3.609375
4
""" A RDBMS-independent class for database/SQL handling. This simplifies Python's DBAPI for convenience. To use, either pass in a RDBMS specific connection, or subclass this class and override the constructor __init__(). """ class ConnectionHelper(object): """ This class simplifies the common usage for a dba...
0bf8c72a765605527fef633e074e4251ea69bb42
Arnav-17/Linear-Algebra
/Transpose.py
429
4.03125
4
import numpy as np if __name__ == '__main__': m = int(input('Enter number of rows\n')) n = int(input('Enter number of columns\n')) a = np.zeros((m,n)) for i in range(m): for j in range(n): a[i,j] = float(input(f'Enter a{i+1}{j+1}\n')) def Transpose(l): b = np.zeros((len(l),len(l[0]))) for i in range(len(l))...
7231620bbaa869ca08c65bd96a2c103beba1bc29
otkelbay/be-fullstack-TDD
/context_manager/context_manager.py
1,812
3.53125
4
#Here write your imports import os from contextlib import contextmanager def simple_open_and_write_without_context_manager(filename): ''' Write 'simple open and write done!' into first.txt, but take fitst.txt as argumant. Dont forget to close. 3 lines ''' if(f.closed): return True...
8159f73ef2efa0035b6b5f790ae16a55226cf4a8
PrimeTime416/PythonPractice
/functionPractice1.py
979
4.5
4
# # Example file for functions # # define a function def function1(): print("IN: function1") # defining function with aurguments def function2(arg1, arg2): print(arg1, arg2) # defining a function that returns a value def cube(x): return(x*x*x) # defining a function that uses default values def power...
435c1b880d56a30cd947d48994a3fd43a7034435
Russellparrish/it-python
/rock.py
1,286
4.0625
4
from random import randint from banner import banner banner("rock, paper, scissors", "Russell") print("we are going to play rock, paper,scissors. the first one to win two out of 3 rounds is the winner") pscore = 0 cscore = 0 while pscore < 2 and cscore < 2: player = int(input("1= Rock,2= Paper,or 3= Scissors?"))...
08b3bd15b9c1928c3170e7036cc2bdb49ebd064a
Russellparrish/it-python
/pythag.py
241
3.609375
4
from banner import banner import math banner("PYHAGOREAN CALCULATOR",'RUSSELL') print("we will help you find the missing side of the right triangle." "The lengths of the two legs are 'a' and 'b', the hypotenuse is 'c'.")
6e9f24bb66b17178e54d5974419b2585adbe0130
logao/leetcode
/daily/290_wordPattern.py
1,697
3.75
4
# 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 # 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 # # 示例1: # 输入: pattern = "abba", str = "dog cat cat dog" # 输出: true # # 示例 2: # 输入:pattern = "abba", str = "dog cat cat fish" # 输出: false # # 示例 3: # 输入: pattern = "aaaa", str = "dog cat cat dog" # 输出: false...
23d39959d8386a0bfe4c410e2b9889463610d8ef
dzui42unit/Python-notes
/source_1.py
978
4.5
4
#!/usr/bin/env python3 """Retrieve and print words from a URL Usage: python3 soutce_1.py <URL> """ import sys from urllib.request import urlopen # http://sixty-north.com/c/t.txt def fetch_words(url): """ Fetch a list of words from a URL Args: url: The URL of a UTF-8 text document Returns: A list of str...
286dff33bb187d43706ff74b2992f2461eab3856
dzui42unit/Python-notes
/copies_are_shallow.py
1,790
4.53125
5
#!/usr/bin/env python3 def main(): # define a list a = [[0, 5], [3, 7]] # copy a list b = a[:] print(a) print(b) # modify a[0] a[0] = [1, 2] print(a) print(b) # append element to the list b[1] b[1].append(4) print(a) print(b) # list repetition l = [1, 2, 3, 4] l_repeat = l * 4 print(l_repeat) ...
96230b4f6784b1d7a0c4e5ad7144837be6310587
anku580/Intro-To-Programming
/Madlib generator/project2.py
3,635
4.21875
4
print "" print "welcome to my quiz" # #questios easy_level=['_____ is the pm of india','_____ is the best 2016 bollywood movie','________ is the First indian women who won silver medal at rio Olympics','_______ develop 0 in Mathematics'] #string for easy level quiz medium_level=['_____ is the best singer worldwide...
b18ca38eba8f295efa64927b6b4e985a70a16ac3
brynned/Roster-Manager
/backups/project04.py
3,276
3.96875
4
import sys class Member: def __init__(self,member_name,phone_no,jersey_no): self.member_name=member_name self.phone_no=phone_no self.jersey_no=jersey_no menu_choice = 0 team_roster_dict = dict() while menu_choice != 9: print("\n\nWelcome to the Team Manager") print("===========Ma...
510c5300ad1e5e54f7776e82739efa3425459239
LiBrian415/PythonProjects
/Text/PigLatin/piglatin.py
375
3.5
4
def main(): vowels = {'a', 'e', 'i', 'o', 'u'} inp = input("Input a string: ") lst = inp.split() for index in range(0, len(lst)): s = lst[index] temp = list(s) i = 0 while s[i].lower() not in vowels: i += 1 lst[index] = s[i:]+s[0:i]+'ay' print (" "...
dcb5854da14d22454f76603fc3235600d937f069
LiBrian415/PythonProjects
/Text/FizzBuzz/fizzbuzz.py
485
3.90625
4
def main(): three = 1 five = 1 for i in range(1, 101): if three == 3 and five == 5: print('FizzBuzz') three = 1 five = 1 elif three == 3: print('Fizz') three = 1 five += 1 elif five == 5: print('Buzz'...
8c5fcca9b621d3a0c3496f976f248cc494123979
chapman-cpsc-230/hw4-ochoa117
/Heaviside.py
449
3.75
4
""" File: <Heaviside> Copyright (c) 2016 <William Ochoa> License: MIT <This code tests the Heaviside function to see if it works.> """ def H(x): if x < 0: value = 0 if x >= 0: value = 1 return value def test_H(): if H(0) != 1: print "Error: " if H(-1) != 0: print "E...
f0bb99f1a90222c63997b6f0a99e95078857c245
Toptimum/algo_and_structures_python
/Lesson_1/3.py
930
4.09375
4
# 3. По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через # эти точки. x1 = int(input("Введите значения координат первой точки (x1):")) y1 = int(input("и y1:")) x2 = int(input("Теперь введите значения координат второй точки (x2):")) y2 = int(input("и y2:")) print...
0cdb0f0978e830f749b1eaa29fc5887d05263873
Toptimum/algo_and_structures_python
/Lesson_3/8.py
1,068
4.0625
4
""" 8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк. Программа должна вычислять сумму введенных элементов каждой строки и записывать ее в последнюю ячейку строки. В конце следует вывести полученную матрицу. """ N = 5 M = 4 array1 = [] print(f"Заполним двумерный массив, размером [{N}][{M...
85033b539cf69fe9b96db3ded5a7d0f0df636c10
Toptimum/algo_and_structures_python
/Lesson_3/5.py
800
3.859375
4
# 5. В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию (индекс) в массиве. from random import randint N = 15 min_number = N min_number_index = None number_series = [randint(-N, N) for i in range(N)] print(f"Список случайно сгенерированных чисел: {number_series}") for i in r...
013966746dbda80142509c7d5c07f31c4ca247fb
Toptimum/algo_and_structures_python
/Lesson_5/2_easy.py
1,068
4.3125
4
# ну очень простая версия программы def addition_numbers(num1, num2): sum_numbers = hex(num1 + num2) sum_numbers = str(sum_numbers)[2:] return sum_numbers.upper() def multiplication_numbers(num1, num2): multi_numbers = hex(num1 * num2) multi_numbers = str(multi_numbers)[2:] return multi_numbe...
d12cbaff6a45c654b0fce4cb4c3e1f4b6e7a8ef0
sametozyurek/pythonExamples
/Donguler/faktoriyel_bulma.py
499
3.9375
4
print(""" *********************************************** \t\t Faktoriyel Bulma Programi Cikmak icin 'q' ya basiniz. *********************************************** """) while True: sayi=input("Sayi giriniz : ") if sayi=="q": print("Program sonlandiriliyor...") break else: sayi...
2e20f6e0d3f1a010f32fe71a222c500de286b9d6
erkankoca/python
/taban_degistirme.py
568
3.796875
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self): self.items.insert(0,item) def pop(self): return self.items.pop(0) def size(self): return len(self.items) def tabandegis(sayi,taban): degerler = "012...
8f3dfc50e620fed65deb7039f3753e4f166c4208
erkankoca/python
/parantez_tamamlama.py
896
3.84375
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): r...
f6c155404122c6ad046411444ead176b917a42b5
Nonnormalizable/NgMachineLearningPython
/ex1/ex1_multi.py
4,408
3.765625
4
#!/usr/bin/env python import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt ## Helper functions def featureNormalize(X): """ Make all features have mean 0 and std 1. Use pandas! """ # Goodness, this is easy with pandas. X_norm = (X - X.mean())...
1098e569f284e1abbfd531f1ef9a14b9fbeb76de
JamesWeiMoseley/HeapAndHashMap
/min_heap.py
4,325
3.765625
4
from a5_include import * class MinHeapException(Exception): pass class MinHeap: def __init__(self, start_heap=None): self.heap = DynamicArray() if start_heap: for node in start_heap: self.add(node) def __str__(self) -> str: return 'HEAP ' + str(self....
c100638dfe765ed97b4f1503b5a05db7e54c2959
k1r91/GB_Python2
/lesson_1/examples/code_assert.py
1,358
3.515625
4
""" Фамилия Имя Часов Ставка Иванов Иван 45 400 Докукин Филимон 20 1000 Ромашкин Сидор 45 500 """ import datetime from collections import namedtuple Salary = namedtuple('Salary', ('surname', 'name', 'worked', 'rate')) def get_salary(line): ''' Вычисление...
f35f3b7194734f3843400e13f9543b2f765bfac3
sayantann11/Automation-scripts
/pdf_encrypt/pdf_encryptor.py
2,058
3.71875
4
import argparse import getpass import pyAesCrypt import os import sys BUFFERSIZE = 64 * 1024 def parse_args(): parser = argparse.ArgumentParser(description="Encrypt " "and decrypt PDF files") parser.add_argument('-e', '--encrypt', dest='encrypt', type=str, ...
9e18e24b53c6120fcf1d1beacb2dadb8c1bedf4b
sayantann11/Automation-scripts
/url_shortener/url.py
436
4.03125
4
# Title :- URL Shortener # The URL shortener is application which takes url input from user and shorts it import pyshorteners import sys # url converter function def make_short(url): shorturl = pyshorteners.Shortener().tinyurl.short(url) return shorturl # this will take multiple url as input def main(): ...
cd39e7303aad0eadf9818c436287ca627470d877
Its-Triggy/Taylor_Series
/TaylorSeries.py
2,511
3.5
4
from numpy import cos, sin, tan, exp, pi import matplotlib.pyplot as plt class TaylorSeries: def __init__(self, accuracy = 10): self.function = input("what is the function? e.g. cos(x) : ") self.accuracy = min(accuracy, 7) self.domain = (-pi, pi) self.spacing = 0.003 def getResult(self, x): self.coefs ...
ed6f319d46cba724a75b2adf8a532f3d986ef269
mdutkin/m2translate
/m2translate/helpers.py
381
3.546875
4
__author__ = 'Maxim Dutkin (max@dutkin.ru)' def dict_reorder(item: dict) -> dict: """ Sorts dict by keys, including nested dicts :param item: dict to sort """ if isinstance(item, dict): item = {k: item[k] for k in sorted(item.keys())} for k, v in item.items(): if isinst...
dd8f62616c4874321de47e46cb32c8f86d00d217
akimi-yano/linux
/regex/regexfun.py
1,083
3.8125
4
import re sentence = "Hello. Bello. World!" print('Sentence: "{}"'.format(sentence)) pattern = r"ello" print("\n######## Pattern 1: {}".format(pattern)) matched = re.match(pattern, sentence) print("Using match(): {}".format(matched)) searched = re.search(pattern, sentence) print("Using search(): {}".format(searched))...
055e555872f2cc5a6b3b6ca80b8ac5ce0fb51146
brendonwelsh/SimpleGame
/src/player.py
1,240
3.5625
4
from constants import DEFAULT_PLAYER_SPEED import pygame class Player: """ Player class """ def __init__(self, x, y, sprite, walk_left_sprites, walk_right_sprites, vel=None): """ Initialize player with an x and y position. :param x: x position :param y: y position ...
e00fe1b81b2fb31dbb0389f5d9edd263708e7940
acalinog/CSS225
/M7P2AC.py
151
3.984375
4
def sum(a, b): sum = a + b a = 1 b= 5 if sum < 10: print("less than 10") if sum > 10: print("greater than 10")
c57f1d68b598623d3b638c71cd40c31d5ce30831
acalinog/CSS225
/Chapter1moduleDRAFT.py
914
3.984375
4
#Chapter 1 def start(): print("Hello! What is your name?") print("It was a sunny September morning. There was a dog laying on the porch and a cat meowing in the grass. The house was green with moss and the air smelled of apples.") #player needs to pick which animal to interact with first. Dog or cat? or if ...
6c72542d3711f2dd291d7d3d1e784c9bf936db16
hariprasath-sivanandam/Algorithm-and-DS
/dynamic prog/jump_game.py
900
3.796875
4
""" Question: https://leetcode.com/problems/jump-game/description/ 55. Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. ...
c4dcb6ea46fd19878a1d4acd8798c41eef6f6829
hariprasath-sivanandam/Algorithm-and-DS
/LinkedList/Reorder List.py
1,434
3.53125
4
""" Question: https://leetcode.com/problems/reorder-list/description/ 143. Reorder List Given a sorted linked list, delete all duplicates such that each element appear only once. Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not modify the values in the list's nodes, o...
ad79121bdd70227d10883e4120a294a43a5294f0
hariprasath-sivanandam/Algorithm-and-DS
/LinkedList/Remove Duplicates from Sorted List.py
943
3.578125
4
""" Question: https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ 83. Remove Duplicates from Sorted List Given a sorted linked list, delete all duplicates such that each element appear only once. Example 1: Input: 1->1->2 Output: 1->2 Example 2: Input: 1->1->2->3->3 Output: 1->2->3 Solutio...
0600bb65ba0b746841b9e5f0fc8501d170e0c5ef
silviolleite/minicursopython2018
/tabuada.py
414
3.875
4
while True: n = int(input("Digite um número: ")) print() print("Tabuada com for") for i in range(1,11): print("{} x {} = {}".format(n, i, n*i)) print() print("Tabuada com while") j = 1 while j <= 10: print("{} x {} = {}".format(n, j, n*j)) j = j + 1 contro...
259d8771b10db0491d9a6ec5c9e5dd6a31635b3a
mikejaron1/zipfian
/7-special-topics/1-graphs/shortest_path.py
1,896
3.90625
4
from Queue import Queue from load_imdb_data import load_imdb_data from sys import argv def shortest_path(actors, movies, actor1, actor2): ''' INPUT: actors: dictionary of adjacency list of actors movies: dictionary of adjacency list of movies actor1: actor to start at actor2: a...
8f916b86a237518b8583e380669cf97389044bc4
mikejaron1/zipfian
/1-software-engineering-and-eda/5-pandas-tutorial/individual_soln.py
9,928
3.8125
4
### To just do some basic exploratory analysis, compute the most common cause of hospitalization (affliction) Compare the execution time of using value_counts() vs. counting with groupby() import pandas as pd ## 1) FIND WAS THE MOST COMMON ILLESS... ### TO FIND THAT YOU HAVE TO GROUPBY THE ILLNESS, AND SUM THE DISCH...
d7f62aad0239d2880a90f6534763ec2b76600b4f
mikejaron1/zipfian
/assessments/assessment-day1/solution.py
7,036
4.15625
4
### Python def count_characters(string): ''' INPUT: STRING OUTPUT: DICT (STRING => INT) Return a dictionary which contains a count of the number of times each character appears in the string. Characters which would have a count of 0 should not need to be included in your dictionary. ''...
2e59fe808f02fe278660b26c9c3c5b92aed1d989
mikejaron1/zipfian
/3-regression/5-gradient-descent/gradient_ascent.py
4,912
3.765625
4
import numpy as np from regression_functions import add_intercept class GradientAscent(object): def __init__(self, cost, gradient, predict_func, fit_intercept=True, scale=False): ''' INPUT: GradientAscent, function, function OUTPUT: None Initialize class variables. Takes two func...
a8998b6da0d7f21e01eb53ca2a222317412f174b
kotaroyama/Suggest-New-Movie
/retrieve.py
1,249
3.640625
4
import json import random import requests import credentials import database def generate_imdb_id(): """Generate a random IMDb ID Each movie has a unique IMDb ID, which consists of letters 'tt' followed by 7 digits. """ imdb_id_int = random.randint(0, 9999999) imdb_id_string = 'tt' + str(i...
9417ae7e67fd9a436a35a9acefee0b47248e6da7
neharika279/temporal-ordering-software
/implementations/graphFunctions.py
2,140
3.90625
4
import sets from sets import Set, ImmutableSet def add (graph, i, j=None, weight=1, undirected=True, noselfloops=True): """Add a vertex or edge to a graph.""" if j is None: if i not in graph.keys(): graph[i] = {} else: if (i==j) and noselfloops: return if i ...
b7740274cef278d5348dab6659df94df486b6889
git-vinit/mycapprojectspython
/schooladminprogram.py
1,370
3.921875
4
import csv def write_into_csv(info_list): with open('student info.csv', 'a', newline='') as csv_file: writer = csv.writer(csv_file) if csv_file.tell() == 0: writer.writerow(["NAME", "AGE", "Class", "Division", "Register no"]) writer.writerow(info_list) if __name__ ...
7dfcd6b928b4e5d51aec991d87386681347a0352
zie225/UBC_ComputerVision
/ComputerVision_course/Assignment 4/assignment4/SIFTmatch.py
7,899
3.671875
4
from PIL import Image, ImageDraw import numpy as np import csv import math def ReadKeys(image): """Input an image and its associated SIFT keypoints. The argument image is the image file name (without an extension). The image is read from the PGM format file image.pgm and the keypoints are read from th...
052c075ddbacdfc2507231fc05c6e8f20f7acde4
simtangaran/Python
/greater.py
316
4.125
4
a=int(input('Enter an integer ')) b=int(input('Enter an integer ')) c=int(input('Enter an integer ')) if(a>b): if(a>c): print(a,' is greater') else: print(f'{c} is greater') else: if(b>c): print(f'{b} is greater') else: print(f'{c} is greater')
4e5f62362f7254f0234b6d7457115c2a1015c230
simtangaran/Python
/sum alter.py
166
3.984375
4
a=int(input('Enter an integer ')) sum=0 for i in range(1,a+1): sum+=i if(i!=a): print(i,end='+') else: print(a,'=',sum)
162efabffac8e6cbb090014fc746f9528789538e
stardeltapower/power_calculators
/power_factor.py
2,123
3.75
4
import math def calculate_power_values(input_var_1, value_1, input_var_2, value_2, decimal_places=4): """ Calculate power factor, apparent power, active power, reactive power, and angle given any two of them. Parameters: input_var_1, input_var_2: Variables to be calculated. Can be 's', 'p', 'q', 'pf',...
272e0d53be7ccd2d9d472733fcd7dc715b893ff4
sqlalchemyorg/zzzeeksphinx
/tools/fix_xrefs.py
16,466
3.609375
4
#!/usr/bin/env python import argparse import os import re import sys import readchar BOLD = "\033[1m" NORMAL = "\033[0m" UNDERLINE = "\033[4m" PURPLE = "\033[95m" CYAN = "\033[96m" DARKCYAN = "\033[36m" BLUE = "\033[94m" GREEN = "\033[92m" def _token_to_str(token): if isinstance(token, str): return tok...
6635d8911646c977ffa43440e9d5d549bd5349ee
AssaultKoder95/codility-training
/level02/frog-river-one.py
1,329
3.609375
4
def solution(distance, falls): if len(falls) == 1 and falls[0] and distance == 1: return 0 elif len(falls) < distance: return -1 positions = set(range(1, distance + 1)) for minute, pos in enumerate(falls): if pos in positions: positions.remove(pos) if n...
82f8b351ea78f596f41494e6fee4723d8b907643
AssaultKoder95/codility-training
/level05/stone-wall.py
675
3.609375
4
""" N in [1..10^5] A[i] in [1..10^9] """ def solution(heights): stack = [] blocks = 0 for height in heights: while stack and stack[-1] > height: stack.pop() if not stack or stack[-1] < height: stack.append(height) blocks += 1 return blocks def...
694fa1f066734a8bf242d8bdcf36b1ef4dfd5bd2
medusaGit/marioAI
/src/helperFunctions.py
3,504
3.53125
4
import numpy as np def write_score(filename, scores): import os l = len(scores) for i in range(100): fn = "res/%s_%d_%d" % (filename,l,i) if not os.path.isfile(fn): break f = open(fn, "w") scores = map(str,scores) f.write(" ".join(scores)) f.flush() f.close()...
83b90dbdccf022bc388ad2f6dfd47d2783096697
alexkim-git/python_snippets
/TimePeriods.py
18,594
3.53125
4
# ------------------------------------------------------------------------------- # Name: TimePeriods.py # Purpose: Manipulate and modify lists of time ranges # Author: Alexander Kim # Created: 10 Oct 2014 # Version: v0.1 # ------------------------------------------------------------------------------- import ca...
0361f21a9e20c7771ef211dbfa35eafb476745b7
jtcass01/Machine-Learning-Classes
/Deep Learning Prerequisites Linear Regression In Python/Practical Machine Learning Issues/gradient_decent.py
1,068
3.5625
4
import numpy as np import matplotlib.pyplot as plt # number of data points N = 10 # Dimensionality D = 3 # Initialize an NxD matrix X = np.zeros((N,D)) # Set the bias term X[:,0] = 1 # Set the first five elements of the first column to one, last 5 of second column to one X[:5,1] = 1 X[5:,2] = 1 #Set the targets to...
5ef2691b3a48a5968b1b4fb334ab62c5643e3956
jtcass01/Machine-Learning-Classes
/Deep Learning Prerequisite Logistic Regression in Python/Practical Concerns/l1_regularization.py
1,028
3.921875
4
import numpy as np import matplotlib.pyplot as plt def sigmoid(z): return 1 / (1+np.exp(-z)) N = 50 D = 50 # Uniformly distributed numbers between -5 and +5 # Subtract 0.5 to center it around zero, then multiply by 10 X = (np.random.random((N,D)) - 0.5)*10 # Only the first three dimensions actually effect the o...
2e2e94e946d088591417ebdbd6f90d5b8fd89139
jtcass01/Machine-Learning-Classes
/Deep Learning Prerequisites Linear Regression In Python/Multiple Linear Regression and Polynomial Regression/systolic.py
1,037
3.75
4
# need to sudo pip install xlrd to use pd.read_excel # data is from: # http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/mlr/frames/mlr02.html # The data (X1, X2, X3_ are for each patient. # X1 = systolic blood pressure = Output # X2 = age in years = Input # X3 = weight in pou...
c8f56027c433edfa75d9b4450ffc991d813d040d
KRios88/CSLab5
/Lab 5.py
2,165
3.703125
4
#Kevin Rios #Lab 5 #Last Modified = 12/5/18 class Heap: def __init__(self): self.heap_array = [] def insert(self, k): self.heap_array.append(k) self.perc_upwards(len(self.heap_array)-1) def perc_upwards(self, node_ind): while node_ind > 0: parent_ind = (node_ind-1)//2 if...
96729fa936e1bf76d549cb6d405f12c085e55e4b
a210082/I2P-Summative
/Summative Coding/2. questions with function (sample) code/quiz with functions version 2.py
2,237
4.25
4
print (" Welcome to python general knowledge quiz created by Yuto Lam.") # print function to print out message print (" This is a sample code/ quiz with 5 random questions. You will either to have answer a true or false question or a multiple choice question") #print out messages # print function to print out message...
c40c516b75bd6bbb9e6bdaa05a1db6f449b0fa86
a210082/I2P-Summative
/Programming Final Project/app.py
8,239
4.0625
4
from tkinter import * #import tkinter from pygame import mixer # import pygame and music and audio stuff import meditation as med # from the meditation.py and call it med class MainWindow(Frame): # class is where all of the instances are kept def __init__(self, *args, **kwargs): # self represen...
fd2d82bcc1dfb03822e5792feeb3e55e1c926160
mw5678/PythonProjects
/Black Jack.py
6,593
3.890625
4
''' This is a basic black jack game. The player can only hit or stand. ''' import random import time import os suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Fiv...
d6642fe6d3a7801344c6f75df36e800b7ecfb866
skymemoryGit/HackRank_interview_tools_and_Solution
/Superdigit.py
1,456
3.78125
4
#!/bin/python3 import math import os import random import re import sys #ottimale 1!! def superDigit(n, k): # check single digits if k == len(n) == 1: return int(n) res = 0 for num in n: res += int(num) return superDigit(str(res*k),1) #...
2f8f190f18e3ca3eaad9b39fdb24fa7684205a6b
skymemoryGit/HackRank_interview_tools_and_Solution
/minmaxsum.py
1,324
3.625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #!/bin/python3 import math import os import random import re import sys # # Complete the 'miniMaxSum' function below. # # The function accepts INTEGER_ARRAY arr as parameter. # def miniMaxSum(arr): X= findmin(a...
f5e756fcc53aaed5d386360c02b91222f7453d12
Shibu778/LaDa
/ga/escan/nanowires/converter.py
6,470
3.578125
4
""" Function object to convert to and from bitstrings and nanowires. """ __docformat__ = "restructuredtext en" class Converter(object): """ Converts to and from bitstrings and nanowires. """ def __init__( self, lattice, growth=(0,0,1), core_radius=2,\ core_type='Si', types=['Si', 'Ge'], thickness=0...
fbfe42eb43a6c713aed11505e5e20eebff840392
Shibu778/LaDa
/process/process.py
5,855
3.90625
4
from abc import ABCMeta, abstractmethod class Process(object): """ Abstract base class of all processes. This class defines the interface for processes. Derived classes should overload :py:meth:`start`, :py:meth:`poll`, and :py:meth:`wait`. The first is called to actually launch the sub-process...
3fd0a8159c47f37dc722effb3043458e5c0b3bd6
Shibu778/LaDa
/tools/input/keywords.py
22,395
3.8125
4
class BaseKeyword(object): """ Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to read the original input ...
02c5e0769a4d27440eb3f0ad82e1bfd447bb749f
Shibu778/LaDa
/process/iterator.py
8,590
4.03125
4
from .process import Process class IteratorProcess(Process): """ Executes an iteration function in child process. An iterator process is a *meta*-process which runs other processes sequentially. It is one which needs iterating over, as shown more explicitely below. Its interface is fairly simila...
aa92b9615af57c79c27afcf1aed398429aa9d788
Shibu778/LaDa
/process/program.py
13,879
3.625
4
from .process import Process class ProgramProcess(Process): """ Executes an external program This process creates and manages the execution of an external program, say VASP_ or CRYSTAL_, via a `subprocess.Popen`__ instance. The external program can be launched with or without MPI, with or without s...
9157dba823914c21f573def3f40e3e3f3f4c5260
TopSE-ML/blackjack
/tests/test_hand.py
3,277
3.65625
4
import unittest from blackjack.card import Card from blackjack.hand import Hand class TestHand(unittest.TestCase): @staticmethod def make_hand(cards): hand = Hand() for card in cards: hand.add(card) return hand def test_score_is_0_when_created(self): hand = ...
db56838a807341df2fcc25b524cfdfb6514211f7
straight-outta-sorbonne-bmwc/Code
/Code-master/simulation/arene/arene.py
6,121
3.6875
4
#coding: utf-8 import numpy as np import math import random import time from . import obstacle class Arene: obstacles = [] # liste d'obstacles def __init__(self, robot): self.taille=1000 # la taille de l'arene est fixe maintenant comme sa pas de prise de tête self.robot=robot ...
9c6e2958dc70382c0b72fca6bd1dd5f39464d18c
VitorAcosta/Exercicios-Tkinter
/Ex9-AgendaTelefonica.py
2,532
3.65625
4
import tkinter as tk from tkinter import filedialog class Tela: def __init__(self, master): self.nossaTela = master #variavel de controle que verifica se já foi escolhido um arquivo #para o salvamento de dados. Evitando a abertura do FileDialog toda #vez que for necess...
3cf8084f9a0dad41a4f71edf81888993b923124f
msknapp/machine-learning
/home_prices/encode/zoning.py
1,383
3.609375
4
import pandas as pd import numpy as np def zoning_to_ordinal(zone: str) -> float: # This converts a zone into a number, in a way that the distance between them makes more sense. if isinstance(zone, float): return zone elif isinstance(zone, int): return float(int) elif isinstance(zone, ...
b8e6cc756d5295a3edf8de308176e546f961968d
Delipriyap/Exercise
/Python Practice/fact.py
113
4.125
4
def factorial(n): f=1 for i in range(1,n+1): f=f*i print(f) n=int(input("Enter the value: ")) factorial(n)
b9a48f578d682760ccd66214d4e231b92a4ce1d0
Delipriyap/Exercise
/Python Practice/facres.py
112
3.8125
4
def fact(n): if(n==0): return 1 return n*fact(n-1) c=int(input("Enter the value:")) val=fact(c) print(val)
7c33166592de3fb63199fca083f5ac750d18beda
yoshinGO/nlp100
/chapter02/n19.py
599
3.609375
4
""" 各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ. 確認にはcut, uniq, sortコマンドを用いよ """ from collections import defaultdict with open('../data/hightemp.txt', 'r') as data_file: col1_elements = [line.strip().split()[0] for line in data_file] count_col1 = defaultdict(lambda: 0) for ele in col1_elements: count_col1[el...
397e485d7fe6630d23822eeb4783563ace8fa6b8
yoshinGO/nlp100
/chapter01/n05.py
575
3.8125
4
""" 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ. この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ. """ def make_n_gram(seq, n, unit): if unit == 'word': seq = seq.split() return [list(seq[i:(i+n)]) for i in range(len(seq) - n + 1)] if __name__ == "__main__": example_sentence = 'I am an NLPer' ...
f913fb20b427870e42bbd00ff2bb05cf21e9d964
yoshinGO/nlp100
/chapter04/n34.py
520
3.609375
4
""" 2つの名詞が「の」で連結されている名詞句を抽出せよ. """ from constants import FNAME_PARSED from n30 import neko_lines for morphemes in neko_lines(FNAME_PARSED): number_of_morpheme = len(morphemes) if number_of_morpheme > 2: for i in range(1, number_of_morpheme - 1): if morphemes[i]['surface'] == 'の' and morphem...
1d83943e0f6e37c41323500dcb25b4bc18c7dad1
rknunes/exercicios-aula304
/exercicio1.py
200
3.8125
4
def numero_par(a): numero = (a) %2 == 0 return numero n1 = int(input('Escolha um número inteiro: ')) if (n1) %2 == 0: print('O número é par.') else: print('O número é impar.')
caca6dab733886b38e425313084bc1da10b4ceeb
asao1103/samurai_python
/func.py
484
3.59375
4
def hello(a, b): print(a + b) hello(21, 29) # 5.4 演習(1) def calc(a, b): print(a * b) calc(2, 3) # 5.4 演習(2) def traingle_area(a, h): return a * h / 2 print(traingle_area(2,3)) # 5.4 演習(3) file_list = [] def add_list(name): file_name = name + ".py" file_list.append(file_name) add_l...