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 |
|---|---|---|---|---|---|---|
39a27b9e5364b124341db83c7f9f52f195630012 | rouseway/Python_Learning | /Data_Analysis/numpy模块/demo01_numpy引入.py | 530 | 3.890625 | 4 | # 假如:已从表格里面读取到数据
data = {
'title': ['苹果','橘子','香蕉','草莓'],
'number': ['3','5.1','2.5','4'],
'price': ['3.6','2','7.5','20.2']
}
# 添加1列:金额
'''
zip()
'''
money = []
for n,p in zip(data['number'],data['price']):
money.append(float(n) * float(p))
data['金额'] = money
print(data)
import n... |
f0a3aaa3887fda773a89156cd18c6ab6097f2a71 | grsantosg/junk | /t7.py | 359 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 11:28:21 2020
@author: german.santos
"""
import tkinter as tk
window = tk.Tk()
def handle_keypress(event):
"""Print the character associated to the key pressed"""
print(event.char)
# Bind keypress event to handle_keypress()
window.bind("<Key>"... |
003d80e264f584d9db5bafd73fcdcd5e5a852810 | NaanPradeep/PythonAlgorithm | /Data Structure/linkedlist.py | 6,768 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
insertion_error = TypeError("Insertion not possible, Previous node does not exists.")
node_error = TypeError("Node doest not exists")
def __init__(self):
self.head = None
def print_list(self):
cur... |
7671a88241782bcdad2dff7c3045ed684b1edc8a | NaanPradeep/PythonAlgorithm | /Data Structure/basic_binary_tree.py | 800 | 4 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert_node(self, data):
if not self.root:
self.root = Node(data)
else:
self._insert_node(data, self.root)
... |
52922dcaa154ca16e53817ab768a2faf63014ae8 | jacksonludwig/ticBotTwo | /board.py | 1,399 | 3.765625 | 4 | class Board:
MAGIC_SQUARE = [4, 9, 2, 3, 5, 7, 8, 1, 6]
def __init__(self):
self.board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def format_board(self):
row1 = f"{self.board[0]} | {self.board[1]} | {self.board[2]}"
row2 = f"{self.board[3]} | {self.board[4]} | {self.board[5]}"
row3 = f"... |
8a74a05d16b434c58993e223130cbaaced80d052 | rgaior/bokeh-newtest | /bokeh-app/main.py | 11,804 | 3.5625 | 4 | ''' Create a simple stocks correlation dashboard.
Choose stocks to compare in the drop down widgets, and make selections
on the plots to update the summary and histograms accordingly.
.. note::
Running this example requires downloading sample data. See
the included `README`_ for more information.
Use the ``b... |
eaf44113dd0775b8bba6abe986f441ca26487e71 | Harshith0307/Game-Design | /Documents/Harsha/Personal/repos/practice/squaring_arrays.py | 435 | 3.953125 | 4 | #read a list of nuumbers and then square it
def square(element):
return element**2
def square_array(elements):
for item in elements:
print(square(item))
if __name__ == '__main__':
count = int(input("Please enter the number of numbers dumma "))
elements = list(map(int, input().st... |
e907ecae5f52334773d65f2923e036c183796e70 | S-Nathalia/URI-s | /src/python_C/semana_1/1017.py | 102 | 3.734375 | 4 | time = int(input())
speed = int(input())
dis = 0.0
dis = time*speed
dis = dis/12
print("%.3f" % dis)
|
a2cd1e6893fe3a237324d7e59fbd53a7d339ee8e | S-Nathalia/URI-s | /src/python_C/semana_2/1087.py | 550 | 3.640625 | 4 | x1, y1, x2, y2, x, y = 0, 0, 0, 0, 0, 0
while(True):
x1, y1, x2, y2 = map(int, input().split(" "))
if(x1 == 0):
break
# abs = valor absoluto i.e. 1 = abs(-1)
x = abs(x2 - x1)
y = abs(y2 - y1)
# se x1 e x2 e y1 e y2 forem iguais, sera o mesmo ponto
if(x1 == x2 and y1 == y2):
... |
6cee84188c5ec6a40e82dffe3d3eb4549ed4fca0 | Jmeggesto/ProjectEulerSolutions | /euler30.py | 195 | 3.6875 | 4 | def DigitFifthPower(number):
return sum([int(digit) ** 5 for digit in str(number)]) == number
fifth_power_arr = [x for x in range(2, 1000000) if DigitFifthPower(x)]
print(sum(fifth_power_arr))
|
e296c302f4d3215dea837a15f8b2e578ebc4172b | Jmeggesto/ProjectEulerSolutions | /euler46.py | 198 | 3.734375 | 4 | import math
def Composite(number):
for i in range(2, int(math.sqrt(number))):
if number % i == 0:
return True
break
return False
a = [x for x in range(0, 100) if Composite(x)]
print(a) |
fbca7f7645c4ae4c5ed12ab12f8d7c64f470015d | Grateki/Avalia-o-Est-gio-Radix | /Questao2.py | 803 | 4.0625 | 4 | n_de_testes = int(input(''))
for _ in range(n_de_testes):
elementos_matriz = int(input(''))
print('Matrix',elementos_matriz,'X',elementos_matriz)
desenha_matriz = [0] * elementos_matriz
desenha_matriz = [[0] * i + [1] + [0] * (elementos_matriz - i - 1) for i in range(elementos_matriz)]
for linha in ... |
15dc8cdd20b3a6ccb57fd58e0acf4a47dccba195 | randolchance/ProjectEulerSolutions | /PE63/PE63-PowerfulDigitCounts.py | 497 | 3.5 | 4 | # PROJECT EULER PROBLEM 63 - Powerful Digit Counts
def powerfulDigitCount():
i = 0
j_0 = 1
count = 0
while True:
i += 1
for j in range(j_0,10):
val = j**i
if len(str(val)) == i:
print("{}**{} = {}".format(j,i,val))
count += 1
... |
3a0a1e119cd0900be42f05f97ebf396f45d67e26 | randolchance/ProjectEulerSolutions | /PE19/PE19-CountingSundays.py | 737 | 3.859375 | 4 | # PROJECT EULER PROBLEM 19 - Counting Sundays
months = {}
months[1] = 31
months[2] = 28
months[3] = 31
months[4] = 30
months[5] = 31
months[6] = 30
months[7] = 31
months[8] = 31
months[9] = 30
months[10] = 31
months[11] = 30
months[12] = 31
year = 1900
month = 1
day = 7
leap = False
count = 0
while year <= 2000:
... |
bb6023ec088b1d772142b08643fad2fe53ecc610 | randolchance/ProjectEulerSolutions | /PE116/PE116-RedGreenOrBlueTiles.py | 1,473 | 3.859375 | 4 | A row of five black square tiles is to have a number of its tiles
replaced with coloured oblong tiles chosen from red (length two),
green (length three), or blue (length four).
If red tiles are chosen there are exactly seven ways this can be done.
If green tiles are chosen there are three ways.
And if blue tiles are... |
9079476c048a7507cbaf165db1ad9aa66fa9eef7 | kazesberger/aoc2019 | /intcode_five/intcode_five.py | 3,064 | 3.671875 | 4 | def read_program(file):
with open(file) as f:
# read_data = map(int, f.read().split(","))
read_data = f.read().split(",")
return list(map(int, read_data))
def parse_op(num2parse: int):
return (num2parse % 100, num2parse // 100)
def parse_param_mode(modes: int, index):
return modes % ... |
090d2c08fc310eec386602a8686fa8694265967e | alfredleo/ProjectEuler | /problem1.py | 2,667 | 4.5 | 4 | import unittest
from utils import performance
def multiplesof3and5(to):
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
https://projecteuler.net/problem=1
"... |
42997cc7da8ef79ab952c1594a30f878aa649ad0 | purusoth-lw/Python | /10.operator.py | 897 | 4.3125 | 4 | """
Operator:
=========
1.arithmatic Operator
2.Relational Operator
3.Logical Operator
4.Bitwise Operator
5.Assignent Operator
6.Special OPerator
1.arithmatic Operator:
=====================
(+) ----> Addition
(-) ----> Subtraction
(*) ----> Multiplication
(/) ----> Division
(//) ----> Floor ... |
4d7e3a931aefc6fb1f4f3e3cd6bef91e51aa8cfe | purusoth-lw/Python | /16.control flow.py | 2,055 | 3.984375 | 4 | """
Control Flow:
============
1.Decision Making
2.Looping Structure
3.Loop control Statements
1.Decision Making:
=================
1.if statements
2.if-else statements
3.nested if else statements
4.Ladder if-else or if-else-if statements
2.Looping Structure:
===================
... |
80b595700516c71fce8cb9a27d205d18e4a793d1 | Vanzcoder/HackerRankChallenges-Python- | /List_Comprehensions.py | 1,655 | 4.375 | 4 | """
Let's learn about list comprehensions!
You are given three integers X,Y and Z representing the dimensions of a cuboid along with an integer N.
You have to print a list of all possible coordinates given by (i,j,k) on a 3D grid
where the sum of i + j + k is not equal to N.
Here, 0 <= i <= X; 0 <= j <= Y, 0 <= k <= Z
... |
08ab1425154d4effc2f08978fbc3d9c18df09fba | D3nii/Data-Structures-Algorithms-Nanodegree---Udacity | /Projects/P2/submission/problem_3.py | 1,711 | 3.921875 | 4 | def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if input_list is None:
return None
if len(input_list) <= 1:
re... |
9c83a43e174e983e35825bdee4867d21e9b657e0 | daianasousa/Ensinando-com-as-Tartarugas | /Desenhando_estrelas.py | 468 | 4.1875 | 4 | from turtle import *
#uma função para desenhar uma estrela
#'def' signica 'define'
def drawStar():
pendown()
begin_fill()
for side in range(5):
left(144)
forward(50)
end_fill()
penup()
#isso vai desenhar uma estrela cinza clara em um fundo azul escuro
color("WhiteSmoke")
bgcolor("... |
a8db2179ab9aa4fb2a0ecf5138a5da55926637b3 | amirnasri/Misc | /src/find_smallest_subarray_with_greater_sum.py | 1,074 | 3.875 | 4 | # Solution is not correct! The complexity is exponential it seems! Revisit and solve with gfg solution.
'''
Smallest subarray with sum greater than a given value
http://www.geeksforgeeks.org/minimum-length-subarray-sum-greater-given-value/
Given an array of integers and a number x, find the smallest subarray with sum... |
3d9560a199181836462d642e8fd7ed90c11377a3 | RagenIV/GSOMpy | /lesson_04/str_n.py | 227 | 4 | 4 | # coding: utf-8
def upperator(s, n):
if len(s) > n:
return s.upper()
else:
return s
print(upperator("Строка для Примера", 5))
print(upperator("Строка для Примера", 42))
|
3387e50b645a793948a49ae67af24919eca4e8cd | RagenIV/GSOMpy | /lesson_06/interval_fun.py | 137 | 3.578125 | 4 | def y(x):
return x*x + 3
def masy(r):
s = []
for i in r:
s += [y(i)]
return s
print(sum(masy(range(10,31,2))))
|
313c2ee5b74caa672fc8f151b1257ca2e6560945 | RagenIV/GSOMpy | /lesson_03/my_func_sinus.py | 143 | 3.59375 | 4 | # coding: utf-8
import math
def f(x):
if .2 <= x <= .9:
return math.sin(x)
else:
return 1
print(f(float(input())))
|
f837496dd51c6864e1c1d184b84995a16c84cf8b | umeshpandey994/Python-2 | /BinarySearchFunction.py | 305 | 3.84375 | 4 | def binarySearch(list_s,item):
first=0
last=len(list_s)-1
while first<=last :
mid=(first+last)//2
if list_s[mid]==item:
print mid+1
break
else:
if item<list_s[mid]:
last=mid-1
else:
first=mid+1
|
b3da52be0f3da55ab3d8d9684dff55eaccaa1d89 | RuleML/psoa-ruleml | /usecases/OfficeProspector/generator/OrderedSet.py | 373 | 3.796875 | 4 | from collections import OrderedDict, Set
class OrderedSet(Set):
def __init__(self):
self.data = OrderedDict()
def add(self, element):
self.data[element] = 0
def __len__(self):
return self.data.__len__()
def __contains__(self, value):
return value in self.data
de... |
bd9c655d46a3e12cd9ec7e3a7cd534c5711ce88d | mandisiS/MyGames | /my_game.py | 9,288 | 4.3125 | 4 | #Capstone project 2
#Compulsory task
#This capstone project utilises pygame to creat a game with one player, three enemies and one award/prize collection
#if player collides with any of three enemies, the user loses and game ends
#if player collides with a prize/award the user wins and the game ends
#if the us... |
c731fb1ed9647d38535cca3aaf178b51f6d5364f | TheProrok29/design_patterns_in_python | /other/visitor/example2/plant.py | 583 | 3.65625 | 4 | from abc import ABC
class Plant(ABC):
def __init__(self, name):
self.name = name
def accept_visitor(self, visitor):
visitor.visit(self)
def water(self, responsible):
print(f'{self.name} watered by {responsible}')
def eat(self, responsible):
print(f'{self.name} eaten ... |
22383a446bb6368765a72f45005ccaceaabd3837 | TheProrok29/design_patterns_in_python | /functional/iterator/explanation.py | 217 | 3.875 | 4 | a_list = [1, 2, 3]
my_iter = iter(a_list)
print(my_iter)
# print(next(my_iter))
# print(next(my_iter))
# print(next(my_iter))
while True:
try:
print(next(my_iter))
except StopIteration:
break
|
a40d042b99c414b1393bca1205abc9b72c33f77d | spectrehck/pythonCardio | /cardio.py | 980 | 3.578125 | 4 | import random
def conversor(opcion):
if opcion == 1:
return 'piedra'
elif opcion == 2:
return 'papel'
elif opcion == 3:
return 'tijera'
else:
return print('Ingrese una opcion valida')
def juez(player, player2):
if piedra == True
def bienvenida():
print('Bien... |
25d48a54698b107614f0fe96d1ccc6d85efd7b07 | jifferent/CSE_130 | /HW6/vector.py | 3,337 | 3.84375 | 4 | """
CSE 130: Programming Assignment 6
vector.py
Author: Daniel Shipps (A10239760)
Date: 5/31/2013
"""
from misc import Failure
class Vector(object):
"""This is class that implements a fixed length vector
and which implements a variety of operations :)"""
def __init__(self, length):
"""constructor... |
1b34b710d70edbb88e6c677e35ac5fff7c795232 | lkr92/Learning-Projects | /Simple Calculator.py | 722 | 4.34375 | 4 | run = True
#Simple Calculator that will run on loop upon user request
while run:
num1 = float(input("Please type a number: "))
operator = input("Please input an operator character: ")
num2 = float(input("Please input a second number: "))
if operator == "+":
print(num1 + num2)
e... |
3569045d9c529618da82c548d70eb40747fc452f | priyanshuc4423/snakegame | /food.py | 415 | 3.546875 | 4 | import turtle as t
import random
class Food(t.Turtle):
def __init__(self):
super().__init__()
self.penup()
self.shape("circle")
self.shapesize(stretch_wid=0.5,stretch_len=0.5)
self.color("blue")
self.refresh()
def refresh(self):
x_cor = ran... |
33b37269116ed8d87170c85861cf1ae099f20da6 | chenLe1232/python_learning | /class/test_imooc.py | 2,264 | 3.828125 | 4 | class Vehicle(object):
# 自定义Vehicle类属性
# 自定义实例的初始化方法
def __init__(self, speed, size, trans_type='SUV'):
self.__speed = speed
self.size = size
self.trans_type = trans_type
# 自定义实例方法show_info,打印实例的速度和体积
def show_info(self):
rest = '我所属类型为:{0},速度为:{1},体积:{2}'.format(se... |
ab2bd9302431d1ffe55c9914b8cd73312fd720a1 | chenLe1232/python_learning | /branch/simple5.py | 167 | 3.8125 | 4 | a = 3
b = 4
print(a+b)
a1 = 3.1
b1 = 4.1
print(a1+b1)
if a > b:
print(a)
elif a < b:
print(b)
else:
print('这两个数字相等')
c = 1.1 + 1
print(c) |
3455154af392b7307a405134dabc50f88388da00 | chenLe1232/python_learning | /tuple/simple2.py | 137 | 3.578125 | 4 | # r1 = range(10, 20)
# print(r1[0:11])
# print(type(r1))
# 增加步长
r2 = range(1, 10, 2)
print(r2)
print(r2[3:5])
print(22 not in r2) |
9c2e1c358f38bdb8519152b7e8e9d33d4cca5710 | TharuniI/Games | /Sudoku/Sudoku.py | 20,410 | 4.34375 | 4 | '''
Sudoku- By Tharuni Iranjan
This is a take on the Sudoku game. In this version the Sudoku grid will be displayed
on the screen using Python Turtle. The user will be asked to enter a row number, column
number, and the number they think should be in that position. If that postition contains a
preset number, 'invalid p... |
692f27d609c9961bf5feed66b17f29066020467f | yamaton/codeeval | /easy/prime_palindrome.py | 1,211 | 4.125 | 4 | """
prime_palindrome.py
Created by Yamato Matsuoka on 2012-07-16.
Description
-----------
Write a program to determine the biggest prime palindrome under 1000.
Input: None
Output: Prints the largest palindrome on stdout under 1000.
"""
import math
def integerdigits(n):
"""Construct list of decimal digits f... |
886eb287181be88f20433007a08dc93bb7fdd82f | yamaton/codeeval | /hard/grid_walk.py | 2,029 | 4.53125 | 5 | #!/usr/bin/env python
# encoding: utf-8
"""
grid_walk.py
Created by Yamato Matsuoka on 2012-07-19.
Description:
There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-... |
280aec3217c41d4c9e647a87532d6bf5ba3eb6b4 | yamaton/codeeval | /moderate/lca.py | 1,521 | 4.03125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
untitled.py
Created by Yamato Matsuoka on 2012-07-16.
Description:
Write a program to determine the lowest common ancestor of two nodes in a binary search tree. You may hardcode the following binary search tree in your program:
30
|
____
| |
8 52
|
___... |
aa4b8ced0ff163c86e0ddcd53608609a0253c138 | yamaton/codeeval | /moderate/jolly_jumpers.py | 1,892 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
jolly_jumpers.py
Created by Yamato Matsuoka on 2012-07-17.
Description:
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the differences between successive elements ta... |
6095a278b6d0625b6c4df3738cdac5805657a1d8 | yamaton/codeeval | /moderate/point_in_circle.py2 | 1,346 | 4.28125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
point_in_circle.py2
Challenge Description
=====================
Having coordinates of the center of a circle, it's radius and coordinates
of a point you need to define whether this point is located inside of this circle.
## Input sample
Your program should accept as its ... |
bef391ae6989b5acc9db9e65fa702c8db2e7dd5f | yamaton/codeeval | /easy/capitalize_words.py2 | 710 | 4.625 | 5 | #!/usr/bin/env python
# encoding: utf-8
"""
Challenge Description:
Write a program which capitalizes words in a sentence.
## Input sample
Your program should accept as its first argument a path to a filename. Input example is the following
```
Hello world
javaScript language
a letter
```
## Output sample:
Print cap... |
9fe52d300f8ec8941b028519e78f8ac9a4387da2 | yamaton/codeeval | /moderate/cycle_detection.py | 2,596 | 4.125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
cycle_detection.py
Created by Yamato Matsuoka on 2012-07-16.
Description:
Given a sequence, write a program to detect cycles within it.
Input sample:
A file containing a sequence of numbers (space delimited). The file can have multiple such lines. e.g
2 0 6 3 1 6 3 1 6 ... |
14d068739845a1f084899d2f40006e6ead7fd33f | yamaton/codeeval | /hard/ugly_numbers_slow.py | 4,274 | 4.25 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
ugly_numbers.py
Created by Yamato Matsuoka on 2012-07-18.
Description:
Credits: This challenge has appeared in a google competition before.
Once upon a time in a strange situation, people called a number ugly if it was divisible by any of the one-digit primes (2, 3, 5 or ... |
d4da83831df94855162f5133e602a82621467666 | yamaton/codeeval | /moderate/string_rotation.py | 835 | 4.4375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
String Rotation Share on LinkedIn
Description:
You are given two strings. Determine if the second string is a rotation of the first string.
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file contains two comma sepa... |
6939b6dcdfdb8225a2b9015d6e72e759240d35b1 | yamaton/codeeval | /moderate/pass_triangle.py2 | 1,089 | 4.0625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
pass_triangle.py
Challenge Description
======================
By starting at the top of the triangle and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 27.
```
5
9 6
4 6 8
0 7 1 5
```
5 + 9 + 6 + 7 = 27
## Input sample
Your pro... |
8d4ed3c4af0a627a1600f7fea201975bfdbca67e | yamaton/codeeval | /hard/string_list.py | 1,689 | 4.125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
string_list.py
Created by Yamato Matsuoka on 2012-07-18.
Description:
Credits: Challenge contributed by Max Demian.
You are given a number N and a string S. Print all of the possible ways to write a string of length N from the characters in string S, comma delimited in al... |
1f2b0c0484b769ca60bb710a77738f37248ddc01 | yamaton/codeeval | /moderate/pangrams.py | 1,485 | 4.09375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
pangrams.py
Created by Yamato Matsuoka on 2012-07-16.
Description:
The sentence 'A quick brown fox jumps over the lazy dog' contains every single letter in the alphabet. Such sentences are called pangrams. You are to write a program, which takes a sentence, and returns all... |
871ce15a4b9c133f78d7acbdcf9ddd84b646f791 | alan-dx/snake-game | /app/snake_pk/snake_class.py | 1,323 | 3.578125 | 4 | import pygame
class Snake:
def __init__(self, init_position):
self.snake_size = init_position
self.snake_skin = pygame.Surface((10, 10)) # set size of pieace snake
self.snake_skin.fill((255, 255, 255)) # set fill of snake pieace
def move_up(self):
self.snake_size[0] = (
... |
fce121c0148df1785a79c3c8b7fb8254ff2a8233 | FisicaComputacionalOtono2018/20180816-clase-diagramadeflujoparprimo-javierjuarez7 | /monstruov4.py | 529 | 3.65625 | 4 | #Javier Juarez Jimenez
#16/08/18
def isPrimeFor(num): #True es primo False no es primo
flag=True
if num==1:
flag=False
if num==2:
flag=True
if num==3:
flag=True
if num==4:
flag=False
if num>4:
for i in range (2, num/2):
if num%i==0:
flag=False
break
return flag
s=12
p=input("Teclea un ... |
db8e52bdf6f0d0a1112cfda44cf31e7b3bd41595 | folkol/tutorials | /python3/9.5.5.class_and_instance_variables.py | 863 | 3.640625 | 4 | class Dog:
kind = 'canine'
def __init__(self, name=None):
self.name = name
fido = Dog('Fido')
buddy = Dog('Buddy')
print(fido.kind) # Canine, shared by all dogs
print(buddy.kind) # Canine, shared by all dogs
print(fido.name) # Fido
print(buddy.name) # Buddy
class BrokenDog(Dog):
tricks = [... |
bb994e5fc4f13d9facf087e48b9762b9efc9844d | folkol/tutorials | /modern_python/type_annotations.py | 163 | 3.515625 | 4 | from typing import Dict, List
def foo(param: Dict[str, List]) -> str:
return 'Hello, world!'
x: Dict[str, str] = dict(foo='bar', baz='qux')
print(foo(x))
|
4072454456bfde8ed1202811f7d017663cdda4e3 | folkol/tutorials | /python3/5.1.4.nested_list_comprehensions.py | 744 | 3.953125 | 4 | matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(matrix)
transposed = [[row[i] for row in matrix] for i in range(4)]
print(transposed)
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
print(transposed)
transposed = []
for i in range(4):
transposed_ro... |
903201ab083f1fed72d932aa7ae7f1eec9cc8e82 | folkol/tutorials | /python3/4.6.functions.py | 658 | 4.3125 | 4 | def fib(n):
"""Print a Fibonacci series of to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
fib(100)
print(fib.__doc__)
def fib_list(n):
"""Returns a list containing the Fibonacci numbers up to n."""
result = []
a, b = 0, 1
while a < n:
... |
22910b17a85c84b34ead34de479cd33530304f09 | folkol/tutorials | /modern_python/2.2.bootstrapping.py | 609 | 3.78125 | 4 | # Bootstrapping is used when re-sampling is hard or expensive
from random import choices
timings = [7.18, 8.59, 12.24, 7.39, 8.16, 8.68, 6.98,
8.31, 9.06, 7.06, 7.67, 10.02, 6.87, 9.07]
from statistics import mean, stdev
mean(timings)
stdev(timings)
# Build a 90% confidence interval
def bootstrap(data)... |
ed67af2c5a5a5c4b12576d304914a92f89d1985e | folkol/tutorials | /python3/5.1.3.list_comprehension.py | 663 | 4.03125 | 4 | x = None
print(x)
squares = []
for x in range(10): # Will leak (and overwrite!) x...
squares.append(x ** 2)
print(squares)
print(x)
x = None
double = lambda x: x * 2
squares = [double(x) for x in range(10)] # Will not leak x
print(squares)
print(x) # Still None
# The rightmost for iterates most frequently. T... |
bf8adf2361ef5a588475ec9b86deabab9b59cab3 | folkol/tutorials | /modern_python/1.1_fundamental_data_analystics.py | 2,350 | 3.640625 | 4 | # %-formatting .format f''
x = 10
print('The answer is %d today.' % 10)
print('The answer is {0} today.'.format(x))
print('The answer is {x} today.'.format(x=x))
print(f'The answer is {x} today.') # Compiled, not evaled
print(f'The answer is {x :08d} today.')
print(f'The answer is {x ** 2 :08d} today.')
# ra... |
791e8a1eb52259f82c7a174b81c2fb1fa71d4335 | folkol/tutorials | /python3/4.3.range.py | 315 | 3.578125 | 4 | words = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(words)):
print(i, words[i])
for i, word in enumerate(words):
print(i, word)
for i, word in enumerate(words, start=666):
print(i, word)
for i in range(0):
if i is 11:
print(i)
break
else:
print("Didn't break")
|
109930802dbe6b749cdeb968240e1506ff54545a | Draculinio/Evil-Tesuji | /Engine.py | 997 | 3.59375 | 4 | __author__ = 'Pablo'
import board
import random
class Engine:
def __init__(self):
self.color = 0
#Here is the process to put a stone.
def put_stone(self,color,my_board):
#Here goes all the magic.
if color=="WHITE":
self.color=2
else:... |
615fc99fe5103f7a0f9f76ebd0b42272f7804beb | ye-susan/projectEuler | /problem001.py | 603 | 4.28125 | 4 | '''
Problem 1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
sum = 0
for num in range(0, 1000):
#if num is divisible by 3 and 5 - add num to sum, else, check that it's d... |
dedde0abfee11d50d222d525f16baf396e2ff1b2 | donnep28/Calculator | /Calculator-2.py | 3,667 | 3.671875 | 4 | from tkinter import *
class calculator(object):
Count = 0
def __init__(self, master, stack = []):
# Set up application
self.stack = stack
self.master = master
master.title('Calculator App')
# create screen widget
self.screen = Text(master, state = 'disabled', ... |
4cd29aa0821443cf8a67033ccac999280019647a | legendarus/pennisattack | /penis_project/bullet.py | 1,344 | 3.875 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""Создаёт пули корабля"""
def __init__(self,pa_settings,screen, ship):
"""Cоздаёт объект пули в текущей позиции корабля"""
super().__init__()
self.screen = screen
#Создание пули в позиции (0,0) и назн... |
221cb87c96becce61f3dad6a7fbde4fff4b070eb | BXGrzesiek/Python_Projects | /scripts/fib.py | 934 | 4.3125 | 4 | # script generating a list with fibonacci sequence elements
# the user is asked for the number of elements
# to reduce the load of computing power,
# the list is displayed after all X elements have been generated
from time import sleep
def fib(n):
try:
if n == 0:
return 0
elif... |
721e2ff5de164b072bab578c5696097ea5b75453 | NielRoman/BSIT302_activity1 | /Enployee.py | 1,553 | 4.3125 | 4 | Employee = []
class employ:
def __init__(self, name, department, position, rate):
self.name = name
self.department = department
self.position = position
self.rate = rate
list = True
while list:
print("""
************************************
Choose Your Option:
[1] Add New Employee's Name
[2] Enter Hourly... |
031f6125cfcc9048ef8ef7826828a3a2fc671d70 | spettigrew/cs2-codesignal-mod-quizzes | /problem_solving/postive_sum.py | 979 | 4.25 | 4 | """
Given an array of integers, return the sum of all the positive integers in the array.
Examples:
csSumOfPositive([1, 2, 3, -4, 5]) -> 1 + 2 + 3 + 5 = 11
csSumOfPositive([-3, -2, -1, 0, 1]) -> 1
csSumOfPositive([-3, -2]) -> 0
Notes:
If the input_arr does not contain any positive integers, the default sum should be... |
f10ab0281a1c0cd70ab11f07d79e37e062f1b0d9 | spettigrew/cs2-codesignal-mod-quizzes | /computer_memory_basics/raindrops.py | 1,586 | 4.5625 | 5 | """
Given a number, write a function that converts that number into a string that contains "raindrop sounds" corresponding to certain potential factors. A factor is a number that evenly divides into another number, leaving no remainder. The simplest way to test if one number is a factor of another is to use the modulo ... |
1bf90ec0db09546d69f3b08820a6f395b60c3716 | spettigrew/cs2-codesignal-mod-quizzes | /problem_solving/remove_vowels.py | 1,237 | 4.21875 | 4 | """Given a string, return a new string with all the vowels removed.
Examples:
csRemoveTheVowels("Lambda School is awesome!") -> "Lmbd Schl s wsm!"
Notes:
For this challenge, "y" is not considered a vowel.
[execution time limit] 4 seconds (py3)
[input] string input_str
[output] string
"""
def csRemoveTheVowels(inpu... |
88285143629d288c3bed4987403b3ec92cc05f0a | Thanisha08/image-processing | /Assignment 1/array operation.py | 1,335 | 4.03125 | 4 | """
.. module:: 3D array operations
:platform: Windows
:synopsis: This module does simple details
.. module author:: Thanisha
.. copyrights: Karomi Technology Private Limited
.. date created: 08/08/2018
"""
import numpy as np
def add(d, e):
"""
this function adds two 3D array
:param d, e: Two 3-D... |
ca75c458d27e49fd0f540b9869f75b5831b2d956 | cs-fullstack-2019-fall/python-basics2f-cw-LilPrice-Code | /index.py | 2,293 | 4.375 | 4 | import random
# Problem 1:
#
# Write some Python code that has three variables called greeting, my_name, and my_age.
# Intialize each of the 3 variables with an appropriate value,
# then rint out the example below using the 3 variables and two different approaches for formatting Strings.
#
# Using concatenation and the... |
90f8097c9451b5b17d5ee2035206eb7e9dbea17a | SaCut/data_collections | /lists&tuples.py | 794 | 4.1875 | 4 | # creating a list
# shopping_list = ["bread", "chocolate", "avocados", "milk"]
# # 0 1 2 3
# print(shopping_list)
# print(type(shopping_list))
# list indexing
# print(shopping_list[0])
# # change a value in the list
# shopping_list[0] = "orange"
# print(shopping_list)
# # add a value to a list
# shopp... |
a157445abacc5fd4135355287103af93bc5933d4 | ludimigliozi/python520 | /Aula 3/parametros.py | 1,671 | 4.03125 | 4 | #!/usr/bin/python3
''' Parametros Python
Documentação'''
####
## parâmetros de função
####
# def retorna_pessoa(nome,idade=99):
# print(f'nome: {nome}\n idade: {idade}')
# retorna_pessoa('Daniel',idade='19')
# ### Especificar tipo de parâmetro e retorno
# def retorna_valor_int( inteiro : int) -> int:
# ... |
f2d33013daa5e80e6501b947703fdbd1ec18a5fc | lincrampton/pythonHackerRankLeetCode | /isPowerOf4.py | 558 | 3.59375 | 4 | '''Given an integer (signed 32 bits), write a function to check whether it is a power of 4. So 16 is a power, as is 0.25 '''
class Solution:
def isPowerOfFour(self, num: int) -> bool:
if num <= 0 :
return False
if num >= 1:
return not(num & (num-1)) and not(num & 0xAA... |
f49900c5308fbec81a5ff6a6e7ba9394ff352583 | lincrampton/pythonHackerRankLeetCode | /leetPascalII.py | 400 | 3.765625 | 4 | '''Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.'''
class Solution12aug:
def getRow(self, rowIndex):
row = [1] #every row starts with 1
for P in range(1, rowIndex+1):
row.append(row[P-1] * (rowIndex-P+1)//P)
return row
input1 = 3
output1 = [1,3,3... |
8fd80e2738feb4d08e9cb8ac9d78f943c5265d21 | lincrampton/pythonHackerRankLeetCode | /existWordSearch.py | 1,022 | 3.890625 | 4 | '''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 cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.'''
class Solution:
def exist(self, board: List[... |
e56869731f3da0b497e669d5a8852aca9cac7a5f | lincrampton/pythonHackerRankLeetCode | /complexNumberMultiply.py | 675 | 4.03125 | 4 | '''A complex number can be represented as a string on the form "real+imaginaryi" where:
real is the real part and is an integer in the range [-100, 100].
imaginary is the imaginary part and is an integer in the range [-100, 100].
i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the compl... |
936f955c53b9aaa62a058c0f5e23805ee1680f95 | lincrampton/pythonHackerRankLeetCode | /numsSameConsecDiffs.py | 1,377 | 3.65625 | 4 | '''Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K. Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid. You may return the answer in ... |
b75cdb242b26c735f1afde00aca2260415091f75 | lincrampton/pythonHackerRankLeetCode | /wordDitionary.py | 1,332 | 4.0625 | 4 | '''Design a data structure that supports the following two operations: void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.'''
# Your WordDictionary object will be instantiated and called ... |
c99cb40b55ea8c0f8da481e3c76bcc730d882581 | lincrampton/pythonHackerRankLeetCode | /swapCase.py | 504 | 4.375 | 4 | '''return a string that has upperCase->lowerCase and lowerCase->upperCase
e.g., 'I am Sam I am!" would become "i AM sAM iAM!"
def swap_case(s):
return_string = ""
for i in range(len(s)):
if s[i].islower():
return_string += s[i].upper()
elif s[i].isupper():
return_s... |
54482b0ebb8235fb66db096fc1dbe569061751ae | lincrampton/pythonHackerRankLeetCode | /string2npArray.py | 284 | 4.4375 | 4 | '''You are given a space separated list of numbers.
Your task is to print a reversed NumPy array with the element type float.'''''
linzStr = " 2 3 4 5"
linzLst = list(map(int,linzStr.split()))
linzLst = linzLst[::-1]
import numpy as np
linzNp = np.array(linzLst, float)
print(linzNp)
|
0b69eba9d411bbc5b1d3b2b2ff2aa2570c27b27a | lincrampton/pythonHackerRankLeetCode | /findDuplicates.py | 430 | 3.9375 | 4 | '''Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime?'''
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
im... |
f605c176c9860b18b241c43902f97ed98b3c848f | lincrampton/pythonHackerRankLeetCode | /rottenOranges.py | 1,197 | 3.609375 | 4 | '''In a given grid, each cell can have one of three values: 0 (empty cell); 1 (fresh orange); 2 (rotten orange). Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impos... |
7e44d28d1463ec6d190dac550cc4a75ca33a97c6 | RonildoSilva/Resolucao-Listas-PAA | /resolucao/r06/q01.py | 640 | 3.90625 | 4 | # produtos como um hash
# onde a chave é o nome do produto
# e o valor, o preco do produto
# com (m) produtos
produtos = {
"pão": 2.39, "leite": 5.29,
"sabonete": 1.09, "sabão em pó": 9.99
}
# lista de compras representada por
# uma lista de items de tamanho (n)
lista_compras = ["leite", "sabonete", "sabonete... |
696cecc070d760e12ae722e58e7a2cb3bc6dc154 | jerryrong/MITx6.00x_ProblemSets | /ProblemSet5/ps5_recursion.py | 3,291 | 4.25 | 4 | # 6.00x Problem Set 5
#
# Part 2 - RECURSION
#
# Problem 3: Recursive String Reversal
#
def reverseString(aStr):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are allowed to use are ... |
6a7c54e7d9039d22ac0ec16226d3a8c47111695e | averjr/Python-playground | /GL test/GL.py | 6,914 | 3.546875 | 4 | import locale
import math
from decimal import *
from eng import correction_list,currency_cent,currency_delimiter,currency_unit,delimiter,hundreds,numerators,ranges,ranges_multiple,ranges_single,tens,ranges_single,ranges_multiple,correction_list
LANG = 'eng'
global correction_list,currency_cent,currency_delimiter,curre... |
69586b04eadf63f9a1326832cdb01df81257bc84 | averjr/Python-playground | /test.py | 1,010 | 3.8125 | 4 | import math
def is_palindrome(n):
string = str(n)
if string == string[::-1]:
return True
return False
def is_prime(n):
for j in range(2, int(math.sqrt(n)+1)):
if n % j == 0:
return False
return True
def multiply(primes):
# [first prime, second prime, multipl]
... |
4616f70fc68c11cfa89707aadd60446df02fd481 | luroto/lpthw | /ex6.py | 691 | 4.4375 | 4 | # Setting a first variable
types_of_people = 10
# Creating a string using this variable
x = f"There are {types_of_people} types of people."
#Setting two more variables
binary = "binary"
do_not = "don't"
# Another string using variables and f option
y = f"Those who know {binary} and those who {do_not}."
# setting vari... |
e421998be4f04317e2b2ba091c8e98293121e835 | PFeynman/Daily-Coding-Problem | /Problem 4/problem_4.py | 700 | 3.578125 | 4 | # My idea made no sense (I wrote it before going to sleep, without thinking a lot).
# After much thinking, I looked for the solution in geeksforgeeks.org, understood it and implemented it.
def separate(array):
j = 0
for i in range(len(array)):
if array[i] <= 0:
array[j], array[i] = array[i], array[j]
... |
726e6e1784183be965634ab02ca3f1f6784fa00d | PFeynman/Daily-Coding-Problem | /Problem 1/test_problem_1.py | 1,032 | 3.546875 | 4 | import unittest
from problem_class import Problem
class TestsProblem1(unittest.TestCase):
def setUp(self):
self.problem = Problem(17, [10, 15, 3, 7])
def test_K_is_defined(self):
self.assertIsInstance(self.problem.k, int)
def test_list_of_numbers_is_defined(self):
self.assertIsInstance(self.prob... |
4236fb201d84748741e8b7f53c955c43e6e039e5 | DaryaSanina/text-generation | /text_normalization.py | 2,178 | 3.765625 | 4 | import nltk
import pycld2
from pymorphy2 import MorphAnalyzer
from re import findall
from sys import argv
# A PorterStemmer object to stem the text in English and a MorphAnalyzer object to lemmatize the text in Russian
stemmer = nltk.stem.PorterStemmer()
morph = MorphAnalyzer()
def normalize(text, languag... |
fcc08e803e09eb81d5c0b1839447b1ce81bb712e | ldcx1/gad-python-gr-2 | /tema_c2.py | 137 | 3.703125 | 4 | li = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6]
ls = sorted(li)
print(ls)
print(list(reversed(ls)))
print(ls[1::2])
print(ls[::2])
print(ls[2::3])
|
b2062f7293adae32d8ab928e8ba6900a3c60ff6f | Psychofun/Snake-Gym | /gym_snake/envs/node.py | 625 | 3.53125 | 4 | class Node:
def __init__(self, point):
# Points must be passed as tuples (x,y)
self.point = point
self.previous_node = None
# Actions must be passed integers
self.action = None
def _recreate_path_for_node(self):
nodes = [self]
prev_node = self.previ... |
607f3a7a2ba239bb519df49d0a40181193290459 | Nipun99/COHDCBIS182F-020 | /Caeser.py | 567 | 4.5 | 4 | ----Code for Encrypting----
plaintext = input('Enter Message :')
alphabet="abcdefghijklmnopqrstuvwxyz"
key=1
cipher=''
for c in plaintext:
if c in alphabet:
cipher += alphabet [(alphabet.index(c) +key)%(len (alphabet))]
print('your encrypted message is :' + cipher)
----Code for Decrypting----
plaint... |
1e9d99214b9c41ac91fe8adc381654e0bb0e9775 | isabiq/algorithms | /pascal/python/pascal.py | 335 | 4.0625 | 4 |
def pascal(r, c):
''' The function return the corresponding value in the pascal triangle, corresponding to a given (row, column)
Zero is the return value for a negative column or row.
'''
if r < 0 or c < 0:
return 0
elif r == c:
return 1
else:
return pascal (r-1, c-1) + ... |
1fd89c0384294c7db265e3978a3c80504e2d9901 | gbuchsbaum/cme211 | /hw2/similarity.py | 11,219 | 3.90625 | 4 | # This program takes in a data file containing movie ratings from an assortment
# of users, and calculates the similarity coefficients of the movies. The data
# is read from the file and placed in a dictionary. It is then processed to
# subtract the average rating for each movie from each individual rating.
# Next, the... |
0b01525ac5c9170c9440802811075aa448d672da | lhs619619/javavara-assignment | /2nd-assignment/mutation.py | 206 | 3.78125 | 4 | #필수과제 3 성공
str = input()
index = int(input())
input_char = input()
if len(str) <= index:
print("The number you gave is too large!")
else:
print(str[:index] + input_char + str[index+1:]) |
908116e678d1e914ce57d6c3ff05bcefef1fc27f | unclezap/practice | /runSum.py | 1,067 | 3.53125 | 4 | # https://leetcode.com/problems/running-sum-of-1d-array/submissions/
import time
# def runningSum(nums):
# for index in range(1, len(nums)):
# nums[index] = nums[index - 1] + nums[index]
# return nums
def runningSum(nums):
for index in range(1, len(nums)):
nums[index] += nums[index - 1]
... |
e0cc41641c4b401d1008637878513d039892a8e7 | luska92/rep2 | /ProFive/AppFive/widzimysie.py | 200 | 3.6875 | 4 |
def kiedy():
x = input("Zależy czy będziemy pić. Będziemy pić?")
if x == "tak":
print("Widzimy się w grudniu")
else:
print(input("A co będziemy robić?"))
kiedy()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.