blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3df71c7c040fa754ab2ec1686c500504fd16a49e
crjcrj/pythonaaa
/链表/入环点.py
1,270
3.875
4
# class Node: # def __init__(self,data): # self.data=data # self.next=None # def is_circle(head:Node): # fast=head # slow=head # while fast and fast.next: # fast=fast.next.next # slow=slow.next # if fast==slow: # return True # return False # if __n...
8f02c409fbd489b959396dcf099d0f3b3bb28d0c
crjcrj/pythonaaa
/排序/归并排序.py
840
3.890625
4
from typing import List def merge(left, right): res=[] while left and right: if left[0] < right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) if left: res.extend(left) if right: res.extend(right) return res def mergesort(nums:Lis...
445bcf21ae6d131cd8a0bd5b67d9104cc2786703
crjcrj/pythonaaa
/排序/冒泡排序.py
299
3.828125
4
from typing import List import random from Randlist import Randlist def sort(nums:List): for i in range(len(nums)-1): for j in range(len(nums)-i-1): if nums[j]>nums[j+1]: nums[j],nums[j+1]=nums[j+1],nums[j] return nums print(sort(Randlist.randlist(10)))
4eb6d9030dd0965e1d98c419c15a55bcbf426172
crjcrj/pythonaaa
/排序/计数排序.py
337
3.5
4
from typing import List def count(nums:List): max_len=max(nums) res=[0]*(max_len+1) for i in range(len(nums)): res[nums[i]]+=1 ilist=[] for i in range(len(res)): for _ in range(res[i]): ilist.append(i) return ilist t=[9,3,5,4,9,1,2,7,8,1,3,6,5,3,4,0,10,9,7,9] prin...
9beac3bc32753d576f79ec39f84628acbb9d29f6
crjcrj/pythonaaa
/复习入环点.py
406
3.578125
4
class Node: def __init__(self,data): self.data=data self.next=None def __repr__(self): return def is_circle(head:Node): fast=head slow=head while fast and fast.next: fast=fast.next.next slow=slow.next if fast==slow: break slow=head ...
c1610c5a0b153070e981a4f4a359f2bc66cdb0f4
crjcrj/pythonaaa
/排序/三数和最小的值.py
1,451
3.75
4
# 16 # def threeSumClose(nums,target): # nums.sort() # res = nums[0] + nums[1] + nums[2] # closest = abs(nums[0] + nums[1] + nums[2] - target) # for i in range(len(nums) - 2): # left = i + 1 # right = len(nums) - 1 # # while left < right: # threesum = nums[i] + nums[l...
12d55820cf5f5073059fb5c7f5b3314d996944b5
PayalDesai424/Project
/Assignment/main.py
686
3.515625
4
import timeit import logging import Arithmetics import Test_Arithmetics import Test import time def PrintName(): print("Hello, Payal here!!") print("End of PrintName Function execution ") def LeapYear(year,four): return (year%four) def test_example(): assert LeapYear(2016,4) == 0 if __name__ == '__main_...
99edf46a90a8df2452227f166b5018e333c196f5
ayumitanaka13/python-basic
/excersize/base5.py
757
4.0625
4
# base5.py from abc import abstractmethod, ABCMeta class Animals(metaclass=ABCMeta): @abstractmethod def speak(self): pass class Dog(Animals): def speak(self): print('わん') class Cat(Animals): def speak(self): print('にゃー') class Sheep(Animals): ...
2f6b1f2e00b169f38bdfff98008525405b3856e5
ayumitanaka13/python-basic
/basic/base14.py
603
3.796875
4
# セットの関数 s = {'a', 'b', 'c', 'd'} t = {'c', 'd', 'e', 'f'} u = s | t # 和集合 u = s.union(t) # 和集合 print(u) u = s & t # 積集合 u = s.intersection(t) print(u) u = s - t # 差集合 u = s.difference(t) print(u) u = s ^ t u = s.symmetric_difference(t) print(u) s |= t # => s = s | t => sがsとtの和集合=>sにtの要素が...
1f28a4bfdfafe0363ae38106347b09661e96995b
ayumitanaka13/python-basic
/basic/base9.py
954
4.4375
4
# リスト # list_a = [1,2,3,4] # list_b = [] # print(list_a) # print(list_a[-2]) # list_a = [1, [1,2,'apple'],3,'banana'] # print(list_a[1][2]) # print(list_a) # list_a[1][2] = 'lemon' # print(list_a) # list_a.reverse() # print(list_a) # リスト関数 list_a = [1,2,3,4,5] list_b = list_a[:3] print(list_b) ...
5962f531bf841c9c38056aa0406303031f3d63c1
ayumitanaka13/python-basic
/basic/base6.py
226
3.8125
4
# 複素数 a = 1 + 3j b = 3 + 5j # print(a,b) # print(a+b) # print(a-b) # print(a*b) # Complex a = complex(1,3) b = complex(3,5) print(a,b) print(a+b) print(a-b) print(a*b) print(a.real) print(a.imag)
ccecf3fb84cfcfaa35339a2c959986cc572c1069
ayumitanaka13/python-basic
/basic/base7.py
1,545
4.1875
4
# 文字列型 # fruit = 'apple' # "" # print(fruit) # print(type(fruit)) # print(fruit * 10) # new_fruit = fruit + ' banana' # print(new_fruit) # # """ # fruits = """apple # banana # grape # """ # print(fruits) # fruit = 'banana' # print(fruit[2]) # # encode, decode(bytes[]型の関数) => bytes[] # byte_f...
1d06a90e3965aa819826e9997f7add1f276685f8
napo-lazo/patito_mas_mas
/playground.py
200
3.734375
4
import re char = 'c' entero = 12 flotante = 37.877 if re.search(r'\-?[0-9]+\.[0-9]+', str(char)): print('float') elif re.search(r'\-?[0-9]+', str(char)): print('int') else: print('char')
25af451b7f4c5a305ab2090311a15a2761bdfbae
tristaaan/NineMensMorris
/stone_game/rules.py
4,813
3.9375
4
# hard coded, used in heuristics too # keep the indexing pattern in-line with the board # An array of 3 length arrays which are mills on the board mills = [ [1, 2, 3], [3, 4, 5 ], [5, 6, 7], [7, 8, 1], # outer [9, 10,11], [11,12,13], [13,14,15], [15,16,9], # middle [17,18,19], [19,20,21], [21,22,23], [23,24,1...
78dfd985694bec4e16039e7ce02964a8393d4e8d
SethDeVries/My-Project-Euler
/Python/Problem074.py
1,242
3.828125
4
import math #How many numbers get to a chain of 60 totalSum = 0 #Sum of factorials -- generates next number in chain tempSum = 0 #Array of digits in previous number digits = [] #Array of all numbers in current chain currentChain = [] #Stops while loop if the chain has a repeat or reached 60 done = False for x in rang...
ef7f416952bce64499197ba24c63ab3690f186f1
SethDeVries/My-Project-Euler
/Python/Problem102.py
863
3.640625
4
#credit to jasonbhill for most of this code, placing this #here because my code did not work for reasons unbeknownst to me def num_divisors(n): # if n is divisible by 2 if (n % 2 == 0): n = n/2 divisors = 1 count = 0 while (n % 2 == 0): count += 1 n = n/2 divisors = divi...
4162f8c527ece4a3a77daeb2678531074deeeed5
CallmeChenChen/leetCodePractice
/DataStructureAndAlgorithm/3_linkList/linkedList_practice2.py
4,933
4.1875
4
# -*- coding: utf-8 -*- from utils import LinkedList, Node # 练习(下) # 合并两个有序链表 # ž合并两个有序链表,返回一个新的列表。新的列表是由这两个列表的节点 # 拼接而成的。 def merge_two_sorted_linked_list(l1, l2): ''' 合并l1 和 l2 2个有序链表 :param l1: :param l2: :return: ''' curr = dummy = Node(0) while l1 and l2: if l1.val > l2...
9a35200911ac2be112a9ce7abab12d5ca4af91a8
CallmeChenChen/leetCodePractice
/27_removeElement.py
1,116
3.78125
4
""" in-place O(1) extra memory nums = [3, 2, 2, 3] val = 3 output 2 length([2,2]) """ class Solution(object): def removeElement(self, nums, val): """ :param nums: list[int] :param val: int :return: int length """ for idx in range(len(nums)): if nu...
3470f2bb4743eaeb2b4bd23533291fbe91f9d202
CallmeChenChen/leetCodePractice
/DataStructureAndAlgorithm/3_linkList/linkedList.py
3,137
4.09375
4
# -*- coding: utf-8 -*- class Node(object): def __init__(self, val=None, next=None): self.val = val self.next = next class LinkedList(object): def __init__(self): self.head = Node() # dummy node self.len = 0 def get_first(self): if not self.head.next: ...
e2949c926b872216e0f7644a4d2ff345b50bac72
sgonzalez137/programaci-n-avanzada
/repaso objetos/python/Phyton_Banda/Clases/Instrumento.py
910
3.546875
4
import random from abc import ABCMeta, abstractmethod class Instrumento(metaclass=ABCMeta): @abstractmethod def afinar(self): pass @abstractmethod def tocar(self): pass @abstractmethod def tocarNota(self, nota): pass class Bajo(Instrumento): def afinar...
60d443304c9a261738423381d58aef8e2e26c512
B10856017/chatbot_telegram_dialogflow
/test_matplotlib.py
617
4
4
import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) # a second figure p...
36569445d35b13d7bce2dfd0ed0c0276e2e80030
leandroflima/Python
/parouimpar.py
140
3.796875
4
numerostr = input("Digite um número: ") numero = int(numerostr) if (numero % 2 == 0): print("par") else: print("ímpar")
ff3aed706121dd82b6061648e069744f728f89fa
leandroflima/Python
/vogal.py
172
3.609375
4
def vogal(letra): vogais = "aeiou" for vogal in vogais: if (letra.capitalize() == vogal.capitalize()): return True return False
3478e462b5958b53a5d224c6469d2b09716a9e9c
matiaszanolli/nestor
/modules/memory.py
4,136
3.609375
4
import numpy as np class Memory: def __init__(self): self._memory = np.zeros(0xffff, dtype=np.uint16) # type: np.ndarray def read(self, address: np.uint16) -> np.uint8: """ Returns an 8-bit chunk of memory from a given address. :param address: a location between 0x0000 and 0...
7cde566cd1acea89bc6c98ba0190717baa35d6cc
krishnakalyan3/BSG
/Code/fasta.py
576
3.546875
4
#!/usr/bin/env python2 def getindices(s): return [i for i, c in enumerate(s) if c.isupper()] def parse_fasta(dna): dna_filtred = filter(lambda x : len(x) > 0, dna) fasts_seq = [] for i in dna_filtred: dna_fix = i.replace('\n','') #print getindices(dna_fix)[1] name_label = dna_fix[0:getindices(dna_fix)...
53c251404363fa1bceaf3530b99c51f074553eff
mishazakharov/DL-library
/DL/nn.py
2,803
3.75
4
''' This file contains a few activation functions for my deep learning library I don't know if this realizations is appropriate! ''' import numpy as np def linear(input_tensor,derivative=False): """ This class realizes a simple linear activation function If we have linear activation function on a layer p...
cbe867ee08841ae135609fc79b6ff001f78e4057
Lera-Z/Python_4th_year
/homework_1/task_1.py
146
3.953125
4
def fibonacci(n): nums = [0, 1] for i in range(2, n): nums.append(nums[i-1] + nums[i-2]) return nums[n-1] print(fibonacci(1))
8ca1e22358ced06a03bb017749a34b512d486489
weichen283/OpenIE
/match-parenthese.py
380
3.609375
4
from geotext import GeoText import sys import re file = str(sys.argv[1]) f = open(file, 'r') text = f.read() # Extract all text in parentheses p = re.compile(r'[(](.*?)[)]') result = re.findall(p,text) for sentence in result: # match items base on city and country if GeoText(sentence).cities or GeoText(se...
60aa9b23d3d47ce1799ebeb390f2c1f342ddf203
matarrubia/matarrubia
/Programming_Foundations_with_Python/rename_files.py
441
3.734375
4
import os myFolder = r"/Users/fernandomatarrubia/Desktop/example/prank" def rename_files(): file_list = os.listdir(myFolder) current_directory = os.getcwd() os.chdir(myFolder) for file_name in file_list: newFileName = file_name.translate(None, "0123456789") print("Old Name - "+file_nam...
3904526842ceb6d360249c84aa68eccf913b472d
tanakornmorbucks/Python101
/condition.py
350
3.609375
4
# ==,<>,!=,<,>,<=,>=,not,and,or # score = 60 # if score >70: # print("good") # else: # print("try harder") def greeting(lang): if lang == "th": print("sawadee") elif lang =="jp": print("konichiwa") elif lang == "kr": print("ann-yeong") else: print("hello") gre...
aa5ca86900c946ad8fd15a0f2c9d6453f3b26e36
hrdyam/git_tutorial_1
/add.py
160
3.828125
4
def add(a,b): # if a and b are integers, return a + b if (type(a) == int and type(b) == int): return a + b # return None otherwise return None
13e9776e3be4a7ed087dea39aef3bde0d0d9f2b7
rustymeepo/VSA-Python
/proj01/proj01.py
781
4.09375
4
# Name: # Date: # proj01: A Simple Program # This program asks the user for his/her name and age. # Then, it prints a sentence that says when the user will turn 100. # If you complete extensions, describe your extensions here! # this will work, no problems here. user_input = raw_input("Enter in your name. " ) print ...
233ecc63b30ae35e1b1c12eb2f51498b867285e8
bevennyamande/bocadillo
/bocadillo/middleware.py
1,946
3.515625
4
"""Bocadillo middleware definition. A middleware is a class that implements the ASGI protocol. There are two kinds of middleware classes: - Routing middleware: suited for performing operations before and after routing occurs. - Common middleware: suited for all other middleware operations. Common middleware should b...
0708f82204021854097ae0d81c62fb263206797d
CodeOx/NeuralNet
/neural_net.py
10,636
3.65625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing import sys import string from sklearn import preprocessing from sklearn.metrics import confusion_matrix import time ################################# # Neural Netwotk ############## def sigmoid(x): return 1 / (1 ...
060389706134362ebefb0fa07288c2976315dd06
maddrum/extreme_consulting_task
/src/common_modules/calculator_module.py
959
4.1875
4
class Calculator: """ Perform calculation action based on number input and given operator """ result = None def __init__(self, number_a, number_b, operator): """ :param number_a: - [float] - number a :param number_b: - [float] - number a :param operator: - [+,-,*,/] ...
2a374d2833d4667192650cd53520d5b5dc57a836
ZacCui/leetcode
/107_binary_tree_level_order_traversal_ii/zac_cui_107.py
827
3.96875
4
#!/usr/local/bin/python3 ''' Author: Zac Cui Created Date: 2019-04-07 06:42:57 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[...
6a12071bbf29bb38f89c12910c10502552a74430
ZacCui/leetcode
/70_climbing_stairs/zac_cui_70.py
377
3.921875
4
#!/usr/local/bin/python3 ''' Author: Zac Cui Created Date: 2019-04-02 18:57:39 ''' class Solution: def climbStairs(self, n: int) -> int: if not n: return 1 if n < 2: return n memo = [None] * 3 memo[0], memo[1] = 1, 2 for i in range(2, n): memo[i % 3] = memo[(i-1...
61994bf00d52b46cef9e005016ec8316197e186f
ZacCui/leetcode
/27_remove_element/zac_cui_27.py
465
3.765625
4
#!/usr/local/bin/python3 ''' Author: Zac Cui Created Date: 2019-03-25 22:28:35 ''' class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ num = 0 j = len(nums) while num < j: ...
44143c4dad9fd1709684b57ec1b58d4117054203
physics91si/spring19-lab9-dorraej
/dynamics.py
1,924
3.671875
4
# Physics 91SI # Spring 2019 # Lab 9 # Modules you won't need import sys import matplotlib.pyplot as plt import matplotlib.animation as animation # Modules you will need import numpy as np import particle from molecule import * # TODO: Implement this function def init_molecule(): """Create Particles p1 and p2 in...
e7cf7a08ae971a4a7f1bd0d7c049949d868a406c
aknam/Programming-in-Python
/ex.py
447
4
4
aList = [2, 'Educative', 'A'] def foo(): print('Hello from foo()!') anotherList = [aList, 'Python', foo, ['yet another list']] print(anotherList[0]) # Elements of 'aList' print(anotherList[0][1]) # Second element of 'aList' print(anotherList[1]) # 'Python' print(anotherList[3]) # 'yet another l...
82755b5e42c52aac8198a380278925f20663b2f4
XSystem32/IOPython
/Filehandling/JsonHandler.py
811
3.578125
4
import json data = {} data['people'] = [] data['people'].append({ 'name': 'Emil', 'website': 'facebook.com/Emil', 'from': 'Denmark' }) data['people'].append({ 'name': 'Henrik', 'website': 'vk.com/Henrik', 'from': 'Norway' }) data['people'].append({ 'name': 'Andrei', 'website': 'vk.com/A...
f99e5918b851c50635e47fdd8c6bfac062d17659
dfialho/adventofcode-puzzles
/day03/day03_pt2.py
3,006
4.21875
4
from math import sqrt, ceil def level(n: int) -> int: """ Returns the level for the given position. The first square contains only 1 - the level 1 The second square contains value 2 to 9 - the level 3 (level 3) The third square contains value 10 to 25 - the level 5 The fourth square contains ...
bad71166b7dae980f5dab148827dc9537244f7fc
dfialho/adventofcode-puzzles
/day14/day14.py
2,881
3.65625
4
from typing import Iterator, Dict, Tuple, NewType, Set import hashing Position = NewType('Position', Tuple[int, int]) def hashes(key: str, n: int) -> Iterator[str]: """ Generates the *n* hash strings for the given *key* """ for i in range(n): yield hashing.knot_hash(f"{key}-{i}") def bits(hash_str...
fff396585c5a67e23ef51fcb9c3283fbd538b788
JakiwS/Chapter1Part2Task16
/Task16.py
153
3.765625
4
weight = int(input('Введите значение веса ')) i = 0 while i < 15: i += 1 weight += 1 moon = weight * 0.165 print(moon)
1b06d22efa548c5eebe0c1244b130e4fcee84bc9
rufinomendoza/learn_python
/euler/euler5.py
157
3.59375
4
import math def f(n): x = 0 y = 0 for i in range(1,math.factorial(n+1)): if i%n == 0: print(i) break
75c81ef7a890d8d2161fed6dab4a68b0ae2357e6
ElephantRBig/python-challenge
/pybank/main.py
2,519
4.1875
4
# Dependencies import os import csv # Creating path to read the file csv_file = os.path.join('pybank.csv') # Declaring some variables out of habit total_months = 0 # total months sum_of_PL = 0 # the sume of profits and loses changes = 0 # the changes between two month differen...
9366ff33724ae25a7b780ec70351cd6aa38a3af7
huny77/employment
/baek/mst/1647도시분할계획/1647.py
666
3.515625
4
import sys sys.stdin = open('input.txt') def find(node: int) -> int: if data[node] != node: data[node] = find(data[node]) return data[node] def union(a: int, b: int) -> None: root1 = find(a) root2 = find(b) data[root1] = root2 n, m = map(int, input().split()) # 집의 개수, 길의 개수 입력받기 edges...
0608329058c39376ae2417c6853daacef1d9037c
LeviWalsh/projectEuler
/p145.py
612
3.796875
4
# Some positive integers n have the property that the sum [n + reverse(n)] # consists entirely of odd (decimal) digits. # How many reversible numbers are there below one-billion? # takes a string and reverses it def reverse(s): if len(s) == 1: return s else: return s[-1] + reverse(s[:-1]) def allOdds(s): if le...
226dfc8c001db502875f6bddb6b0ad207d5e2159
LeviWalsh/projectEuler
/p036.py
577
3.6875
4
# Find the sum of all numbers, less than one million, which are palindromic # in base 10 and base 2. # takes in a string and checks if it is a palindrome def isPalindrome(s): if len(s) <= 1: return True else: # recursively calls isPalindrome if the first and last digit match if s[0] == s[-1]: return isPali...
bcf3d3ab430f0e6ed57084d5a62dce38c4d9118b
LeviWalsh/projectEuler
/p030.py
610
3.875
4
# Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. # returns true if the digits in the number to the fifth power equal the number def digit_fifth_powers(num): digits, forDigits, total = [], num, 0 while forDigits > 0: digits.append(forDigits % 10) forDigits //= 10 ...
3ef58f43452c0f32de8e9bacc8b9727191597057
evan0590/PythonSlotMachineCL
/slotmachine/main.py
2,629
3.8125
4
from slotmachine.purse import Purse from slotmachine.slot_machine import Slot def main(): """Slot machine function that runs the code contained within the classes imported above. Will only accept integers, will not account for floating point values placed as bets. """ # Create wallet object ...
43081e174528c17710eba8c60d3b5fa2c03c5e9c
jesales28/taylor_series
/factorial/factorial.py
363
4.4375
4
""" /lectureNote/chapters/chapt03/codes/examples/factorial/factorial.py Computes n! using recursive function """ from numpy import sqrt as np_sqrt def get_factorial(n=1): if n == 0: return 1 else: result = n * get_factorial(n-1) return result if __name__ == "__main__": n=5 p...
9761c7788dd613a76a82cd95c9c1ca64e765ede5
cburian/RPS-0.2
/rps_game.py
9,394
3.9375
4
""" Rock, Paper, Scissors v1.0 Plays a game of Rock, Paper, Scissors (RPS) The only initial input is a file with the rules Is able to play multiple types of RPS: - RPS-3 (Rock, Paper, Scissors) - RPS-5 (Rock, Paper, Scissors, Lizard, Spock) - RPS-7 Objectives: - make functions do 1 thing - docume...
d0f1ad1d2837bbe89eb9d51ce46f990a0d172988
penguinmenac3/babilim
/babilim/data/specialized_readers/data_downloader.py
1,095
4.09375
4
import os import urllib.request from zipfile import ZipFile def download_zip(root_dir: str, url: str) -> None: """ Download a zip from a url and extract it into a data folder. Usefull for downloading small datasets. The zip file gets extracted in the root_folder. It is recommended to set the root dir...
e6daefc93c0b1be393fa879c11014d339d2436cc
stavyy/Robot-Vision-Filtering
/problem2.py
3,343
3.5
4
# Stavros Avdella # 3939968 # Robot Vision Spring 2019 # Programming Assignment 1 # Problem 2 import numpy as np from matplotlib import pyplot as plt from PIL import Image # A median filter cannot be expressed as a convolution so we cannot create a kernel in this case since we have to # take the image and ...
eaf9ffccafbd29db0ce977b2322e6cd37c01931f
isakura313/24_04
/slovar.py
581
3.640625
4
amount_of_words = input(" Сколько слов в словаре") aow = int(amount_of_words) slovar = {} for i in range(aow): key = input("Ведите слово на английском\n: ").strip().lower() value = input("Ведите перевод\n: ").strip().lower() slovar[key] = value for key in slovar.keys(): print("Ввeдите перевод слова",...
a1cbf7a4fb29f7837ef43af4e305894ad9af954b
davidsenica/visual-secret-sharing
/VisualSecretSharing/encrypt.py
5,649
3.53125
4
import numpy as np from PIL import Image import random from .halftone import ordered_dithering def binary_image(image: str, alg='standard') -> (np.ndarray, np.ndarray): """ Function encrypts binary image (image contains only black and white pixels) :param image: Location of the image :param alg: Algo...
3c5ad4afb14fcf79793298217b217ca9f73fe963
Tenzin-sama/LabExercisesPYTHON
/Lab Exercises/Lab Exercise 1/Q3.py
631
3.859375
4
# Lab Excersise 1, Question 3 """N students take K apples and distribute them among each other evenly The remaining (the undivisible) part remains in the basket How many apples will each single student get? How many apples will remain in the basket? The program reads the numbers N and K It s...
2e7dcdd4368b0dbdeb7a5eea30bf797eed0797fb
Tenzin-sama/LabExercisesPYTHON
/Lab Exercises/All LabEx2 Q&As.py
8,322
4
4
# Lab Exercises 2, from LMS # Submitted by Tenzin Tsering Shrestha, 27 C def q1(): """Lab Exercise 2, Question 1 Check whether 5 is in list of first 5 natural numbers or not. Hint: List => [1,2,3,4,5]""" natnum = [1, 2, 3, 4, 5] if 5 in natnum: print("5 is in the list of first fi...
dd63606a510277263129b212b0bed9565210244c
Tenzin-sama/LabExercisesPYTHON
/Lab Exercises/Lab Exercise 1/Q2.py
401
4.3125
4
# Lab Excersise 1, Question 2 """reads the length of the base and the height of a right-angled triangle Prints the area Every number is given on a separate line""" print("Enter the measurements of the right angled triangle") length = int(input("Length: ")) height = int(input("Height: ")) print("The a...
198b373b8406dff0c4e5086a5bdc8cc03832fb22
csmberkeley/csm-88
/topics/disc-topics/interfaces/vectors/text/vector.py
469
3.5625
4
class Vector: def __init__(self, vector): self.vector = vector def __neg__ (self) : "*** YOUR CODE HERE ***" def __add__ (self, other): "*** YOUR CODE HERE ***" def __sub__ (self, other): return self.__add__(-other) def __mul__ (self, other): "*** YOUR CODE HERE ***" def __rmul__(...
5fee9f4eb7f37b6516eae2b241464d37d08cead0
MarvinMartin24/Fully-Connected-Neural-Network
/activation_layer.py
513
3.5
4
import numpy as np class ActivationLayer: def __init__(self, activation, activation_prime): self.activation = activation self.activation_prime = activation_prime self.input = None self.output = None def forward_propagation(self, input): self.input = input self.o...
dfc578fd33164ff7eaf72ad07d40decf5291663f
WhitLove2630/freqtraining
/freqtest/username.py
880
3.75
4
import sqlite3 def login() : while True : username = input('Enter Username:\n') with sqlite3.connect('freqtest.db') as db: c = db.cursor() c.execute("SELECT * FROM users WHERE username = ?", (username,)) results = c.fetchall() if results: fo...
0fca91e9bdd618fc46266c07eb8bdb517f65f980
rafneves/gym-oddsevens
/src/gym_oddsevens/envs/OddsEvensAdversarialHard.py
3,674
3.546875
4
import gym from gym import spaces from gym.utils import seeding import numpy as np class OddsEvensAdversarialHardEnv(gym.Env): """ Description: Two competitors (agent and environment) play Odds and Evens. The goal is to win from the environment as many as it is possible. Observation: T...
df591edbb3a8f2f010bf5cf848a07e23ac69ea54
jaldag/Advent2020
/day8/day8.py
696
3.65625
4
file = open("data.txt", "r").readlines() size = len(file) def traverse(file, flip) : vals = set() x, acc = 0, 0 while True : if x in vals : if flip == -1 : break #Part 1 else : return 0 #Part 2 vals.add(x) if x >= len(file) : return acc op = file[x][0:3] if flip == x : #Part 2 if op ...
1719e87f4ecd68b4971035572fe5041c1a50c496
Adib-LGS/Python3
/function.py
288
4.25
4
# return Max value between Two different values def max(value1, value2): if value1 > value2: return value1 elif value2 > value1: return value2 value1 = int(input("Enter the first value: ")) value2 = int(input("Enter the second value: ")) print(max(value1,value2))
c622d993e0cea3e38e7a28d15fc00e81b9e59862
jswashburn/csv-cleaner
/clean.py
1,893
3.84375
4
import os import csv def numeric(value): """Check if value can be converted to float or integer, if not just return value""" if "." in str(value): try: float(value) except ValueError: return value.strip() else: return float(value) else: tr...
9e4823a27c383d178354bfa0b7da825bf5c8f686
SiweiMa/snake-game
/game_core.py
2,753
3.78125
4
import random import pygame from constant import * from snake import * from pygame.locals import * class GameCore: def __init__(self): """ Attributes: win: a display Surface in pygame clock: a clock object that can be used to track time direction: default movin...
dcadc90788e7590a2df2517fec774d74cf6b307c
tapanmayukh/Computational-Physics-IITG
/Expt 7 - Bisection Method, Strum Sequence and Derivative/Derivative.py
732
4.0625
4
# Finding the derivative and double derivative of a function # Tapan Mayukh - 170121048 - 23/09/2019 from math import sinh, tanh def derivate(func, val): h = pow(10, -9) d = (func(val + h) - func(val)) / h return d def dbl_derivate(func, val): h = pow(10, -4) d = (func(val + 2 * h) - 2 * func(val + h) + f...
cb0e8772bd285612af6829870d4ef06e0815ae1b
tapanmayukh/Computational-Physics-IITG
/Expt 9 - 4th Order Runge-Kutta Method/1stOrderODE.py
921
3.859375
4
# Numerical Solution to 1st order ODE using 4th order Runge-Kutta Method # dy / dx = x^2 + 1 # Tapan Mayukh - 170121048 - 14/10/2019 def fun_f(x, y): return x * x + 1.0 def runge_kutta(x0, y0, x, h): n = int((x - x0) / h) y = y0 with open("data_1.dat", "w") as f: f.write("{} {}\n".format(x0, y)) for i in...
c30c12b10eb61ed1c6ad1dcf586298049d66e6b9
iledantec/ProgramacionAvanzada
/Tareas/T03/server/funciones.py
755
3.53125
4
def generar_dict_costos(parametro_costo, nombre): dict_costo = {"madera": int, "arcilla": int, "trigo": int} nombre = nombre.upper() for key in parametro_costo: if key == f"CANTIDAD_MADERA_{nombre}": dict_costo["madera"] = parametro_costo[key] elif key == f"CANTIDAD_TRIGO_{nombre...
4c95a194deaf98161ed0a5b3dea4ddc51f314b56
iledantec/ProgramacionAvanzada
/Actividades/AF02/verificar.py
4,694
3.84375
4
from estudiante import cargar_datos, cargar_datos_corto def verificar_numero_alumno(alumno): # Levanta la excepción correspondiente # Condicion 1 pos_char = 0 for char in alumno.n_alumno: if char.isalpha(): if (char != "J") or (pos_char != len(alumno.n_alumno) - 1): ra...
6d10bd5c7cf46e69dab2dee6d0293f2546e490b7
Kushalkumar23/sdet
/python/Activity_4.py
1,385
4.1875
4
# Get the users names user1 = input("What is Player 1's name? ") user2 = input("What is Player 2's name? ") # Get the users choices while True: user1_answer = input(user1 + ", do you want to choose rock, paper or scissors? ").lower() user2_answer = input(user2 + ", do you want to choose rock, paper ...
595df73ae837011ca1ad410513256379a1e432ec
davhg96/python_binp16
/python/ha3/amino.py
2,484
3.890625
4
""" Title: amino.py Date: 2017-10-17 Author: David Hidalgo Gil Description: This program will retrieve sequences from a .fasta file and will count the abundance of each aminoacid (aa) List of functions: read_fasta_to_dict: this function takes a fasta file as an input and outputs a dictionary with the...
0ec78edb682566809e0e83eb21b4090746f8f7fd
NipunSyn/DSA
/Data Structures/Stack/reverse_string.py
244
4.09375
4
from stack import Stack #reversing string def reverse(string): s = Stack() for c in string: s.push(c) new = "" for _ in range(len(s.get_stack())): new += s.pop() return new print(reverse('hello'))
7e972859165e56665f82809d031f01e0ede75690
NipunSyn/DSA
/Dynamic Programming/memoization/fib_memoization.py
460
3.984375
4
#recursive method #would fail for large numbers def fib(n): if n<=2: return 1 return fib(n-1) + fib(n-2) #memoized method #using a dictionary to store the values. keys will be the arguement, and value will be the return value of the function def fib_memo(n, memo = {}): if n in memo: retu...
6f04871bb8769a0ca2f35801278d884b755a4265
NipunSyn/DSA
/Data Structures/Graphs/graph.py
1,951
3.921875
4
class Graph: def __init__ (self, edges, print_dict= False): self.edges = edges self.graph_dict = dict() #need to convert it to a better data structure: dictionary for start, end in self.edges: if start in self.graph_dict: self.graph_dict[start].append(end)...
2a1abb04af23100f81607c1e5db27504e4674c86
401-Python/snakes-cafe
/snakes_cafe.py
1,529
3.984375
4
import sys Menu = { 'Appetizers': { # 'name': 'Appetizers', 'wings': 0, 'cookies': 0, 'spring rolls': 0 }, 'Entrees': { # 'name': 'Entrees', 'Salmon': 0, 'Steak': 0, 'Meat Tornado': 0 }, 'Desserts': { # 'name': 'Desserts', 'Ice Cream': 0, 'Cake': 0, 'Pie': 0 }, 'Drinks': ...
010a4555d0cc9a0eafd25389e9f0a417982da625
ekankshi12/Assignments
/Assignment20.py
1,249
3.953125
4
# *** Question 1 *** import pandas as pd import os new_dataframe = pd.DataFrame( { "name" : ['Ekankshi', 'Garima','Parth', 'Nandini', 'Shiven'], "age" : ['20', '19','18', '18', '17'], "mail_id" : ['ekankshi@gmail.com', 'garima@gmail.com','parth@gmail.com', 'nandini@gmail.com', 'shiven...
50f6666b8688890852f87ba815ee16e48ff78a4d
khalillakhdhar/python
/application/controle.py
133
3.84375
4
i=-1 while i<0: print("donner un entier positif!") i=int(input()) else: print("votre saisit est maintenant positif")
2fef61f7dbd2aa4a52578b264149cfd76af3697d
khalillakhdhar/python
/application/athlete.py
862
3.75
4
#from classes import personalisation class Athlete: def __init__(self, nom, age,sport): self.nom = nom self.age = age self.sport= sport def personalisation(self): print("le nom est %s et l'age est de: %s"%(self.nom,self.age)) def categorie(self): if self.age<15: print('l ...
1cbac25ab663a5fb6397416a420c9b0ce5ecbb0a
DomenickCE/SortingAlgorithms
/BubbleSortAlgorithm.py
999
4.4375
4
'''Bubble Sort compairson-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.''' def BubbleSort(numFile): #total number of passes/"bubbles" for FirstNum in range(len(numFile)): #number of iterations/checks per b...
da60506d7940104ed4f703c3728d1a952390cbd5
brookebon05/pizzeria
/NumPy/MyArrays.py
1,866
3.734375
4
import numpy as np import random # cntrl shift P, start REPL integers = np.array([1, 2, 3]) print(type(integers)) # prints # create 1D array producing list of ints 2-20 new_ints = np.array([i for i in range(2, 21, 2)]) print(new_ints) # 2d array ints = np.array([[1, 2, 3], [4, 5, 6]]) # two rows of 3 columns ints2...
de14cf6d4210a37f79abecd66099b1e9c472b0bc
brookebon05/pizzeria
/dictionary start file.py
2,192
4.25
4
phonebook = {"Chris": "555−1111", "Katie": "555−2222", "Joanne": "555−3333"} print() print("***** start section 1 - print dictionary ********") print() # print(phonebook) print() print("***** end section 1 ********") print() print() print("***** start section 2 - search dictionary ********") pr...
b1832adde85ea01be5d092de4b9b7893f3431645
brookebon05/pizzeria
/ML/ml_exercise2.py
1,179
3.5625
4
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import seaborn as sns import numpy as np import matplotlib.pyplot as plt nyc2 = pd.read_csv("ave_yearly_temp_nyc_1895-2017.csv") # One column is a series X_train, X_test, y_train, y_test = train_...
6f1c9abd1c24021f316a5121d2ff593b92f2b620
hermbot/python_scripts
/batch_resize.py
1,638
3.546875
4
# Run this script from a directory that contains images you want to resize. It # will process all files in the directory. For Python 3, use pillow library # which is still imported as 'PIL' for some stupid reason. # This script will overwrite previously generated files if ran multiple times # in the same directory. f...
ad2381b6bf9a89ffc243531fff2658db3ba209cb
Creplav/school
/reverse_numbers_10.2.py
257
4.375
4
''' This program takaes a list of integers and prints them out in reversed order ''' numberList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def print_list_reversed(list): list.reverse() for i in list: print(i) print_list_reversed(numberList)
bf6d11f1670cd545c3010000641ae5b2e5d8b191
vermillion23/all
/python/if game.py
1,714
4.125
4
print('Вы очнулись в старом замке и ничего не помните. С трудом вы вспоминаете своё имя. Ваши действия?') x=input('Введите 1, чтобы осмотреть замок, введите 2, чтобы проверить карманы') if(x=='1'): print('Вы долго шли по тёмному коридору, пока наконец не дошли до лестницы.') y=input('Нажмите 1, чтобы спуститься...
32a9e19bd8846c83e8a0c0ccc5b986334800b877
devsjee/MyCorpus
/myCorpus.py
2,514
3.78125
4
import string import pylab import matplotlib #vocab is the global dict containing the words and their frequency of occurence in the corpus VOCAB ={} #fnames is the the total list of files from which input is processed fnames =['f1.txt'] N = 1 #corpus is the string form of all text files processed so far CORPUS ="" ...
5b9e3175a46bc4d967ef4aa33612c7866ce62c1c
ukadev/pairsGenerator
/main.py
1,986
3.59375
4
import tkinter as tk from tkinter import ttk, scrolledtext, Button class Application: def main(self): window = tk.Tk() window.title("Generador de Parejas") window.geometry("810x530") # Title Label ttk.Label(window, text="Introduce las palabras en el bloqu...
ff96aaac1f16739c5cbee1ad4a51f6280e4443c6
mmmonk/crap
/random_fun/python_challange/c03.py
323
3.53125
4
#!/usr/bin/env python # http://www.pythonchallenge.com/pc/def/equality.html import urllib import sys import re t = urllib.URLopener().open("http://www.pythonchallenge.com/pc/def/equality.html").read() a = re.search("<!--(.+)-->",t,re.S).group(1) b = re.findall("[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]",a) print "".join(...
f68bd49b8ebb9e78976a5e0d5c402593aae5a8d1
EDAII/Lista5_RenanCristyan
/arvore_avl.py
7,773
3.828125
4
# Nome: Renan Cristyan A. Pinheiro # Matrícula: 17/0044386 # Disciplina: Estruturas de Dados 2 - 2019/2 # Professor: Maurício Serrano # Árvore AVL from random import randint from time import sleep def random_nodes(quantity, max_number, repeated=False): nodes = [] i = 0 if repeated is False and max_numbe...
293ce299c4be01392c21ac94d2c20027a20661d7
Lastshadows/Theory-of-information-Project-2
/Channel.py
1,594
3.5625
4
import random class Channel: # msg must be a list of strings. Each string representing a binary value # proba is the probability for a bit in the message to be shifted. Must be # bewteen 0 and 100. def __init__(self, msg, proba): self.message = msg self.corruptedMessage = [] ...
8d7c1fe784ee1a1326d63ce4fba33cefe03a8be5
Miseq/EllipticCurves
/ec_dhe.py
1,461
3.90625
4
# Primary Author: Aadesh M Bagmar <aadeshbagmar@gmail.com> # # Purpose: Diffie Hellman Using ECC from ecc import * def generate_keys(p: int, a: int, b: int, G: Tuple, n: int)->Point: """ Generates keys according to the Diffie Hellman Algorithm Args: p (int): Prime field size a (int):...
6876af1b8268ee497a9be6a2052efb1245903db4
university-of-southampton-1920/qiuzhao2020
/2020_05_24/字符串替换.py
438
3.71875
4
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here i = 0 while(i<len(s)): if s[i] == ' ': if i+1>(len(s)-1): s = s[:i] + '%20' i += 2 else: s ...
50c7a7d9ac809065ceea94363de17651f58de5d8
university-of-southampton-1920/qiuzhao2020
/2020_05_31/biss_726.py
1,310
3.546875
4
from collections import Counter class Solution: def countOfAtoms(self, formula: str) -> str: stack, i = [Counter()], 0 while i < len(formula): if formula[i] == "(": stack.append(Counter()) i+=1 elif formula[i] == ")": j = i + 1 ...
3315d1ecefc821863b8fe2152a2f277cb19d952b
university-of-southampton-1920/qiuzhao2020
/2020_03_14/saurystand_82.py
1,807
3.859375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head == None: return None if head.next != None and head.val == head.next.val: ...
33f6496c4b056c9f584ea74b0708e797460da4ce
university-of-southampton-1920/qiuzhao2020
/2020_02_17/runorz_947.py
752
3.5625
4
class Solution: def find_connected(self,stones,visited, x): visited[x] = True result = [x] for i in range(len(stones)): if visited[i] == False: if stones[i][0] == stones[x][0] or stones[i][1] == stones[x][1]: result = result + self.find_connect...
0d7614e6ac1863d9a5ea71ddbd1ab6c1fc09eba4
DunDunDunDone/LinkedLists
/ex05/sort_asc.py
1,119
3.75
4
from given_code import * import random x = SinglyList() for i in range(100): x.add_head(Node(random.randint(0, 100))) def sort_asc(unsorted_list): newlist = SinglyList() unsorted_listtemp = unsorted_list.next newlist.head = unsorted_list newlist.head.next = None unsorted_list = unsorted_listt...
6409f8377a618ef285facc4a74c2b1c5d546afaf
NitishGadangi/Code-Jungle
/FindtheTownJudge.py
610
3.546875
4
#https://leetcode.com/explore/featured/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3325/ #10May2020 class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: town=list(range(1,N+1)) for li in trust: if li[0] in town: town.remove(li[0]) ...