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 |
|---|---|---|---|---|---|---|
40da06e6cafdf80c4c5e513e45df39f05ed904b3 | emanuelfeld/advent-of-code-2017 | /day_04/main.py | 1,151 | 3.5625 | 4 | with open('input.txt', 'r') as infile:
data = infile.readlines()
data = [row.split() for row in data]
# part 1
def is_valid_1(row):
return len(row) == len(set(row))
def part_1(data):
return sum([is_valid_1(row) for row in data])
def test_1():
assert is_valid_1('aa bb cc dd ee'.split()) == Tr... |
97801fad6e272de3c1f1e41528095ffd871508f1 | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/22 MID EXAM - Дата 2-ри ноември/Group 2 (My Group)/03. Tanks Collector.py | 4,465 | 3.625 | 4 | """
Programming Fundamentals Mid Exam - 2 November 2019 Group 2
Check your code: https://judge.softuni.bg/Contests/1862/Programming-Fundamentals-Mid-Exam-2-November-2019-Group-2
SUPyF2 P.-Mid-Exam/2 November 2019/2. - Experience Gaining
Problem:
Tom is a world of tanks player and he likes to collect premium ta... |
3e247a0be9bcec16c53d3260e78e4b3b93b1f83c | jmgc/pyston | /test/tests/boolops.py | 1,167 | 3.578125 | 4 | def f(msg, rtn):
print msg
return rtn
n = 0
while n < 64:
i = n & 3
j = (n >> 2) & 3
k = (n >> 4) & 3
print f('a', i) and f('b', j)
print f('a', i) or f('b', j)
print f('a', i) and f('b', j) and f('c', k)
print f('a', i) and f('b', j) or f('c', k)
print f('a', i) or f('b', j) a... |
b0ae0a60c7bb4ec45dc74e2c860b3de5d9ec763c | JeonSuHwan/StudyingPython | /Chapter4/h4_1.py | 156 | 4.1875 | 4 | num=int(input("Enter number : "))
count=0 #number of digits
while num>0:
count+=1
num//=10
print("The number of digits in the number is :",count)
|
ac7860e98d6e4f61c49fdb6dbd4025a9c5ecba5a | abbhowmik/PYTHON-Course | /chapter 10.py/constructor.py | 907 | 3.9375 | 4 | class Employee:
company = 'Google'
def __init__(self, name, salary, subunit):
self.name = name
self.salary = salary
self.subunit = subunit
print('Employee is created!')
def getDetails(self):
print(f'The name of the employee is {self.name}')
print(f'The salar... |
d5b135739b40cb2ca034d69a6a26c52fc9930ee5 | harshadevireddy/Instacart-Product-Recommendation | /EDA.py | 8,866 | 3.671875 | 4 |
# coding: utf-8
#import libraries and modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
color = sns.color_palette()
plt.style.use('ggplot')
#load and read all six csv datasets as dataframe objects and then look into them
# aisles.csv -- contains aisles identifier ... |
7259e49c97fba352f431fec1bcd24c01cb3a03cf | charan2108/pyprocharmprojects | /pythoncrashcourse/crashcourse/inputs/inputs.py | 221 | 4.03125 | 4 | name =input("Enter your name\n")
age =int(input("Enter age\n"))
city =input("Enter city\n")
email =input("Enter email\n")
print(f"your name is {name} \n and age is{age} \n and city is{city}\n and email is {email}\n")
|
07afea790adfa8625ea3983bd8fb4ab90bfe5d03 | khatoonfatima/Python-Programming | /Recursive Function.py | 5,175 | 4.84375 | 5 | #!/usr/bin/env python
# coding: utf-8
# # RECURSIVE FUNCTION
# A function that calls itself is known as Recursive Function
# Example:
# factorial(3)=3*factorial(2)
#
# =3*2*factorial(1)
#
# =3*2*1*factorial(0)
#
# = 3*2*1*1
# ... |
a36d7ec6f2760bfb814c09424395027f24cfaf8d | ryanpbrewster/Python-Tic-Tac-Toe | /src/AI.py | 2,988 | 4.1875 | 4 | """
A class containing all of the logic for an AI that plays TicTacToe
A note on the way the static and non-static methods work in this class:
* Static methods take a board, a tac to check, and a position, and return an
evaluation (true or false).
* Non-static methods, however, are called by an instance of the AI c... |
7fa74a7e2632d59652adcc411374558c81311f65 | jonathanshuai/solid | /liskov_substitution_principle/animal.py | 1,022 | 4.125 | 4 | """This animal class is to look at Liskov Substitution Principle.
The Liskov substitution principle says a sub-class must be substitutable for its
super class. In other words, we should be able to put a subclass in place of a
super class and run without errors.
"""
# We have our animal class again. Let's say we want... |
913dfc4cce717fcad35331ee2d957995b11d9b8f | ramador0010/github-upload | /for.py | 67 | 3.71875 | 4 | for i in range(2,8,3):
print("The Value of i is currently:",i)
|
402c6d71acb6fb65a1cc4d390fbf2b062b4d7cef | oneiromancy/leetcode | /medium/1315. Sum of Nodes with Even-Valued Grandparent.py | 1,361 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def sumEvenGrandparent(self, root):
nodes = [root]
total = 0
while nodes:
currentNode = nodes.pop()
... |
599285ff90828874c7e8e654f9feb26e5fae7fc1 | jbeaulieu/MIT-ES.S70 | /lecture_9/group_9_with_plot.py | 2,827 | 3.65625 | 4 | #################################
# Title: Lecture 9 Group Script #
# Lesson: Magnetic Field/Force #
# Filename: group_9.py #
# Original Author: Joe Griffin #
# Most Recent Edit: 2/6/2014 #
# Last Editor: Joe Griffin #
#################################
# This script calculates positions, velocities, and accel... |
a11a919f3ab831162d61becfe7962f48ebf7fe2c | margaridav27/feup-fpro | /PEs/PE02 model/genealogy_by_order.py | 1,006 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 09:06:34 2019
@author: Margarida Viera
"""
def rule(item):
name, relation = item
order = ('sibling', 'parent', 'cousin', 'grandparent').index(relation)
return order, name
def genealogy(l):
tree = sorted(l, key = rule, reverse = False)
retu... |
d74ef1fc6f148ad2ca7ce4a39c567e2e512078bd | zhangchizju2012/LeetCode | /134.py | 786 | 3.515625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 6 19:57:49 2017
@author: zhangchi
"""
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if len(gas) == 0:
... |
50439f98a547e1d8290d8344941c5fc1955cb302 | SanchoMontana/Pong | /Pong.py | 7,995 | 3.671875 | 4 | import pygame
from time import sleep, time
if __name__ == '__main__':
from Paddle import Paddle
from Ball import Ball
from PowerUp import PowerUp
DISPLAY_WIDTH = 1200
DISPLAY_HEIGHT = 700
PADDLE_GAP = 60
PADDLE_GIRTH = 20
PADDLE_SPEED = 8
BALL_RADIUS = 25
BALL_START_VEL = 10
FPS = 80 # Frames per second... |
c0d019032a6cd01633a5b5d95591e5e3f5515c18 | hellwarrior-2/codewarskatas | /delet_ocurrences_nth.py | 1,415 | 4 | 4 | #Exercise 6 kyu
#Delete occurrences of an element if it occurs more than n times
#Enough is enough!
#Alice and Bob were on a holiday. Both of them took many pictures
#of the places they've been, and now they want to show Charlie their
#entire collection. However, Charlie doesn't like this sessions, since
#the motive... |
6ea6e432f9fdd0b08e4f6e4e423ee68d8dfc4e58 | WilliamKulha/learning_python | /looping_lists/pizzas.py | 483 | 4.34375 | 4 | pizzas = ['Margherita', 'Sicilian', 'Neopolitan']
for pizza in pizzas:
print(pizza)
for pizza in pizzas:
print(f"Oh my god! Have you tried their {pizza} pizza?? It's to die for!\n")
print("\nMan I really love pizza!")
friends_pizzas = pizzas[:]
pizzas.insert(0, 'Meat Lovers')
friends_pizzas.insert(0, 'Supreme... |
19a0215529eeb6f5f22994b5c2ae40be41e7c862 | CrtomirJuren/pygame-projects | /array_backed_grid/array_backed_grid_oop_2.py | 2,860 | 4 | 4 | """Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 33:00
"""
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLU... |
5a49402162b5e6f00e4fe5df8c3e753decc41939 | i-m-alok/ProblemvsAlgorithm | /Problem2/problem2.py | 2,333 | 4.0625 | 4 | def find_pivot(arr):
# count=0
start=0
end=len(arr)-1
while start <= end:
# count+=1
# print(count)
mid= ( start + end ) // 2
#if mid+1 is less than mid it means pivot is arr[mid]
if arr[mid] > arr[mid + 1]:
return mid+1
#if start is less than ... |
82487afd9df120a41346622f187bd61582425027 | jgneshbpatel/Python | /PrimeNumber.py | 675 | 4.09375 | 4 | #FileName: PrimeNumbers.py
#Defining function to get prime numbers till provided number
def func(n):
primeNumbers=[]
for x in range(n+1):
i=1
count = 0
while i<=x:
if x%i==0:
#print ('x is:', x)
#print ('i is:', i)
... |
0dbf9880f2da2d2688bc0f52155641991b8f3dfb | fooSynaptic/exam | /Coding/find_mid.py | 276 | 3.609375 | 4 | #py3
import random
arr = [random.randint(0,50) for i in range(100)]
print(arr[len(arr)//2])
def findmid(arr):
fast, slow = 0, 0
while fast < len(arr):
slow += 1
fast += 2
#print(slow ,fast)
return arr[slow]
print("res:",findmid(arr)) |
ceb493998373c96c18b3aba20b0f58b3d96cdc9c | daniel-reich/ubiquitous-fiesta | /KExMohNcKkJYeTE2E_18.py | 184 | 3.796875 | 4 |
def is_orthogonal(first, second):
if len(first)==2:
return first[0]*second[0]+first[1]*second[1]==0
else: return first[0]*second[0]+first[1]*second[1]+first[2]*second[2]==0
|
f41ccb3b5e4dc9113c92bca4b931e917bc86d821 | Guikaio/algorithms | /python/Sequencial/exc2.py | 653 | 4.28125 | 4 | #2.Faca um programa que receba tres notas, calcule e mostre a media aritmetica entre elas.
print("********************SEQUENCIAL*************************")
print("********************Programa*2*************************")
print("************Calculo da média aritmética. **************")
print("***************************... |
52c3980cfc3e1623f4c4f6a52f01047c4bf5c432 | rafaelmm82/learning | /datacamp/case_study_hacker_statistics.py | 1,656 | 4.25 | 4 | """
Application of initial functions, packages and libraries associated with
datascience using python, course:
"Intermediate Python for Data Science"
This project concerns on simulate a random walk through the floors stages on
Empire State Building, by rolling a virtual dice
code conducted by: datacamp
cod... |
64fea56b6c0e81f643e2d490f0ecf709482305d0 | babilonio/CodingGame | /twoegg.py | 507 | 3.953125 | 4 |
#A building has N floors. One of the floors is the highest floor an egg can be dropped from without breaking.
#If an egg is dropped from above that floor, it will break. If it is dropped from that floor or below, it will be completely undamaged and you can drop the egg again.
#You are given two identical eggs, find th... |
42e019ddb2d388374706174ff0c46456accd2380 | gabriellaec/desoft-analise-exercicios | /backup/user_344/ch48_2019_04_05_01_39_10_703847.py | 251 | 3.59375 | 4 | mes=['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro']
n=[1,2,3,4,5,6,7,8,9,10,11,12]
a=input('Qual numero mes? ')
i=0
while i<len(n):
if mes[i]==n[i]:
print(n[i])
i+=1
|
6018f7656cdbd52c7decec68a02cba4f50fa2508 | ootz0rz/tinkering-and-hacking | /2021/LeetCode/AlgoIII/1231 Divide Chocolate v2.py | 3,826 | 3.828125 | 4 | # https://leetcode.com/problems/divide-chocolate/
"""
we want to optimize for the biggest chunk we can make from any slicing
of sweetness into k+1 slices, such that the chunk is also the smallest
from all the other chunks in that current slicing
if k = 0, then there is only 1 slice with min sweetness = sum(sweetness)
... |
01239082b1edd108cd72e351a9be7a6c85090422 | yaodeshiluo/python_cookbook | /1_12.py | 677 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 序列中出现次数最多的元素
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my... |
fffa1e7215495b0189420275b56c2abbc60803e4 | eduardoquerido/turtle_graphics | /desenhos/spectral_harmonograph/spectrahamonograph.py | 27,491 | 3.796875 | 4 | # ------------------ First section: import statements -----------------
import math
import random
import turtle
from tkinter import *
# ------------------ Second section: global variables -----------------
firstWindow = None
secondWindow = None
errorWindow = None
# ------------------ Third section: function definiti... |
aa6882d3278ceb70c485c83266786dda9bf572df | karsevar/Crash_Course_Python- | /CCpython_ch9_part2.py | 9,597 | 4.40625 | 4 | ##Modifying an attribute's value through a method:
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
... |
99b92b8bd2b42df98e09a722f64ab12bb18bb44b | AIGW/1807 | /02.04day/02-保护对象属性.py | 297 | 3.546875 | 4 | class Dog():
def __init__(self):
self.__age = 0 #私有方法
def sleep(self):
print('sleep')
def setAge(self,age):
if age > 15 or age < 1:
print("年龄不符合")
else:
self.__age = age
def getAge(self):
return self.__age
hsq = Dog()
hsq.setAge(10)
print(hsq.getAge())
|
36dd370370d89bdfe80ff50d51c1b29a5669d2d3 | pierreforstmann/mpc | /pg_update.py | 1,481 | 3.53125 | 4 | #
# pg_update.py
#
# Python code to update PG table
#
# $ python3 pg_update.py
#
# Copyright Pierre Forstmann 2023
#------------------------------------------------------------------------------------------------
import psycopg2
import argparse
import pg_connect
def update_item(p_item: int, p_price: float, p_brand: s... |
8df7a6b7614b597594982392c5f6937cfcca3768 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3986/codes/1592_1800.py | 156 | 3.6875 | 4 | a=int(input("valor de a: "))
b=int(input("valor de b: "))
c=int(input("valor de c: "))
l= ((a ** 2)+ (b ** 2) + (c ** 2)) / (a + b + c)
print(round(l, 7))
|
6754cbe7918fe67883ea2e86029a29bc6af7a14d | henriquebraga/katas | /katas/fizzbuzz.py | 658 | 3.828125 | 4 | # not multiple: return own number
#multiple of 3: return fizz
#multiple of 5: return buzz
from functools import partial
multiple_of = lambda base, num : num % base == 0
multiple_of_3 = partial(multiple_of, 3)
multiple_of_5 = partial(multiple_of, 5)
def robot(pos):
say = str(pos)
if multiple_of_3(pos):
... |
d7e57caa33a190d0146e89ded586bf2b8245e6b6 | CNikiforuk/CS3130 | /ass1/main.py | 1,566 | 4.125 | 4 | #!/usr/bin/env python3
import sys
import db
################--Description--#################
#Basic employee database example main run file.
################-----Author-----#################
#Carlos Nikiforuk
ID, FIRST, LAST, DEPT = range(4) #FIELD defines, 0-4
MAXNAMESIZE = 11 #Max na... |
1be45e0e94498939c1dafe1d91eae8354ea4411b | derek-damron/tictactoe | /tictactoe/tictactoeboard.py | 4,584 | 3.828125 | 4 | from copy import copy
class tictactoeboard:
"""Current board stored as a dictionary with the following keys:
```
11 | 12 | 13
------------
21 | 22 | 23
------------
31 | 32 | 33
```
Where the shorthand is:
- First number is the row starting at the top
- Second num... |
e7d526fb9a88fcbb22ca7d1f22b8a4871b0b4a75 | liusu042/gbase_tools | /del_utf8_to_fixed_len_gbk/check_length_for_lines.py | 676 | 3.875 | 4 | #!/usr/bin/env python
# encoding:utf8
# @FileName: check_length_for_lines.py
# @Author: liulizeng@gbase.cn
# @CreateDate: 2017-12-03
# @Description: check length of each line.
import sys
def check_length_for_lines(filename):
result = {}
with open(filename) as f:
for line in f:
lineLength... |
725acc81315e8fb43ec4ebf5b569b044f7e4bf4d | Programwithurwashi/calculator | /calculator.py | 886 | 4.1875 | 4 | def addition(first,second):
return first+second
def Substraction(first,second):
return first-second
def Multiplication(first,second):
return first*second
def division(first,second):
return first/second
print('''Enter the operation to be performed:
1> Addition
2> Subtraction
... |
ff18af7b701d78c27f64b7cbabae36e06928bd11 | sbsreedh/Design-1 | /minStack.py | 1,641 | 3.78125 | 4 | #Time Complexity : pop:O(1), top:O(1) , push:O(1), getMin: O(1)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode :Yes
# Any problem you faced while coding this :In calculating space and time complexity, I am not sure about the complexities I have mentioned above
# Your code here along with commen... |
111abfac7d6c3e7a8d7edefe80277d27a7cdbda3 | alihaiderrizvi/Leetcode-Practice | /all/48-Rotate Image/solution.py | 517 | 3.625 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
lst = []
for z in matrix:
lst.append([])
for i in range(len(matrix)-1,-1,-1):
for j in ran... |
37a835ffcd86af6d674ebacb81b5d3dc768f0f2c | poob/RealPython | /Chapter 7/Assignment solutions/remove_files.py | 667 | 3.671875 | 4 | # 7.2 remove_files.py
# Remove JPG files from multiple folders based on file size
import os
path = "C:/Real Python/Course materials/Chapter 7/Practice files/little pics"
for currentFolder, subfolders, fileNames in os.walk(path):
for fileName in fileNames:
fullPath = os.path.join(currentFolder, fil... |
343010e27049fa17b6f88df88d8a6727adc84441 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/1282.py | 253 | 4.0625 | 4 | def word_count(passage):
'''
Counts occurrences of each unique word in a phrase.
1 input (string) --> 1 output (dictionary)
'''
words = passage.split()
return {word : words.count(word)
for word in set(words)}
|
ac1b8ccd68d22114100a86530788e86deb7b9558 | sapnashetty123/python-ws | /labquest/q_17.py | 93 | 3.890625 | 4 | inp = input("entr the sen:")
if inp.endswith("y"):
inp=inp.replace("y","ies ")
print(inp) |
b3a9b9517fc34cfe121ff18536ce9f7701eef0b7 | aksh0001/algorithms-journal | /questions/trees_graphs/SortedArrayToBST.py | 2,049 | 4.125 | 4 | """
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never
differ by more than 1.
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10... |
c482764ac04193e229e5b450d584b763670a2a42 | MrZhangzhg/nsd_2018 | /nsd1807/python1/day03/mtable.py | 511 | 4.0625 | 4 | # for i in range(3): # [0, 1, 2] 外层循环控制打印哪一行
# for j in range(i + 1): # [0] [0, 1] [0, 1, 2] 内层循环控制行内打印几次
# print('hello', end=' ') # 多个hello打印到同一行
# print() # 每一行结尾需要打印回车,否则就成为一行了
################################
for i in range(1, 10): # [1, 2, 3, 4, 5, 6, 7, 8, 9]
for j in range(1, i + 1): ... |
f9f084e89606ca8d011ac6cf3e5a0c451f6b229c | elodeepxj/PythonFirstDemo | /test1/Ex4.py | 214 | 3.5625 | 4 | # -*- coding:utf-8 -*-
print map(str,(1,2,3,4))
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax +n
return ax
return sum
f = lazy_sum(1,3,5,7,9)
print f() |
3f40786702b9431fe55778db2971b17dbc92cbb3 | brunv/pyCrashCourse | /09 - Classes/importando_classes.py | 2,184 | 4.0625 | 4 | # Para estar de acordo com a filosofia de Python, quanto menos entulhados
# estiverem seus arquivos, melhor será. Para ajudar, Python permite
# armazenar classes em módulos e então importar classes em seu programa
# principal.
# É uma boa prática incluir um docstring no nível de módulo qu... |
8939d0981234c6f0630482dcc8d17e361262e566 | mrshahalam/New-Python-programme | /instagrame.py | 1,988 | 3.703125 | 4 | import requests
from bs4 import BeautifulSoup
# Defining the scrapeInstagram() with the soup1 as the argument
def scrapeInstagram(soup1):
# Creating empty list called insta_Data for saving the scrapped results
insta_Data = []
# Looping through the <meta> tags with attribute propety as og:description
f... |
8ff9cb6587e1f5b0f142f963a45fe5e920da9d43 | michael86/Python-Projects | /hangman/functions.py | 2,812 | 3.96875 | 4 | class HmFunctions:
def show_length(self, word): # This returns the length of the word as under scores _ _ _
length = ""
for letter in range(0, len(word)):
length += '_ '
return length
# This checks that the user input doesn't contain a number
def check_for_digits(sel... |
ade0f65774d105c56f0b2306189084482acea8c0 | SakuraSa/MyLeetcodeSubmissions | /Symmetric Tree/Accepted-13463407.py | 1,616 | 4.125 | 4 | #Author : sakura_kyon@hotmail.com
#Question : Symmetric Tree
#Link : https://oj.leetcode.com/problems/symmetric-tree/
#Language : python
#Status : Accepted
#Run Time : 240 ms
#Description:
#Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#For example, ... |
9e2320a54316116768af7f8212a9d6fd334ca13a | Impact-coder/CodeChef | /First and Last Digit (FLOW004).py | 177 | 3.578125 | 4 | # cook your dish here
N = int(input())
for i in range (0,N):
x = input()
x = list(x)
first, last = int(x[0]),int(x[len(x)-1])
print(first + last)
|
220135567db04ce33ea20daa37e19585310fc2d7 | shahidshabir055/python_programs | /personClass.py | 678 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 16 11:20:12 2020
@author: eshah
"""
class person():
def __init__(self,name,age,height,grade):
self.name=name
self.age=age
self.height=height
self.grade=grade
def isEligible(self):
if(self.grade>7.5):
... |
4ee22cd1bc61688846aacf3a62780a48659fae24 | HCDigitalScholarship/FastBridge | /FastBridgeApp/text.py | 6,167 | 3.734375 | 4 | class Text(object):
"""A Text object for storing all the data and getting sections nicely"""
def __init__(self, name : str, sections : dict, words : list, section_linkedlist : dict, subsections : int, language : str, local_def: bool = False, local_lem: bool = False):
self.name = name
self.secti... |
22c4878fc6031610778981d89d0b24ac4aa38a62 | suacalis/VeriBilimiPython | /Ornek16_3.py | 360 | 3.671875 | 4 | '''
Örnek 16.3: Girilen iki sayının toplamını yapan programda eğer kullanıcı sayı
haricinde bir karakter girer ise program, hata mesajı yerine 'sayı giriniz!'
uyarısı vermelidir.
'''
def topla(a,b):
try:
return(a + b)
except: #bir hata olursa
print ("sayı giriniz!")
#Ana program
print (topla(5,... |
da3949bcf3ba4f32cdb92ab24764f71d96634c44 | vinceajcs/all-things-python | /algorithms/dp/knapsack01.py | 1,761 | 4.15625 | 4 | def naive(weights, values, capacity, n):
"""Given a list of weights and values of n items to be placed in a knapsack,
determine the max value of items in the knapsack given its capacity.
"""
if n == 0 or capacity == 0:
return 0
# weight of nth item is > capacity, thus item cannot be include... |
4970ca102bc967e7f3d6e3ea98ec71daa8bba5e5 | GabrielSalazar29/Exercicios_em_python_udemy | /Exercicios Seção 07 parte 1/ex016.py | 943 | 4 | 4 | """
Faça um programa que leia um vetor de 5 posições para números reais e, depois, um
código inteiro. Se o código for zero, finalize o programa; se for 1, mostre o vetor na ordem
direta; se for 2, mostre o vetor na ordem inversa. Caso, o código for diferente de 1 e 2
escreva uma mensagem informando que o código é invál... |
60c272a4e6aeb1fbd4d3b1379ba15e0605c120d5 | jbischof/algo_practice | /epi3/queues.py | 1,804 | 3.9375 | 4 | """Queue problems."""
from collections import deque
class QueueWithMax(object):
"""Queue class with fast access to max.
Brute force: Scan the collection every time max() method is called.
Time: O(N), Space: O(1)
q = [4, 8, 5, 2, 7, 2, 1, 4]
This queue has max of 8. However, once first two elemen... |
69ce87a46294d44d789c7a5725b9cb3d80ef4cfe | DanielKenji/personal | /trash/ReajusteSalarial.py | 307 | 3.578125 | 4 | salario = float(input("Digite seu salário "))
print("Digite a porcentagem do seu aumento. Por exemplo, para 20% de aumento, ")
aumento = float(input("Digite 20, sem o sinal de porcentagem. "))
reajuste = (aumento*salario)/100
print("seu salário era R$",salario,"e passa a ser R$",salario+reajuste)
input() |
f009d8455cdd977561c7bc147d86b28b7a404297 | Jerome-Celle/BricaBrac | /tri.py | 526 | 3.671875 | 4 | fichierInput = input('Le nom du fichier à trier?\n')
delimiteur = input('Le delimiteur de fin de fonction?\n')
ofiInput = open(fichierInput, 'r')
ofiOutput = open('fichierOutput.txt', 'w')
tableauFonction= []
text = ofiInput.read()
ofiInput.close()
fonction = ""
for y in range(len(text)):
fonction = fonction + text[y]... |
8f8b384e7c68a4294f1b27bb62448e1d1bc35bf9 | piotrbartnik/pythonCodewars | /16.py | 200 | 3.890625 | 4 | # returns position of capital letter
def capitals(word):
i = 0
result = []
while i < len(word):
if word[i].isupper():
result.append(i)
i += 1
return result
capitals('CodEWaRs') |
aae219d377dd4579932250cca41a0b0a6a871458 | lingyun666/algorithms-tutorial | /lintcode/Tree/IsBalanced/balancedTree.py | 1,557 | 3.875 | 4 | # coding: utf8
'''
LintCode:http://www.lintcode.com/zh-cn/problem/balanced-binary-tree/
93. 平衡二叉树
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ ... |
cc2b45d9f65126dfa2b773e6757c95b0b5ed3c49 | cheriesyb/cp1404practicals | /prac_02/files.py | 268 | 3.953125 | 4 |
# 1
output_file = open("name.txt", 'w')
user_name = input("What is your name?")
print(user_name, file=output_file)
output_file.close()
# 2
input_file = open("name.txt", 'r')
user_name = input_file.read().strip()
print("Your name is", user_name)
input_file.close()
|
1394dd1e015c63371f61da6f4a07db2c5a4f56c3 | what-name/misc-python | /WeatherGetter/WeatherGetter.py | 333 | 3.75 | 4 | # Load API Key from APIKey file
apiKeyFile = open("APIKey")
apiKey = apiKeyFile.read()
# Ask for city's name
print("Which city do you want the weather for?")
city = input()
# FIXME validate that input is a string
def getWeather(city):
# FIXME make API call
print("Nice and shiny weather we have today in", city)
get... |
9ef86ae54fdc9532893f6bd085937ae5479c3308 | animeshchittora/D-Straverse | /Web_crawler.py | 1,322 | 3.703125 | 4 | #!/usr/bin/env python
import requests
print("Welcome to Web crawler")
print("press 1 for subdomains traversal 2 for directory traversal")
number = input("Enter your choice : ")
if(number==1):
def request(url):
try:
return requests.get("http://"+url)
except requests.exceptions.Connec... |
2ae892d03e1850e78c8cc6fdbc161b6008477e7b | Sapnavishnoi/KBC-game | /kbc/kbc.py | 3,676 | 3.890625 | 4 | print("*************************************************************************************************")
print("welcometo my KBC game")
print("**************************************************************************************************")
money =[1000,2000,3000,5000,10000,20000,40000,80000,160000,320000,640000,1... |
e532573ac3d7d6a53d71864b8c4fbce2622efc08 | nikhilchoudhari/Pythonex | /py1.py | 284 | 3.875 | 4 | hrs = input("Enter Hours:")
rph = input("Enter rate per hours:")
h = float(hrs)
hh = int(hrs)
r = float(rph)
#rr = float(rph)*1.5
if h <= 40:
print ("The total pay is:", h*r)
else:
#hh = int(hrs)
rr = 0
for i in range (40,hh):
rr += 1.5*r
print ((40*r)+rr) |
c1c6138dc3585c45c120045827fda60bcfa94311 | ahmettkarad/Python_Learning | /Başlangıç/bb.py | 719 | 3.84375 | 4 | musteriAdi = 'ahmet'
musteriSoyadi = 'karadas'
musteriadsoyad = musteriAdi + ' ' + musteriSoyadi
mustericinsiyet = 'erkek'
musterikimlikno = '10000'
musteriyasi = 21
print(musteriadsoyad)
print(mustericinsiyet)
print ( musterikimlikno)
print("ahmet\nkaradaş")
print("Muhammed\t\t\tKaradaş")
print("merhaba Ahmet\'in dü... |
be9400b863f346a7792309b3175c6b1dd87c4e9d | RomanAleksejevGH/Python | /03112020.py | 5,774 | 3.75 | 4 | import math
def perimetr(): #Roman Aleksejev, 03.11.2020, Задача 2.
print('Вычислить периметр треугольника.')
while True:
try:
a=int(input('Введите сторону "а": '))
b=int(input('Введите сторону "b": '))
c=int(input('Введите сторону "c": '))
print('Перимет... |
874c3e2a808c69d9f135c40f5d3ab93126b31a00 | Isabel-Cumming-Romo/Classify-Falls-ML | /nn_mySGD.py | 4,905 | 3.734375 | 4 | import random # for w's initalizations
import numpy # for all matrix calculations
import math # for sigmoid
import scipy
import pandas as pd
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + numpy.exp(-x))
def sigmoidGradient(z):
#Parameters: z (a numerical input vector or matrix)
#Returns: ve... |
6baccb270aca97314cc96c226a6edad62f59a4b1 | adamcasey/Interview-Prep-With-Python | /isPalindrome.py | 3,050 | 4.40625 | 4 | '''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes ... |
e8dbf7870b09b82748a2ac609edf15410caadc3b | korzair74/Homework | /Homework_4-23/Classes.py | 721 | 4.0625 | 4 | """
Build three classes, two of which must inherit from the first and employ
polymorphism. Between the three classes, there must be at least 5 methods,
3 instance attributes, 1 class attribute, and the parent class should
have a dunder init. If you want you can add dunder str and dunder repr
to each class.
"... |
04a98004e523f2acf8b2eafe912c6e930987749c | eganjam/MOOCs | /Coursera_UniversityOfMichigan_PythonForInfomatics/02c_ExtractHourlyDistributionOfEmails.py | 840 | 3.921875 | 4 | # prompt for the file
fname = raw_input("Enter file name: ")
# press enter to use the default file
if len(fname) < 1 : fname = "mbox-short.txt"
# open the file
fh = open(fname)
count = 0
counts = {}
# for loop to go through each email and extract
# the hour in which that email was sent
for line in fh:
if line.st... |
870b5fa8ef7faa9efd0a4ddf1a5ef8d6f6c2f461 | mainadwitiya/Data-Structures | /python_codes/dynamic_prog/fibo.py | 204 | 3.609375 | 4 |
#memoization
def fibn(n):
memo={0:1,1:1}
def helper(n):
if n not in memo:
memo[n]=helper(n-1)+helper(n-2)
print(memo)
return memo[n]
return helper(n)
z=10
result=fibn(z)
print(result) |
31081d8a3c8cb2579d5fca1abbf67dd9995c8da4 | rayankikavitha/InterviewPrep | /Tries/Trie_implementation.py | 2,577 | 4.03125 | 4 | import unittest
class TrieNode:
def __init__(self, letter):
self.letter=letter
self.isTerminal=False
self.children={} # dictionary to store key as child letter, value as pointer address to node
self.positions=[] # to store the order of the incoming text
class Trie(TrieNode):
... |
5ce3b9ffee8d6bba45458397c75bc2d86d6fa646 | Superbeet/LeetCode | /Non-leetcode/Reverse_String.py | 653 | 3.75 | 4 | # class Solution:
# # @param s, a string
# # @return a string
# def reverseWords(self, s):
# words = s.split()
# words.reverse()
# return " ".join(words)
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
res = ""
s... |
417810a0395d79b3dde73003e09f2c3d6af83d55 | zhouhaosame/leetcode_zh | /offer/36_二叉搜索树与双向链表.py | 2,270 | 3.953125 | 4 | """
def Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List(root):
很明显,这个需要将树的指针都重新改变,正好左右子树就是双向指针啊
if not root:
return root
def reverse(node):
if node:
if not node.left and not node.right:
return node,node
else:
left_start,left_end... |
878bda9c5415ac85b0c4095bdf3a02d837d7ecc4 | Elisa-Vitoria/AtividadesDeLPC | /atv.1.py | 202 | 3.5 | 4 | # ETE PORTO DIGITAL
# LPC - Introdução a Python
# Prof. Cloves Rocha
# Estudante: Elisa Vitória
# Turma: 1°B
#1. Faça um Programa que mostre a mensagem "Olá mundo" na tela.
print('\033[35mOlá, mundo!\033[m') |
3b0cf11c65077075da455aab745a378263ef7e7f | seven320/AtCoder | /test/99.py | 135 | 3.640625 | 4 | # encoding: utf-8
for i in range(1, 10):
for j in range(1, 10):
print(" {:02}".format(i * j), end = "")
print("")
|
bb32f5bb718f30780946f0c7c20ed18dfa4c09ca | EithanHollander/ProjectEulerAnswers | /solution_57.py | 877 | 3.84375 | 4 | from fractions import Fraction
if __name__ == '__main__':
previous_denominator, current_denominator, previous_numerator, current_numerator = 1, 2, 1, 3
temp_denominator, temp_numerator = 0, 0
counter_of_expansions = 0
amount_of_exceeding = 0
while counter_of_expansions < 1000:
if len(str(cu... |
61ef536003edebfb3b31452bfb1bd04a877fe257 | dragonslice/nxdom | /languages/utils.py | 1,313 | 3.875 | 4 | VOWELS = 'aeiouy'
TRIPLE_SCORES = {}
def word_groups(word):
"""
>>> list(word_groups('weight'))
['w', 'ei', 'ght']
>>> list(word_groups('Eightyfive'))
['ei', 'ght', 'y', 'f', 'i', 'v', 'e']
"""
index = 0
word = word.lower()
while index < len(word):
# Find some consonants.
... |
e9102d5aa24ddee817c2fd36ec3d06ba28c01616 | hustsong/leetcode | /python/680. Valid Palindrome II.py | 423 | 3.546875 | 4 | class Solution:
def validPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i <= j:
if s[i] == s[j]:
i += 1
j -= 1
continue
pivot = len(s) // 2 + len(s) % 1
return s[i + 1:j + 1] == s[i + 1:j + 1][::-1] or ... |
27470b0f2a286d48019ce911f16df7fb58acce28 | severinson/uibdoc-python | /scientific-solutions.py | 2,113 | 3.53125 | 4 | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
'''
last task from basic.
'''
import random
def flip():
if random.random() < 0.5:
return 0 # heads
else:
return 1 # tails
def sample():
count = 0
outcome = flip()
while outcome == 0:
... |
b37df0668f2e8887416e0558acffa61955260ef6 | KwameKert/algorithmDataStructures | /smallestDifference/code/__init__.py | 862 | 3.796875 | 4 |
#finding the smallest difference from two arrays
def smallestDifference(firstList, secondList):
#sorting both arrays
firstList.sort()
secondList.sort()
smallestPair = []
idxOne = 0
idxTwo = 0
current = float("inf")
smallest = float("inf")
#loop through both arrays till the end o... |
f69bfc08f80d3600fe429184a7a59892c6aa1dae | tofuriouz/snakify_final | /snakify/unit 1/two_timestamps.py | 271 | 3.65625 | 4 | # Read an integer:
# a = int(input())
# Read a float:
# b = float(input())
# Print a value:
# print(a, b)
a = int(input())
b = int(input())
c = int(input())
x = int(input())
y = int(input())
z = int(input())
s = (a*3600 + b*60 + c)
t = (x*3600 + y*60 + z)
print(t - s)
|
44e207e3fccebd95833b268a05f8d2783c7bff6d | eaudeweb/edw.utils | /edw/utils/iter.py | 307 | 3.890625 | 4 | from collections import Iterable
def is_iter(v):
"""Returns True only for non-string iterables.
>>> is_iter('abc')
False
>>> is_iter({'a': 1, 'b': 2, 'c': 3})
True
>>> is_iter(map(lambda x: x, 'abc'))
True
"""
return not isinstance(v, str) and isinstance(v, Iterable)
|
c5108c50fc4b003bdfa0bb89c2fda6fd5593095c | arturbs/Programacao_1 | /prologo/Converte_Temperatura/convtemp.py | 173 | 3.5625 | 4 | fahr = float(input())
cels = (fahr - 32) * (5.0/9)
kel = cels + 273.15
print ("Fahrenheit: %0.3f F" %fahr)
print ("Celsius: %0.3f C" %cels)
print ("Kelvin: %0.3f K" %kel)
|
665584e93525945e0fdc46996acf3c14a8607684 | Akards/Medusa | /Medusa/matrix/multiplication.py | 1,716 | 3.59375 | 4 | import numpy as np
import multiprocessing as mp
from functools import partial
def multiply(A, B, proc_num):
"""
Multiplies 2D numpy matrices A and B using n total processes.
Args:
A (np.array): a 2D matrix
B (np.array): a 2D matrix
proc_num (int): number of processors
Returns:
... |
11b45d85ed41053eda8d25545bf4ba1ce0093b1e | MrJustPeachy/CodingChallenges | /Kattis/Difficulty - 1/Difficulty - 1.3/spavanac.py | 402 | 3.75 | 4 | data = input().strip().split()
hours = int(data[0])
minutes = int(data[1])
hourTime = 0
minuteTime = 0
if minutes >= 45:
hourTime = hours
minuteTime = minutes - 45
else:
if hours > 0:
hourTime = hours - 1
else:
hourTime = 23
minuteDiff = minutes - 45
minuteFixed = 60 + minu... |
e2589d8a260908e6aa58aed3af79b7762183a043 | yckfowa/Automate_boring_stuff | /Ch.08/Sandwich_maker.py | 1,276 | 4.03125 | 4 | import pyinputplus as pyip
price_list = {'breads': {'wheat': 5, 'white': 3, 'sourdough': 6},
'main': {'chicken': 7, 'turkey': 10, 'ham': 5, "tofu": 3},
'cheeses': {'cheddar': 3, 'Swiss': 4, 'mozzarella': 3}}
def main():
total = 0
print("Welcome to SubWaiyi, please make your order ... |
3a9c70d2e1bda14652f62095272d5a7067f00455 | SphericalPendulum/Pendulum-Art-2.0 | /plot_or_animate2D.py | 2,379 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
num_layers = int(input("Enter the number of paint layers you plan to add: "))
# get filenames
filenames = []
for i in range(num_layers):
filename = input(f'Enter the name of data file #{i+1}: ')
filenames.append(... |
ec0bf55690e538ad7baff00c34b0ee3deb83ad61 | Try-Try-Again/lpthw | /ex1-22/ex19_drill3.py | 164 | 3.5625 | 4 | def bedtime(devin):
print(f"The last one in bed's a {devin}-baby!")
races = ["blue", "red", "green", "purple", "orange"]
for race in races:
bedtime(race)
|
2ca5b0fe35dbfb6789be92fce4ddee2e1e09fc70 | Saptarshidas131/NPTEL | /Joy of Comuting using Python/assignments/2019JOC_Assignments/W4PA3.py | 2,071 | 4.65625 | 5 | '''
You all have used the random library of python. You have seen in the screen-cast of how powerful it is.
In this assignment, you will sort a list let's say list_1 of numbers in increasing order using the random library.
Following are the steps to sort the numbers using the random library.
Step 1: Import the... |
06df8705e59d0d3b4921b77748d76f9d46846e97 | BastiennM/Jeu-du-pendu | /brouillon/program.py | 1,404 | 3.5 | 4 | # coding=utf-8
import random
# jeu du pendu
# fichier de mots dans liste
liste = []
fichier = open("liste.txt", "rt")
for x in fichier:
liste.append(x.rstrip("\n"))
mot = liste[random.randint(0, len(liste) - 1)]
# liste contenant les caractères du mot
mot_l = list(mot)
# liste des caractères cachés soit _
mot_c =... |
2e536de7dfa7d7c2d9b8a5e3ab8d3a7419160983 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/plltam005/question4.py | 832 | 4.125 | 4 | """Drawing a graph
Tameryn Pillay
16 April 2014"""
import math
def graph():
"""Plotting the graph from the equation given"""
function = input("Enter a function f(x):\n")
for y_axis in range(10,-11,-1):
for i in range (-10,11):
x = i
y = round(e... |
851f58cf8a2c5d262b8cb9e71048260047e1f3bb | daniel-reich/ubiquitous-fiesta | /jzCGNwLpmrHQKmtyJ_16.py | 151 | 3.703125 | 4 |
def sum_digits(n):
return n%10 + sum_digits(int(n/10)) if n else 0
def parity_analysis(num):
return (sum_digits(num) % 2 == 0) == (num % 2 == 0)
|
a035bf938f692950f945e652b0e29915a8dfeed3 | stevekutz/python_iter_sort | /HackerRank/tuples.py | 696 | 4.21875 | 4 | """
Task
Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of
hast(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
Input Format
The first line contains an integer,
, denoting the n... |
32612ba620b9e64608f64637ff17cf95f090562c | ecaterinacatargiu/FP | /Backtracking/o.py | 60 | 3.671875 | 4 |
x = 10
def f(y):
y+=1
z = f(x)
print("x=", x, "z= ", z) |
c0daf0c0096d2e0cb19eb5ae4dd36c5b91f52a9a | schnitzlMan/ProjectEuler | /Aufg6.py | 127 | 3.59375 | 4 |
totalSum = 0
for i in range (101):
print(i)
for j in range(i):
totalSum += i*j
totalSum *=2
print(totalSum)
|
fa39c25efc9c60a0ec364264fec82a409f911edd | vitords/ProjectEuler | /009.py | 410 | 3.5 | 4 | # Special Pythagorean triplet
# Problem 9
# Brute force, but works...
result = 0
for c in range(100, 500):
for b in range(100, c):
for a in range(100, b):
if a**2 + b**2 == c**2:
if a + b + c == 1000:
result = a * b * c
break
els... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.