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 |
|---|---|---|---|---|---|---|
dcbe69d5095815419df2130635fca147b87a0c74 | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/11_UsingColumnIndexes.py | 1,692 | 4.15625 | 4 | import pandas as pd
titanic_survival = pd.read_csv('titanic_survival.csv')
# Drop all columns in titanic_survival that have missing values and assign the result to drop_na_columns.
drop_na_columns = titanic_survival.dropna(axis=1, how='any')
# Drop all rows in titanic_survival where the columns "age" or "sex"... |
3537f940e58dd5db3427731bb044f4b446ea4df0 | kds0280/Programmers | /level1/키패드 누르기.py | 1,077 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def distance(pos, num, hand, L_memory, R_memory):
L_distance = abs(pos[num][0]-pos[L_memory][0]) + abs(pos[num][1]-pos[L_memory][1])
R_distance = abs(pos[num][0]-pos[R_memory][0]) + abs(pos[num][1]-pos[R_memory][1])
if L_distance == R_distance:
retur... |
189e44beb87a71a61b9d5186c3343bcb6ff4c74c | Efimov-68/CoursesPython2.x-3.x | /fiveName.py | 3,923 | 3.859375 | 4 | '''
# Задание 1
# Имена должны сохраняться в списке и выводиться в конце программы.
# Запрос от пользователя
name_1 = input('Введите 5(пять) имен (после каждого нажатия Enter):\nИмя №1: ')
name_2 = input('Имя №2: ')
name_3 = input('Имя №3: ')
name_4 = input('Имя №4: ')
name_5 = input('Имя №5: ')
# Создание списка
name... |
7dfeae6e699f74dd5ba670e715bdd59d13886eff | cajimon04/Primer-Proyecto | /primer_ejercicio.py | 887 | 3.96875 | 4 | numero_ganador = 13
numero_del_usuario = int(input("Dime un numero del 1 al 15: "))
if numero_del_usuario == numero_ganador:
print ("Has ganado")
else:
print ("Te quedan 4 intentos")
numero_del_usuario_2 = int(input("Dime un numero del 1 al 15: "))
if numero_del_usuario_2 == numero_ganador:
print("Has gan... |
62f20b936ae79a706943461ee2e15e800d17da82 | whuybrec/MiniGamesBot | /minigames/mastermind.py | 1,046 | 3.59375 | 4 | import random
from minigames.minigame import Minigame
COLORS = ["blue", "red", "purple", "yellow", "green", "orange"]
class Mastermind(Minigame):
def __init__(self):
self.history = []
self.code = list()
while len(self.code) < 4:
color = COLORS[random.randint(0, 5)]
... |
ee4e10870c6062e8df5f45c2c765d6cc93d57721 | TakeMeHigher/mssf | /链表/单链表.py | 7,278 | 3.734375 | 4 | class LinkNode(object):
def __init__(self, data=None):
self.data = data
self.next = None
class LinkNodeList(object):
def __init__(self):
self.head = None
def create_link(self, data_list):
"""
创建链表
:param data_list: 数据列表
:return:
... |
8d9bd7df14c3017536782f78bfe5b592e6cb9963 | nicoops/python-projects | /trips.py | 952 | 4.3125 | 4 | import math
import sys
def triple_check():
print("Input the length of each side of your triangle.")
sides = []
while len(sides) != 3:
side_length = input('> ')
if side_length.isdigit() == True and int(side_length) != 0:
sides.append(int(side_length))
else:
p... |
c617b41c5f77098c9105bca9b5c02fbdece4feef | brudolce/codewars | /7-kyu/Is this a triangle?.py | 129 | 3.84375 | 4 | def is_triangle(a, b, c):
if (a + b > c) and (b + c > a) and (c + a > b):
return True
else:
return False
|
ce7f00249b9c8cf2a1bc0f08a8c57368b88e73a2 | bemsuero/python | /ex5.py | 503 | 3.9375 | 4 | my_name = "Bemilton Suero"
my_age = 27
my_height = 74
my_weight = 140
my_eyes = "Brown"
my_teeth = "White"
my_hair = "Black"
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("That's not that heavy.")
print(f"He's got {my_eyes} eyes and {my_hai... |
7e9f5ae58ab66753d40b8677e781860b2f47c03d | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/203/41885/submittedfiles/testes.py | 94 | 3.828125 | 4 | n=float(input('digite n: '))
exp=0
while r!=0:
r=n%2
s=s+r*10**exp
n=n//2
print(s) |
cc4a677342c1583d48211bd8466d266ec150be06 | oGabrielSilva/Gestao-de-TI | /Prova 2/quest4/quest4.index.py | 264 | 3.9375 | 4 | def main():
quest_est = ['primavera', 'verão', 'outono'];
print('a)', len(quest_est));
print('b) Inverno adicionado a lista.');
quest_est.append('inverno');
for x in quest_est:
if x == 'verão': print('c)', quest_est.index(x));
main(); |
b2e4dd37e785b92dde0f875d35a1a41645a94340 | Arephan/kijiji-iphone-market-analysis | /Kijiji-Repost-Headless/kijiji_repost_headless/csv_to_yaml.py | 3,607 | 3.921875 | 4 | # Takes a file CSV file called "data.csv" and outputs each row as a numbered YAML file.
# Data in the first row of the CSV is assumed to be the column heading.
# Import the python library for parsing CSV files.
import csv
import urllib2
import os
import glob
# Open our data file in read-mode.
csvfile = open('data.csv'... |
3c99706f3bd57619c3c60c0ae8e62a01fb3c15d3 | itaborai83/grouper | /grouper.py | 7,452 | 3.546875 | 4 | import math
#from aggregates import *
class RowExpr(object):
""" Represents an Expression that returns a value given a dict"""
def __init__(self, label):
self._label = label
def label(self):
""" return the label for an expression """
return self._label
def value(self, row):
... |
6dadb0384cebb0f40f6b098993b57545ad7d9e5f | PrimeNumbers/primes_search | /test_str_subtract.py | 1,131 | 3.65625 | 4 | import unittest
from str_subtract import subtract
class TestSubtractStrings(unittest.TestCase):
def test_obvious_small(self):
self.assertEqual(subtract('100','50'), '50')
self.assertEqual(subtract('9999','1234'), '8765')
self.assertEqual(subtract('7','0'), '7')
self.assertEqual(sub... |
673b5d4b9ec45ec19ff49c1bbef23907cc70c55f | srosenfeld/costOfLivingCalculator | /cost_of_living_testing.py | 242 | 3.765625 | 4 | utilities = ""
internetCable = ""
rent = ""
print("What value would you like to see?")
check=input()
if check == "utilities":
print(utilities)
elif check == "internetCable":
print(internetCable)
elif check == "rent":
print(rent)
|
6cb3208007a9708751af911c795f5924e607aeac | drewherron/class_sheep | /Code/charlie/python/lab17.py | 2,141 | 3.96875 | 4 | # #lab17.py
# ''' i want to input a string
# then i want to convert the string into indicies
# then i want to compare the first and last indicies to determine if they are the same
# if they are the same, return true
# else return false
# '''
#
import string
abc_list = list(string.ascii_lowercase) #defines ascii string ... |
7c60227d7cfc740a24f29708313d91d6edee2d23 | xuweixinxxx/HelloPython | /nowcoder/foroffer/Solution12.py | 1,248 | 3.734375 | 4 | '''
Created on 2018年4月16日
按层序打印二叉树 A
B C
D E F
输出:
A
B,C
D,E,F
@author: minmin
'''
class TreeNode:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
class Solution12:... |
6a0a22d90ba6ceda777bf1912d252858b7c356e0 | athu1512/calculator | /input.py | 622 | 3.921875 | 4 | import calculator as c
a=int(input("Enter the first number"))
b=int(input("Enter the second number "))
ch=0
while ch!=6:
print("MENU")
print("1.ADD \n 2.SUBTRACT\n 3.MULTIPLICATON \n 4.DIVISION \n 5.MODULUS \n 6.EXIT")
ch=int(input("enter your choice"))
if (ch==1):
z=c.add(a,b)
print(z)... |
420eef0473e2e08091c88408a9415ead34b0dea5 | edu-athensoft/stem1401python_student | /py210109b_python3a/day19_210515/scale_01.py | 1,290 | 4.03125 | 4 | """
Scale
basic usage of Scale
get value via Scale object
['activebackground', 'background', 'bigincrement', 'bd', 'bg',
'borderwidth', 'command', 'cursor', 'digits', 'fg',
'font', 'foreground', 'from', 'highlightbackground', 'highlightcolor',
'highlightthickness', 'label', 'length', 'orient', 'relief',
'repeatdelay... |
187b732d4cdd7764d3057abe5d81202f9de0475c | sarkarChanchal105/Coding | /Leetcode/python/Google/3Sum.py | 1,993 | 3.65625 | 4 | """
https://leetcode.com/explore/interview/card/google/59/array-and-strings/3049/
"""
class Solution:
def threeSum(self, nums):
## hadnle edge cases
if len(nums)>3 and list(set(nums))==[0]:
return [[0,0,0]]
if nums==[]:
return []
if len(nums)<3:
... |
5c3339849d75726d0ab9171ea66740a37f856153 | fplucas/exercicios-python | /estrutura-de-repeticao/11.py | 331 | 4.03125 | 4 | numeros = []
for numero in range(0, 2):
numeros.append(int(input('Entre com o {}o. número: '.format(numero + 1))))
if(numeros[0] > numeros[1]):
print('Intervalo inválido!')
else:
soma = 0
while(numeros[0] < numeros[1]):
soma = soma + numeros[0]
numeros[0] += 1
print('Soma: {}'.form... |
244b91486ac3af60461a390f2e4ab4f897cda0df | sasuwaidi/Hackerrank-Coding-Challenges-Code | /2 - Nested Lists.py | 676 | 4.03125 | 4 | #initializing marksheet list (with names and scores) and score list
msL=[]
sL=[]
if __name__ == '__main__':
#itertating based on students
for _ in range(int(input())):
#identifying student and score and inputting it into respective list
Name = input()
Score = float(input())
... |
cba91d9a988ff1e8a15a66d07bda9c11c93c808d | hunnain-atif/amazonPriceTracker | /priceTracker.py | 1,838 | 3.546875 | 4 | from bs4 import BeautifulSoup
import time
import smtplib
import requests
#user info for the product they want to track, the price they are looking for
#and their email information
TARGET_PRICE = 20.00
EMAIL_ADDRESS = 'YOUR_GMAIL_EMAIL_ADDRESS_HERE'
HEADERS = {"User-Agent": "YOUR USER AGENT HERE"}
URL = "YOUR DESIRED ... |
665aff7698b556af12f1bb5bb4cadbc1acb76492 | JordanRushing/CCI-Exercises | /cci_1-4.py | 504 | 4.03125 | 4 | """
Cracking the coding interview - Exercise 1.4
March 4th, 2017
"""
import sys
def replace_space(testString):
"""
This function replaces any spaces present in a provided string
with the char sequence "%20"
"""
newString = ""
for c in testString:
if c != ' ':
newString += ... |
7959355fe52a2443ae243e7fdadc52a6f89d1709 | mori-c/cs106a | /sandbox/khansole_academy-v3.py | 1,285 | 3.796875 | 4 | import random
min = 1
max = 99
total = 0
input
pass_count = []
def main():
question()
answer()
validate()
game_check()
'''
Helper Functions
'''
def question():
num1 = random.randint(min, max)
num2 = random.randint(min, max)
total = num1 + num2
total = str(num1 + num2)
print('What is ' + str... |
5fcdc645aedec186fdba5c14b717d1abcba41cbc | dennisahuja/codecheff | /divisors.py | 178 | 3.515625 | 4 | import random
def Divisors(n):
divisors = []
for i in range(1,((n/2)+1)):
if (n % i == 0):
divisors.append(i)
return divisors
a = random.choice(Divisors(10));
print a
|
5ed0aae04ac16cc8d60e3e760450e38ee51cb864 | Shyam-Makwana/Cool-Python-Codes | /MadLibs Game/MadLibs.py | 475 | 3.875 | 4 | print("*"*30)
print("\tMad Libs Game")
print("*"*30)
excl = str(input("\nEnter any exclamation word : "))
adverb = str(input("Enter any adverb : "))
noun = str(input("Enter any noun : "))
adj = str(input("Enter any adjective : "))
sentence = "\n{}! he said {} as he jumped into his convertible {} and drove off with his... |
c5322bdba10602ee8ac3fdce940fc752f74c9a85 | myz19/Final_M | /venv/CS1110/hw3/matricesandvectors_officehours.py | 2,720 | 3.859375 | 4 | from __future__ import annotations
import copy
from typing import List
class Vector:
"""Assumed to be a column vector by default"""
def __init__(self, data: List[int]):
self.data = data
def __repr__(self):
return str(self)
def __str__(self):
data = ""
for number in... |
d70aad9046fa9792f6dfb7256c8a916b989512de | nitikayad96/Hearts | /GamePlay.py | 890 | 3.84375 | 4 | '''
A few notations to consider in this program:
The four suits: spades, hearts, diamonds and clubs are always going to be lowercase
The players are stored as objects. The player object contains the hand and the number of points.
'''
import random;
Deck = [];
class Card:
#implement here
class Player:
points =... |
975a3a06443ee6844a4c345679ea09f6054ce990 | Sarchieo/Python-Learning-Homework | /第一周/CyConvert.py | 580 | 3.609375 | 4 | # -*- coding: utf-8 -*
import re
'''
货币转换
人民币和美元间汇率固定为:1美元 = 6.78人民币
人民币采用RMB表示,美元USD表示
'''
CyStr = input("请输入需要转换的货币:")
if re.search(r"^\d+(?:\.\d+)?RMB$|^RMB\d+(?:\.\d+)?$", CyStr):
USD = eval(re.findall(r'\d+(?:\.\d+)?', CyStr)[0]) / 6.78
print("USD" + '%.2f' % USD)
elif re.search(r"^\d+(?:\.\d+)?USD$|^US... |
2fc4e8b8d9169c5b65bdd10916d09aca4815e0b4 | Kytusla908/0 | /PY0101EN - Module 1.py | 432 | 3.765625 | 4 | import sys
print(sys)
print(sys.version)
print('Hello, Python') #This line prints a string
print("Hello, Python")
int(2.13423)
type(int(2.13423))
float('6.312')
int(float('6.312'))
type(int(float("6.312")))
type(True)
int(True)
bool(1)
int(False)
bool(0)
type(6/2)
int(6/2)
type(6//2)
#How ... |
264ada37fea019c2880740401087eb1eb94970db | darkbodhi/Some-python-homeworks | /powerOf2.py | 222 | 4.375 | 4 | power = int(input("Please input the required power: "))
x = 1
if not power > 0:
raise Exception("The power should be a positive natural number.")
else:
while x <= power:
print(2**x, end =" ")
x += 1 |
d9b13f539ba748350bf97e6a9bd49129fb6445ca | srcmarcelo/Python-Studies | /PythonTest/ex014.py | 112 | 3.78125 | 4 | """for c in range(1, 11):
print(c)
print('END')"""
c = 1
while c < 11:
print(c)
c += 1
print('END')
|
4b41a0e1871ddf3cdb1ead09ad970a20067e68a6 | Kamil-Jan/Algorithms_and_Data_Structures | /Algorithms/Sorting/counting_sort.py | 763 | 4.0625 | 4 | """
Counting Sort algorithm.
"""
def counting_sort(arr):
# Create empty lists for output and counting
output = [0 for i in range(len(arr))]
count = [0 for i in range(10)]
# Add the count of each elements into count array
for num in arr:
count[num] += 1
# Change count[i] so that cou... |
b32d5904526f5f76ad08453428ca1fa2f46d8aa9 | pcsai23/python-review | /chapter6/exercise6.4.py | 570 | 4.53125 | 5 | #!/usr/bin/env python3
###############################################################################
#
print("\nExercise 6.4\n")
#
# Question 1
# 1. A number, a, is a power of b if it is divisible by b and a/b is a power of
# b. Write a function called is_power that takes parameters a and b and returns
# True if a ... |
43ad26139a1bc68687fdeff31487476f495ff0d2 | knghiem/Visualizing-Fraction | /orbit2.py | 17,173 | 4.125 | 4 | from graphics import *
from math import *
from time import *
from turtle import *
from buttonclass import *
from random import *
def __inputBox(gwin,height):
""" __inputBox(gwin,height) is a hidden construction method
that creates an input box"""
inputBox=Entry(Point(225,height),2)
... |
2b072f327e474f6e9b271665f78ab70d5451c728 | y2k10110/django_facebook | /main/week3_practice2.py | 290 | 3.71875 | 4 | num1 = 21
num2 = 22
if (num1 % 7) == 0:
print(str(num1) + "은 7의 배수입니다.")
else:
print(str(num1) + "은 7의 배수가 아닙니다.")
if num2 % 7 == 0:
print(str(num2) + "은 7의 배수입니다.")
else:
print(str(num2) + "은 7의 배수가 아닙니다.") |
22be5b358e3e96dc950e77f638124d14ea8158c0 | shaunakganorkar/PythonMeetup-2014 | /16.powerof2and3.py | 173 | 4.09375 | 4 | num =float(raw_input("Enter the Number to find its Square and Cube: "))
def square(a):
return a**2
def cube(a):
return a**3
print square(num)
print cube(num) |
5e9e659495999cf1452415663c5913c406a0039b | KotaCanchela/PythonCrashCourse | /7 User input and While statements/Confirmed Users.py | 1,442 | 4.125 | 4 | # Use a while loop to modify a list as you work through it
# Start with users that need to be verified
# and an empty list to hold confirmed users
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users
# Move each verified user into the lis... |
25c77c0ae303f4f79cd969fb504d3318b30bd4f3 | kaslock/problem-solving | /Programmers/[Hash]전화번호 목록.py | 342 | 3.546875 | 4 | from collections import defaultdict
def solution(phone_book):
answer = True
dd = defaultdict(int)
for pb in phone_book:
dd[pb] = 1
for pb in phone_book:
tmp = ""
for i in range(len(pb) - 1):
tmp += pb[i]
if dd[tmp] == 1:
return F... |
389c24539b7201bbd16431b0853ebd9ff70276bd | ash/python-tut | /50.py | 223 | 3.6875 | 4 | def area_of_rectangle(width = 2, height = 1):
print('width=' + str(width))
print('height=' + str(height))
return width * height
print(area_of_rectangle(height=20, width=10))
print(area_of_rectangle(height=10))
|
a8faa8b252c584c4bc8d62cc49859c5f272722b3 | Rebell-Leader/bg | /dd_1/Part 1/Section 10 - Extras/11 -command line arguments/example6.py | 1,213 | 4.46875 | 4 | # simple use of argparse module
# to parse command line parameters, we need to set up a parser object
# and we tell it a few things:
# 1. a description of what the program does that will be displayed
# when the argument is -h or --help. The arg parser will
# automatically add help information for the diffe... |
5636d30e45a9283bdbc35b7366c590ec37f92221 | jenniferwx/CTCI_python | /Chapter1/1_1.py | 641 | 3.90625 | 4 | def isUnique(string):
if len(string)>256:
return False
a = [0]*256
for ch in string:
if a[ord(ch)]:
return False
a[ord(ch)] = 1
return True
def isUnique2(string):
a = {}
if len(string)>256:
return False
for ch in string:
if ch in a:
... |
95e31bd72ee4220a91a2d2ecd6c4cfa560c3cfea | adh2004/Python | /Lab13/RetirementNew/employee_main.py | 845 | 3.921875 | 4 | from employee import Employee
def main():
emp_name1 = ''
emp_salary1 = 0
emp_year1 = 0
sentinel = 0
emp_name1 = input('Enter name: ')
emp_salary1 = float(input('Enter salary: '))
emp_year1 = float(input('Enter years of service: '))
employee1 = Employee(emp_name1, emp_salary1, emp_year1... |
f2370af37c8b8f2e68680d4f7486b1de95089fde | shamuad/python-materials | /simple-examples/12-zar-atma-oyunu.py | 1,005 | 3.953125 | 4 | import random
raw_input("Please user 1 press ENTER for the dices")
user1_dice1 = random.randint(1, 6)
user1_dice2 = random.randint(1, 6)
user1_get_double = False
if user1_dice1 == user1_dice2:
user1_get_double = True
print "User One dice {} - {}".format(user1_dice1, user1_dice2)
raw_input("Please user 2 press ... |
3f84333dbd34458c3183c7a8d62223270601ebdf | Gmeski/traveling-salesman | /simulated_annealing/__init__.py | 4,263 | 3.671875 | 4 | import math
from random import random, randint
import matplotlib.pyplot as plt
from tour import Tour
class SimulatedAnnealing:
_temp = 1000
_cooling_rate = 0.0003
x_graph = []
y_graph = []
ini = None
end = None
best_distance = 0
def __init__(self, window, cities_list, show_window=Tru... |
2602fdc2f06983d4afc2101c5b17aec13b6b33fb | nikita1610/100PythonProblems | /Problem94/Day94.py | 257 | 3.5625 | 4 | from string import punctuation
def get_pnc_count(strng):
return len([ele for ele in strng if ele in punctuation])
def get_list(l):
l.sort(key = get_pnc_count)
return l
l = ["Hello@%^", "Best!"]
a=get_list(l)
print(a)
|
fb47ede2cf623c88bec1040f1c476b1c05789e77 | NearJiang/Python-route | /分数2.py | 488 | 3.84375 | 4 | grades = input('分数:')
num = int(grades)
if 90<num<=100:
print('A')
elif 80<=num<=90:
print('B')
elif 60<=num<80:
print('C')
elif 0<=num<60:
print('D')
while num>100 or num <0:
grades = input('请输入0~100的数字,请重新输入:')
num = int(grades)
if 90<num<=100:
print('A')
elif 80... |
39d02909c0e056b0057501dc2a561f7cb7b6694a | Holysalta/pp2-tsis-3- | /dtribonacci.py | 166 | 4.03125 | 4 | def trib(n):
if n==0:
return 0
elif n ==1 or n ==2:
return 1
else:
return trib(n-1)+trib(n-2)+trib(n-3)
n=int(input())
print(trib(n))
|
56057a5ed7054b9426b5229c9f80b220895b9177 | Scott-Clone/python-practice | /100day/day_6_challenge.py | 2,734 | 3.828125 | 4 | from collections import OrderedDict
import re
from itertools import chain
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jee... |
00e1d749c2508c5f6c75fbe42dc10adaec24aba1 | DrydenHenriques/50-coding-interview-questions | /string/49_Fibonacci-Number.py | 688 | 4.25 | 4 | #!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/2/12'
Given an integer n, write a function to compute the nth Fibonacci number.
fibonacci(1) = 1
fibonacci(5) = 5
fibonacci(10) = 55
Notes: assume n positive number.
'''
def fibonacci1(n):
# recursive
if n == 1 or n == 2:
ret... |
7638fcbd1f9f4614cee1ed1f838ea23e30820a8b | srihariprasad-r/workable-code | /500_Practise Problems/zero_sum_subarray.py | 546 | 3.53125 | 4 | """Input:
{3,4,-1,3,1,3,1,-1,-2,-2}
subarray with 0 sum are:
{3,4,-7}
{4,-7,3}
{-7,3,1,3}
{3,1,-4}
{3,1,3,1,-4,-2,-2}
{3,4,-7,3,1,3,1,-4,-2,-2}
"""
def zero_sum_subarray(array):
prevlist = [0]
occurance = {}
for i in array:
prevlist.append(prevlist[-1]+i)
for j in prevlist:
if j in ... |
7319140dc7de78a11bcb1a3aebb249aef17c5d4a | jjkr/puzzles | /kadane.py | 813 | 3.796875 | 4 | # Given an array of integers, find contiguous subarray within it which has the largest sum.
# For example,
# Input: {-2, 1, -3, 4, -1, 2, 1, -5, 4}
# Output: Subarray with the largest sum is {4, -1, 2, 1} with sum 6.
def kadane(arr):
assert(len(arr) > 0)
max_start = 0
max_end = 0
max_sum = arr[0]
... |
6660595445834ed69902aa75d645960e0813e656 | cskamil/PcExParser | /python/py_functions_multiple_parameters/challenge/1/multiple_parameters_ch.py | 3,853 | 4 | 4 | '''
@goalDescription(Construct a program that calculates the pay and current savings.)
@name(Multiple Parameters)
@distractor{code(paycheck = calculatePay()), helpDescription()}
@distractor{code(paycheck = calculatePay(food)), helpDescription()}
@distractor{code(current_savings = paycheck), helpDescription()}
@di... |
1d90fbfc1716d7e23a0781651ff0b65cb8f5a919 | lunar-r/sword-to-offer-python | /剑指offer/35 第一个只出现一次的字符.py | 1,495 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
File Name: 35 第一个只出现一次的字符
Description :
Author : simon
date: 19-2-25
"""
# -*- coding:utf-8 -*-
# class Solution:
# def FirstNotRepeatingChar(self, s):
# # write code here
# if not s:
# return
#
# strlist = list(s)
# ... |
e60de006c405b1c93298e36af08b2427420ee273 | yangbaoxi/dataProcessing | /python/JSON/jsons.py | 1,220 | 3.78125 | 4 | # JSON 与 Python 数据类型对应表
# Python => JSON
# dict => object
# list\tuple => array
# str => string
# int, float, int- & float-derived Enums => number
# True => true
# False => false
# None => null
# JSON => Python
# object => dict
# array => list... |
dcb5bfe03ec6c86f544f592fb778d0ce3ac8f6cd | rainieluo2016/TextMiningCMU | /CollaborativeFiltering/eval_rmse.py | 1,634 | 3.828125 | 4 | #!/usr/bin/python3
import sys
import math
def main():
"""main"""
# the first argument is our golden file
golden_in = open(sys.argv[1], 'r')
# test is the second arg
test_in = open(sys.argv[2], 'r')
line = 0
error = False
E = 0.0
num_ratings = 0
while True:
g_line =... |
5ad9ac896aa31c2874781404b12874b4ae3e109b | Thespunkiller/Learn-Python | /Skole/Dag 3 loops/Øvelse1.py | 204 | 3.609375 | 4 | # val = ("hej")
# i = 0
# # while i<5:
# # i+=1
# # print(i*val)
# for i in range (0,5):
# i+=1
# print(i*val)
inp = input()
n = 5
new = ""
for i in range (n):
new += inp
print (new)
|
e7ed0839d372eb166297d4cb6352e400379eb2cf | Seba5404/DSC-430-Python-Programming | /Assignment 4/A4_P4_SZ.py | 16,296 | 3.8125 | 4 | #November 6th, 2018 Sebastian
# I have not given or received any unauthorized assistance on this assignment.”
import random
import math
class ellipse(object):
'Class that holds ellipse information'
def __init__(self,Major,Minor):
'Set up the primary numbers to calc the ellipse, major and minor a... |
806d001e343ffd7a637608b61263fb0aa3476fb5 | webclinic017/pyTrade-ML | /src/pytrademl/strategies/strategy_template.py | 1,324 | 4.1875 | 4 | """!
This contains the generic template for any trading strategy.
All custom trading strategies are to inherit this class and implement the run_strategy method.
"""
from abc import ABC, abstractmethod
class Strategy(ABC):
"""
This is the generic Stategy class.
This class is inherited by all implemented s... |
b8adb8b815615f8124eb31298e8bb85163e0f792 | ks2842/keerthikaa.py | /80.py | 81 | 3.6875 | 4 | k=input()
k=list(k)
for x in k:
x=int(x)
if x % 2 !=0:
print(x,end=" ")
|
9099b4ccf6ed27908a81a186e247b1daf23a39ca | RohithR13/Python_tutorials | /New folder/New folder/newer.py | 505 | 3.734375 | 4 | import json
from typing import Dict
def search_id(item):
for keyval in items:
if (item == keyval["manager_id"]):
print( keyval["emp_id"]," "+keyval["name"])
return True
with open('empj.json')as json_data:
items= json.load(json_data)
item =input("enter the... |
6d95dca24c4d5ccba084a35586e73bbc7b80cca3 | kohrongying/room-cleaner | /python/robot_test.py | 1,479 | 3.53125 | 4 | import unittest
from robot import Robot
class RobotTest(unittest.TestCase):
def setUp(self):
self.robot = Robot()
def test_set_initial_robot_position(self):
customRobot = Robot(1, 2, 'E')
self.assertEqual((1, 2, 'E'), customRobot.get_current_state())
def test_get_current_state(... |
efc9fa8315240a7ce80079c2774f23f1a2fe7076 | mluisas/ProgLab | /dividindooimperio.py.py | 502 | 3.734375 | 4 | n = int(input())
adj = {}
for i in range(n - 1):
x, y = input().split()
if x not in adj.keys():
adj[x] = [y]
else:
adj[x].append(y)
if y not in adj.keys():
adj[y] = [x]
else:
adj[y].append(x)
# A ideia seria fazer uma lista com os vértices adjacentes e p... |
6004b6366ac5ea86433787a1c3356f2031dae171 | NelsonBurton/EZProgrammingChallenge | /question3.py | 1,442 | 3.609375 | 4 | import copy
class Animation:
def change_to_x(self, list):
out = ""
for i in range(len(list)):
if list[i][0] == 'L' or list[i][1] == 'R':
out += "X"
else:
out += "."
return out
def all_dots(self, list):
for i in range(len(l... |
0e88fc87269bbd8f813aa3886a4b3f0ac7665ff3 | r1zon/exceptions | /polska.py | 1,283 | 4.0625 | 4 | class LenError(Exception):
pass
def action(a,b,c):
if c == '+':
print(int(a) + int(b))
elif c == '-':
print(int(a) - int(b))
elif c == '*':
print(int(a) * int(b))
elif c == '/':
try:
print (int(a) / int(b))
except ZeroDivisionError:
pr... |
bc11da046803ce184352bfd98888c54b6350d271 | afairlie/katas | /find-smallest.py | 405 | 4.03125 | 4 | def find_smallest(arr):
smallest = arr[0]
for n in arr:
if n < smallest:
smallest = n
return smallest
print(find_smallest([78, 56, 232, 12, 11, 43])) # 11
print(find_smallest([78, 56, -2, 12, 8, -33])) # -33
# better solution
def find_smallest_int(arr):
return min(arr)
print(find_smallest_int([78,... |
4dd10dfa345db365d21af83155c12f774c223d0c | ROXER94/Project-Euler | /046/46 - Goldbach'sOtherConjecture.py | 720 | 3.859375 | 4 | # Calculates the smallest odd composite that cannot be written as the sum of a prime and twice a square
def isPrime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... |
6691199355dfe2e7557179098ce457becc99deb2 | Elephantxx/gs | /04_函数/x_08_打印分割线.py | 530 | 4.25 | 4 | # 需求1:定义一个print_line函数,能够打印 * 组成的一条分隔线
def print_line1():
print("*" * 50)
print_line1()
# 需求2:定义一个函数,能够打印 任意字符 组成的一条分隔线
def print_line2(char):
print(char * 50)
print_line2("-")
# 需求3:定义一个函数,能够打印 任意重复次数 的一条分隔线
def print_line3(char, times):
print(char * times)
print_line3("+", 30)
# 需求4:定义一个函数,能够打印 5行 分... |
568ddfe70fe9f2818a8c80653cfb9b64aa67cef9 | pjbardolia/miniprojects | /binaryToDecimal.py | 1,191 | 4.0625 | 4 | def get_input(question):
return int(input(question))
def get_squares(digits):
mylist = []
i = 0
while i < digits:
mylist.append(2 ** i)
i += 1
return mylist
def main():
binaryNoList = []
FinalDecimal = []
theNumber = get_input('Enter a binary number in either 1 or 0... |
896e6df34da44b80049fb387a5320571bb28c442 | Big-d1pper/homework | /lesson10.py | 2,035 | 3.703125 | 4 | class Bird:
def __init__(self, name="Kesha"):
self.name = name
def flight(self):
print(f"{self.name} Flight now!")
def walk(self):
print(f"{self.name} Walk now!")
class Raccoon:
def make_some_destroy(self):
# self.steel()
print("Raccoon make some wierd stuff... |
1ec9a4ee2aae7e3ecb389925fbdfb2cdecc542ce | pengxingyun/learnPython | /basePython/IO/stringIO.py | 254 | 3.53125 | 4 | from io import StringIO
# 写入内存
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world')
print(f.getvalue()) # getvalue()方法用于获得写入后的str
# 读取StringIO
while True:
s = f.readline()
if s == '':
break
print(s.strip())
|
0892948cc0068771e09afaaa73565f596439a8c8 | Vahid-Esmaeelzadeh/CTCI-Python | /Chapter5/Q5.6.py | 405 | 4.46875 | 4 | '''
Conversion : Write a function to determine the number of bits you would need to flip to convert
integer A to integer B.
EXAMPLE
Input: 29 (or: 11101), 15 (or: 01111)
Output: 2
'''
def conversionBitsCount(a: int, b: int):
c = a ^ b
count = 0
while c != 0:
c = c & (c-1)
count += 1
... |
fa3143a0a938b39e82960f23171d9955db9543e3 | miko73/codity | /FibFrog.py | 1,805 | 3.515625 | 4 | def fib(n=25):
# there are 26 numbers smaller than 1000
f = [0] * (n)
f[1] = 1
for i in range(2, n):
f[i] = f[i - 1] + f[i - 2]
print("fib - {}",f)
return f
## projedu si zadané pole pozic updatnu si to poctem skoků na kolik nejméně se tam dá dostat ?
def solution(a):
a.insert(0... |
f37b29be438ebc36aa9098003259bfe30e8b0f97 | JinshanJia/leetcode-python | /Decode Ways.py | 1,024 | 3.90625 | 4 | __author__ = 'Jia'
'''
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) ... |
9e1fbc1469e5fe3152abbe8681fd0bb0388c5e88 | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/03_Conditional-Statements-Advanced/00.Book-Exercise-4.1-06-Point-on-Rectangle-Border.py | 972 | 4.3125 | 4 | # точка върху страна на правоъгълник
# Да се напише програма, която проверява дали точка {x, y} се намира върху някоя от страните на правоъгълник {x1, y1} - {x2, y2}.
# Входните данни се четат от конзолата и се състоят от 6 реда: десетичните числа x1, y1, x2, y2, x и y (като се гарантира, че x1 < x2 и y1 < y2).
# Да се... |
365c75a5b6d3a7315a6704fc9a6a977bd1fbe470 | ffvv0123/SchoolActivities | /파이썬 수업 복습/Ch.3/종달새가 노래할까.py | 564 | 3.8125 | 4 | import random
time = random.randrange(24)
weather = random.randrange(4)
print("지금 시간은",time,"시 입니다.")
if weather == 0 :
print("지금 날씨는 화창합니다.")
elif weather == 1 :
print("지금 날씨는 흐립니다.")
elif weather == 2 :
print("지금 날씨는 비가 옵니다.")
elif weather == 3 :
print("지금 날씨는 눈이 옵니다.")
if ... |
0be22873ed1b1e82d6e5f888e93072ed2defcab8 | afridig/SeleniumAutomation_Python | /assertionTest5.py | 1,045 | 3.625 | 4 | #relational comparisons
#assertGreater
import unittest
class Test(unittest.TestCase):
def testName(self):
#self.assertGreater(100,10) #positive test --> test passes
#self.assertGreater(10,100) #negative test --> test fails
#assertGreaterEqual
#self.assertGreaterEqual(10... |
96193199dfad8ee530c4ce5f2ed38f9d6807eb25 | LucioMaximo/SimpleChallenges | /WordCensorer.py | 701 | 4.28125 | 4 | # Create a function that takes a string txt and censors any word from a given list lst.
# The text removed must be replaced by the given character char.
# e.g censor_string("Today is a Wednesday!", ["Today", "a"], "-") ➞ "----- is - Wednesday!"
# difficulty: Hard
censoredwords = ["Today", "a", "cow", "over", "did", "c... |
8a94220e5e87be64d273bbf8146187133e9ccdf3 | pra-kri/old_pra-kri.github.io | /ToyNeuralNetwork.py | 3,396 | 4.34375 | 4 | """
A Neural Network from scratch in Python (only using Numpy)
Quick toy example of a NN in Python, to learn about backpropagation
Note that there is no 'bias' term in any of the neurons. Only have weighted inputs.
References:
http://iamtrask.github.io/2015/07/12/basic-python-network/
https://brilliant.org/wiki/backp... |
b9ec629fa6b510756e8cabf05966783e6c9b5bb7 | AbirRazzak/MyScripts | /Advent_Of_Code/Advent2020/01/main.py | 1,298 | 4.25 | 4 | from typing import List, Tuple
def convert_file_to_list(
filename: str
) -> List[int]:
file = open(filename, 'r')
values = []
for line in file:
values.append(int(line))
return values
def find_two_numbers_that_add_up_to_2020(
numbers_list: List[int]
) -> Tuple[int, int]:
f... |
1ee9a550e496b2dfc123078873252301a7d93c31 | jduchimaza/A-December-of-Algorithms-2019 | /December-02/credit_card.py | 1,555 | 3.9375 | 4 | '''
Problem
Are credit card numbers just a random combination of the digits from 0-9? NO!
Credit card numbers are a systematic combination of numbers that can satisfy a single test. This test is created so that errors can be avoided while typing in credit card numbers as well as detect counterfeit cards!
The algorithm... |
ae2818ddb328903a083bee15d86ced062b8281b3 | luangcp/Python_Basico_ao_Avancado | /map.py | 1,556 | 4.65625 | 5 | """
Map -
Com Map, fazemos mapeamento de valores para a função.
"""
# -*- coding: UTF-8 -*-
import math
def area(r):
""" Calcula a área de um circulo com raio 'r'. """
return math.pi * (r ** 2)
print(area(2))
print(area(5.3))
print('\n')
raios = [2, 5, 7.1, 0.3, 10, 44]
# Forma comum
areas = []
for r in r... |
f0a2415f62a65432e779b4f454df4c8c52b121a2 | Adityalio/class103 | /scatter.py | 188 | 3.671875 | 4 | import pandas as pd
import plotly.express as px
df = pd.read_csv("data.csv")
fig = px.scatter(df, x="Population", y="Per capita",color="Country",size="Percentage")
fig.show()
|
4e77648c4279d65763d3b3cdedc4674833d2df7a | JunDang/PythonStudy | /power.py | 190 | 4 | 4 | def square(x):
result = 1
for turn in range(2):
#print('iteration: ' + str(turn) + ' current result: ' + str(result))
result = result * x
return result
print square(3)
|
27c70a6684449763a0cc657bab24a7c63c75208c | Bye-lemon/DUT-CS-Homework | /Python Language Programing/Char Counter.py | 202 | 3.984375 | 4 | # ChapCounter
def count_letter(str, ch):
count = 0
for char in str:
if char == ch:
count += 1
return count
string=input()
char=input()
print(count_letter(string,char))
|
1746138520de9eed939ccd72d5fbf8e7bde42b7e | slick514/image_processing | /detect_faces.py | 707 | 3.828125 | 4 | # import the necessary packages
import cv2
# load our image and convert it to grayscale
image = cv2.imread("images/orientation_example.jpg")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# load the face detector and detect faces in the image
detector = cv2.CascadeClassifier("/usr/local/share/OpenCV/haarcascade... |
151d55f32a2c27f9262217269624275322ed08c3 | rohan-singhvi/digit-recognizer-ML | /train_data.py | 3,267 | 3.6875 | 4 | import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.utils import np_utils
import matplotlib.pyplot as plt
# loa... |
6dd7232ee36685b6e0645d2ce12d220398fba865 | kajankowska/homework | /schoolbase.py | 3,305 | 4.03125 | 4 | # Program that supports the school base
# Assign three types of users to classes and a teacher to a subject
import sys
phrase = sys.argv[1:]
print(sys.argv)
# lists and dictionaries:
educators = {}
teachers = {}
students = {}
school_class = {}
class_list = []
class_data = []
users = "uczeń", "... |
a7b8a37b508a969a715763e9c387bacabd7f288d | Barracas-azazaza/Curso-principiante-Python | /number.py | 229 | 3.609375 | 4 | 10
14.4
print(type(9))
print(type(10.1))
print(1+1)
print(2**3)
print(3//2)
print(3%2)
age=input("insert your age: ") #hace la función del cout y del cin
age=int(age)+5
new_age=int(age)+5
print(age)
print(new_age)
5 |
d8edb70fdabe88f9e86223ad4feda897382e9b50 | manuwhs/Coursera-Codes | /Algorithms and Data Structures/2.1 Directed and Undirected Graphs/CDiGraph.py | 2,103 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 3 12:12:59 2016
@author: montoya
"""
import numpy as np
class CGraph():
def __init__(self, V, directed = False): #create an empty graph with V vertices
self.V = V # Number of vertex
self.G = [] # G is a list of lists G[N][E]. It contains,for ev... |
c2d4eee51b4f24d3b1903f70384ad921a50b6940 | paul-manjarres/coding-exercises | /python/com/jpmanjarres/hackerrank/warmup/CircularArrayRotationEasy.py | 1,198 | 3.609375 | 4 |
# Algorithm is correct, but Python is not fast enough
'''Rotates the array'''
def rotate(a, k):
if k<=0:
return a
l = len(a)
effective_rotations = k
right = True
#print("k: %s len: %s" % (k,l))
if k > l :
effective_rotations = k % l
if k > l/2:
right = False
... |
861c0f5c4813025f75ee28e4e372c80d6427903e | Tsarcastic/Python-Mini-Projects | /fibonacci_sequence.py | 222 | 3.8125 | 4 | list = [0, 1]
for x in range(0, 10):
new = list[-2] + list[-1]
list.append(new)
print list[0]
print list[1]
print list[2]
print list[]
answer = int(raw_input('Which number in the sequence?'))
print list[answer]
|
9b5b96c4229c1d4f9e58f5d84208161f88a484e5 | 101156/101156 | /PR1/PR1.py | 600 | 3.921875 | 4 | #Задание 1
a = 5
b = 10
a += b
b = a - b
a -= b
print(a,b)
#Задание 2
c=0
d = int(input())
while d > 0:
c += d % 10
d //= 10
print(c)
#Задание 3
print("Введите коэффициенты ")
print("ax^2 + bx + c = 0:")
a = float(input("a = "))
b = float(input("b = "))
c = float(input("c = "))
D = b ** 2 - 4 * a * c
print(... |
fb634ff5c40f9a61086dfa48cce07176a0613cef | Shivanshu10/Coding-Practice | /Hackerrank/Mini-Max Sum/code.py | 394 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
arr.sort()
mi = 0
ma = 0
n = len(arr)
for i in range(4):
mi += arr[i]
ma += arr[n-i-1]
print(str(mi) + " " + str(ma))
if __name__ == '__main__'... |
de8fb5631e135c098dc8cc3325915ed904a283b8 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/RepetitionLoops/sentinelpracitce.py | 665 | 4.09375 | 4 | # This program displays property taxes
# calc property tax on multiple properties, loop using number 0 as a sentinel value
# TAX_FACTOR is used as a globa
TAX_FACTOR = .0065
# The main function
def main():
print("Enter the property lot number or 0 to end")
lot = int(input("Lot number: "))
... |
652229c7a22c94565791fb1ee0ab837337e956e8 | rubelbd82/Machine-Learning | /Python/ann_my.py | 2,326 | 3.546875 | 4 | # Artificial Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# Install Tensorflow from the website: https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html
# pip install tensorflow
# Installing Keras
# pip install --upgra... |
684570add281f71baebb0f6cfb30ddf2ba61cc31 | harrifeng/Python-Study | /Leetcode/Sum_Root_to_Leaf_Numbers.py | 1,919 | 4.21875 | 4 | """
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12... |
e4e0342b5fa78f19ed9b7e87a873bab7bb5b9f9b | YiannisVasilas/Project | /P3_Ioannis.py | 2,627 | 3.59375 | 4 | #!/usr/bin/env python3
"""
Author: Ioannis
Author : Anastasia
Student Number:
This python script has to parse a GenBank file and outputs a FASTA file
and an ordered table with detail statistics
"""
from sys import argv
import subprocess
import os.path
from operator import itemgetter
def record_finder(lines):
... |
8c3a851609031423c4c6f8d123d490377737805a | sailepradh/Python_practise | /Script/day4.py | 333 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def dist(x1,x2,y1,y2):
d = ((x2-x1)**2) + ((y2-y1)**2)
return math.sqrt(d)
def calculte_angle(x1,x2,y1,y2):
d = ((x2-x1)**2) + ((y2-y1)**2)
a = math.acos((x2-x1)/d)
return a
test1 = dist(2,5,8,10)
test2 = calculte_angle(2,5,8,10)
print ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.