blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b579c70ca6c69a24d139b79eff4d35be6b3a3da5
betty29/code-1
/recipes/Python/573453_String_representatidict_sorted/recipe-573453.py
662
3.5
4
def genkvs(d, keys, joiner): for key in keys: yield '%s%s%s' % (key, joiner, d[key]) def dictjoin(_dict, joiner, sep): keys = sorted(_dict.iterkeys()) return sep.join(genkvs(_dict, keys, joiner)) def test_dictjoin(): """This test function can be used for testing dictjoin with py.test of no...
1354105660b167e33f7cbcc9205820b1609c6186
AaronTengDeChuan/leetcode
/leetcode/45.JumpGameII_AC.py
422
3.703125
4
#!usr/bin/env python #-*-coding:utf-8-*- import sys class Solution(object): def jump(self, nums): curMax = 0 curLen = 0 step = 0 for i in range(len(nums)): if curLen < i: step += 1 curLen = curMax curMax = max(curMax, nums[i] +...
9a7c1a9ab6ffdcd61c57325721a31f2411660693
AdamZhouSE/pythonHomework
/Code/CodeRecords/2908/60759/258584.py
143
3.5625
4
n = int(input()) strSet = set() for i in range(n): item = ''.join(sorted(input())).strip() strSet.add(item) print(len(strSet), end='')
e4997f7c1dfbc920d3f254304b41e82273a6a428
laoniule/pythoncrashcourse
/Chapter07/rollercoaster.py
216
4.09375
4
#!/usr/bin/python height = input("How tall are you, in CM\n") height = int(height) if height > 170: print("\nyou are enough tall to ride") else: print("\nYou will be able to ride when you're allite older")
dd3f38ce711633d336bfbbf76c9e07e558d221cf
rlavanya9/cracking-the-coding-interview
/recursion/quarters.py
1,046
3.828125
4
def count_money(n): countHelper(n, "Quarter") def countHelper(n, tyoe): count = 0 sum = 0 if tyoe == "Quarter": while n > count*25: sum+= countHelper(n - count*25, "Dime") elif tyoe == "Dime": while n > count*10: sum+=countHelper(n - count*10, "Nickel") e...
4053912f6ba6448270f646efce7aadc02530c338
FelSiq/statistics-related
/dist_sampling_and_related_stats/normal_sampling_box_muller.py
2,346
3.796875
4
"""Samples from normal distribution using Box-Muller transformation. The transformation is applied to the bivariate normal distribution. """ import typing as t import numpy as np def sample_normal(num_inst: int = 1, loc: float = 0.0, scale: float = 1.0, random_s...
42c1c96bb6f3d31508024329487787de13e64d5f
emastr/2D_Solar_System_Simulation
/plotData2.py
1,746
3.515625
4
import matplotlib.pyplot as plt import numpy as np def readData(filename): print("Reading...") file = open(filename + ".txt") text = file.read() file.close() print("Evaluating...") data = eval(text) print("Done!") return data def plotAngles(): data = readData("angle...
71f3c64e410dce1821fde4daedf027529983795a
nagask/leetcode-1
/503 Next Greater Element II/sol.py
970
3.671875
4
""" Similar to next greater element I, we keep a stack containing the indexes of the items that haven't been assigned a successor yet. The stack will contain a decreasing sequence, so the first item that is greater than the top of the stack is going to be the successor of the top of the stack. We have to traverse the a...
a77f28d9ebce756667d18318897dbffe6b667991
Vanditg/Leetcode
/Number_of_1_bits/EfficientSolution.py
1,308
3.828125
4
##================================== ## Leetcode ## Student: Vandit Jyotindra Gajjar ## Year: 2020 ## Problem: 191 ## Problem Name: Number of 1 Bits ##=================================== # #Write a function that takes an unsigned integer and return the number of '1' bits it has #(also known as the Hamming w...
5c08fcc433079c5e2aca8b086c9625a7e3942245
niujie/Python_Course_2020
/code/P2/fibonacci_recursion.py
325
4.46875
4
def fibonacci_recursion(n): """calculate Fibonacci sequence using recursion""" if n < 3: # n == 1 | n == 2 return 1 else: return fibonacci_recursion(n - 1) + \ fibonacci_recursion(n - 2) if __name__ == '__main__': for i in range(21): print(i, fibonacci_recursion...
49764303d5eb617c03f73c006b51478d386c5b45
pablosq83/Pruebas3
/superpos.py
1,178
3.84375
4
#!usr/bin/python # -*- coding: utf -8 -*- """ Función que recibe como parámetro dos arreglos y se debe determinar si hay elementos en común o no. Devuelve cierto si hay al menos uno en común o de lo contrario devuelve falso. Autor: Pablo Sulbarán (psulbaran@cenditel.gob.ve) Fecha: 27-02-2018 """ vector1 = [] n = int(...
bd6eabd145679684b1ca0b551bfdcc01c2be7aa6
dnov09/InterviewPrep
/Sorting Algorithms/algos.py
1,493
4.15625
4
# Sorting Algorithms #%% def selection_sort(lst): # find the minimum in the unsorted subarray for i in range(len(lst)): min_idx = i # checks the next number and performs the check for j in range(i + 1, len(lst)): if lst[min_idx] > lst[j]: min_idx = j #...
d07ae0bf949aaf7512b46343ec11d4a6bd462a7f
Jesus-Acevedo-Cano/holbertonschool-interview
/0x03-minimum_operations/0-minoperations.py
335
3.59375
4
#!/usr/bin/python3 """ Method that calculates the fewest number of operations """ def minOperations(n): count = 0 div = 2 if not isinstance(n, int) or n <= 1: return 0 while n > 1: if n % div != 0: div += 1 else: n = n / div count += div ...
fd2ff6b7c8ea0ed252092c453d1eb5924ad2b09c
winterfellding/mit-cs-ocw
/6.006/clrs/chap2.py
2,224
3.96875
4
def insert_sort(ary): for i in range(1, len(ary)): key = ary[i] j = i - 1 while j >= 0 and ary[j] > key: ary[j + 1] = ary[j] j -= 1 ary[j + 1] = key ary = [5, 2, 4, 6, 1, 3] print(ary) insert_sort(ary) print(ary) """ ex2.1-1 [31, 41, 59...
7b441bf0e6044f6d50e5760f359f59e9ec5bf766
jakobpederson/cookbook
/flatten_a_nested_sequence.py
379
3.578125
4
from collections import Iterable class FlattenANestedSequence(): def flatten(self, lst): return list(self.recurs(lst)) def recurs(self, lst): print(lst) for value in lst: if isinstance(value, Iterable) and type(value) not in (str, bytes): yield from self.re...
ea74dd0a425c0f42188884e7758a1051c6a674d9
whalejasmine/leetcode_python_summary
/2-24/314-Binary-Tree-Vertica- Order-Traversal.py
2,803
4.34375
4
# Time: O(n) loop all tree node # Space: O(1) # Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). # If two nodes are in the same row and column, the order should be from left to right. # Examples 1: # Input: [3,9,20,null,null,15,7] # 3 # ...
336cdaa8db21efa587a762e00adfe4e4dbafa28a
sipakhti/code-with-mosh-python
/CS 112 Spring 2020/Functions.py
8,182
4.28125
4
def count_multiples(num1, num2, N): """ Reutrns the number of multiples of N that exist between num1 and num2 N cannot be 0 while num1 and num2 can be in any order """ count = 0 if num1 > num2: num1, num2 = num2, num1 for i in range(num1, num2 + 1): if i % N == 0: ...
cea1df4b30ce59cee68d61e845046444747aa76b
idotc/Interview-And-Algorithm-Experience
/第一章/1.1节/1_1-2.py
626
3.875
4
import sys def ReverseWord(s, to): start = 0 while(start < to): t = s[start] s[start] = s[to] s[to] = t start = start + 1 to = to - 1 return s def LeftRotateWord(s): s = s.split(" ") n = len(s) s = ReverseWord(s, n-1) str = [] for i in range(2*n-...
ec7c0724f1e35485301cef84330976386244fc91
tsotonov2604/StringManipulation-
/ReverseStr+RemoveNonLetters.py
334
4.0625
4
import string def reverse_letter(stri): letters = string.ascii_letters reverse = stri[::-1] new = [] for letter in reverse: for char in letters: if letter == char: new.append(letter) word = "".join(new) print(word) reverse_letter(...
02ddf965ba6d702b8adbfd667a95d4f4c70289c3
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test_3.31.20.py
678
3.59375
4
#Test for March 31st, 2020 # # military_gen.py # user_letters = input("Give me some letters : ") # mil_dict = {'a': 'alpha', # 'b': 'bravo', # 'c': 'charlie', # 'd': 'delta', # 'e': 'echo', # 'f': 'foxtrot', # 'g': 'golf'} # output = '' # for letter in user_letters: # output += mil_dict[letter] + '' # prin...
1237b2a0a4e8960afa3b501262bfb94926d6dfc2
richruizv/Ejercicio_Media
/media.py
1,086
4.21875
4
import random as rd def run(): print(''' ************************************************************ WELCOME TO MEDIA CALCULATOR This program calculates the media of a random sample from a series of numbers. ************************************************************ ...
02983b7ce46fd0556f8cdd4d61b78545d21c30b8
ivan-fr/oc_projet_8
/purbeurre/utils.py
1,837
3.53125
4
def get_words_from_sentence(sentence): """Get words from sentence.""" cursor, i, sentence = 0, 0, sentence.strip().lower() + " " while i <= len(sentence) - 1: if not sentence[i].isalpha() and not sentence[i] == "'": if i - 1 >= cursor: word = sentence[cursor:i] ...
b0d07a7552b88785387c63cc677186fbe47c9c2c
SebastianColorado/DylansBot
/Main.py
1,329
3.5625
4
"""Tweets out a random city name + the phrase.""" import csv import twitter import os import random import time numRows = 15633 cities = [] with open('cities.csv', 'rt') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: cities.append(row[0]) # Authenticate the twitter bot by ...
4ef3686e8a60f113c0db1882a7fee486b2b59afb
ShafiqullahTurkmen/kodluyoruzilkrepo
/Simple Coffee Machine/coffee_machine.py
2,075
4.15625
4
water = 400 milk = 540 coffee_beans = 120 cups = 9 money = 550 print('Write action (buy, fill, take, remaining, exit):') n = input() print() while n != 'exit': if n == 'buy': print('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:') x = input() ...
6b847d057c4b53910eaa50a0eefa4a2cd256acf4
jdanray/leetcode
/minCostClimbingStairs.py
806
3.5
4
# https://leetcode.com/problems/min-cost-climbing-stairs/ class Solution(object): def minCostClimbingStairs(self, cost): memo = [0 for _ in range(len(cost))] memo[0] = cost[0] memo[1] = cost[1] for i in range(2, len(cost)): memo[i] = cost[i] + min(memo[i - 1], memo[i - 2]) return mi...
f7495ff73c18c6eb62a34418cac696a2d8555f4d
Gratisfo/HSE-Programming
/hw2/Caeser's_cipher.py
253
3.75
4
#Caesar's cipher alpha = ' абвгдеёжзийклмнопрстуфхцчшщъыьэюя' n = int(input()) s = input() res = '' for letter in s: res += alpha[(alpha.index(letter) + n)] print('Result: ', res)
06c5e879bdf271151b5407c55d2bb1d580f228a8
ganzevoort/project-euler
/problem67.py
866
3.828125
4
""" Maximum path sum II By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triang...
1ef5d11717692288de6b9b8b61816c1fdaf5109c
jethrozperez/python_work
/python_for_everybody_solutions/ch_7_ex.py
743
3.8125
4
### Write a program that prompts for a file name then opens that file ### and reads through looking for ''X-DSPAM-Confidence: 0.8475' ### Count those lines and extract floating point values, extract the ### value and average those values to produce the output 'Average spam confidence: 0.750718518519' fname = input...
d83d23ff486a2c3660ee1b0db8004addb6ba7a47
RodrigoSierraV/holbertonschool-interview
/0x13-count_it/0-count.py
1,337
3.84375
4
#!/usr/bin/python3 """ Recursive function that queries the Reddit API""" import requests def count_words(subreddit, word_list, after="", to_print={}): """ Function that queries the Reddit API """ if not after: for word in word_list: to_print[word] = 0 url = "https://www.reddi...
e3ca668d88674d2934ac7994f959d526b392cc59
dimasiklrnd/python
/highlighting numbers, if, for, while/The number of even elements.py
610
4.28125
4
'''Посчитать количество четных элементов в массиве целых чисел, заканчивающихся нулём. Сам ноль учитывать не надо. Формат входных данных Массив чисел, заканчивающийся нулём (каждое число с новой строки, ноль не входит в массив) Формат выходных данных Одно число — результат.''' n = int(input()) x = 0 while n != 0: ...
c0096bceeb31121799415080ba033af2173780ae
OO7kartik/AllMachineLearning
/K_nearest_neighbours.py
1,968
3.828125
4
# training data = training_set # training labels = training_labels ( either 1 or 0 ) # validation_set # validation_labels # THE MANUAL METHOD #euclidean distance def distance(obj1,obj2): squared_difference = 0 for i in range(len(obj1)): squared_difference += (obj1[i] - obj2[i])**2 return squared_difference**0...
a7d01fd2e5119213ad1b9ef672a7347924a96f95
jackowayed/advent2020
/10.py
1,280
3.546875
4
#!/usr/bin/env python3 import fileinput import re def jumps(nums, n): return sum(nums[i] + n in nums for i in range(len(nums) - 1)) def read(): raw = sorted([int(line.strip()) for line in fileinput.input()]) nums = [0] nums.extend(raw) nums.append(nums[-1] + 3) return nums def part1(): ...
e1decf06a38d8f20b6cc7c7938c9972fefe21d87
darkhipo/Air_Traffic_Controller
/AirTrafficController_Python/FlightCombinator.py
1,396
4.09375
4
""" This file contains the algorithm of how all the FlightPlan possibilities are calculated. """ import itertools from math import factorial class FlightCombinator: # public class FlightCombinator implements Iterable<FlightPlan>{ def __init__(self, lf, r): ...
ae36b475a1bb460c95f07e3787858af6ba6650b8
haivmptit/ManageAccount
/test.py
422
3.609375
4
def allLongestStrings(inputArray): lenn = 0 out = [] for i in inputArray: if len(i) > lenn: lenn = len(i) print(lenn) for i in inputArray: print(i + " " + str(len(i))) if len(i) == lenn: out.append(i) return out a = ["a", "abc", "cbd", "zzzz...
e61563a47486fcd8f79e658e536167f6e03274ae
nojongmun/python_basics
/step05_array/array/arrayEx5.py
566
3.75
4
# 크기가 5인 정수형 배열을 만들고 # 배열에 데이터를 입력 받아서 출력하고 최대 , 최소값을 구하세요 # ar[0]의 값을 입력하세요 : 25 # ar[1]의 값을 입력하세요 : 25 # ar[2]의 값을 입력하세요 : 25 # ar[3]의 값을 입력하세요 : 2 # ar[4]의 값을 입력하세요 : 25 # 최대값 : 25 # 최소값 : 2 import array ar=array.array('i') for i in range(0,5): ar.append(int(input('ar[%d]의 값을 입력하세요 : ' % i))) print(ar) pr...
57d16485447515b0a032e8cf171047f208c2b353
emuuli/advent_of_code_2018
/1_exercise/solution.py
784
3.734375
4
FILE_NAME = "input.txt.txt" def read_in_file(file_name): with open(file_name, 'r') as input_file: result = [int(line) for line in input_file] return result def find_first_duplicate(i_list): results = set() current_result = 0 results.add(current_result) while True: for i in ...
2548010404a3be8ff220048ea763862d8d546b5f
jakesig/cs2020fall
/Week 7/Week 7 - Web/lab4.py
311
3.703125
4
#!/usr/bin/python print( "Content-type: text/html\n\n" ) print("<TITLE>Lab 4</TITLE>") print("<h1>Lab 4</h1>") print( """ <html> <body> <table> """ ) for x in range(100): print("<tr><td>%s</td><td>%s</td></tr>" % (x+1, (x+1)*100)) print( """ </table> </body> </html> """ )
df59099ceb33d93ad6e3f47b700162479f46286e
timing2211/sawppy_ros
/scripts/chassis_wheel_calculator.py
1,932
4.28125
4
#!/usr/bin/python3 import sys class chassis_wheel: """Information needed to calculate angle and speed for a specific wheel Axis orientation conforms to REP103. (+X is forward, +Y is left, +Z is up) https://www.ros.org/reps/rep-0103.html""" def __init__(self, name, x, y): self.name = name ...
b42681078fd055e910b0866022f905c98303f796
ywcmaike/OJ_Implement_Python
/leetcode/16.11. 跳水板.py
958
3.671875
4
# author: weicai ye # email: yeweicai@zju.edu.cn # datetime: 2020/7/27 上午10:12 # 你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter,长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。 # # 返回的长度需要从小到大排列。 # # 示例 1 # # 输入: # shorter = 1 # longer = 2 # k = 3 # 输出: [3,4,5,6] # 解释: # 可以使用 3 次 shorter,得到结果 3;使用 2 次 shorter 和 1 次 long...
173d8ab466575fef56d453d44697ba2812dbd08f
tushant1037/InfyTQ
/assign20.py
818
4.0625
4
''' Write a python function, find_pairs_of_numbers() which accepts a list of positive integers with no repetitions and returns count of pairs of numbers in the list that adds up to n. The function should return 0, if no such pairs are found in the list. Also write the pytest test cases to test the program. Sample Inp...
4f5cd77c02bfd0baa7045c6bf02e42ee714bbbd9
Govrie/Govrie.github.io
/HW1-5.py
401
3.765625
4
#!/usr/bin/env python3 -tt """File: hello.py """ def get_digit_d(n): string_repr = str(abs(n)) digit_d = 0 for digit in string_repr: if (n % int(digit)) > 0: digit_d +=1 if digit_d == 0: return True else: return False #Run only if called as a script if __name__ ==...
218bbe55c6d949964db7d0a5b907b679c51f52d6
mucius/misc_patches
/viewvc/forChardet/toutf8.py
236
3.578125
4
import chardet def toutf8(txt): if not txt: return txt c = chardet.detect( txt) try: u = unicode( txt, c['encoding']) return u.encode('utf-8') except UnicodeError: pass except TypeError: pass return txt
ea6d8b05e06f9526c3cbaed12f313eac35e2ce40
alexthefatcat/CuratedCode-GIT
/Advanced_Python/object_orintated_stuff.py
1,051
4
4
# -*- coding: utf-8 -*- """Created on Mon Nov 18 15:45:02 2019 @author: Alexm""" # Dynamically add methods to a Object if ("Dynamically add methods",True)[1]: class A: def __init__(self,name,age): self.name = name self.age = age a = A("monkeyman",(12,3)) def print...
3785a9eaf0c7ba28ec7562943b6ca04e38263aac
Zaymes/python-assignment
/data types/data_types5.py
992
4.21875
4
# question 41 # convert tuple to string def tuple_to_string(tup): if type(tup) not str: tup = str(tup) str = ''.join(tup) return str tuple1 = ('p','y','t','h','o','n') string = tuple_to_string(tuple1) print(string) print(tuple_to_string(1,2,3,4)) # question 42 # convert list to a tuple de...
9d5e6c6c99626ccbc84e29a4b0100a54c2ef050e
CX-Bool/LeetCodeRecord
/Python/Easy/206. 反转链表.py
961
3.8125
4
'''执行用时 : 36 ms , 在所有 Python 提交中击败了 54.75% 的用户 内存消耗 : 13.6 MB , 在所有 Python 提交中击败了 44.51% 的用户''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :typ...
9f4da80ab4893b4e179e92863527a3561671c90a
lbxa/first-neural-net
/src/feed_forward_net.py
9,064
3.640625
4
''' Feed-Foward Artificial Neural Network ------------------------------------- Feed-foward nets are the simplest NN's to master. They are comprised of an input layer, one or more hidden layers and an output layer. Since the dimensionality of out data is 2 inputs to 1 output, there will be 2 input ...
5b5c1f8d450908ea49ead75ed88a128f1f9f15ac
buru255/Calculator
/calculator.py
3,515
3.78125
4
from tkinter import* import math def btnClick(numbers): global operator operator=operator + str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator operator="" text_Input.set("") def btnEqualInput(): global operator sumup=str(eval(operator)) text_Inp...
7f330c060b987141c23e39702fa351a972957a98
q737645224/python3
/python基础/python笔记/day06/exercise/list1.py
941
4.0625
4
# 练习: # 1. 写程序,让用户输入一些整数,当输入-1时结束输入, # 将这些数存于列表L中 # 1) 打印用户共输入了几个数? # 2) 打印您输入的数的最大数是多少 # 3) 打印您输入的数的最小数是多少 # 4) 打印您输入的这些数的平均值是多少? # 1. 写程序,让用户输入一些整数,当输入-1时结束输入, # 将这些数存于列表L中 L = [] while True: x = int(input('请输入整数: ')) if x == -1: break # 结束循环输入 L += [x] # print("L="...
c6efa04b5744f23fe94de8f33477d554abc972be
mangeshii/hackerrank-python-practice
/Built-Ins/any-or-all.py
547
3.984375
4
''' Task You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer. Input Format The first line contains an integer . is the total number of integers in the list. The second line contains the space separated list of integers. O...
d4d7ded7eca5dac68fc192ea17bb3c85a103a64d
oustella/coding-exercises
/myLinkedList.py
3,297
4.34375
4
# all things LinkedList class ListNode(): def __init__(self, x): self.value = x self.next = None def print(self): temp = self while temp and temp.next: print(temp.value, end='->') temp = temp.next print(temp.value) # singly linked list class Li...
e7f37b8ad28a81df73c4cd37c154d831ecded30d
minhoryang/advertofcode
/2017/17/spinlock.py
472
3.984375
4
class SpinLock(object): def __init__(self): self._data = [0] self.len = 1 self.idx = 0 def spin(self, next=3): for _ in range(next): self.idx += 1 if self.idx == self.len: self.idx = 0 return self._data[self.idx] def insert(self, data): self.len += 1 self.idx += 1 self._data.insert(self.i...
ded2f4ba5c99b8372adfd2b5255967173f04394b
Yingying0618/DS-Career-Resources
/leetcode/remove_duplicates_linked_list.py
457
3.796875
4
''' 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 ''' # Standard approach - O(n) time, O(n) space def deleteDuplicates(self, head): curr = h...
0ce076fc50f93a7aad19f78f5349258c56f50a5e
MrittikaDutta12/MrittikaDutta12.github.io
/dictionaryatack.py
708
3.9375
4
f = open("dictionary.txt","r") file = f.readlines() print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password c =input(" Enter password to be checked ") for i in range(100):i if c.casefold() in open("dictionary.txt","r").read(): pr...
a16d09f32cb31addc651f9d7352ea056b8ea3b2f
simdis/distributedCNNs
/graph.py
8,051
3.546875
4
import numpy as np from matplotlib import pyplot as plt import os def euclidean_distance(x1, x2, y1, y2): x = x1 - x2 y = y1 - y2 return np.sqrt(x * x + y * y) def create_graph(nodes=10): g = dict() for i in range(nodes): g[i] = set() return g def add_node_to_graph(graph): n =...
f6f290488d31d9915a3031b24f8c972f29f988ca
jennyliuwhu/Data-Visualization
/relational_data.py
9,862
3.53125
4
import csv import math import sqlite3 import matplotlib.pyplot as plt import pandas as pd # Use svg backend for better quality import matplotlib import time matplotlib.use("svg") plt.style.use('ggplot') # you should adjust this to fit your screen matplotlib.rcParams['figure.figsize'] = (10.0, 5.0) __author__ = 'jiali...
80a3e4b667e72a113896491f5738a01ee01964b3
macosta-42/100_days_of_code
/1_Beginner/day4_Rock_Paper_Scissors/main.py
943
4.15625
4
# Rock Paper Scissors rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) ...
f3cf8b58d42c6629ea3bdffddd63b1f60effc61c
linegpe/FYS2160
/Oblig1/opg1q.py
929
3.640625
4
from random import randint from numpy import zeros, histogram, linspace, exp import matplotlib.pyplot as plt N = 50 M = 10000 M_values = zeros(M) Omega0 = 1100 Omega = zeros(M) # Create random integers and make s = +/- 1 # Store final values in array M_values print "Looping..." for j in range(0,M): i = 0 s = 0 whi...
0acc2a152c7721369a2799fcd47e2085482d6e14
urquia22/Interfacing-Pinguino-Matplotlib-1.01
/AnalogReadSerialMatplotlib-1.01.py
1,585
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import PBpinguino # importamos librerias necesarias // import necessary libraries import matplotlib.pyplot as plt from collections import deque a = PBpinguino.TAPinguino() # iniciamos comunicacion via serial // star...
8eb09d680f9b9461049573011822daa19dea0d9e
joyceromao22/phyton_fundamentals
/Aulas/erros_excessoes.py
527
4.03125
4
# -*- coding: utf-8 -*- #erros e excessoes # while True: # try: # x = int(input('Digite o primeiro numero: ')) # y = int(input('Digite o segundo numero: ')) # print(f'resultado: {x +y}') # except Exception as e: # print('Digite apenas numeros!') funcionarios = ['rafael', 'mari...
15cd91de9ef6f695c3ebd3881a1ea47e1d9bd3da
anisinha77/sil_lab
/skill_lab/lab02-ass01/q09.py
274
3.640625
4
p = float(input("enter principal amount: ")) r = float(input("enter rate per annum: ")) t = float(input("enter time in years: ")) si = (p * r * t) / 100.0 ci_amt = p * pow((1 + r / 100), t) ci = ci_amt - p print(f"simple interest: {si}") print(f"compound interest: {ci}")
d0f6dee3f81467329590f2c726a69ac523a9fbbc
shyamala987/CtCI_Py_Solns
/chap2/1_removeDup.py
955
3.71875
4
''' Write code to remove duplicates from an unsorted linked list Follow up: How would this change if a temp buffer is not allowed? i/p 1 -> 3 -> 5 -> 2 -> 4 -> 2 -> 3 -> 5 -> 6 o/p 1 -> 6 ''' import linkedList from linkedList import Node, LinkedList class Solution: def __init__(self): self.cache = {} ...
63ea9e7395b964601b02092e32342a4634b62b88
nedimperva/simple_python_projects
/higher-lower/main.py
1,347
3.640625
4
import random from art import logo, vs from gameData import data import os score = 0 should_end = False #function for clearing command line screen clear = lambda: os.system('cls') #instead of'cls' put 'clear' on Linux systems #function to print game data def print_data(a): a_name = a["name"] a_description = ...
070da229b01c36653b4bc66a69c0eb782547e9e7
guilhermemaas/guanabara-pythonworlds
/exercicios/ex048.py
435
3.953125
4
""" Faca um programa que calcule a soma entre todos os numeros impares que sao multiploes de 3 que se encontram no intervalo de 1 ate 500. """ count = 0 soma = 0 for c in range(1, 501): if c % 3 == 0 and c % 2 != 0: print(c, end=' ') count += 1 soma += c print('\nA soma de todos os valores ...
d3adbd3e3ff871dc5fb52cef87c3675e0bdb9dd1
Satendarsingh/pythonlab
/shivraj.py
245
3.8125
4
def func1(m): print("hii",m) func1("man") def func(a,b,c): d=a+b+c print(a,b,c,d) func(3,5,8) def func2(a,b): c=a+b return c def func3(): print("hello,i am going to call the function") s=func2(2,7) print("''addition is",s) func3()
bcb96a4e39d0f023c2babe901e8316a7340c352b
KlimChugunkin/PyBasics-Course
/Perper_Leonid_dz_8/task_8_3.py
1,270
3.671875
4
""" Задание 3 Написать декоратор для логирования типов позиционных аргументов функции. Если аргументов несколько - выводить данные о каждом через запятую. Вывести тип значения функции. Решить задачу для именованных аргументов. Замаскировать работу декоратора. Вывести имя функции. """ from functools import wraps def ...
f6846b8ab88110f09359da376e6ddad90112ec07
kamkarm/Stock-Analysis
/graph_data/first_day_difference.py
1,059
3.765625
4
""" Create a line graph of how the stock value compares to it's value on 1/02/2019 for each stock. For each stock, the query will find the difference between the stock's value at day X and 1/02/2019 Query is then plotted on as a bar graph on matplotlib """ import psycopg2 import matplotlib.pyplot as plt import sys...
b7b96d107c7d04fb841ba85f9448ebb1cd4d3257
Mpatel1618/Python_Data_Analysis
/project_final_facebook.py
5,217
3.765625
4
# import pandas library as pd and matplotlib.pyplot linrary as plt import pandas as pd import matplotlib.pyplot as plt #Part 2: graphs and relationships with time series df = pd.read_csv('123_employee_reviews.csv', encoding = 'latin-1') #locating the company data in the dataframe facebook_data = df.loc[df['company']...
476d111c29d5f8a7bf120b81f136a06d69aff77b
ritwiktiwari/AlgorithmsDataStructures
/Recursion/problem-19.py
294
4.03125
4
""" Find greatest common divisor using recursion """ def gcd(a: int, b: int): assert a == int(a) and b == int(b), "a and b must be integers" if a != 0 and b == 0: return a # if a % b == 0: # return b return gcd(b, a % b) print(gcd(48, 18)) print(gcd(48, 0))
f5e8ecaab2b55fed4994ee77859dcae7317d6ba3
kbutler52/Teach2020
/typesData.py
626
4.03125
4
#06-02-2020 #while loop i=0 while i < 10: print(f"We have {i} things") i=i+1 a = 0 for q in range (1,10): print("We have %d cats." %(q)) apples = 25 pears = 20 print(apples < pears) print(not(apples < pears)) print(apples %2==0) print(not(apples %2==0)) print(pears %2==0) p...
dcba53c8778b92abd32fe83508139c39588cad00
Vk-Demon/vk-code
/ckarray16.py
314
3.609375
4
nnum=int(input()) # You are given an array of ids of prisoners. The jail authority found that there are some prisoners of same id. Your task is to help the authority in finding the common ids lt=[int(i) for i in input().split()] st=[] for i in range(0,len(lt)-1): if(lt[i]==lt[i+1]): print(lt[i],end="")
37222b5f144cd1d2bda87e50f683473f2574cc17
sergeichestakov/InterviewPrep
/palindromePartitioning.py
950
3.640625
4
# Given a string s, partition s such that every substring of the partition is a palindrome. # Return all possible palindrome partitioning of s. class Solution: def partition(self, s): """ :type s: str :rtype: List[List[str]] """ ret = [] self.generatePartitions(ret, ...
7cbafb9f1fb77a9b029173d83aba7439183f67c6
kimoba/Code-in-Place-2021
/Extra Work/05 Lists/Shorten/shorten.py
395
4.25
4
SAMPLE_LIST = ['a', 'b', 'c', 'd', 'e'] MAX_LENGTH = 3 def shorten(lst, max_len): # removes items from the end of the list while len(lst) > max_len: removed_item = lst.pop() print(removed_item) # prints item until lst is max_len items long print("The new list is: ", lst) def main(): ...
505dc2ebb3f741864cdc4fecdffe9f47c56961cf
OldTaoge/python_edu
/#4/test6.py
96
3.5
4
#4-6 table = [] for num in range(1,21,2): table.append(num) for num in table: print(num)
7012239f7799ae9aefba18ba7655ef5574b6169b
Cluxnei/uri-online-judge-problems
/INICIANTE/NIVEL-1/1002/1002.py
71
3.6875
4
radius = float(input()) print('A={:.4f}'.format(radius ** 2 * 3.14159))
5e5e9fa40c8398677050ced6c24c6c19db8389d0
NeonMiami271/Work_JINR
/Python/max_among_parity.py
241
3.59375
4
import random N = 5 max = 0 x = list() for i in range (0,N): a = random.randint(-100,100) x.append(a) print(str(x)) for i in range (0,N): if ((i+1) % 2 == 0) and (x[i] > max): max = x[i] print("Ответ: " + str(max))
1c56a4c6b5b48db444809d291c3f2197f7f82858
agamat/genetics-multiple-alignment
/utils.py
4,898
4
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt from numpy.random import choice def cost(letter1, letter2): """ Calculate the cost or score of the alignment of 2 letters. Parameters: ---------- letter1: character letter2: character Return: ------ score: int score of th...
29cfba5aca32dec55cb8c5ea709b70232178ff7d
MaksymSkorupskyi/HackerRank_Challenges
/30 Days of Code/Day 03 - Intro to Conditional Statements.py
763
4.40625
4
"""Day 3: Intro to Conditional Statements https://www.hackerrank.com/challenges/30-conditional-statements/problem Given a positive integer, n, perform the following conditional actions: If is odd, print Weird If is even and in the inclusive range 2 of 5 to , print Not Weird If is even and in the inclusive range o...
15db6018c8a8c0c72dcd50c83cd9a7c7c2166996
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2_neat/16_0_2_AmolMandhane_BL.py
813
3.609375
4
cases = input() def successor(stack, move): move += 1 new_stack = [""] * len(stack) for i in xrange(len(stack)): if i < move: new_stack[i] = "+" if stack[move - 1 - i] is "-" else "-" else: new_stack[i] = stack[i] return "".join(new_stack) for T in xrange(cases...
b3fd0b6ef8aaa326f37c796b765f044327d7c5d3
wuyongqiang2017/AllCode
/day29/继承与派生.py
2,912
4.0625
4
# class ParentClass1:#定义父类 # pass # class ParentClass2:#定义父类 # pass # class SubClass1(ParentClass1):#单继承,基类是ParentClass1,派生类是SubClass # pass # class SubClass2(ParentClass1,ParentClass2):#python支持多继承,用逗号分隔开多个继承的类 # pass # # print(ParentClass1.__bases__) # print(SubClass1.__bases__) # print(SubClass2.__ba...
a62bf7fe40e5aceb6fdcb761c7eebfe6acdef75c
amanullah28/code_practice
/python_practice/oop/class_var.py
583
3.8125
4
class Pet: allowed = ['cat', 'dog', 'hen'] def __init__(self, name, species): if species not in Pet.allowed: raise ValueError(f"You can't have {species} pet!") self.name = name self.species = species def set_species(self, species): if species not in Pet.allowed: raise ValueError(f"You can't have {spec...
419e5ff62d7d9c8b398442d904dd3ca2612a0489
JiahuiQiu/Python-Learning
/ZJU-Python/CH3/ch3-6.py
703
3.703125
4
# -*- coding: utf-8 -*- """ 求整数序列中出现次数最多的数 本题要求统计一个整型序列中出现次数最多的整数及其出现次数。 输入格式: 输入在一行中给出序列中整数个数N(0<N≤1000),以及N个整数。数字间以空格分隔。 输出格式: 在一行中输出出现次数最多的整数及其出现次数,数字间以空格分隔. 题目保证这样的数字是唯一的。 输入样例: 10 3 2 -1 5 3 4 3 0 3 2 输出样例: 3 4 """ list1 = input().split(" ") list2 = list1[1:] most_occur_num = max(list2...
ce07e9b6609d74050f7eadbadba0d17892acbea9
crobarcro/pyscape-presentation
/presentscape.py
8,390
3.828125
4
#!/usr/bin/python # # This script converts a presentation made in inkscape and saved # as SVG to a PDF presentation. # # Invoke the script on the command line with: # # presentscape.py <yoursvgname.svg> # # This is done by converting layers in the SVG to individual pdf files # and merging them. Merging will only be do...
d33c1cf957ab3eeabae17bed0c721e4ad9707584
YasserZhang/foobarChallenge
/google_foobar_level1.py
587
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 18 22:00:12 2017 @author: ning """ def answer(s): letters = "abcdefghijklmnopqrstuvwxyz" reverse_letters = letters[::-1] letters_dict = {} for l, r in zip(letters, reverse_letters): letters_dict[l] = r translation = "" for letter in s: ...
a0bee0002897abb0e2ccbb0fb2c91b42d67df525
geokhoury/htu-ictc6-python-webapp-development
/W2/S3/PA01/solutions/famous_dinner.py
2,459
4.5625
5
# Famous Dinner # You are inviting three famous people for dinner. guests = ['nicola tesla', 'albert einstine', 'leonardo da vinci'] # Invite your guests to dinner. name = guests[0].title() print(f"{name}, please come to dinner.") name = guests[1].title() print(f"{name}, please come to dinner.") name = guests[2].ti...
3b3f372a85c257d434972af59af347e2b9bb36b8
NIROJ-SATYAL/database
/database.py
3,519
4.0625
4
from tkinter import * import sqlite3 root=Tk() root.title("database") #create a database or connect to one conn=sqlite3.connect("hello.db") #create a curser c=conn.cursor() '''c.execute("""CREATE TABLE HELLO( first_name text, last_name text, address text, city text, state text, phone_numbe...
dc3a4869723e65d8cd6ca8ceae8944584d364761
celestachay/chay-family
/c2/python/prog.100/assignments/assignment6_collections.py
1,798
3.859375
4
# Christopher Chay # Assignment 6 # 2016.3.15 # Grade: _____ super1 = { 'Superhero': 'Spider Man', 'Secret Identity': "Peter Parker", 'Age': 20, 'Powers': "Wall crawling, super strength, agility, web"} super2= { 'Superhero': 'Captain America', 'Secret Identity': "Steve Roger...
9524919da8a6395bbfb1c818790533f36fe4c550
ehdqhddl/python_study
/section10.py
2,680
3.640625
4
# Section10 # 에러 및 예외 처리 # 예외 종류 # 문법적으로 에러가 없지만, 코드 실행(런타임) 프로세스에서 발생하는 예외 처리도 중요 # linter : 코드 스타일 가이드, 문법 체크 # SyntaxError : 잘못된 문법 # print('Test) # if True # pass # NameError : 참조변수 없음 # a = 10 # b = 15 # print(c) # ZeroDivisionError : 0 나누기 에러 # print(10/0) # IndexError : 인덱스 범위 오버 # x = [10,20,30] # pr...
9890290da015e49a451a3da94e32564054217560
rathore99/datastructure-in-python
/max_heap.py
2,841
4.1875
4
'''1. implement maxheap using list 2. operations to implement i) push() ii) pop() iii) peek() ''' class MaxHeap: def __init__(self, items = [] ): self.heap = [0] for item in items: self.heap.append(item) self.__floatup(len(self.heap)-1) print(self.__str()) ...
a1991e92002ff09394858ed5eb98557bf49f8c20
Sunsetjue/python
/基础语法/05.py
2,780
3.75
4
#汉诺塔方程 def hanno(n,a,b,c): if n == 1: print(a,' -> ',c) return None if n == 2: print(a,' -> ',b) print(a,' -> ',c) print(b,' -> ',c) return None ''' 当n=n 时候,把 n-1 个盘子从 a 借助于 c 运到 b 上,然后将 a 盘上的一个运到 c 塔上 然后将 b 塔上的 n-1 个盘子通过 a 塔运送到 c 塔上 ''' hanno(...
87b317b234820ab86867c09eea8f1be73b2493a5
two2er/ml-toys
/supervised/decision_tree.py
6,976
3.796875
4
import numpy as np class TreeNode: """node of decision tree""" def __init__(self, X, y, leaf, depth, split_feature=None, split_value=None): self.X = X self.y = y # whether this node is a leaf node or not: true or false self.leaf = leaf self.depth = depth # if th...
6ee53403ad8adad92848737cb8056ed28c13fd8a
ivan-chai/detection-adaptation
/src/dalib/config.py
2,990
3.5
4
r"""Tools for configuration using default config. All configurable classes must have :meth:`get_default_config` static method which returns dictionary of default values. Than you can use :func:`prepare_config` function to construct actual config. Actual config can be ``None``, ``dict`` or ``str`` containing path to th...
54d9ab5ac2047e5c862b62fbb92fcec1d994a5f7
doug-cady/python
/adventure.py
6,834
4.21875
4
# -*- coding: utf-8 -*- """ Text Adventure Game An adventure in making adventure games. To test your current solution, run the `test_my_solution.py` file. Refer to the instructions on Canvas for more information. "I have neither given nor received help on this assignment." author: Kane van Doorn """ __version__ = 8 ...
f4f39248c2e8ed6373829c70437c6d51d5ef7733
ugurkam/PythonSamples
/Samples/sets.py
564
3.953125
4
fruits = {'portakal', 'elma', 'muz'} print(fruits) for x in fruits: print(x) # Fruits setine eleman eklemek için fruits.add('karpuz') fruits.update(['kavun', 'visne']) print(fruits) myList = [1,3,5,7,1,4,3,8] print(myList) print(set(myList)) # Fruits setinden eleman silmek için #fruits.remove('...
0cf63f8e5fa915c9300b66836f52b6217ff5d72b
CS7591/Python-Classes
/2. Python Intermediate/6. Assorted Topics/3. Exception Handling.py
4,471
4.375
4
''' Exception handling is one of the most important features in Python Usually has the form: try: <code> <code> <code> except: <code> <code> finally: <code> ''' # One the most important features of Python # # Example 1 # amount = float(input('Enter with the amount:')) # split = float(input('E...
fb8ea357bb9973163ed7f4c344e10e6f3ac0a869
pseemaJohn/python-lab
/OperatorTraining.py
226
3.546875
4
print(2*3+4) print("value is",len("hi how are you")) print(2 or 0) print(2 and 0) print(bool(2 and 0)) print(2 | 1) print(5 // 2) print(5 / 2) print("hi"+"how are you") print("Seema" * 6,end=": \n") print(2 ** 4)
a2863b2bf3b0abaf059bbffafe3789616fc6846e
aruimk/ud_pyintro
/lesson16_list.py
827
3.6875
4
s = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(s) s[0] = 'X' print(s) print(s[2:5]) s[2:5] = ['C', 'D', 'E'] print(s) s[2:5] = [] print(s) s[:] = [] print(s) n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(n) n.append(100) # 一番最後に要素を追加したい時 print(n) n.insert(0, 200) # 指定した要素位置にデータを挿入したい時(この場合は 0番目に200を挿入) print(n) ...
651e45164cb6e957661a1cf73e902437a64f5aac
VFagundes/Algorithms
/challenges/data_structures/linked_lists/print_the_elements_of_a_linked_list.py
471
3.984375
4
#https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem from singly_linked_list import SinglyLinkedList def printLinkedList(head): if not head.head: return node = head.head while node: print node.data node = node.next data = '''2 16 13 ''' arr = data....
bbb6a2c5e8505aa736967d64e9abf3ae8d868e2b
Madhivarman/DataStructures
/topological.py
1,043
3.921875
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self,src,dest): self.graph[src].append(dest) def topologicalSortUtil(self,visited,node,stack): visited[node] = True for i in self.graph[node]: if visited[...
517c587459833d3710c0199b6adcc3c31293cc1d
kwoshvick/Algorithm-practice
/careercup/shadow.py
714
3.921875
4
# https://www.careercup.com/question?id=5655096797429760 # # Given array of ball size we need to return the sum of shadow balls # # For example # # 7 3 2 8 1 # # shadow ball of 7 ---> 3, 2, 1 # shadow ball of 3 ---> 2, 1 # shadow ball of 2 ---> 1 # shadow ball of 8 ---> 1 # # Output ---> 3+2+1+1 --> 7 # # Complexity sh...
d6a0da8ddd5eeda08639b6b7704581454bcf2ef5
NovaStriker/Proyecto_Algoritmos_1ER_parcial-2T-2018
/pry_algoritmos_1er_parcial.py
8,702
3.890625
4
from random import randint import time import os.path from pathlib import Path def insertionSort(alist): #definir la funcion del algoritmo que reciba una lista for index in range(1,len(alist)): #recorrer la lista currentvalue = alist[index] #valor que va tomando index position = index while positi...