blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
2e7418533b0e96ccdbcc1be9958c0210639b4815 | gt6192/NeuralNetworks | /Perceptron_Model/Perceptron_Model.py | 1,173 | 3.53125 | 4 | class Perceptron:
def __init__ (self):
self.w = None
self.b = None
def model(self, x):
return 1 if (np.dot(self.w, x) >= self.b) else 0
def predict(self, X):
Y = []
for x in X:
result = self.model(x)
Y.append(result)
return np.array(Y)
def fit(self, X, Y, epoc, learning_ra... |
bd22633c3919249f080d56ea0a3c21b21d6f576f | sachin28/Python | /MustKnowPrograms/CaseSwap.py | 238 | 4.09375 | 4 | inpstr = raw_input("Enter string input: ")
revstr = []
for i in inpstr:
if i.isupper():
i = i.lower()
revstr.append(i)
else:
i = i.upper()
revstr.append(i)
revstr = "".join(revstr)
print revstr
|
989ecf8899186ac3ac3a9692834142b1edcea3b9 | Szubie/Misc | /6.00.1x Files/Week 3/Recursion/Recursive function recurPower(base, exp).py | 743 | 4.28125 | 4 | # want to multiply base by itself exp times.Cannot use ** or loops.
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
#First, what is the base case? if exp = 0, then the answer is 1. (If exp = 1, the answer is base)
#Now need to think of a r... |
ffab14e253440e8e3d1c0979dcefa03fec336060 | alaktionov-hub/python_study | /OOP_5_at_class/vacancy.py | 2,243 | 3.953125 | 4 | #!/usr/bin/env python3
import datetime # date and time
import random # For random choose
import sqlite3 # db Stotred on data
#
# Db was need create and have Vacansy . And some programmers
#
# Get data from consloe
vacancy_title = input('Enter title of vacancy! ')
salary = int(input('Salary is '))
vacancy_main_ski... |
977ddc247a544dcf42ff63a6b98eccfc302b0d34 | zupph/CP3-Supachai-Khaokaew | /Lecture105_Supachai_K.py | 855 | 3.53125 | 4 | class Vehicle:
licenseCode = ""
serialCode = ""
def turnOnAirCondition(self):
print("turn on : Air")
class Car(Vehicle):
def turnOnAir(self):
print("Car ", end="")
car = Vehicle()
car.turnOnAirCondition()
class Van(Vehicle):
def vanTurnOnAir(self):
print("Va... |
76ac9791d7460faa638d0935033df2e73c56cf51 | TanakitInt/Python-Year1-Archive | /In Class/Week 7/[Decision] easterPrediction.py | 1,507 | 4 | 4 | """[Decision] easterPrediction"""
def main():
"""start"""
import calendar as cl
year_in = int(input())
#exception for invalid year
if year_in > 2099 or year_in < 1900:
print("Invalid input.")
else:
#stop for exception
a_num = year_in % 19
b_num = year_in % 4
c... |
732919f3c3cd2ab449e64e408bb60f90530b6e51 | Geek-Tekina/Coding | /Python/DSA/Sorting/BubbleSort.py | 593 | 4.125 | 4 | def bubble_sort(data):
swap=False
for i in range(len(data)-1): #For first element in an array
print("First data:", i)
for j in range(len(data)-1-i): # For second element in an array
print("Second data:", j)
if data[j] > data [j+1]:
data[j], data[j+1] = dat... |
dbd9e4e3aef6201a94419346fd482118cb01a01b | attiquetecnologia/python_librarys | /automato/modulo.py | 4,276 | 3.59375 | 4 | #-*- coding: utf-8 -*-
class Estado:
def __init__(self,name,id,final=False,initial=False,x=0.0,y=0.0):
try:
self.id = int(id)
self.name = str(name)
self.final = final
self.initial = initial
self.x = x
self.y = y
... |
beaa7a0ed07753483b0f09e429a557e873266aa9 | sapka12/adventofcode2017 | /day09/program.py | 996 | 3.578125 | 4 | garbage_start = "<"
garbage_end = ">"
group_start = "{"
group_end = "}"
ignore = "!"
def task1(text):
result = ""
in_garbage = False
need_ignore = False
group_level = 0
counter = 0
for i in range(len(text)):
actual_char = text[i]
if in_garbage and actual_char != garbage_e... |
007a60180c464d2879be299a6aa65252a71866f2 | TaroBubble/advent-of-code | /day6/puzzle1.py | 391 | 3.5 | 4 | textFile = open('day6\input.txt', 'r')
def solution(textFile):
res = 0
solutionSet = set()
for line in textFile:
line = line.strip()
if line:
for char in line:
solutionSet.add(char)
if not line:
res += len(solutionSet)
solutionSe... |
c3bd44dad9e617279b263edf5cf8d1e19b34c29b | Chaenini/Programing-Python- | /example.py | 359 | 3.734375 | 4 | def min_max(*args):
min_value = args[0]
max_value = args[0]
for a in args:
if min_value > a :
min_value = a
if max_value < a :
max_value = a
return min_value,max_value
min,max= min_max(52.-3,23,89,-21)
print... |
0d82a6a4f90b6464a02543093185e371fad3e22f | StoneRiverPRG/Python_Study | /配列.py | 645 | 4.34375 | 4 | # 配列 list の基礎
print("配列!")
# 配列の宣言(空の配列、宣言と同時に初期化)
list = []
list2 = [1, 1, 2, 3, 5]
# 要素の追加
print(list2)
list2 = list2 + [8, 13, 21]
print("要素追加後")
print(list2)
# 要素の追加(別の方法)
list2 = [10, 20, 30]
list2.append(40)
print(list2)
list2.insert(2, 21)
print(list2)
list2.insert(0, 0)
print(list2)
... |
3d9ac2a8d17859a2517bbf14a46d51b0da4b116b | TheRealJenius/TheForge | /TK.py | 5,009 | 4.28125 | 4 | # And so it begins
"""
Things to do:
- Define Functions required
- Enter input
- Display input as output
- Delete input
- Copy input
- Paste input
- Create a GUI
- TKinter seems to be the default a good place to start
- Create Menus
- File
- Edit
- About
- Time and date package
... |
65320b8bfb1f29f4c3c6d860193709317b83872d | tenten0113/python_practice | /8/super.py | 731 | 3.90625 | 4 | class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def show(self):
print(f'私の名前は{self.lastname}{self.firstname}です! ')
# Personを継承したBusinessPersonクラスを定義
class BusinessPerson(Person):
def work(self):
print(f'{self.lastna... |
52e37ca9e0a3f428fed1046a2fc4df3001d7b8af | jiin995/Ai | /plot | 142 | 3.59375 | 4 | #!/usr/bin/env python
import matplotlib.pyplot as plt
plt.plot([1,5,3,4],[0,2,4,6])
plt.ylabel('some numbers')
plt.show()
print 'hello'
ciao
|
719ddc3049716a8e761bfd4d433ea41d97c8f085 | AaronYang2333/CSCI_570 | /records/07-21/link.py | 1,064 | 3.71875 | 4 | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '7/22/2020 10:10 PM'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def initList(self, data):
# 创建头结点
self.head = ListNode(data[0])
p = self.head
# 逐个为 data 内的数据创建结点, 建立链表... |
f7e4932acafd4b432503fbe5c9e8ba913d44e316 | AbuSheikh/Python-Course | /Week 1/Practise1-C.py | 805 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def CToF():
celsius = float (input ("Enter the temperatures degree in celsius "))
fahrenheit = (celsius * 1.8) + 32
print(f"{celsius} degree Celsius is equal to {fahrenheit} degree Fahrenheit")
def FToC():
fahrenheit = float (input ("Enter the temper... |
c8b82b199e34fb8a1247f1b078637f2991aee66c | Arina-prog/Python_homeworks | /homework 7/task_7_7.py | 597 | 4.4375 | 4 | # Create several functions store them inside variables for handling collection of
# movie names using lambdas
# Создайте несколько функций,
# сохраните их внутри переменных для обработки коллекции имен фильмов с
# использованием лямбда-выражений
movies = ["Farsazh 1", "Farsazh 2", "Farsazh 3", "Farsazh 4"]
movies1 =... |
de3fa8c1a77c36cfb511948cfc4438f26ec683e5 | self-study-squad/Python-examples | /Data Structure/Exercise-10.py | 356 | 3.703125 | 4 | # Write a Python program to group a sequence of key-value pairs into a dictionary of lists.
# Expected output:
# [('v', [1, 3]), ('vi', [2, 4]), ('vii', [1])]
from collections import defaultdict
class_roll = [('v',1),('vi',2),('v', 3), ('vi', 4), ('vii', 1)]
d = defaultdict(list)
for k, v in class_roll:
d[k].app... |
10dc434bae574e490d7821aa5f6680fb540aa4f3 | gracesin/hearmecode | /demos/lesson1_demo_test_ssn_basic.py | 1,607 | 4.1875 | 4 | # -*- coding: utf-8 -*-
#Test to see if SSN is issued by SSA
#Criteria at http://policy.ssa.gov/poms.nsf/lnx/0110201035
import re
#enter SSN to test
#test_ssn = raw_input("enter an SSN to test\n")
test_ssn = "123-45-6789"
#Remove dashes from SSN and get rid of spaces at beginning and end
test_ssn = test_ssn.replace... |
32060aafa97c0649a3f6879935d31a7c4eb300b0 | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção10-Expressões_Lambdas_e_Funções_Integradas/zip.py | 1,338 | 4.625 | 5 | """
Zip -> Cria um iteravel (Zip Object) que agrega elemento de cada um dos iteráveis
passados como entrada em pares
lista1 = [1, 2, 3]
lista2 = [4, 5, 6]
zip1 = zip(lista1, lista2)
print(zip1)
print(type(zip))
# SEMPRE podemos gerar uma lista, tupla ou dicionario
print(list(zip1))
zip1 = zip(lista1, lista2)
print... |
f2ee24ba4eb6f05a04bae1af5456538da306e074 | uniqueimaginate/Coding | /Coding Test/bfs.py | 423 | 3.75 | 4 | graph = {
1: [2, 3, 4],
2: [5],
3: [5],
4: [],
5: [6, 7],
6: [],
7: [3]
}
def bfs(v):
discovered = [v]
queue = [v]
while queue:
curr = queue.pop(0)
for w in graph[curr]:
if w not in discovered:
queue.append(w)
dis... |
f2f8d54eea0c9af7cd4d3b67e4571d912a25bd5a | Gai-shijimi/investment-analysis | /analysis/CS/cs_analysis.py | 2,094 | 3.703125 | 4 | # キャッシュフローのパターンだけ
class CashFlow:
def __init__(self, cf_business_activities, cf_investing_activities, cf_financing_activities):
self.cf_business_activities = cf_business_activities # 営業活動によるキャッシュフロー
self.cf_investing_activities = cf_investing_activities # 投資活動によるキャッシュフロー
self.c... |
07e891f9412e999a2c1be25e17257b2a6a173b35 | SW-418/EulerProject | /src/Python/SumOfEvenFibonacci.py | 384 | 3.5625 | 4 |
first = 1
second = 2
lessThan4Mil = True
sumOfEvenValues = 2
while lessThan4Mil:
new = first + second
print(f'First: {first} - Second: {second} - New: {new}')
if new > 4000000:
lessThan4Mil = False
elif new % 2 == 0:
sumOfEvenValues += new
print(f'Value is even: {new}')
f... |
0a76f8dea5a00623d6f1ae14ad73378c509eaf14 | zpfarmer/assignments | /Assignments/afs-210/Week 3/heapqueue.py | 529 | 4.4375 | 4 | #google heapq for more information and a list of what all commands you can use with it
import heapq as hq
#original list
list = [25, 35, 22, 85, 14, 65, 75, 22, 58]
print("Original list:")
print(list)
#using heapq as hq
#nlargest command will return with however many items from the list the user wants
#nsmallest is th... |
51ce0092ea6ecfed449218507bcd27820b170657 | Kew4sK/CSC-132-Project | /button tester 3.py | 1,895 | 3.890625 | 4 | #####################################################
#Team 3: Pete Mace, Conan Howard, Justin Turnbull
# Date: 5/9/17
# Purpose: The system that the teams will come enter
# the code they get from the puzzle into
#####################################################
#imports libraries neccesary
import RPi.GPI... |
78c009cef3b5f9d3f92baf45de82b47eabee3a59 | bohanxyz/amath584 | /temp.py | 1,301 | 3.5 | 4 | # L-14 MCS 507 Fri 27 Sep 2013 : power_method.py
"""
The script is a very simple illustration using numpy
of the power method to compute an approximation for
the largest eigenvalue of a complex matrix.
"""
import numpy as np
def power_method(mat, start, maxit):
"""
Does maxit iterations of the power method
... |
f389ca6d73c4a65b594702baabd17caabb33e132 | bravicsakos/Adatkezeles | /RSA.py | 3,541 | 3.765625 | 4 | import random
def gcd(a, b):
"""
Euklideszi algoritmus
"""
while b != 0:
a, b = b, a % b
return a
def kibov_euklidesz(phi, a):
"""
Kibővített Euklideszi alg.
"""
base_a, base_phi = a, phi
x0, x1, y0, y1, s = 1, 0, 0, 1, 1
while a != 0:
#... |
93fdfd151b369d0486e8626068d808fbdf056c13 | udaykkumar/PEular | /Python/problem-24.py | 1,106 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 ... |
35b49e0888953d07d3e1d5ff85568a36de4a6e4e | jezhang2014/2code | /leetcode/ExcelSheetColumnTitle/solution.py | 266 | 3.703125 | 4 | # -*- coding:utf-8 -*-
ass Solution:
# @return a string
def convertToTitle(self, num):
l = []
while num > 0:
c = chr((num-1) % 26 + ord('A'))
l.append(c)
num = (num-1) // 26
return ''.join(l[::-1])
|
6c93c264e6de4d08d5efeef33d023fc59ea4199d | minibrary/Python_Study | /Input_Output/2.py | 225 | 3.546875 | 4 | in_str = input("아이디를 입력해주세요.\n")
real_josh = "11"
real_k8805 = "ab"
if real_josh == in_str:
print("Welcome, josh!")
elif real_k8805 == in_str:
print("Welcome, k8805!")
else:
print("Get Out!")
|
7a0439d9e464f4ab4ce0195f7ba26dac6c75146c | NanLieu/COM404 | /Practice Assessment/AE1 Review - TCA 2/5-Nesting/bot.py | 961 | 4.03125 | 4 | # Setting value of variable for 'health' at 100
health = 100
# Print statement stating amount of 'health' and the code is starting
print("You health is",health,"%. Escape is in progress")
# For loop which loops 5 time stated in the range
for count in range(0, 5, 1):
print("...Oh dear, who is that?")
# Awaits us... |
01bf0770314852f7fc807161d1af0bffc2e81a01 | RawToast/JapaneseStudy | /anki/plugins/morphman2/morph/matchingLib.py | 3,555 | 3.5 | 4 | class Edge():
def __init__( self, s, t, w=0 ):
self.s, self.t, self.w = s, t, w
def __repr__( self ): return '%s -> %s = %d' % ( self.s, self.t, self.w )
class Graph():
# Creation
def __init__( self ):
self.adj, self.flow = {}, {}
self.S, self.T = '#', '&' #XXX: must not be in V... |
ff5c76e0317588f017a5ca40d6443887369b3ff2 | ng3rdstmadgke/codekata_python | /20_1_tree/tree.py | 376 | 4.15625 | 4 | #!/usr/bin/env python
from turtle import Turtle
def tree(n, t):
if n == 1:
t.forward(10*n)
t.back(10*n)
return n
else:
t.forward(10*n)
t.left(15)
tree(n-1, t)
t.right(30)
tree(n-1, t)
t.left(15)
t.back(10*n)
return n
if ... |
2da61b6dfdb6dd034f922a41ae826e86c0af9b3f | shyam96s/python1 | /largest3f.py | 348 | 4.28125 | 4 | def largest(n1,n2,n3):
if(n1>n2 and n1>n3):
print(str (n1)+" is the largest")
elif(n2>n1 and n2>n3 ):
print(str (n2)+" is the largest")
else:
print(str (n3)+" is the largest")
x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
z=int(input("Enter 3rd nu... |
9e89d37de9e86db57cf153919849e14ce7462d22 | santoshdkolur/didactic-lamp | /antiMatrix.py | 2,123 | 3.984375 | 4 | #HARD
'''
Given a matix, sort the elements and rotatle the layers of the matrix in anti-clockwise manner by one unit.
Note: It works for all square matrices
Input:
n - size of the matrix
2*2 elements
Output:
Sorted matrix
AntiClock wise rotated matrix
Example:
Input:
Enter the size of the matrix: 4
En... |
129792ac36679095406331e5c88f2d061c355ddc | monmarko/higher-lower-game-followers | /main.py | 1,771 | 3.75 | 4 | import random
from art import logo
from art import vs
from game_data import data
def get_random_account():
return random.choice(data)
def format_data(account):
name = account["name"]
description = account["description"]
country = account["country"]
# print(f'{name}: {account["follower_count"]}')... |
2f04e6419dbdf36ec9075c2fbaa02b9e4ed85528 | mohitleo9/interviewPractice | /Stacks_And_Queues/Stack.py | 1,063 | 3.578125 | 4 | import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from Linked_Lists.LinkedLists import LinkedList, Node
class Stack:
def push(self, node):
if not node:
return
if not self.top:
self.top = node
return
... |
bb7b80df9015b8ffcb1de6f284cfc8de93df0bf4 | keerthana0110/PythonBasics-xplore- | /classexample.py | 193 | 3.6875 | 4 | class Dog:
def __init__(self,name,age):
self.name=name
self.age=age
def bark(self):
print("Bow bow")
pet=Dog("Jade",2)
pet.bark()
print(pet.name)
print(pet.age)
|
a6b13ea92f0435b3fbc474f76f2dac3b44b3a78e | BFRamZ/IT505-Final-Project | /Database.py | 1,118 | 3.609375 | 4 | import sqlite3
from sqlite3 import Error
class Database:
def __init__(self, datfile):
self.connection = self.create_connection(datfile)
pass
def create_connection(self, path):
connection = None
try:
connection = sqlite3.conne... |
85639044b697e997db8071116e03c7db4ab69edc | marcazgomes/exercicios | /e060.py | 196 | 3.984375 | 4 | num = int(input('Digite o valor que deseja fatorar:'))
result = 1
cont = 1
while cont <= num:
result *= cont
cont += 1
print(result)
#fiz simples e sem mostrar lado por lado, irei corrigir |
93b388785197f4d4bacf152afdfc821df10c31f6 | rubiyadav18/if-else_question | /malel_faemle_ques_.py | 313 | 4.125 | 4 | sex=input("enter a sex")
age=int(input("enter a age"))
if sex=="female":
print("she work only urban areas")
if sex=="male":
if age>=20 and age<=40:
print("he work anywhere")
if sex=="male":
if age>=40 and age<=60:
print("he work only urban areas")
else:
print("nothing") |
4f0fc693df4ba16b4d9f8d91d6a1e88fa736e000 | Polovnevya/python_algoritms | /Lesson_1/task_5.py | 918 | 4.0625 | 4 | """
Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.
https://drive.google.com/file/d/1Ui2yipbPwl4C9ZbY4KEk6VSmB2YBMh-k/view?usp=sharing
"""
char_1 = input('Введите первую букву из диапазона a-z ')
char_2 = input('Введите вторую букву из диапазона a-z '... |
060a6eb7ded769bd20da0509407fc62b2e152231 | gargisingh1993/tweety-fiesta | /mytweet.py | 3,517 | 3.890625 | 4 | # A Simple Function to
# Fetch relevant tweet for a single REST Api request provided a keyword as a param
# Imported relevant libs - json , requests, request_oauthlib
# imported json since twitter api returns the output as a json object ( when we hit the end point )
# important information which is needed for run... |
dbd584358ed7ba19067eaa069a95fd0195c9e9db | zazuPhil/prog-1-ovn | /Att välja.py | 442 | 3.78125 | 4 | svar = input('Hur tar du dig hem ')
if svar == 'gå':
print('Du få motion, sent')
elif svar == 'cykla':
print('Du få motion, I tid')
elif svar == 'buss':
print('få inte motion, kom tidigare')
buss = input('25 kr för bussbiljett? [ja/nej]')
if buss == 'ja':
print('förlorade 25 kr')
elif ... |
2d5324e38e033789d3256af5593b65c3b2de273a | ccxxgao/Tour-Scheduler | /scheduling.py | 4,948 | 3.640625 | 4 | import csv
import pandas as pd
import numpy as np
def getAvailabilities(string):
s = string.split(', ')
avail = [0,0,0,0,0]
for day in s:
if day == 'Monday': avail[0] = 1
elif day == 'Tuesday': avail[1] = 1
elif day == 'Wednesday': avail[2] = 1
elif day == 'Thursday': avail[... |
c38fb1f774833ebd470402882ce2d2153e1cfdcf | FahimFBA/Toph-Problem-Solution-by-FBA | /Fibonacci_Numbers.py | 234 | 3.84375 | 4 | n=int(input())
a=1
b=1
for i in range(0, n-2): #I gave two numbers to a & b already. So for managing them all properly, I have deducted them from the range of the loop
t=a+b #t is a temporary variable here
b=a
a=t
print(t) |
8a3b5322d2b29787a24408db3d6c84ad93aeca92 | AnkithAbhayan/math-functions | /maths/factors finder.py | 750 | 3.828125 | 4 | from math import *
import time
number = int(input("enter a number:"))
print("\n" * 1)
item_list = []
multiplication_list = []
factor_list = []
for i in range(number + 1):
if i == 0:
pass
else:
item_list.append(i)
length = len(item_list) + 1
for i in range(len(item_list)):
lengt... |
b59e3b256cc72c7b49cfa1072312ba3652982244 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/backtracking/combinatorial/generate_all_permutations.py | 912 | 3.84375 | 4 | def generate_all_permutations(lst, start, end, solutions):
if start >= end:
solutions.append(list(lst))
for i in range(start, end):
lst[start], lst[i] = lst[i], lst[start]
generate_all_permutations(lst, start + 1, end, solutions)
lst[start], lst[i] = lst[i], lst[start]
def gene... |
a49d529dc5b4978e0ab2c58c8868554d01227c34 | frankpiva/leetcode | /2020/12/26.py | 1,474 | 4 | 4 | """
Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input:... |
548e221b7b5383521b906325abb4e8544289503b | drenwickw/this | /testcoded/test2.py | 780 | 4 | 4 | '''
repeat = True
while repeat:
try:
my_input = input('Type an integer here -->')
print (int(my_input))
repeat = False
except ValueError:
print ("try again")
'''
from random import randint
def coin_flip(number):
heads = 0
tails = 0
for trial in range(0, number):
... |
acdb0ee0f25254591fac1875be103230231f2acd | starxfighter/Python | /pythonoop/animalOOP.py | 1,594 | 4.34375 | 4 | # Set definition of the parent animal class
class Animal():
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
... |
7aa8ae4c55c18c601d03725199f618eb7bb581df | lucasjct/python_curso_em_video | /Mundo_2/while/ex71.py | 544 | 3.625 | 4 | cinquenta = vinte = dez = um = 0
v1 = (int(input('Qual valor você quer sacar? ')))
while True:
while v1 >= 50:
v1 = v1 - 50
cinquenta +=1
while v1 >= 20:
v1 = v1 - 20
vinte += 1
while v1 >= 10:
v1 = v1 - 10
dez += 1
while v1 >= 1:
v1 = v1 - 1
... |
631dbfd0c22f964468cf194bf17d78c13cfa25e4 | amol10/practice | /sort/quick_sort.py | 846 | 3.53125 | 4 | from copy import copy
unsorted = list(map(int, input().split()))
bsorted = copy(unsorted)
def qsort(arr, start, end):
if start >= end:
return
pivot_idx = partition(arr, start, end)
qsort(arr, start, pivot_idx - 1)
qsort(arr, pivot_idx + 1, end)
def partition(arr, start, end):
pivot_idx = start + int((end... |
8723d93dd70ddf9685a7354aaa346de17647c87d | ggarcz1/LeetCode | /58. Length of Last Word.py | 152 | 3.578125 | 4 | def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
val = s.split(' ')
return len(val[len(val)-1]) |
ed78dc82cc23f8dd15b2cc2bb127d421437df5f1 | claytonjr/ProgrammingCollectiveIntelligenceExercises | /Chapter9/Exercise4.py | 2,080 | 4 | 4 | """ Chapter 9 Exercise 4: Hierarchy of interests.
"Design a simple hierarchy of interests, along with a data structure to represent it.
Alter the matchcount function to use the hierarchy to give partial points for matches."
I implemented a scoring system based upon the activeness levels of the interests.
... |
c85be6ac2c97db0b2ebc9aa6334095e9cbcd6793 | wanghan79/2020_Python | /朱旻鸿2018012708/平时作业2 修饰器随机数生成筛选/朱旻鸿 第二次作业封装为修饰函数方法.py | 2,930 | 3.578125 | 4 | ##!/usr/bin/python3
"""
Author: MinHong.Zhu
Purpose: Generate random data set by decorator.
Created: 17/5/2020
"""
import random
import string
def DataSampling(func):
def wrapper(datatype, datarange, num, *conditions,strlen=15):
'''
:param datatype: basic data type including int float string... |
855bf53b19ad5584f647b7cbbe402f5f5d39cf11 | Pritam-Rakshit/Connection-monitoring-tool | /portscanfp.py | 4,572 | 3.828125 | 4 | #!/usr/bin/env python
#!/usr/bin/env python
#import argparse
import socket
import sys
import os
def scan_ports():
""" Scan remote hosts """
#Create socket
try:
os.system('dialog --menu "Port Scanner" 20 40 2 "1" "FQDN based scanning" "2" "IP based scanning" 2> choice')
option = open(... |
77d330d7e2f51df5120887cb17f65899797b55f4 | legendbabs/Automate-The-Boring-stuff | /Chapter07/project/phone_number_email_extrctor.py | 1,831 | 4.28125 | 4 | '''
Say you have the boring task of finding every phone number and email
address in a long web page or document. If you manually scroll through
the page, you might end up searching for a long time. But if you had a program
that could search the text in your clipboard for phone numbers and
email addresses, you could sim... |
7d2c9b9f1331b9b3bc78191391da077fae28812e | iamshafran/Learning_Python | /Learn/No Scratch Python/10-5-programming_poll.py | 263 | 3.703125 | 4 | filename = "Learn/No Scratch Python/programming_poll.txt"
answer = " "
while answer:
answer = input("Why do you like programming? ")
if answer == "0":
break
with open(filename, "a") as file_object:
file_object.write(f"{answer}\n")
|
aaa7f5ddc3f2259d4289b613c1183e37a2113648 | mandjo2010/geog786course | /Assignments/Assignment-1/Assignment1.py | 999 | 3.96875 | 4 | #Python Assinment 1 by Shahid Nawaz Khan
import math as libmath
R=6371
#Location of salt lake City
lat1= 40.7607793
lng1= -111.8910474
#location of newyork
lat2= 40.7127837
lng2= -74.0059413
#changing latlng from degrees to radians
#first set of coordinates changing from degrees to radians
lat1= libmath.radians(lat... |
3918af515cbdd72515be0484a63df3f38a547d2e | LJLee37/HackerRankPractice | /Algorithms/Sorting/ClosestNumbers.py | 988 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the closestNumbers function below.
def closestNumbers(arr):
arr.sort()
smallList = []
smallest = -1
for i in range(len(arr) - 1):
if smallest == -1:
smallest = arr[i + 1] - arr[i]
smallLi... |
833c3d72596ac7fac21949b3070ccfcb6290dcce | bettingf/imagesofsatellite | /Exercise.py | 6,867 | 3.546875 | 4 |
# coding: utf-8
# In[245]:
import numpy as np
import pandas as pd
import sklearn
def generateDataset(size, ndim=4):
bias=1
x = np.linspace(-2*np.pi, +2*np.pi, size)
timeSeries=4*np.sin(x)+bias
features=np.zeros((size, ndim))
labels=np.zeros((size, 1))
for i in range(size):
... |
18e43f61237162612f387f7a4e26e1e5e84634d8 | MaX-Lo/ProjectEuler | /104_pandigital_fibonacci_ends.py | 907 | 3.5 | 4 | """
idea:
"""
import time
import math
def main():
# n = 10000 t: 2.325
# n = 10000 t: 1.189
# n = 10000 t: 0.131
# n = 10000 t: 0.1
f1 = 1
f2 = 2
count = 3
t0 = time.time()
while True:
if count % 5000 == 0:
print('n =', count, 't:', round(time.time() - t0, 3)... |
ee1f07189fc8cce67e4150d2d4c38c160654cc72 | AlirezaMojtabavi/Python_Practice | /Elementary/3- string - list - dictionary - tuple/Ex_11_counting_the_votes.py | 290 | 3.578125 | 4 | from collections import OrderedDict
number = int(input())
dictOfVotes = OrderedDict()
i=0
while i < number :
votes = str(input())
dictOfVotes[votes] = dictOfVotes.get(votes,0) + 1
i+=1
for thisOne in sorted(dictOfVotes.keys()):
print(thisOne," ",dictOfVotes[thisOne]) |
d78feaf63fb56d0494aa8124d4d7ea712c27d685 | lbranera/CMSC-110 | /Loop 1 to 10/one-to-ten.py | 158 | 3.890625 | 4 | # WHILE LOOP style
i = 1
while (i<=10):
print(i, end=" ")
i = i + 1 # or i+=1
'''
FOR LOOP style
for i in range(1, 11):
print(i, end=" ")
''' |
695ad348a32f48ee544513df078de86b16bddcdc | ianhom/Python-Noob | /Note_3/Example_24_2.py | 378 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
'''
a = 2.0;
b = 1.0;
s = 0.0;
for n in range(1,21):
s += a / b;
b,a = a , a + b;
print s;
s = 0.0;
for n in range(1,21):
s += a / b;
b,a = a , a + b;
print s;
# result
'''
32.6602607986
32.360679776
... |
cb2c7a2d111fc1b9f76d1fe4cacff9262adec4b2 | aadithya/exercise | /g_anagrams.py | 322 | 4 | 4 | def group_anagrams(words):
anagrams = {}
for word in words:
key = ''.join(sorted(word))
anagrams[key] = anagrams.get(key,[]) + [word]
return anagrams
if __name__ == "__main__":
words = [word.strip() for word in raw_input("Enter all the words:").split(',')]
print group_anagrams(words... |
e25ba797e0d239bb741168d7f53a0f3eed874c82 | OpLaa/Document-Search-using-Inverted-Index- | /otherTestFiles/invertedindex.py | 1,257 | 3.734375 | 4 | arra1=["aaa","bbb","ccc","ddd","aaa","bbb","ccc","bbb","bbb","bbb","ccc"]
b = []
unique = []
k=0
for i in range(0,len(arra1)):
presense=False
for check in range(0,len(unique)):
presense=False
if(arra1[i]==unique[check]):
presense=True
break
if(presense==True):bre... |
2ce5ad45a94dc921faf42633b64fc56ea0fde70d | ACTCollaboration/enlib | /autoclean.py | 1,251 | 3.765625 | 4 | """This module defines a class decorator that makes sure that the __exit__
function gets called when the program exits, if it hasn't been called before.
Its purpose is to allow interactive use of resource-using classes. In those
situations, the standard "with" approach does not work."""
import atexit
_toclean_ = set()... |
93d65752521f574d580acbf853194fce0bd0706c | yoda-yoda/my-project-euler-solutions | /solutions/347.py | 2,111 | 3.65625 | 4 | #!/usr/bin/python
"""
Author: Denis Karanja,
Institution: The University of Nairobi, Kenya,
Department: School of Computing and Informatics,
Email: dee.caranja@gmail.com,
Euler project solution = 347(Largest integer divisible by two primes)
Status.. PENDING...
"""
from time import time
def is_prime(num):
"""Check if a... |
ba8522f06deeb3fe9a7a551d21a2d1722b490474 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex36 - Game Designing and Debugging.py | 9,853 | 3.625 | 4 | import random
import time
def enter_command():
enter_command = str(input(":> "))
return enter_command
def start(usrName, location, usrGendr):
print('\n############################')
print('# Rise of the Dragon Rider #')
print('############################\n')
print(' - Play - ... |
8a60d618f47ce9917bf2c8021b2863585af07672 | sreesindhu-sabbineni/python-hackerrank | /TextWrap.py | 511 | 4.21875 | 4 | #You are given a string s and width w.
#Your task is to wrap the string into a paragraph of width w.
import textwrap
def wrap(string, max_width):
splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)]
returnstring = ""
for st in splittedstring:
returnstring += s... |
485c98650c27b73af00318dbe6ad5d8c51670739 | gsteinb/ace | /final/user_assignments.py | 8,177 | 3.71875 | 4 | import tkinter as tk
from tkinter import ttk, font, Tk, Label, Button, Entry,\
StringVar, DISABLED, NORMAL, END, W, E
from tkinter.messagebox import showinfo
import database_api as db
import sqlite3
from user import *
from main import *
from random import sample
conn = sqlite3.connect('a... |
1c8c6b421234239d6e254cd918c35d6795ad5676 | defibull/leetcode | /matrix_median.py | 739 | 3.546875 | 4 | def count_small_or_eq(B,x):
low = 0
high = len(B)-1
curr = -1
while low <= high:
mid = (low+high)/2
if B[mid] <= x:
curr = mid
low = mid+1
else:
high = mid-1
return curr +1
def findMedian( A):
... |
e861d7f8aeb8c4c030e2da315df9d23da91b143b | SMerchant1678/frc-hw-submissions | /lesson5/lesson5number2.py | 261 | 3.8125 | 4 | name = raw_input("What is your name? ")
color = raw_input("What is your favorite color? ")
pet = raw_input("How many pets do you have? ")
array = [name, color, pet]
print array[0] + "'s favorite color is " + array[1] + ". They have " + array[2] + " pets."
|
7b47e55fc2aeb225e041a347b88ee73f612a722c | chrisjackson4256/nlpIMDB | /review_to_words.py | 598 | 3.578125 | 4 | from bs4 import BeautifulSoup
import re
def review_to_words( raw_review ):
''' function to convert raw IMDB review
to list of words'''
# remove markup and tags
bs_review = BeautifulSoup( raw_review )
# remove numbers and punctuation
letters_only = re.sub(r'[^a-zA-Z]', ' ', bs_review.get_text())
# convert to l... |
ce4be701d31baffd748aaa7c1cc79486b2399dce | GoncaloPascoal/feup-fpro | /Recitations/RE10/flatten.py | 312 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def flatten(alist):
"""
Given a nested list, returns a single list with each of the non-list elements.
"""
l = []
for i in range(len(alist)):
if type(alist[i]) is list:
l += flatten(alist[i])
else:
l += [alist[i]]
return l
|
51338b2b6b0b070f8ca7da04374386bb86f3439c | murphy-codes/challenges | /Python_edabit_VeryHard_Unique-Character-Mapping.py | 644 | 4.15625 | 4 | '''
Author: Tom Murphy
Last Modified: 2019-10-23 15:54
'''
# https://edabit.com/challenge/yPsS82tug9a8CoLaP
# Unique Character Mapping
# Write a function that returns a character mapping from a word.
def character_mapping(phrase):
char_map = []
mapping = dict()
i = 0
for l in phrase:
if ... |
77bb8d91891c66914a97c6f21721b3e195edf36f | mrparkonline/py_basics | /solutions/basics1/squareTiles.py | 417 | 4.4375 | 4 | # Write a program that inputs the number of tiles and then prints out the maximum side length. You may assume that the number of tiles is less than ten thousand.
from math import sqrt as squareRoot
# input
tiles = int(input('Enter the number of tiles: '))
# processing
max_side_length = squareRoot(tiles)
max_side_len... |
13e834539990883adf53817e52291264f51abdd5 | ddaypunk/tw-backup | /Python/CodeAcademy/Python Class/notes_Mar3_2013.py | 1,094 | 4.46875 | 4 | """
CODE ACADEMY NOTES - MAR 3
"""
""" Lists """
#the following will add a value to the end of a list
list_name.append(value)
#the follwing will add a list to the end of a list
list_name.extend(value)
#alternately using append
for each in list_name2:
list_name1.append(each)
#the following will search for a value ... |
65d8fc5db3e8b6dd52d8874633f0eb168e44f638 | Arslan186/GeekBrains-Python | /lesson4_3.py | 201 | 3.796875 | 4 | my_list_1 = [2, 2, 5, 12, 8, 2, 12]
my_list = []
for a in my_list_1:
if my_list_1.count(a) == 1:
my_list.append(a)
print("Уникальные числа списка: ", my_list)
|
7c73420a99e9c29278a9111de1a841db46b3c5c7 | umunusb1/PythonMaterial | /python2/13_OOP/07_Class_Variables.py | 1,070 | 4.09375 | 4 |
class Employee:
"common base class for employee"
empcount = 0 # class variable
def __init__(self, name, salary):
self.name = name # instance variable
self.salary = salary
Employee.empcount += 1
def displaycount(self):
print "total employee%s" % Employee.empcount
... |
da245462977164dfad5eb86059c10f83222580ed | leigon-za/Learning_Python | /10_15_failing_silently.py | 626 | 4.25 | 4 | def count_words(filenames):
"""Count the approximate number of words in a file"""
try:
with open(filename, encoding = 'utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass
else:
words = contents.split()
num_words = len(words)
print(f"The fi... |
621e6a47378c02fac8b89a7244a095bb2f3e629e | christianns/Curso-Python | /03_Control_de_flujo/14_Ejercicio_9.py | 1,248 | 3.828125 | 4 | # Problema 09: Un restaurante ofrece un descuento del 10% para consumos de hasta $ 100.00
# y un descuento de 20% para consumos mayores, para ambos caso se aplica un impuesto de 19%.
# Determinar el monto del descuento, el impuesto y el importe a pagar.
# Análisis: Para la solución de este problema, se requiere que
# ... |
c08f13449767a15c8e3bc2704f649ec1094fc4d0 | ALENJOSE5544/Python-lab | /pythoncycle1/P04.py | 154 | 4.125 | 4 | #Program to find sum of two integers
a=int(input("Enter the frist number:"))
b=int(input("Enter the second number:"))
s=a+b
print("The sum is:")
print(s)
|
75196503764d71f7a6e5ff73df06a20e421de35e | imjoseangel/100-days-of-code | /python/howsum/howsum.py | 1,104 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
def howSum(targetSum: int, numbers: list, memo: dict = None) -> list:
if memo is None:
memo = {}
if targetSum in memo:
return memo[targe... |
963c154eb4b383271452048826d1d4e1788fde54 | frclasso/turma1_Python_Modulo2_2019 | /Cap05_Tkinter/18_PainedWondw.py | 312 | 3.8125 | 4 |
from tkinter import *
root = Tk()
root.title("PainedWindow")
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
left = Entry(m1, bd=2)
m1.add(left)
m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)
top = Scale(m2, orient=HORIZONTAL)
m2.add(top)
button = Button(m2, text="ok")
m2.add(button)
root.mainloop()
|
16bb0a81bcda4d1c63d5c6483c54c0383a43a7d6 | ClearlightY/Python_learn | /top/clearlight/base/liaoxuefeng/functional_programming/higher_function/Map_Reduce_HigherOrder_Function.py | 3,474 | 3.96875 | 4 | from functools import reduce
# 高阶函数: map/reduce
# 变量可以指向函数
print(abs(-10))
print(abs)
x = abs(-10)
print(x)
# 变量指向函数
x = abs
print(x)
# 变量指向abs函数本身. 直接调用abs()函数和调用变量x()完全相似
print(x(-19))
# 函数参数传入函数
def add(x, y, f):
return f(x) + f(y)
# 一个函数能够把其它函数作为参数使用,这个函数就是高阶函数。
print(add(-5, 6, abs))
# map/reduce
#... |
02036b74755314bfa61c61221a4a9e968d0145cb | realy-qiang/project | /finally/swiper/qdz/Swiper/libs/test.py | 1,002 | 3.65625 | 4 | # class myIteration(object):
# def __iter__(self):
# self.x = 0
# return self
# def __init__(self, n):
# self.n = n
# def __next__(self):
# if self.x < self.n:
# self.x += 1
# return self.x
# else:
# raise StopIteration
# my_iteration = myIteration(5)
# for i in my_iteration:
# print(i)
impor... |
d1c1dcb8a83b08f94dce18df6c6e18cf35a9dea4 | maxpt95/6.00.1xPython | /Midterm/keyWithValues.py | 427 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 27 10:47:39 2021
@author: maxpe
"""
def keysWithValue(aDict, target):
'''
aDict: a dictionary
target: an integer
'''
targetKeys = []
for key, value in aDict.items():
if value == target:
targetKeys.append(key)
... |
083809c950da1736f06c72977afd37a7a929a6f9 | haochen208/Python | /pyyyy/12 break、continue/02continue.py | 245 | 3.984375 | 4 | # continue:控制程序结束本次循环,直接进入下一轮循环!
# i = 1
# while i < 8:
# i += 1
# if i == 5:
# continue
# print(i)
for i in range(5):
if i == 3:
continue
print(i)
|
e957732614a518d8d608b4157d9d80f7d8102dd0 | dOtOlb/mmls | /lib/ItemRecord.py | 1,151 | 3.5 | 4 | import sys
import datetime
import operator
class ItemRecord:
"""A data structure holding all the information about an item"""
def __init__(self, type, id, score, data):
self.type = type
self.id = id
self.score = score
self.boosted_score = score
self.data = data
s... |
653cc9d592c85bc0aac44018b28d194fdc04ce76 | dhany007/ark | /4.py | 540 | 4.125 | 4 | def thirdHighest(arrNumber):
lst = []
if(type(arrNumber)==list):
if(len(arrNumber)<3):
print("Minimal array length is 3!")
else:
for i in arrNumber:
if type(i)== int:
lst.append(i)
lst.sort(reverse=True)
... |
cd851c231fa5659416432bea5a7f57f0b0b50eb3 | NineOnez/Python_Language | /28_String.py | 729 | 4.09375 | 4 | '''
text = "Hello"
print(text[0]+"Hello")
print(text[1]*3)
print(text[0:4])
print("********************************")
address = "18/215 Donmeuang Bangkok"
print("Bangkok" in address)
print("BKK" not in address)
print("********************************")
name = "FirstOnez"
birthPlace = "Chaing Mai"
print("Hello" + name... |
34b58383fa28ad045e39f78890f8d8c7eeb2883f | chuzhinoves/DevOps_python_HW4 | /2.py | 816 | 3.921875 | 4 | """
2. Представлен список чисел. Необходимо вывести элементы исходного списка,
значения которых больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка.
Для формирования списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
... |
6f94ae61da9dbc5b01d1641193586c5cdb68fa9f | sandeepbaldawa/Programming-Concepts-Python | /recursion/power.py | 305 | 3.796875 | 4 | def power(base, exp):
if exp == 0:
return 1
half = power(base, exp/2)
if exp & 1: # odd number or not exp % 2
return base * half * half
else:
return half * half
print power(5,3)
print power(5,0)
print power(5,2)
print power(2,2)
|
c3a879af8b4301e67363f705175764b9ef5c169d | PacktPublishing/Mastering-Object-Oriented-Python-Second-Edition | /Chapter_7/ch07_ex4.py | 1,031 | 3.859375 | 4 | #!/usr/bin/env python3.7
"""
Mastering Object-Oriented Python 2e
Code Examples for Mastering Object-Oriented Python 2nd Edition
Chapter 7. Example 4.
"""
# Comparisons
# ======================================
# Using a list vs. a set
import timeit
def performance() -> None:
list_time = timeit.timeit("l.remove... |
ffd25919a225ecaaeb5ba85e8f24e50ced54ae44 | jeffanberg/Coding_Problems | /leetcode_problems/problem11.py | 480 | 3.875 | 4 | '''
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You m... |
ae5c05558de8bfd1cff176448a0e298a14310e49 | Eduarda8/ExercicioProva2bim | /questao24.py | 280 | 4.25 | 4 | '''
Questão 24 :
Faça um programa que calcule o mostre a média aritmética de N notas.
Resposta :
'''
quantidade = int(input("Digite a quantidade de notas"))
soma = 0
for i in range(quantidade):
soma += int(input("Digite uma nota:"))
print("A media e: ", soma/quantidade)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.