blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1bb515279af5c67ea52ed4045065259701cd5746 | xywanhh/pythonPrimary | /pyService/classdemo/cls12.py | 790 | 3.796875 | 4 | class A(object):
def test(self):
print('from A')
class B(A):
def test(self):
print('from B')
class C(A):
def test(self):
print('from C')
class D(B):
def test(self):
print('from D')
class E(C):
def test(self):
print('from E')
class F(D,E):
# def test(s... |
962d34b3a2d37fffc23c462a8c2f004a2af540c6 | xywanhh/pythonPrimary | /pyService/classdemo/cls13.py | 496 | 4.03125 | 4 | from abc import ABCMeta,abstractmethod
class Animal(metaclass=ABCMeta): #同一类事物:动物
@abstractmethod
def talk(self):
pass
class People(Animal): #动物的形态之一:人
def talk(self):
print('say hello')
class Dog(Animal): #动物的形态之二:狗
def talk(self):
print('say wangwang')
class Pig(Animal): #动... |
62bda586a5eeb1dca739f11b6d931ebdc32244e6 | xywanhh/pythonPrimary | /pyService/classdemo/m1.py | 598 | 3.9375 | 4 | from math import pi
class Circl:
def __init__(self, r):
self.r = r
def area(self):
return pi * self.r * self.r
def premeter(self):
return 2 * pi * self.r
class Ring:
def __init__(self, r1, r2):
self.c1 = Circl(r1)
self.c2 = Circl(r2)
def area(self):
... |
e1f4e9573692dab88221a904476a5fb0bc3a339c | PJensen/project-euler | /Python/p25.py | 348 | 3.515625 | 4 |
s = [1,1]
def fast_fib(n):
ax = 1
while (ax < n):
s.append(s[-1] + s[-2])
ax += 1
return s[-1]
print fast_fib(10)
def fib(n):
if (n == 1):
return 1
elif (n == 2):
return 2
else:
return fib(n - 1) + fib(n - 2)
dx = 100
while len(str(fib(dx))) < 1000:
dx += ... |
29bccb91a4da1a38eba91f6ca2540464d739b19b | driscollis/python101code | /chapter33_xml/parse_xml.py | 534 | 3.734375 | 4 | # parse_xml.py
from xml.etree.ElementTree import ElementTree
def parse_xml(xml_file):
tree = ElementTree(file=xml_file)
root_element = tree.getroot()
print(f"The root element's tag is '{root_element.tag}'")
for child_element in root_element:
print(f'{child_element.tag=}, {child_element.text=}... |
bd78b07ab6d3c89c6e231cd0b7b0a9d22065e8fc | HANDS-FREE/handsfree | /handsfree_tutorials/script/5_advance_app/nav_square.py | 6,277 | 3.75 | 4 | #!/usr/bin/env python
# coding:utf-8
""" nav_square.py - Version 1.1 2013-12-20
A basic demo of the using odometry data to move the robot
along a square trajectory.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2012 Patrick Goebel. All rights reserved.
This program is... |
333d17221f0a90d3f4a133289dea62fac2b36e7d | jazzpi/rudolph | /doc/scripts/util.py | 1,463 | 4.0625 | 4 | #!/usr/bin/env python3
from typing import List, Mapping
def parse_header(header: str) -> List[str]:
"""
Parse a table header.
Headers are of the form
| Col A | Col B | Col C |
(This would return ["Col A", "Col B", "Col C"])
"""
columns = []
for col in header.split("|")[1:-1]: #... |
21d78e36b0d9c0ec15dc33f4282dda5a58fd9c3a | danieltimar/exercism-python | /python/bob/bob.py | 758 | 3.984375 | 4 | import string
def hey(phrase: str) -> str:
"""
The function takes a string input, and returns a string response, based on the content of the input.
"""
clean_phrase = phrase.strip()
all_letters = [i for i in clean_phrase if i in string.ascii_letters]
all_uppercase_letters = [i for i in clean... |
c061bfc2d35ccf525de564d966aecf34db712e9c | sdraeger/lnc | /py/rt/vec3.py | 2,377 | 3.5625 | 4 | import math
import random
class vec3:
def __init__(self, e1, e2, e3):
self.e = [e1,e2,e3]
def __str__(self):
return repr(self.e)
def x(self):
return self.e[0]
def y(self):
return self.e[1]
def z(self):
return self.e[2]
def r(self):
return self.e[0]
def g(self):
return self.e[1... |
26a0e6bfe146f0dfa222cdafea86a593c69c57e7 | JoannaGriffiths/Coral-population-responses-to-acidification | /OrthoFinder Analysis/find_genes_both_pop_from_ortho.py | 1,895 | 4.0625 | 4 | #!/usr/bin/env python
"""
This is a program that that finds OrthoGroups that only have genes from both populations
Created by Joanna S. Griffiths on May 2017
Copyright 2017 Joanna S. Griffiths. All rights reserved.
"""
import argparse
def files():
parser = argparse.ArgumentParser(
description='Orth... |
57158761b76415ab40a067029c5cb0fd8304bb79 | triump0870/TrustModel | /web_service.py | 639 | 3.546875 | 4 | import Database
import sys
def error():
print "\nError!!! You entered wrong values\n"
if __name__=='__main__':
db = Database.Database()
q = "select * from WebServices"
p = db.query(q)
N = 0
Ns = 0
print type(p)
for i in p:
print type(i)
print "Id=%s"%i['name']
r = input("\nEnter raing for the above web ... |
d92de1c9c464ac74e765e68bb745236fc4e64786 | nebffa/project-euler | /python/49.py | 2,626 | 4 | 4 | # performs Miller-Rabin deterministic test. Essential conditions are: testPrime > 1 and testPrime is odd
def checkPrime(testPrime):
# fetches the parameters required for test
s = 0
d = testPrime - 1
while d % 2 == 0:
s += 1
d = d/2
# the algorithm assumes testPrime is prime... |
bc3056b1e4b5ef4c02bf674aa17182450d95d747 | nebffa/project-euler | /python/66.py | 1,964 | 3.59375 | 4 | from math import sqrt
from time import time
from copy import copy
from fractions import gcd
t = time()
def next_level_fraction(fraction):
temp = [0, 0, 0, 0]
simplify = gcd(fraction[3], (fraction[1] - fraction[2] ** 2))
temp[1] = fraction[1]
temp[0] = fraction[0] * fraction[3] / simplify
... |
25c0b9169ba65f2bb2f3222af59966fc8e4717c3 | nebffa/project-euler | /python/45.py | 218 | 3.5 | 4 | from math import sqrt as squareroot
i = 143
isFound = False
while not isFound:
i += 1
h = i * (2 * i - 1)
if (1 + squareroot(1 + 24 * h)) % 6 == 0:
isFound = True
print h |
2715d85d498c700db323db2370908d12f17c5a19 | xDarKyx/School-Work | /Python/Lab2-4/Lab2-4P03/undoFunction.py | 1,005 | 3.859375 | 4 | '''undoOp() function: restores the list from before the last operation'''
def undoOp(undoExp,expenses):
if(undoExp==expenses):
print("")
print("No operations have been made that changed the list")
else:
for k in undoExp:
expenses[k]=undoExp.get(k)
print("")
pr... |
d1311111efbb7a988492471d9255de46060370f4 | xDarKyx/School-Work | /Python/Lab2-4/Lab2-4P03/characteristicFunctions.py | 6,064 | 4.09375 | 4 | import operator
''''List with the only valid types of expenses allowed for the dictionary'''
expTypes=["Transport","Food","House keeping","Clothing","Telephone&Internet","Others"]
'''sumType() function: returns the sum of expenses from a specific type from the whole month'''
def sumType(expenses):
t=input("Type:"... |
8cc90a94a8ae3241b583ba85f80d8f470ea30d7a | xDarKyx/School-Work | /Python/Lab5-7/Lab5-7P01/Functions.py | 4,443 | 3.75 | 4 | from student import *
from grades import *
from statistics import *
import operator
def AddStudent(sID,students):
isInList=False
for x in students:
if x.getStudentID()==sID:
isInList=True
print("The ID is already in use!")
if isInList == False:
sNAME=str(input("Stud... |
85a639394910bdc79df9030ffcda1f00c5da410b | ashishnoko/pythonoop | /loop.py | 385 | 3.65625 | 4 | # sum = 0
# i = 0
# while i < 10:
# sum = sum + i
#
# i+=1
# # print(f"The sum is {sum}")
# item = ["car","mobile","eeee"]
# for a in item:
# # print(a)
# for item in range(0,10):
# print(item)
data = [
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]
]
for i in data:
f... |
b682f1d13cc74c6b3d66b58d1713ff66f30ce0cb | Jungjaeyoon/study | /effective_python/Better_Way_11.py | 548 | 4.125 | 4 | # zip
names = ['Jeon','Yu','Ri']
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count
print(longest_name)
#Use zip for easier code
for name, count in zip(... |
2a0e320d4d62c47140ee7c0cdeab0b5c6e2452bd | suryatejaparisa/python_oops_matplotlib_socket | /pythonweek1/Q4.py | 3,024 | 3.984375 | 4 | class Paper:
t_area = 0 #occupied area in the paper
info = ""
def __init__(self, area):
self.area = area
if self.area <0:
try:
raise Exception()
except Exception as e:
print(type(e))
print("Paper should have positive ar... |
1ae0db4e621829ad06450118e31debeded81f989 | JulienBouchardIT/Pi-Car | /light_led.py | 1,349 | 3.609375 | 4 | import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)
GPIO.setup(10, GPIO.OUT, initial=GPIO.LOW)
GPIO.... |
80b4b97fb781bde551ad4d958abb1baba78c485b | ahmadaz/RankingSystem | /finalProjectSolution.py | 2,082 | 3.953125 | 4 | # read the names and marks of at least 4 students
# rank the top 3 students with highest marks
# give cash rewards: 1st $500, 2nd $300, 3rd $100. (non modified value)
# appreciate students who scored 950 or above
# {"John": 875,"Laureen": 924,"Sarah": 983,"Smith": 952}
import operator
def readStudentDetails... |
9072d786fa2326cd7995ac3dcd4cba060c96ba11 | Castaldo/US-Mortgage-Analysis | /Data/Pre_Processing.py | 804 | 3.515625 | 4 | import pandas as pd
Mortgage = pd.read_csv('Data/Unprocessed/hmda_2017_nationwide_all-records_labels.csv')
Mortgage = Mortgage[(Mortgage['loan_purpose_name'] == 'Refinancing')]
Mortgage = Mortgage[(Mortgage['action_taken'] <= 3)]
Mortgage.drop(Mortgage.columns[[0, 1, 2, 3, 5, 7, 9, 10, 11, 14, 15, 16, 18, 26, 28, 32... |
13acdcd523033f3e4e2a30984e66217d2d353a4b | Neeraj-kaushik/Data_Structures_python | /linked_list-2/kreverse.py | 1,205 | 3.71875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse(head):
if head is None or head.next is None:
return head, head
smallHead, smallTail = reverse(head.next)
smallTail.next = head
head.next = None
return smallHead, head
... |
571b5668d67ae6153eeb5fb989d0db231f1de0ca | Neeraj-kaushik/Data_Structures_python | /Recursion Assingment/stringtoint.py | 249 | 3.671875 | 4 | def stringtointeger(str1):
if len(str1)==1:
return ord(str1[0])-ord('0')
a=stringtointeger(str1[1:])
a1=ord(str1[0])-ord('0')
a1=a1*(10**(len(str1)-1))+a
return int(a1)
str1=str(input())
print(stringtointeger(str1)) |
7172cb3e2f2ebdc1cf151d0d2e610cf19461ef37 | Tyrna/cs4310 | /Strassen/Strassen.py | 4,159 | 3.703125 | 4 | ###
# By: Oscar Vanderhorst
# Date: 09/27/18
# Purpose: Implementation for Strassen's algorithm on a static 4x4 matrix
# Does not include recursion for the sake of this assignment.
###
X = [[2,2,2,1],[5,8,3,2],[3,3,5,9],[1,3,4,2]]
Y = [[5,4,2,1],[7,1,4,4],[4,8,6,3],[5,7,4,2]]
print("\nX Matrix : \t\tY Matrix: ")
pr... |
4ba222eaba8e889f1a37c312cb41cf2d6b6d287d | hvna/ughsprite | /sprite.py | 51,023 | 4.09375 | 4 | """pygame module with basic game object classes
This module contains several simple classes to be used within games. There
are the main Sprite class and several Group classes that contain Sprites.
The use of these classes is entirely optional when using Pygame. The classes
are fairly lightweight and only provide ... |
312a2944cb71857e75d35d40b24f9abe20fee13e | ABD36017/rvaun | /positive.py | 135 | 4.03125 | 4 | a=int(imput("enter value of a"))
b=int(input("enter value of b"))
if(a>b):
print(a,"is positive")
elif(b>a):
print(b,"is positive") |
abf043422eb078b41cb153ffd474534c48ad7800 | MrRooots/Project_Euler | /Problem_41.py | 798 | 4.03125 | 4 | def is_prime(num): # Возвращает True, если num - простое
from math import sqrt
flag = True
if num >= 2:
for init in range(2, int(sqrt(num) + 1)):
if num % init == 0:
flag = False
break
else: flag = False
return flag
def pan_digital... |
d725ea46aa06ced2dcc6ffa59616b88a6da0b59f | MrRooots/Project_Euler | /Problem_16.py | 181 | 3.921875 | 4 | def Sum(number):
number =2 ** 1000
result = 0
for digit in str(number):
result += int(digit)
return result
print(Sum(int(input("Enter a number: ")))) |
190fde5632fb315e9e4da24a3f42230839bb8c2b | MrRooots/Project_Euler | /Problem_17.py | 372 | 3.9375 | 4 | # Count of chars in numbers
# num2words ----> 115 == one hundred and fifteen
def char_counting(count):
from num2words import num2words
result = 0
for number in range(1, count + 1):
for char in num2words(number):
if char.isalpha() == True:
result += 1
return r... |
6ebe820c3d61c2b2438f6eab12896f8ab61ad2a6 | MrRooots/Project_Euler | /Problem_45 OPTIMIZE.py | 568 | 3.65625 | 4 | def triangle_hexagonal_pentagonal():
triangle = []
for n in range(10000, 10000001):
triangle.append(int((n*(n+1))/2))
hexagonal = []
for n in range(10000, 10000001):
hexagonal.append(int(n*(2*n-1)))
pentagonal = []
for n in range(10000, 10000001):
pentagona... |
d5d8871f8e294664b2f5c6265339a520d4ce437e | igorbragaia/CES-22 | /bim1/week3/15.12.3.py | 890 | 3.625 | 4 | import sys
def test(did_pass):
"""
Prints test result
:param did_pass: test result
:return:
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(... |
4b4530110e981d6f8331fcc75b246a812fec7235 | igorbragaia/CES-22 | /bim2/aulas 14 e 15-design pattern/fabrica_abstrata.py | 325 | 3.65625 | 4 | from abc import ABCMeta, abstractmethod
class Base(metaclass=ABCMeta):
def __init__(self):
self.id = 1
@abstractmethod
def metodo(self):
pass
class Exemplo(Base):
def __init__(self):
super().__init__()
def metodo(self):
pass
if __name__ == "__main__":
Exem... |
dce8c2242ffb7722ff18125a65282aa15c09269c | igorbragaia/CES-22 | /bim2/aulas 14 e 15-design pattern/decorador.py | 839 | 3.640625 | 4 | from abc import ABCMeta, abstractmethod
class Component(metaclass=ABCMeta):
@abstractmethod
def operation(self):
pass
class Decorator(Component, metaclass=abc.ABCMeta):
def __init__(self, component):
self._component = component
@abstractmethod
def operation(self):
pass
... |
819e5da6a51d662e4e633b2e0c5c7cba4ef7a841 | vish198910/CrackingCodesWithPython | /venv/CaesarCipher.py | 718 | 3.609375 | 4 | import pyperclip;
# message to be encrypted
message = input()
mode = "e"
S = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
encrypted = ""
key = int(input())
for symbol in message:
if symbol in S and (key <= 65 and key >= 0):
symbol_index = S.find(symbol)
if mode == "e":
... |
645f985635f68c36f6ce6574bb2ac4ab1fd0b735 | mml1/bubble_sort | /bubble.py | 416 | 3.59375 | 4 | import random
import time
#variables
arr=[]
i = 0
#print the random numbers
for x in range(100):
arr.append(random.randint(0,10000))
# will go through the array and bubble sort
while i < len(arr)-1:
for item in range(0, len(arr)-1):
if arr[item+1] < arr[item]:
temp= arr[item+1]
arr[item+1] = arr[item]
... |
0b8b3e15d953583bfb37d5750544b3b8e6b09b25 | MuhummadShohag/PythonAutomation | /Loop_Pass_Break_Continue/Range_function.py | 972 | 4.625 | 5 | '''
* range():
-- It is a build in function
-- it is generates integers as a list
* Syntax:
range(start,stop,step)
3-argument ==> by default start = 0, step = 1
'''
print(range(5))
print(list(range(5)))
# start value 0, stop value 5
print(list(range(0,5)))
# start value 0, s... |
e04a52463beb243bdc9befb130a43861b8dfb52b | MuhummadShohag/PythonAutomation | /Conditional_Statements/simple_if_condition.py | 1,422 | 4.40625 | 4 | '''
*If is called simple conditional statement
*Used to control the execution of set of lines or block of code or line
if expression:
statement1
statement2
*Expression like: comparision, identity, membership, logical Operators
'''
import os
get_terminal_size=os.get_terminal_size().col... |
149ba1a4b6e5f1fcf30475c7aa08fef33bd1cbcc | kelele67/python-king | /codewinner/PythonicSort/insertion_sort.py | 583 | 3.90625 | 4 | def sort(seq):
for i in range(1, len(seq)):
item = seq[i]
hole = i
while hole > 0 and seq[hole - 1] > item:
seq[hole] = seq[hole - 1]
hole = hole - 1
seq[hole] = item
print seq
return seq
if __name__ == '__main__':
arr = [23, 14, 50, 67, 41, 8... |
fc5f9478d35c4d0aaae6ab5d6077e674fb5382ab | kelele67/python-king | /codewinner/PythonicSort/bogo_sort.py | 510 | 3.84375 | 4 | import random
def sort(seq):
if len(seq) == 1:
return seq
random.seed()
while not is_sorted(seq):
if len(seq) == 2:
i = 0
j = 1
else:
i = random.randint(0, len(seq) - 2)
j = random.randint(i, len(seq) - 1)
seq[i], seq[j] = seq[... |
696730c257a4ba6956bd1662a6c17f4f4a72ed17 | kelele67/python-king | /morePython/property_example.py | 873 | 4.3125 | 4 | class Mat(object):
"""动态读,class 内部只存 temp 的值,每次取 pro 的时候实时计算"""
def __init__(self, t):
self.tmp = t
@property
def pro(self):
return self.tmp * self.tmp
a = Mat(5)
print (a.tmp, a.pro)
a.tmp = 10
print (a.tmp, a.pro)
# 不加属性
# 5 <bound method Mat.pro of <__main__.Mat object at 0x109014... |
39f84fe994c5db486f0bbc71998564c2d8f62b67 | kelele67/python-king | /oldcode/evaluate.py | 835 | 3.578125 | 4 | # def evaluate():
# N = int(raw_input())
# count = 0
# for i in range(N):
# x, y = raw_input().split()
# if x == y:
# count = count + 1
# print ("%.2f%%") %(100* float(count)/N)
# evaluate()
# while True:
# try:
# count = 0
# N = int(raw_input())
# ... |
7275a16c7ae48b764ef548d90a9f59d09f5f121d | kelele67/python-king | /codewinner/Tree/trieTree/trie_pre_match.py | 5,958 | 4.03125 | 4 | # -*- coding: utf-8 -*-
class Trie_tree(object):
def __init__(self):
# node = [father, child, keep_char, is_word]
self._root = [None, [], None, False]
self.tmp = []
def insert(self, word):
current_word = word
current_node = self._root
self._insert_operation_1(c... |
e6ae5feaef16ffe4df73e98e5c7daeaa16a7bdb4 | kelele67/python-king | /oldcode/palindromeCount.py | 499 | 3.8125 | 4 | def isPalindrome(str):
for i in range(0, len(str)/2):
if str[i] == str[len(str)-1-i]:
continue
else:
return False
return True
def palindromeCount(str, insert_str):
count = 0
for i in range(0, len(str)+1):
new_str = ''
new_str = str[:i] + insert_st... |
65b4ea1c40dc3bb235f9f95b0ed7da00e89cc584 | kelele67/python-king | /codewinner/Sort/shellSort.py | 425 | 3.890625 | 4 | #!/usr/bin/python
def shell_sort(arr):
n = len(arr)
gap = n/2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j-gap] > temp:
arr[j] = arr[j-gap]
j -= gap
arr[j] = temp
... |
dd6783c54809f4255150838de86adae2c72a4fc1 | kelele67/python-king | /codewinner/PythonicSort/selection_sort.py | 330 | 3.59375 | 4 | def sort(seq):
for i in range(0, len(seq)):
iMin = i
for j in range(i+1, len(seq)):
if seq[iMin] > seq[j]:
iMin = j
if i != iMin:
seq[i], seq[iMin] = seq[iMin], seq[i]
return seq
if __name__ == '__main__':
arr = [4, 3, 9, 6, 7, 7]
print (... |
066a4e0b5ddbf89d0ff6e0c8033f49e339471efc | kelele67/python-king | /codewinner/LinkedList/untitled file.py | 704 | 3.5 | 4 | # -*- coding: utf-8 -*-
# 剔除最大数-> 找子数组有没有等于 t - 1, t-2...的 然后+最大的数
def find_sum(arr, n, target):
temp = arr[:]
sums = 0
for i in range(n):
for j in range(i, n):
sums = sums + arr[j]
temp.remove(arr[j])
if (sums == target):
return temp
return ... |
77862ac532f37e3b0f11a5dd46ef7e8ae53bb408 | coyotespike/machinelearning | /Hoeffding.py | 2,383 | 3.90625 | 4 | """
We want to flip 1000 fair coins, flipping each 10 times. From these 1000 coins,
we will choose 3: the first one flipped, a random coin, and the one with the
minimum number of heads (in case of tie, the first such). We then take the
fraction of heads obtained out of 10 tosses.
Run this 100,000 times to get a good ... |
296f6c845bda1d6d3610e23deb4af37eda5a1314 | Boiannn/week0HW | /test/5.py | 163 | 3.8125 | 4 | def is_prime(n):
if n < 0:
n = abs(n)
prime = True
for i in range(2,n):
if n%i == 0:
prime = False
return prime
return prime
print is_prime(15)
|
90a791298a44ab1e31b224f50e8c065be6983e0b | Boiannn/week0HW | /test/10.py | 374 | 3.859375 | 4 | def contains_digit(number , digit):
if number < 0:
number = abs(number)
while number > 0:
a = number%10
if a == digit:
return True
number = number // 10
return False
def contains_digits(number , digits):
for i in digits:
truth = contains_digit(number , i)
if truth == False:
return False
r... |
05ecc7bf22e9ec03e875aee6d2e22ec735f1ca1b | Boiannn/week0HW | /test/tessst.py | 58 | 3.71875 | 4 | def divisor(n)
if number/3**n == 1:
print n
divisor(3) |
a75aa4ac55e8ea532c5481edd96177aef0120d29 | niroyb/CompInfo_H13 | /Combien de Triangles/triCount Optimized.py | 845 | 3.59375 | 4 | """Finds the number of triangles of an input
containing the segment representation of an image"""
__author__ = "Nicolas Roy"
from collections import defaultdict
import sys
lines = sys.stdin.read().splitlines()
mapAdj = defaultdict(set)
#Create optimized adjacency dictionnary
for line in lines:
nodes = sorted(li... |
63f0257b23344f3b8ea3ba5805cd562ba1c2edd5 | rk385/tathastu_week_of_code | /Day3/program1.py | 132 | 4.34375 | 4 | string=input('enter a string: ')
rev=''
for i in range(len(string)-1,-1,-1):
rev=rev+string[i]
print('reversed string is:',rev)
|
a8e6e745cdf110d3b1efe36ae2bba0b7dc86234d | rk385/tathastu_week_of_code | /Day4/program3.py | 340 | 3.765625 | 4 | t=int(input('enter no. of values in a dictionary:'))
dict={}
for i in range(t):
key,value=input().split()
value=int(value)
dict[key]=value
lst=[]
for i,j in dict.items():
lst.append(j)
lst=sorted(lst)
k=lst[-2]
for i,j in dict.items():
if j==k:
l=i
print('second maximum value in dictionary... |
12a51e82ee0c776db7e9adab4fd119ac24359650 | rk385/tathastu_week_of_code | /Day5/program5.py | 403 | 3.890625 | 4 | def even(x):
lst1=[]
for i in x:
if i%2==0:
lst1.append(i)
return sorted(lst1)
def odd(k):
lst2=[]
for i in k:
if i%2!=0:
lst2.append(i)
return sorted(lst2)
x=[int(x) for x in input('enter integers:').split()]
a=even(x)
b=odd(x)
k=[]
for i in range... |
abf1d0b6cf5ded3a0b38b7570d35ed15b8d53e26 | rk385/tathastu_week_of_code | /Day2/program1.py | 324 | 3.609375 | 4 | def per(lst,str=''):
Set=set(lst)
slist=[]
if len(Set)==1:
str+=''.join(lst)
return list([str])
for i in Set:
Lst=list(lst)
s=str+i
Lst.remove(i)
slist.extend(per(Lst,s))
return slist
str = input('enter a string:')
lst=per(list(str))
print(','.join(ls... |
d921de7240a7ad122e15fff1ab6a8f0695241773 | rk385/tathastu_week_of_code | /Day6/program5.py | 596 | 4.03125 | 4 | def fabonacci(fablist):
a = int(input('Enter a number from fabonnaci list:\n'))
b = int(input('Enter 2nd numbr from fabonaaci list:\n'))
c = a+b
m=0
if c in fablist:
print('sum of these numbers is a fabonaaci number:\n')
m=1
if m==0:
print('sum of these nu... |
06a096fa47e737fd4ffd69497333f930fcea13d4 | Someone-Who-Dares/randstr | /randstr.py | 600 | 3.984375 | 4 | ## Generates random strings and hashes them with crypt.mksalt() and saves the hashed string in an output file
import string
import crypt
import readline
from random import *
chars = string.ascii_letters + string.digits
getfilename = input('Choose outputfile: ')
filename = getfilename+'.rpw'
randchars = "".join(choi... |
47d0392d527abb24e9f1b3e47519e73ed423fc8f | LySuzz/Repositorio-Erick-Mtz-Mtz | /practica1for.py | 72 | 3.5625 | 4 | #for usando una lista
for i in [1,2,3,1]:
print("Hola: "+str(i))
|
e9b85d373953cede8d2b2bc363fae219140a4a32 | LySuzz/Repositorio-Erick-Mtz-Mtz | /S3Ejerciciore4.py | 615 | 3.5625 | 4 | import re
cadena="Vamos a aprender expresiones regulares, aprender programacion"
textobuscar="aprender"
textoencontrado=re.search(textobuscar,cadena)
if textoencontrado is not None:
print("Funcion start(): Inicia en "+ str(textoencontrado.start()))
print("Funcion end(): Termina en "+ str(textoencontra... |
95671f034b1f8bf595644d49fa9506738bf91a0b | andrewLay/Advent-of-Code-2020 | /Advent of Code 2020 Py/Day 12.2 Cartesian Movement.py | 4,216 | 4.28125 | 4 | # DAY 12.2 EXAMPLE
# ================
# The instructions now refer to a waypoint relative to the ship's position.
# The waypoint starts 10 units east and 1 unit north relative to the ship.
# The ship starts at (0, 0).
#
# Action N means to move the waypoint north by the given value.
# Action S means to move the waypoi... |
8d1e24b5151a3675d5d62c47f71152e957ffd2ac | zea2/DeviceManager | /device_manager/device.py | 20,882 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Device types that are supported by the device manager and scanners.
Currently two types of devices are supported: USB and LAN devices. USB devices are identified by
their vendor id, product id and serial number. The ethernet (LAN) devices use their mac address for
a uni... |
c68b97b1e7c64a2dc2dde333045ea4dd40447cf1 | pdghawk/systrade | /systrade/monte/generator.py | 3,950 | 3.5625 | 4 | """ Module for statistal/random number generators
"""
import numpy as np
import copy
class Normal:
""" object for generating random normally distributed numbers"""
def __init__(self,mean=0.0,var=1.0):
self.mean = mean
self.var = var
def get_samples(self,n_samples=1):
""" get sampl... |
cc923b4776d5a573086a487a331dda889799cc96 | Korede34/ATM-mockup | /task3.py | 3,703 | 3.96875 | 4 | from datetime import date
from random import randint
def greetings(msg):
print(msg)
def register():
print('Register an Account')
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
username = input('Enter your username: ')
email = input('Ent... |
5d6de52574bd0b28a95c9a1cc9cc7258c9b2047d | Purplemexican/History-PBL | /HistoryhPBL.py | 3,260 | 3.6875 | 4 | # Caleb McGuire, Hunter
print 'You are a Jewish citizen during the time of Hitler\'s rule. Type ok to proceed'
scenario = raw_input('> ')
while scenario != 'ok' and scenario != 'OK':
scenario = raw_input("Sorry, I didn't catch that. Try again: ")
if
print 'The Nazis come through your home town.'
print 'Y... |
9149457bfee6fe515268cea8c571622e5e7f65e6 | coltynw/cs-module-project-algorithms | /single_number/single_number.py | 737 | 3.96875 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
def single_number(arr):
# Your code here
# the idea for the first-pass soltuion
# we'll keep an array, call it 'no_dups' to hold numbers we see int eh nums array
# iterate through nums
# check to see ... |
8615d564e12354c1948f5d7afeef9baa85bdd8a1 | ErenBtrk/PythonJsonExercises | /Exercise6.py | 240 | 3.953125 | 4 | '''
6. Write a Python program to create a new JSON file from an existing JSON file.
'''
import json
with open("jsondata.json","r") as file:
data = json.load(file)
with open("newjsondata.json","w") as file:
json.dump(data,file)
|
78ff5ccb5f2614d08f2528cc8fcdb906cb054a85 | damionjerrod/second-language-homework | /list-program.py | 106 | 3.921875 | 4 | my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
if(i == 7):
print("Element is in the List") |
53f874f61f9cd971903fd64e1d7882f3be483ecb | evsasse/ine5429-security | /t5-primenumbers/fermat.py | 451 | 3.578125 | 4 | import random
from .prime_number_generator import PrimeNumberGenerator
class Fermat(PrimeNumberGenerator):
@staticmethod
def test(n, k=30):
assert(n > 1)
if n == 2 or n == 3:
return True
if n%2 == 0:
return False
for _ in range(k):
... |
40be9454bbc10473e5915ae905215fd6efe85d34 | arthurweslen/PythonExercicios | /009_Decimal_Inteiro/Numero_inteiro.py | 282 | 3.703125 | 4 | print('='*28)
print(f'\033[1:7m{"NÚMERO INTEIRO":=^28}\033[m')
print('='*28)
from math import floor
num = float(input('Digite um número decimal: '))
num_int = floor(num)
print('O número {} é um número decimal. Ele inteiro fica: \033[1:4m{}\033[m'.format(num,num_int)) |
22c2b693309e57047b77a136b34496d83591cd73 | arthurweslen/PythonExercicios | /017_JOKENPO/jokenpo.py | 1,573 | 3.703125 | 4 | #Essas primeiras linhas são apenas um título, com cores invertidas
print('='*28)
print(f'\033[1:7m{"VAMOS JOGAR JOKENPO":=^28}\033[m')
print('='*28)
import random
jogadas = ('','Pedra','Papel','Tesoura')
numPermitidos = [1,2,3]
jkp_pc = random.choice(numPermitidos)
print('Digite 1 para PEDRA \nDigite 2 para... |
da2d54e0840140c882d82f1b1b0aebb200e8740f | arthurweslen/PythonExercicios | /001_Numero_Digitado/numdigitado.py | 222 | 3.625 | 4 | print('='*28)
print(f'\033[1:7m{"NUMERO DIGITADO":=^28}\033[m')
print('='*28)
num = int(input('Digite um número: '))
print('Número digitado: {} \nNúmero antecessor: {} \nNúmero posterior: {}'. format(num,num-1,num+1)) |
2842e2421e08ed69a751dbfdc9796327be50f599 | devm33/jam | /round1a/rank/ans.py | 1,923 | 3.765625 | 4 | #!/usr/bin/env python
def find_col(N, lists):
for i in range(1, N):
l = lists[i]
if l[0] in lists[0]:
c = lists[0].index(l[0])
cur = 1
for j in range(1, N):
if i != j and lists[j][c] == l[cur]:
cur += 1
if c... |
894de61541de5e3d78b9762d2bee01e7100f49e2 | vasylbo/py-sample-speedup | /speed_test.py | 717 | 3.515625 | 4 | import timeit
import functools
POPULATION_SIZE = 5000
MIN_TEST_POPULATION = 900
MAX_TEST_POPULATION = 5000
TEST_STEP = 2000
TIME_IT_NUMBER = 100
def test_speed(test_cases):
for fun in test_cases:
test_sample(fun[0], fun[1])
def test_sample(name, sample_fun):
print('Speed test for %s' % name)
po... |
f1364c55170f8e0318ca5d30ad025652091c57d4 | nbhh1234/test1 | /code/day05.py | 108 | 3.546875 | 4 | x,y=eval(raw_input('Enter balance and interest rate:'))
Q=x*(y/1200)
print('The interest is {}'.format(Q))
|
741be9fffa14fdd7cee3a2c4b385deec5b2df4ed | uberchurch/MOOC_A_Gentle_introduction_to_Python | /HM 1/hw1.py | 1,229 | 4.125 | 4 | # Name: Timothy S Brower
# Section:
# Date:10/26/13
# hw1.py
##### Template for Homework 1, exercises 1.2-1.5 ######
print 'hello, world!'
print "********** Exercise 1.2 **********"
# Do your work for Exercise 1.2 here
print ' | | '
print '--------'
print ' | | '
print '--------'
print ' | | '
print "*... |
18a5b66b67df8a791f120a93ac0b003a53525bff | CalS96/210CT | /Q1.py | 625 | 4.03125 | 4 | import random
def shuffle(array):
array1 = [] #Empty array where the new shuffled list will go
while len(array) != 0:
randomPos = random.randint(0, len(array)-1) #makes a random positon for an integer of the length of the list
randomNum = array.pop(randomPos) #pop will remov... |
54ce8cffbdda62263b9ccff2202db2d6deaab04e | diving16/Visualize_Learn | /pandas_intro.py | 1,505 | 3.734375 | 4 | import pandas as pd
#dataframe
#每一列是一个series
pd.set_option('display.max_row',100)
pd.set_option('display.max_columns',100)
#批量输入及更改header
#user_input_cols=['a1','a2','a3',
# 'a4','a5','a6',
# 'a7','a8','a9']
df=pd.read_csv('diabetes.csv',)
# names=user_input_cols)
#head... |
a99db76acd4f2cb400b2df42155360a40a10ba24 | diving16/Visualize_Learn | /data_visual.py | 504 | 3.515625 | 4 | from matplotlib import pyplot as plt
import pandas as pd
#x=[1,2,3,4,5,6,7,8,9,10]
#y=[1,3,5,6,7,8,9,10,13,17]
#z=[2,4,6,8,10,11,12,14,16,20]
#导入外部数据
data1=pd.read_csv('sample_data.csv')
print(data1)
print(type(data1))
#选取表格中某个数据
number=data1.column_b.iloc[8]
number2=data1.iloc[3,1]
print(number)
print(number2)
#... |
d0b6da8636642404981e736f1dbda5f1ba61974f | obs145628/py-softmax-regression | /softmaxreg.py | 3,082 | 3.53125 | 4 | '''
Softmax regression implementation
More informations:
- http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/
- https://medium.com/@awjuliani/simple-softmax-in-python-tutorial-d6b4c4ed5c16
'''
import numpy as np
import dataset_mnist
'''
Compute matrix version of softmax
compute the sofmax functon for... |
08316a51bcb2bca6ead20fc240a9437c74159be2 | lcsdn/RL-alphazero | /RLcode/data_structures/tree.py | 1,111 | 4 | 4 | class DictTreeNode:
"""
Define a tree data structure, whose children are encoded in a dictionary
and whose value at each node is also encoded in a dictionary.
Instantiate a tree by its root node.
"""
def __init__(self, dict_value, parent=None, children=None):
self._dict = dict_value
... |
69a54fced661802440573727e80fd8974e7eb746 | srikarpavan/python | /ICP1/SOURCE/digits and numbers counting.py | 608 | 4.21875 | 4 | data=input("enter a string") # Taking a string from user
letters=numbers=0 # Initially taking letters and numbers as zero
for i in data:
if i.isdigit(): # checking whether it is a digit or not using isdigit
numbers =numbers+1 # storing that digit in the numeric
elif i.isalp... |
14ca25fe6dc169aa7532638e5180b92019667dc7 | LordSomen/Python-Projects | /simple-python-code/karatsuba.py | 586 | 3.8125 | 4 |
def karatsuba(num,n,a,b,c,d,i = 0):
i += 1
if(i == 1):
sum = (10** n) *num + karatsuba(a * d + b * c,n// 2,a,b,c,d,i)
return sum
elif(i == 2):
sum = (10** n) *num + karatsuba(None,None,a,b,c,d,i)
return sum
elif(i == 3):
return (b * d)
num1 = inpu... |
76d01469ce2974c5ca5a80e6f6d76502145087b6 | dan-sf/leetcode | /univalued_binary_tree.py | 687 | 3.625 | 4 | """ Problem statement: https://leetcode.com/problems/univalued-binary-tree/ """
import lib.tree_util as tu
class Solution:
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def _is_unival(node, val):
if node is not None:
if ... |
93c503d71ff9109a670d5d149b20df0c587adbd3 | dan-sf/leetcode | /alt_bits.py | 537 | 3.71875 | 4 | """ Problem statement: https://leetcode.com/problems/binary-number-with-alternating-bits/description/ """
class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bin_str = bin(n)
if '00' in bin_str or '11' in bin_str:
re... |
0540da63be24bacc364eb65870cb7248f4d20b94 | dan-sf/leetcode | /climb_stairs.py | 1,345 | 3.96875 | 4 | """ Problem statement: https://leetcode.com/problems/climbing-stairs/ """
class Solution(object):
def climbStairs(self, n):
""" Iterative solution using the fibonacci sequence """
fib = [0,1,2]
if n <= len(fib)-1:
return fib[n]
for i in range(3, n):
current ... |
d21322751dc265b99a3865bb17d6d3843a034ab3 | dan-sf/leetcode | /remove_dups_linked_list_sorted.py | 1,109 | 3.6875 | 4 | """ Problem statement: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ """
class Node(object):
def __init__(self, x):
self.val = x
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def add(self, item):
n = Node(item)
n... |
89fe5f03e7f27d5eab586fe6acaf470836530387 | dan-sf/leetcode | /reverse_word_in_string_list.py | 343 | 3.65625 | 4 | """ Problem statement: https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ """
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
output = []
for word in s.split():
output.append(word[::-1])
re... |
b58fd9fc03fccaadcf7ca9dae7d6a29e42161976 | dan-sf/leetcode | /binary_watch.py | 2,052 | 3.625 | 4 | """
Q401. A binary watch has 4 LEDs on the top which represent the hours (0-11),
and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
Given a non-negative integer n which represents the number of LEDs that are
currently on, return a... |
b53f0dd750ebf6a0bba5a97a18022468c9980d57 | dan-sf/leetcode | /roman_numeral.py | 730 | 3.6875 | 4 | """
Q13. Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
"""
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman_map = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
... |
ef88140d3f93b8e8b7c7b78fd2382e9564af0787 | a1928375/multiple_turtle | /multiple_turtle_triangle.py | 975 | 3.59375 | 4 | import turtle
def detail_1(name):
name.forward(30)
name.left(60)
def detail_2(name,n):
name.left(120)
name.forward(60)
name.left(60)
name.forward(60*n)
name.right(180)
def draw_small(name):
for i in range(0,3):
name.forward(60)
name.left(120)
... |
ff3598bc044a865f431ac20049fab08ef1aa14df | jquintus/PiProject | /spikes/switch.py | 380 | 3.59375 | 4 | '''
https://projects.raspberrypi.org/en/projects/physical-computing/9
'''
from gpiozero import LED, Button
from signal import pause
led = LED(23)
button = Button(24)
led.off()
'''
button.when_pressed = led.on
button.when_released = led.off
'''
def pressed():
# led.toggle()
print("pressed")
button.when_pr... |
591455d64403e4b497e6a78ad0c8daa0ce68db62 | TheSameMan/GeekBrains | /Алгоритмы и структуры данных на Python. Интерактивный курс/les_2/les_2_task_3.py | 497 | 4.03125 | 4 | '''3. Сформировать из введенного числа обратное по порядку
входящих в него цифр и вывести на экран. Например, если введено
число 3486, надо вывести 6843.
'''
print('Обратное число из введенного.')
try:
print(''.join(reversed(str(int(input('Введите целое число:\n'))))))
except ValueError:
print('Некорректный в... |
395c500c6465f51dc0089f85e1acd37f9c390028 | TheSameMan/GeekBrains | /Алгоритмы и структуры данных на Python. Интерактивный курс/les_2/les_2_task_4.py | 561 | 3.921875 | 4 | '''4. Найти сумму n элементов следующего ряда чисел: 1, -0.5,
0.25, -0.125,… Количество элементов (n) вводится с клавиатуры.
'''
print('Сумма n элементов ряда: 1, -0.5, 0.25, -0.125, ...')
try:
n = int(input('Введите число элементов ряда:\n'))
if n <= 0:
raise ValueError
sum = 0
for i in rang... |
3c92bd7ff0ffee0672c29b67d419c40b38d876fa | TheSameMan/GeekBrains | /Алгоритмы и структуры данных на Python. Интерактивный курс/les_3/les_3_task_7.py | 1,310 | 4.125 | 4 | '''7. В одномерном массиве целых чисел определить два наименьших
элемента. Они могут быть как равны между собой (оба минимальны),
так и различаться.
'''
print('Определение двух наименьших элементов в массиве целых \
чисел')
try:
n = int(input('Введите число элементов случайного массива: \n'))
if n <= 0:
... |
6c04641b59012c36bbbd13829036a6dc3340f32b | JingQian87/NLP | /hw2/jq2282-hw2/models.py | 6,205 | 4.125 | 4 | """
COMS 4705 Natural Language Processing Fall 2019
Kathy McKeown
Homework 2: Emotion Classification with Neural Networks - Models File
Authors: Elsbeth Turcan <eturcan@cs.columbia.edu>
<Jing Qian>
<jq2282>
"""
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn
class DenseNetwork(nn.... |
328b913a5a996996c89a10ff58e6b05314d80b19 | Kiaradamiancoloma/T07_DAMIAN-MENDOZA | /DAMIAN_COLOMA/for5.py | 102 | 3.640625 | 4 | #Programa que muestre la siguiente serie 1 6 11 16
n=1
while(n<=20):
print(n)
n+=5
#fin_while
|
9ef885b465d15ab6865d3eca6091fffe42f5b4b6 | Kiaradamiancoloma/T07_DAMIAN-MENDOZA | /MENDOZA GONZALES/iteracion5.py | 548 | 3.890625 | 4 | #Programa que pida dos numeros
#Declaracion
num1,num2=0,0
import os
#Input
num1=int(os.sys.argv[1])
num2=int(os.sys.argv[2])
for i in [num1 and num2]:
#Muestre en pantalla si el primero es mayor
if(num1>num2):
print("El primer numero",num1," es mayor que ",num2)
#si el numero 2>numero 1, indicarlo en pant... |
ef96479c5bf610c336bdff52faf298526acd8284 | Kiaradamiancoloma/T07_DAMIAN-MENDOZA | /DAMIAN_COLOMA/rango2.py | 212 | 4.125 | 4 | #programa que pida una asignacion al usuario
#la muestra 15 veces en pantalla
#Declaracion
asignacion=""
#input
asignacion=input("introduce una asignacion:")
for i in range(15):
print(asignacion)
#fin_for
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.