blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b7ab7f89f3d93f5244a1f5c8d1f6eb2d1e2d591a | joyceyu6/coding_courses | /2021_4_19_to372/2Pointers_3.LongestSubstring.py | 1,608 | 4.09375 | 4 | '''
3. Longest Substring Without Repeating Characters (Medium)
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer ... |
aed3371004de2059583bf305c2c5ff3abbbf9477 | joyceyu6/coding_courses | /2021_4_19_to372/Dictionary_Lambda_347.top-k-frequent-elements.py | 1,312 | 3.875 | 4 | '''
Given an integer array nums and an integer k, return the k most frequent
elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.legth <= 105
k is in the range [1, the number of un... |
24145f0ac09b51b3d83359b65b8ce261be1a2d4c | joyceyu6/coding_courses | /2021_4_19_to372/Recursive_79.word-search.py | 1,543 | 3.765625 | 4 | #
# @lc app=leetcode id=79 lang=python3
#
# [79] Word Search
#
# @lc code=start
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are horizontally or vertically neighboring. The same letter cell may not... |
bcd5ae970ca6a737827231628c55a2d266e8a78c | vcrini/adnd-generator | /dice.py | 1,421 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import random
def rnd(n=1, n_faces=6, plus=0):
"""
>>> rnd(1,1)
1
>>> rnd(1,1,1)
2
"""
s = random.randint(1, n_faces) + plus
if n > 1:
for _ in range(n - 1):
s += random.randint(1, n_faces)
return s
def rnd2(
tot=... |
98aa28e305f4209a625b9aca8187a4a84afd8472 | dmitryshurov/simple_data_storage_library | /src/ds_simple_db/core/serializer.py | 1,023 | 3.53125 | 4 | from typing import List
from ds_simple_db.core.entry import Entry
class Serializer:
"""
The base class for all serializers.
To implement a new serializer you need to implement the following methods:
* entries_to_string (serialize a list of entries to a string)
* entries_from_string (dese... |
f66c566486099112b31c7f8883d7a173d9765481 | vidyakov/geek | /lesson7/task_1.py | 1,438 | 4.09375 | 4 | # 1 Отсортируйте по убыванию методом пузырька одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100).
# Выведите на экран исходный и отсортированный массивы.
# Примечания:
# ● алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
# ● постарайтесь... |
b7f7a1ec2ec63e46c1162b3e5e6967048f222569 | vidyakov/geek | /2lesson/2_task.py | 572 | 4.28125 | 4 | # Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
a = input('Введите натуральное число: ')
even = 0
odd = 0
for i in a:
if int(i) % 2 == 0 or i == '0':
even += 1
else:
odd += 1
print(f... |
6f695cb3ed658fc801e00eff6a0bd5bf0b63f177 | parth461/calculatorr | /Calculator.py | 2,260 | 3.96875 | 4 | def Calculator(a):
if a==1:
try:
x=int(input("Enter number 1:"))
y=int(input("Enter number 2:"))
print(x,"+",y,"=",x+y)
a=int(input("Calculator \n Enter 1.ADDITION 2.SUBTRACTION 3.MULTIPLICATION 4.DIVISION:"))
Calculator(a)
except E... |
19aa4d68f3cb6fce81b0871a7742b6275d843113 | atlas-comstock/Barrage-game | /Angle.py | 610 | 3.59375 | 4 | import math
def angles(pos1,pos2):
y_se= pos1[1]-pos2[1]
x_se= pos1[0]-pos2[0]
if x_se==0 and y_se>0:
angle = 360
if x_se==0 and y_se<0:
angle = 180
if y_se==0 and x_se>0:
angle = 90
if y_se==0 and x_se<0:
angle = 270
if x_se>0 and y_se>0:
angle = math.... |
dcf302f6c0ebbc8c000b9a5fa1e894dd0c917351 | GiulioRossetti/cdlib | /cdlib/evaluation/internal/TOPSIS.py | 3,041 | 3.640625 | 4 | import numpy as np
# Step 1: normalize the decision matrix
def norm(x, y):
"""normalization function; x is the array with the
performances and y is the normalization method.
For vector input 'v' and for linear 'l'
"""
if y == "v":
k = np.array(np.cumsum(x**2, 0))
z = np.array(
... |
6cb6ad802b278fb1de5383e865daca7aba05f8ee | openredact/nerwhal | /nerwhal/combination_strategies.py | 3,460 | 3.859375 | 4 | def combine(ents, strategy=None):
"""Process a list of entities using different strategies to deal with overlapping or conflicting entities.
This function offers the following strategies:
- None: Keep all entities.
- `disjunctive_union`: This function keeps and returns all entities, but assumes their c... |
b87740d7acc356195f37931f8b5881da55d7e4b1 | nagora/module | /escape_split.py | 1,298 | 3.5625 | 4 | # Sample code -1 to split the string and escape the split delimiter position
import re
def split_1():
data = "ab,cj\,shdhdkdm,dhj,dsdgj\,asdhask,kil," # need to add "delim" at the last to get the last string as well
pattern = re.compile(r"[^\\],")
split_data =[]
matches = pattern.finditer(data)
... |
bebec6b37a1fe94673d27454f0c90dc6913f6894 | novking/Deep-Learning-Project | /regex_testing.py | 114 | 3.640625 | 4 | import re
l = "this is cool, 123hr or 5% or 0"
obj = re.search(r'([0-9].+)', l)
for i in obj:
print (i) |
2e501e61652dddbca93adea4b4a8cd8d8714c18a | janick187/distance-caluclator | /place_finder.py | 1,554 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import requests
class Route:
def __init__(self, origin, destination, distance):
self.origin = origin
self.destination = destination
self.distance = distance
def __str__(self):
return '\n\nThe distance between {} and {} is {}'.format(self.ori... |
fd28c83a4d158875fbd4b641d3fb215736a6c011 | stgilhool/PythonThingy | /tests/test_Square.py | 364 | 3.78125 | 4 | """Test for square class"""
from Square import Square
def test_Square_init_empty():
sq = Square()
assert sq.getSide() == 0
def test_Square_init_params():
sq = Square(2)
assert sq.getSide() == 2
def test_Square_Area():
sq = Square(3)
assert sq.getArea()==9
def test_Square_Perimeter():
sq ... |
e19631370707c327318bd8a11021bcf81f19a2e3 | debramaelee/python-exercises | /Week 1-2 Exercises/banner.py | 174 | 3.71875 | 4 | user_input = raw_input("What do you want your string to be? ")
numstars = len(user_input)
numstars += 4
print "*" * numstars
print "*", user_input, "*"
print "*" * numstars
|
f06e4c603e1259c0a2de44014ad627972002d14a | debramaelee/python-exercises | /Week 1-2 Exercises/tip_calc.py | 1,044 | 3.765625 | 4 | bill_amount = float(raw_input("Total bill amount? "))
service_lvl = raw_input("Level of service? ")
# ----------FIRST ATTEMPT did not show extra 0 after dec.
# if service_lvl == "bad":
# tip_percent = '{:,.2f}'.format(.15 * bill_amount)
# elif service_lvl == "fair":
# tip_percent = '{:,.2f}'.format(.18 * bill_... |
d5c800f682ff9ab015ef87ad7a88bba90975777e | debramaelee/python-exercises | /Week 1-2 Exercises/factors.py | 732 | 3.890625 | 4 | #student solution example
#
# user_num = int(raw_input("Enter a number "))
# last = user_num
# divisor = 1
#
# left = []
# right = []
#
# while (last > divisor):
# if(user_num % divisor == 0):
# last = user_num / divisor
# if (last == divisor):
# left.append(divisor)
# else:
# ... |
1264c49acd5aa8facf6e8a5fffd9460b64446b56 | debramaelee/python-exercises | /Week 1-2 Exercises/altsolutionguess.py | 354 | 3.78125 | 4 | import random
def play_again():
play_again = raw_input("Do you want to play again? (y or n) ")
if play_again == "y":
guess_num()
else:
print "Bye"
def guess_numb():
count = 5
secret_num = random.randInt(1, 10)
print "I am thinking of a num between 1 - 10. You have %d guesses le... |
84375fb76c6e6b90af692e6c31e1f08c4abb5a9e | debramaelee/python-exercises | /Week 1-2 Exercises/guess_the_number2.py | 358 | 3.953125 | 4 | secret_number = 5
print "I am thinking of a number between 1 and 10"
switch = int(raw_input("What's the number? "))
while switch != 5:
if switch < 5:
switch = int(raw_input("%d is too low. What's the number? " % switch))
elif switch > 5:
switch = int(raw_input("%d is too high. What's the numbe... |
77637b2eaef358ad308de773a915caddab871f12 | begogineni/cs-guided-project-python-basics | /src/demonstration_03.py | 566 | 4.40625 | 4 | """
Challenge #3:
Create a function that takes a string and returns it as an integer.
Examples:
- string_int("6") ➞ 6
- string_int("1000") ➞ 1000
- string_int("12") ➞ 12
"""
import re
def string_int(txt):
'''
input: str
output: int
'''
# Your code here
#what to do if there is a letter in the... |
2bea7f84ca43f1bfde89b3590f7212edf469a5d9 | tarushsinha/WireframePrograms | /3fizz5buzz.py | 452 | 4.125 | 4 | ## program that returns multiples of 3 as fizz, multiples of 5 as buzz, and multiples of both as fizzbuzz within a range
def fizzBuzz(rng):
retList = []
for i in range(rng):
if i % 3 == 0 and i % 5 == 0:
retList.append("fizzbuzz")
elif i%3 == 0:
retList.append("fizz")
... |
ea92e6de805e1bf87229b1ffc7546a566921b923 | tarushsinha/WireframePrograms | /reverseNumber.py | 378 | 3.765625 | 4 | def reverseNumber(inp):
ret = list(str(inp))
ret.reverse()
v = ""
for i in ret:
v = v + i
return int(v)
## same as above method, works without relying on List.reverse()
def independentReverse(inp):
ret = list(str(inp))
v = ""
for i in ret[::-1]:
v = v + i
return int(... |
e7b20100d04460486b6df622ca4ed965a2c272fc | snehalkulabkar/Python-assignment | /Day 3/Day 3 assignment.py | 493 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[26]:
print ("Question1: sum of n no with while loop")
# In[27]:
print ("question2: take a integer and find prime or not")
# In[30]:
n = int(input("Enter n number you want for sum:"))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print("the sum of n no is",sum1)
... |
6c1cd2f06c6816856885b85c93a26aed029d7986 | namgudi007/Assignments | /assignments/NumPattern.py | 916 | 3.96875 | 4 | n = int(input("Enter n: "))
# for i in range(1, n+1):
# for j in range(1, i+1):
# print(j, end="")
# print("\n")
# next
# for i in range(1, n+1):
# for j in range(1, i+1):
# for k in range(1, i+1):
# print(k, end=" ")
# print("\n")
# next
# for i in range(1, n+1)... |
4f39f467f83616c061f8e6488d541ce4e1596e2a | BrunoICardoso/GEO4ALL | /RN/ETLDataPoints.py | 6,179 | 3.671875 | 4 | import codecs
from decimal import *
# Essa Classes Guarda toda a regra de extração dos arquivos "data_points_"
# Conforme o algoritmo tem a função de guardar os valores como objeto como Latitude,Longitude,Distance,Bearing
# Tambem se percebe que faltava valores como por exemplo Latidade onde o algorismo faz dele um v... |
7e9db73ee9a5c09dbea03ec3b12eb9f340349586 | RyanDefost/PythonAchievements | /ShuffleAndReturn.py | 617 | 3.765625 | 4 | import random
import os
def shuffle(original):
return(''.join(random.sample(original, len(original))))
os.system("cls")
print("---------------------------------------------------")
WOORD = input("welk woor wil je shuffle?: ")
antwoord = shuffle(WOORD)
os.system("cls")
print(antwoord)
print("-------------------... |
1af5f0a2b93c395fb646320cbfcc6e30ff91fc0d | pomgolian/servo_calibrate | /servo_calibrate.py | 1,300 | 3.578125 | 4 | import pi_servo_hat
global servo_number
global direction
servo_number = 0
direction = 1
servo_value = 100
servo = pi_servo_hat.PiServoHat()
# Restart Servo Hat (in case Hat is frozen/locked)
servo.restart()
print('Enter 1, 2 or 3 for sun, mask or moon')
print('Enter f for forward or r for reverse for servo direct'... |
a6320192b7dadf54923e1ae8ca6ff7fe9a1ef963 | Harikrishna30/files | /tasksmod1.py | 2,132 | 4 | 4 | # variables and datatypes
# first method
# L=["digital","lync","hyd","gachibowli"]
# a="lync"
# if a in L:
# print("present")
# else:
# print("not present")
# # second method
# print(a in L)
# bit wise ope
# a=45
# b=65
# print(a & b)
# print(a | b)
# print(a ^ b)
# print(~b)
# print(a>>b)
# print(b<<a)
# q3
# Z=65.3... |
1faa772819cdca175fc69612f2bf0329728d7900 | mrmthornton/ud120-projects | /datasets_questions/explore_enron_data.py | 5,022 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features a... |
605bb48468c6e0de1401e4004d9b9828c83c33d4 | ankitjainlfc/python_examples | /asg1/2. Write a Python program to Print all natural numbers in reverse.py | 78 | 3.890625 | 4 | n = int(input("Please enter a number: "))
while n:
print (n)
n = n-1
|
5058e52a59077e7fbd72e2ff091a08e68192f41c | Nzen/Simpletron | /testMateria/analog.py | 2,236 | 3.8125 | 4 |
# Fuck, now I have to build something analagous.
class struct( object ) :
def __init__( self ) :
self.symbol = ""
#def __init__( self, name ) :
# self.symbol = name
class handleBob( object ) :
def __init__( self ) :
self.many = [ struct() for i in range( 5 ) ]
## this pattern is called a list comprehension... |
b9421ce40fa0737986920349dfc6a825d03e00ec | Gaya3balu0509/program | /printdgt.py | 141 | 3.609375 | 4 | str1=input()
s=[]
for i in str1:
if i.isdigit():
s.append(i)
if s==[]:
print()
else:
for i in s:
print(i,end='')
|
f603d0126b836bcf4b3d8e2e00dd0d548731e86d | Gaya3balu0509/program | /swapoddeve.py | 98 | 3.640625 | 4 | stng=input()
for i in range(0,len(stng),2):
print(stng[i+1],end="")
print(stng[i],end="")
|
00f3f606ffa976f5b0dada66f57e90e5e06a0072 | Gaya3balu0509/program | /encode.py | 130 | 3.890625 | 4 | nstr=input()
for i in nstr:
if ord(i)<88 :
print(chr(ord(i)+3),end="")
else:
print(chr(ord(i)-23),end="")
|
cc3955239bdf5d9f39a4dce8866b9062fe174133 | Gaya3balu0509/program | /fibo.py | 116 | 3.75 | 4 | numb1=int(input())
a,b=0,1
print(b,end=" ")
for i in range(1,numb1):
c=a+b
print(c,end=" ")
a=b
b=c
|
b4ef7c68ceabaa9d747c2cb4b8aadd7be68ce2f1 | Gaya3balu0509/program | /range.py | 123 | 3.71875 | 4 | num1=int(input())
ct=0
for i in range(0,11):
if i==num1:
ct=1
if ct==1:
print("yes")
else:
print("no")
|
6370f035571d8550ce234a808aad2ee4ec12e163 | Gaya3balu0509/program | /sumofk.py | 87 | 3.765625 | 4 | num1=int(input())
sumval=0
for i in range(1,num1+1):
sumval=sumval+i
print(sumval)
|
b79b62854b976bcb35fd743dcbcaba3620d212e0 | ZahraNabilaIzdihar/Backpropagation-Neural-Network-for-Multivariate-Time-Series-Forecasting | /2.IntializeNetwork.py | 514 | 3.59375 | 4 | from random import seed
from random import random
# Initialize a network
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]
network.append(hidden_layer)
output_layer = [{'weights':[random() fo... |
799061a7cd1f401ae28ab2e6c09d6629699f4d6d | rickyricky787/CSCI-499 | /HW 2/hw2.py | 4,281 | 3.5625 | 4 | # HW2: Linear Interpolation
# Author: Ricky Rodriguez
# Note: More detailed on Jupyter file
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import seaborn as sns
sns.set()
# Function for linear extrapolation (to get right points)
def getRightPoints(nan_pos, df, co... |
fe16f4ead6e5a1c3774d14182acd32fcb84a3a6e | qinysy/Learning-python | /ex8.py | 2,019 | 3.671875 | 4 | #!/usr/bin/env python3
#coding: utf-8
#__author:qinzhang
#字典定义的基本形式: key:value
d={'name':'egon','age':18}
d=dict({'name':'egon','age':18})
print(id(d),type(d),d)
#定义字典需要注意的问题:key必须是不可变类型,或者说是可hash类型
print(hash(1))
print(hash('xxxxxx'))
print(hash((1,2,3)))
#print(hash({'a':1}))
d={1:'id','a':1,'b':2,'name':'egon',... |
ce7e07250ab747c98b51c00c9028c1e7d14c27a3 | qinysy/Learning-python | /ex13.py | 865 | 3.96875 | 4 | #!/usr/bin/env python3
#coding: utf-8
#__author:qinzhang
#形参与实参
def foo(x,y):
return x+y
foo(1,2)
#位置参数:按照从左到右的顺序依次定义的参数
def foo(x,y):
print(x)
print(y)
#按位置定义的形参,必须被传值,多一个不行,少一个不行
#foo(1,2,3)
#按位置定义的实参,与形参一一对应
foo(2,10)
#关键字参数:实参在定义时,按照key=value形式定义
def foo(x,y):
print(x)
print(y)
foo(y=10,x=1) #关键字参数可以不用像位置... |
9d6ce64498d536071c0f8ca238c6b54f82895a41 | Shoaib-Alauudin/Python-Crash-Course | /Practice(3-26-17).py | 3,747 | 4 | 4 | import this # Some lines of sentences
'''
name = input("Please Enter your Name")
print(name)
message = "Hello Python"
print(message)
NewMessage = "New Hello World Pyhton"
print(NewMessage)
'''
Name = " shoaib alauddin "
print(Name.title()+" Title Case")
print(Name.upper()+" Upper Case")
print(Name.lower()+" Lower Cas... |
ce11dbd13e60cfa64834fe3edac0745c79956ae3 | Shoaib-Alauudin/Python-Crash-Course | /Assignment2.py | 914 | 3.625 | 4 | message = "I love"
foods = ["Biryani","Nahari","Pai","Palao","Qorma","Haleem","Zinger"]
for food in foods[0:3]:
print(message+" "+food)
print("-------------------------------------------------------------")
range = int(len(foods)/2)
for food in foods[range-1:range+2]:
print(message+" "+food)
print("-----------... |
04cf475e0066d48c880da95738616724706ddd6f | Shoaib-Alauudin/Python-Crash-Course | /Chapter6.py | 4,606 | 4.375 | 4 | print("----------------------Chapter-6--(2/April/17)-----------------------")
# print("----------------Dictionary-------------")
# it is also known as JSON format representation
# Student = {"Name":"Shoaib","Age":23,"Roll_No":1074,'c':"Hello Python",1:"Hello World"}
# print(Student["Age"])
# print(Student["Roll_No"])
#... |
c0fea6f68f644732ce24b6a77dca0d0f8be539d2 | NaveenkumarP0018/loops-patterns | /demo.py | 2,964 | 3.65625 | 4 | def first_last6(nums):
if (nums[0] == 6) or (nums[len(nums)-1] == 6):
return True
else:
return False
a=first_last6([1,2,6])
print(a)
b=first_last6([6,1,2,3])
print(b)
c=first_last6([13,6,1,2,3])
print(c)
print("==========================================================")
def same_fi... |
6efc1dbd6e2ebe0d6d2c7d897170177cefcd9899 | b4basitali/PIAIC-Python | /Quarter # 1 Final Python Assignment/piaic_python_functions.py | 6,048 | 4.15625 | 4 | from datetime import datetime
#Object # 1
def circle_area(radius,phi=22/7):
area = phi * (radius*radius)
print("Area of Circle is = {}".format(round(area,2)))
#Object # 2
def check_num(num):
try:
num = float(num)
if num > 0:
print("The Number "+str(num)+ " is Positive"... |
e19e56e43ae31b580165ce7b08c2a0ebfc035ea0 | prishagoel/py-getrfc | /main.py | 3,473 | 4.03125 | 4 | import argparse
import requests
from requests.exceptions import HTTPError
'''
Python script to fetch RFC data from IETF's website using the requests
library and perform one of two actions -
1) Display it in stdout (terminal)
2) Write it to a file specified by this user
Open to collaboration.
'''
class Error(Exceptio... |
e4ce1ea0a3a39c6b01044283ec4a1b13c228408b | Juaquigm/Pruebita | /Prueba.py | 256 | 3.65625 | 4 | print("Esto es una prueba para ver si funciona: ")
input("Introduzca un numero: ")
#Supongamos un ejemplo que esto es editado en la pagina web
print("Esto es de la página web")
#Esto esta hecho en el Visual Studio
print("Esto es del editor visual Studio") |
321bdf524cdebdbe84323af63e9f868d64969d8d | vm/4500 | /3/player.py | 3,848 | 4.15625 | 4 | """
This doc specifies the interface for a player.
Implementers should inhereit from the BasePlayer class and override the
following methods:
- pick_card
- pick_stack
"""
from collections import namedtuple
Card = namedtuple('Card', ['face', 'bull'])
# represents a single card
# face is an int for the face va... |
fa93c84e20bf9127434f663f2365288c42d8fe90 | brextonpham/djinn | /edit_distance.py | 1,710 | 3.6875 | 4 | #############################################################################
# Edit Distance Functions #
#############################################################################
class EditDistance:
def dameraulevenshtein(self, seq1, seq2):
"""Calcula... |
b8820f1702deb4aec0d56b58b616fc3ee8b06bf6 | FreakX23/EBook_Training | /app5.py | 195 | 4.09375 | 4 | for x in (1, 3, 5): #will iterate once with 1, 3, etc
usrRange = 4
for x in range (1, usrRange): #variables can be used as well
print ("I will repeat this the specified number of times")
|
0e6333cc381c91b697a99105deacf81a3c32a5b0 | maximuse/feladatok20181020 | /nevDatum.py | 372 | 3.765625 | 4 | # Írjon programot, ami bekéri a teljes nevet, a születési dátumot, majd kiírja a „Szia <keresztnév>! Te <x> éves vagy.”
import datetime
teljesNev = input("Teljes név: ")
ev = int(input("Születési év: "))
keresztNev = teljesNev.split(" ")[1]
kor = int(datetime.datetime.now().year - ev)
print("Szia " + keresztNev + "... |
a3c12598370b0e061a4359256ecdae189944c6ce | maximuse/feladatok20181020 | /osztalyzat.py | 620 | 3.5625 | 4 | # Egy dolgozatra annak pontszámától függően a következő osztályzatot adják:
# elégtelen (1): 0 – 29 elégséges (2): 30 – 37 közepes (3): 38 – 43 jó (4): 44 – 49 jeles (5): 50 – 55
# Kérje be a dolgozat pontszámát, majd írja ki az osztályzatot számmal és betűvel!
p = int(input("Pontszám: "))
if (p == 0) or (p <= 29):
... |
21656fe31f19be2703b317c1033dc4d9216c0fcf | maximuse/feladatok20181020 | /hasabFelszinTerfogat.py | 295 | 3.578125 | 4 | # Kérd be a konzolról egy téglatest három élének hosszúságát, majd írd ki a hasáb felszínét és térfogatát!
a = int(input("A: "))
b = int(input("B: "))
c = int(input("C: "))
print("felszín:\t" + str(a * b * c) + "\ntérfogat:\t" + str((a * b * 2) + (a * c * 2) + (b * c * 2)))
|
21b5eaec76fd69ca499b319ec963bd606dccaa91 | wisecube-cn/LeetCode | /0014 Longest Common Prefix.py | 1,131 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 09:48:19 2019
@author: 24283
"""
inputStr=["flower","flow","flight"]
class Solution:
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
global i,j
global n
global minLen
... |
fc910316e5c49a430cd9022533455424aebbcb2c | MatenRehimi/University | /Year 3/Dissertation (Python)/Predict football matches code/Scraper/TeamWagesScraper.py | 1,010 | 3.546875 | 4 | import csv
class TeamWagesScraper:
def __init__(self):
self.csvFile = open("Scraper/Data/TeamWages.csv",encoding="utf8")
self.reader = csv.reader(self.csvFile)
#Finds a team in the TeamWages.csv file
def findTeam(self, team):
self.csvFile.seek(0)
for row in self.reader:
... |
06e1b3a195af69dd1127fc67824aba06269d0c4b | mtanji/intro-algorithm-python | /4.repetition/aula8.exercicio.1.parte1.py | 237 | 4.03125 | 4 | # [Parte 1] Faça um programa que receba a idade do usuário e diga se ele é maior ou menor de idade.
idade = input('digite sua idade ')
idade = int(idade)
if idade >= 18:
print('maior de idade')
else:
print('menor de idade')
|
859a1524c78986734176b3ea0eb0d65fc4113230 | rebelliovs/Project-Euler | /Python/19.py | 528 | 3.984375 | 4 | # Importing the 'calendar' library so we can easily get the day of the week
import calendar
# Initializing the number of Sundays to 0
sundays = 0
# Iterating through the loops from 1901 to 2000 inclusive
# and for months from 1 to 12;
for y in range(1901,2001):
for m in range(1, 13):
if calendar.weekday(y,m,1) == ... |
52f36317552e8eb0e533b61c0f4947b653e7d52d | saikirandulla/HW06 | /HW06_ex09_04.py | 1,337 | 4.40625 | 4 | #!/usr/bin/env python
# HW06_ex09_04.py
# (1)
# Write a function named uses_only that takes a word and a string of letters,
# and that returns True if the word contains only letters in the list.
# - write uses_only
# (2)
# Can you make a sentence using only the letters acefhlo? Other than "Hoe
# alfalfa?"
# - writ... |
326f97eacfae3f00c18f85468bcae9ec6b877a6b | YoungdanNoh/Machine_learning_basic | /선형회귀 가설함수 구현/main.py | 483 | 3.546875 | 4 | import numpy as np
def prediction(theta_0, theta_1, x):
"""주어진 학습 데이터 벡터 x에 대해서 예측 값을 리턴하는 함수"""
# 코드를 쓰세요
return theta_0 + theta_1*x
# 테스트 코드
# 입력 변수(집 크기) 초기화 (모든 집 평수 데이터를 1/10 크기로 줄임)
house_size = np.array([0.9, 1.4, 2, 2.1, 2.6, 3.3, 3.35, 3.9, 4.4, 4.7, 5.2, 5.75, 6.7, 6.9])
theta_0 = -3
theta_1 =... |
d3203fb4d32113cdd3b637fb9cd6b97fca628dc8 | namor87/codewars | /python/we_are_familly/we_are_family.py | 3,837 | 3.546875 | 4 | import itertools
class Person:
FEMALE = "F"
MALE = "M"
UNKNOWN = "?"
def __init__(self, name):
self._name = name
self._parents = []
self._children = set()
self._gender = self.UNKNOWN
def __repr__(self):
return str(self.get_name())
def get_name(self):
... |
666b8b04aa7a50c1e3140929bc39696034acc09d | marat92d/Portfolio | /примеры моего кода на python/durak.py | 2,242 | 3.78125 | 4 | value=['6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] #в список записываем все значения карт по возрастанию
first,second=input().split() #читаем две карты
suit=input() #читаем козырную масть
if first[-1]==second[-1]: #если масти двух карт равны
if value.index(first[0:-1])>value.index(second[0:-1]): #то сравнием ... |
9efbcfe02632ec3bc3c8e29ddd6c70218ad435f3 | glasswm/leetcode | /144.py | 844 | 3.953125 | 4 | #Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root ==... |
8d0c062dfc7f560064cf4300cab0ced220d546ec | seongjeonggi/python-ex | /algorithm_basic/e14-1-getname.py | 455 | 3.90625 | 4 | #!/usr/bin/python3
# Dictionary search
# input:
# a: dictionary of student's no.(key) and name(value)
# x: student's number to search
# output: student's name on success, otherwise '?'.
def search_name(a, x):
if x in a:
return a[x]
else:
return "?"
# main
stu_nn = {39:"Justin", 14:"John", 67:"Mike", 105:"... |
3e3935f7439019e84946db6d5c2cf4a112bba9da | seongjeonggi/python-ex | /algorithm_basic/p07-ex1.py | 368 | 3.90625 | 4 | #!/usr/bin/python3
# Sequential search (2)
# input:
# a: list
# x: target value
# output: all index of x on success, otherwise -1.
def search_list(a, x):
n=len(a)
xl = list()
for i in range(0, n):
if x == a[i]:
xl.append(i)
return xl
# main
v = [17,92,18,33,58,7,33,42]
print(search_list(v, 18))
print(... |
f031848655a69c88d7cbf95343f441e0e9c147df | seongjeonggi/python-ex | /algorithm_basic/p05-2-gcd.py | 269 | 4.03125 | 4 | #!/usr/bin/python3
# Euclid's GCD(Greatest Common Divisor) algorithm
# input: a, b (both integer)
# output: gcd of a and b
def gcd(a, b):
if b==0:
return a
return gcd(b, a%b)
print(gcd(1,5))
print(gcd(3,6))
print(gcd(60,24))
print(gcd(81,27))
print(gcd(17,13))
|
ddb6c1e167ea2dab53a01853e51351a7cc3a2a67 | seongjeonggi/python-ex | /algorithm_basic/p06-1-hanoi.py | 607 | 4.09375 | 4 | #!/usr/bin/python3
# Hanoi tower
# input:
# n = the number of a disk to move
# from_pos = starting pole which has a disk to move.
# to_pos = destination pole to move a disk.
# aux_pos = auxiliary pole to move a disk
# output: the order of moving disk.
def hanoi(n, from_pos, to_pos, aux_pos):
if n==1:
print(f... |
ca68b2625f96a4f81108a8f16f1a126bbf345c3c | seongjeonggi/python-ex | /basic/trun2.py | 1,756 | 3.953125 | 4 | #!/bin/python3
# Turtle Run 2
import turtle as t
import random
score = 0
playing = False
te = t.Turtle() # enemy turtle(red)
te.shape("turtle")
te.color("red")
te.speed(0)
te.up()
te.goto(0, 200)
ts = t.Turtle() # feed (green circle)
ts.shape("circle")
ts.color("green")
ts.speed(0)
ts.up()
ts.goto(0, -200)
def... |
79fa984dc450951faca5035453f3c4a60c92483f | seongjeonggi/python-ex | /algorithm_basic/p18-3-compare.py | 1,074 | 3.734375 | 4 | #!/usr/bin/python3
# Compare processing time between two algorithms
# Time complexity of O(n*n) and O(n)
import time
import random
def max_profit_slow(prices):
n = len(prices)
max_profit = 0
for i in range(0, n-1):
for j in range(i+1, n):
profit = prices[j]-prices[i]
if profit > max_profit:
max_prof... |
08d03de0e51a2c841dc857486e091faa158fefc6 | Cai-Pei-Xuan/Region_Filling | /region_filling.py | 5,627 | 3.6875 | 4 | from PIL import Image, ImageDraw
# 取得座標(x, y)附近的像素值
def getpixel(image, x, y):
pixel_list = []
# 取得3*3的像素值
for i in range(-1, 2):
for j in range(-1, 2):
pixel = image.getpixel((x + j ,y + i))
pixel_list.append(pixel)
return(pixel_list)
# 將黑白圖片做Complement
def Compl... |
75f8f117d61fef1e9464609493492c8b3bf2a826 | vikasvk7/Graph_API | /database.py | 554 | 3.875 | 4 | import sqlite3
db = sqlite3.connect("Fb.db")
cursor = db.execute("SELECT * FROM MYDATA")
c = 0
for row in cursor :
if(c==0):
print("Name ", "Gender ", "Location ", "Email ", "Recent-Liked ")
print("--------------------------------------------... |
b41daa7f29b6557e6a7d4572b89bf2e98d5f83ae | yotroz/white-blue-belt-modules | /19-apis/apis.py | 2,074 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 09:36:14 2018
@author: yotroz
"""
#%%
import requests
def get_lyrics(artist, song_name):
url = "https://api.lyrics.ovh/v1/" + artist + "/" + song_name
# Other way to write this synthax
# url = "https://api.lyrics.ovh/... |
31f3c7d5da418e3abbf4c44fced349ab7aac1fab | yotroz/white-blue-belt-modules | /17-exceptions/blue_belt.py | 488 | 4.53125 | 5 | #%%
#Create a function that reads through a file
#and prints all the lines in uppercase.
#
#
#
#be sure to control exceptions that may occur here,
#such as the file not existing
def print_file_uppercase(filename):
try:
file = open(filename)
for line in file:
print(line... |
58859986e27c700d947986850624d00d0b490e25 | mmiyaji/isreport | /isbookshelf/strage/shell/tfidf/tfidf.py | 1,361 | 3.515625 | 4 | #!/usr/bin/env python
# encoding: utf-8
#
# 名詞の出現頻度を数える
__usage__="""
count.py [raw text file] > [output file]
"""
import sys
sys.path.append("/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/")
import MeCab
import os,re
import operator
t = MeCab.Tagger(" ".join(sys.argv))
ignones ... |
147ebca997008e894bd6b5f6f74d63c658643188 | Umesh8Joshi/My-Python-Programs | /numbers/PItoNth.py | 274 | 4.21875 | 4 | '''
Enter a number to find the value of PI till that digit
'''
def nthPI(num):
'''
function to return nth digit value of PU
:param num: number provided by user
:return : PI value till that digit
'''
num = input('Enter the digit')
return "%.{num}f"(22/7).format(num) |
05aa4556a9f0186e963a4699d9cbbd377e6ee406 | Umesh8Joshi/My-Python-Programs | /numbers/bin2decViceVersa.py | 537 | 4.09375 | 4 | '''
In this program we will create two separate functions
First function will take decimal number and return binary
Second function will take binary number and return decimal
'''
def bin2dec(bin):
'''
Function to convert binary to decimal
:param bin: Binary number provided as a string
:return: Integer in int da... |
bf04389636be7ed1633747f782aa92774f3f70a1 | h1dd3nfigs/simple-games | /bees.py | 1,792 | 3.9375 | 4 | #!/usr/bin/env python
from __future__ import print_function, unicode_literals, division
from random import random, choice, randint
from time import sleep
init_bees = 100
init_wasps = 5
num_flowers = 500
turns = 100
class Hive(object):
honey = 5
def __init__(self):
self.bees = [Bee() for _ ... |
af6c0f4a338b2f74558ab755eba3851b8aec729f | h1dd3nfigs/simple-games | /tictactoe.py | 1,820 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import sys
from random import choice as randchoice
from itertools import cycle
from board import Loc, Board
size = 3
blank = '.'
players = 'XO'
class TictactoeBoard(Board):
def filled(self):
return not any(tile==blank for tile in self)
def rand... |
9fda70b32d7632ce9302216413a3954cad41d8bf | andremoraes/Python-Course | /other/python_lambda.py | 253 | 3.6875 | 4 | li1=[(1,2),(4,1),(5,3)]
li2=li1[:]
def last(x):
return x[-1]
def summed(x):
return x[0] + x[1]
li1.sort(key=lambda x: x[-1])
li2.sort(key=last)
print li1
print li2
li1.sort(key=lambda x: x[-1]+x[0])
li2.sort(key=summed)
print li1
print li2
|
e11c66d2e2d97253bfd7715e7bb1c30c9b08418f | Chener-Zhang/HighSchoolProject | /Assembly/hw6pr1.py | 3,702 | 3.96875 | 4 | # hw6pr1.py - Hmmm!
#
# problem number: Lab!
#
# name:
# date:
#
# you'll write unique (or uniq) later in the lab...
#def unique(L):
# Example1 is an example program that
# 1) asks the user for two inputs
# 2) computes the product of the inputs
# 3) prints out the result (with write)
# 4) stops
Example1 =... |
d05ea438611f9a1af279a4935c1c966047ae41d5 | Chener-Zhang/HighSchoolProject | /Assembly/hw6pr5.py | 2,447 | 4.15625 | 4 | # hw6 problem 5
#
# date:
#
# Hmmm...
#
#
# For cs5gold, this is the Ex. Cr. recursive "Power" (Problem4)
# and recursive Fibonacci" (Problem5) program
# Here is the starter for gold's Problem4 (recursive power):
# This is the recursive factorial from class, to be changed to a recursive _po... |
94c190a472f07e3c616bae21d4e2674e64105120 | emilylawton/cryptopals-challenges | /challenge1.py | 415 | 3.8125 | 4 | '''
Challenge 1: Convert hex to base64
The string:
49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
Should produce:
SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
So go ahead and make that happen. You'll need to use this code for the rest of the exer... |
85365a26643a2b8d1f5ea313182460efd8a293ab | ssong10/LeetCode | /leet/valid-parentheses.py | 786 | 3.828125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
tmp = []
for i in s:
if i == '(':
tmp.append(i)
elif i == ')':
if tmp and tmp[-1] == '(':
tmp.pop()
else:
return False
elif i... |
4f1860b1d606ae8ef2f930114ea11d9f346658b5 | pujkiee/python-programming | /begginer level/positive or negative.py | 199 | 3.953125 | 4 | num = input("Enter the number to check")
if(1 <= num <= 100000):
print("The given number is Positive")
elif(num <= -1):
print("The given number is negative")
else:
print("The given number is Zero")
|
8a02668661185c1140b075acea199b4cfcabecba | pujkiee/python-programming | /begginer level/factorial.py | 161 | 4 | 4 | num = input("Enter the Number")
fact = 1
if(isinstance(num,int)):
for i in range (1,num+1):
fact *= i
print fact
else:
print "Invalid Input"
|
bcacac64442881b530ba1a17b1ec38b2e006a8dc | CodeGuardianAngel96/OOPS-I-Posted | /MoreThan7.py | 354 | 3.984375 | 4 | '''
Write a function words() in python to read lines from a text file "WORD.txt",
and display those words, which are less than 7 characters.
'''
if __name__ == "__main__":
file = open("Q4.txt", 'r')
count = 0
for i in file:
for word in i.split():
if len(word) < 7:
... |
a6ed41b73b361d4d021ed75612e60ad47a07f7e7 | CodeGuardianAngel96/OOPS-I-Posted | /TriangleSquare.py | 267 | 4.0625 | 4 | '''
1.Write a function area() to calculate area of a square and area of a triangle
'''
def area(length, breadth):
print("Area of traingle", 0.5 * length * breadth)
print("Area of Square: ", length * length)
if __name__ == "__main__":
area(10, 10)
|
10563cd0367fb57ecd02189e4a3e182c156932cb | AnnaGottfried/Kodilla | /lat.py | 252 | 3.65625 | 4 | import sys
def print_maturity(age):
if age >= 18:
print("You are an adult")
else:
print("You are a kiddo!")
if __name__ == "__main__":
if len(sys.argv)<2:
exit(1)
age = int(sys.argv[1])
print_maturity(age) |
e0f1bb36aed5f92cd6f654131c6d1ab4200f984a | sadmanishrak/python-oop | /inheritance.py | 1,156 | 4.09375 | 4 | # Inheritance
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f"I am {self.name} and I am {self.age} years old\n")
def speak(self):
print("I don't know what to say")
class Cat(Pet): # Inheriting the Pet class
def __in... |
3055be19916c317a84d6e2f56c904b2c6c1bad7a | katya-varlamova/2-sem-Python-Prog | /lab_01 (newton)/newtonLib.py | 1,961 | 3.5 | 4 | def f(x):
return x*x*x + 2*x -1#x*x*x - 2*x + x*x - 2
# Newton-Raphson method
def newton(func, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50,
fprime2=None):
if tol <= 0:
raise ValueError("tol too small (%g <= 0)" % tol)
if fprime is not None:
p0 = 1.0 * x0
fder2 = 0
... |
e64b3d4a46afc9f0b6932857532505885f1830fb | jr80939393/python | /week08_ex1_105701051..py | 84 | 3.703125 | 4 | k=0
for i in range(3,26):
k+=i
print("從3到25的所有整數加總為",k)
|
5d706a7e44afb20369ecac0b8c2d1b857b6cef08 | shahid456/python_practice | /Data_structure/problem15.py | 2,175 | 3.703125 | 4 | class Node:
def __init__(self, info):
self.data = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.data)
def inOrder(root):
if root==None:
return
inOrder(root.left)
print(root.data, end=" ")
inOrder(root... |
70386713f6e29ac6f32e43380741cf1b855aa40c | TDhondup/Unit_3_Lesson_6 | /Lesson 6/problem1.py | 84 | 3.859375 | 4 | name = input('What is your name? ')
print('UGH, I HATE YOU ' + name.upper() + '!c')
|
5ac7e1738791324885a2067476850d7666541781 | JijoongHong/Algorithms | /4-1_merge_sort.py | 1,130 | 3.9375 | 4 | def merge_sort_td(arr, lo, hi):
if lo == hi:
return arr
mid = (lo + hi) // 2
merge_sort_td(arr, lo, mid)
merge_sort_td(arr, mid+1, hi)
merge(arr, lo, mid, hi)
return arr
def merge(arr, lo, mid, hi):
temp = []
i = lo
j = mid + 1
# 인덱스 증가시키며 큰 값 집어넣기
while i <= mi... |
ade014428fabb8b39179eaf4814575865be3f90e | JijoongHong/Algorithms | /2-7_radix_sort.py | 570 | 3.578125 | 4 | def lsd_sort(arr):
width = 3
n = len(arr)
r = 128
temp = [None] * n
for d in reversed(range(width)):
count = [0] * (r+1)
for i in range(n):
count[ord(arr[i][d]) + 1] += 1
for j in range(1, r):
count[j] += count[j-i]
for i in range(n):
... |
b172dfec9e85f684fad70d71e7bca9af8357ed44 | hannah-rae/Intro-to-Computer-Science--the-Less-Sucky-Edition | /projects/Fundamentals of Problem Solving with Python/planets.py | 2,006 | 3.828125 | 4 | def getRadius(planet):
for body in planetInfo:
if body[0] == planet:
return int(body[2])
def getDiameter(planet):
return getRadius(planet)*2
def getCircumference(planet):
return getDiameter(planet)*3.14
def getSurfaceArea(planet):
rad = getRadius(planet)
surfaceArea = 2*3.14*(rad*rad)
return surfaceArea
... |
1fa20508880e5ba40e635add5a182a8050aacc9e | hannah-rae/Intro-to-Computer-Science--the-Less-Sucky-Edition | /projects/Fundamentals of Problem Solving with Python/palindrome.py | 435 | 4.09375 | 4 | def isPalindrome(wurd):
wurd = wurd.lower()
spaceless = ""
for char in wurd:
if char != ' ':
spaceless += char
reversedWord = ""
for i in range(len(spaceless)-1, -1, -1):
reversedWord += spaceless[i]
if reversedWord == spaceless:
return True
else:
return False
while(True):
word = raw_input("Enter a... |
f18ece988081efed2c55f0f5f2f9fc69f089d5e8 | guiaramos/CS50-2019 | /week6/credit/credit.py | 954 | 3.921875 | 4 | # Modules
from cs50 import get_int
from math import floor
# Variables
digit1 = 0
digit2 = 0
numDigits = 0
sumDoubleOdds = 0
sumEvens = 0
# Asking for input credit card
creditCard = get_int("Number: ")
# Checking the credit card number
while creditCard > 0:
digit2 = digit1
digit1 = creditCard % 10
if num... |
f0a12ada295d28b1f5ab23ad0c5a65fd6fa9f494 | dtmw8z/NumberTheory | /menu.py | 1,713 | 3.578125 | 4 | from sys import exit
from os import system, name
o1 = " 1. Encrypt"
o2 = " 2. Decrypt"
o0 = " 0. Exit (Enter 0 in any field to exit)"
p1 = " 1. From Terminal"
p2 = " 2. From To File"
p3 = " 3. From Clipboard"
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.