blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
734c815aeb25ecad5b1468c3e017f2497a79bf7b | Inna99/homework | /tests/homework1/test_task2.py | 373 | 3.65625 | 4 | from homework1.task2 import check_fibonacci
def test_positive_case():
"""Checking that the data is a Fibonacci sequence"""
assert check_fibonacci([])
assert check_fibonacci([0, 1])
assert check_fibonacci([0, 1, 1, 2, 3, 5, 8])
def test_negative_case():
"""Checking that the data is not a Fibonacc... |
8c4abf0e927fc9680b536f5d0253907030ce3a29 | william-cheng/leetcode | /medium/triangle_number.py | 1,125 | 3.53125 | 4 | # 611. Valid Triangle Number
class Solution(object):
def triangleNumber(self, nums):
nums = filter(lambda x:x>0, nums)
nums.sort(reverse=True)
k = 0
count = 0
len_nums = len(nums)
while k < len(nums):
tgt = nums[k]
i = k + 1
j = len... |
2b7418e2abf921e6d82b49c850afc4fc2528c494 | ajitg9572/session2 | /session13.py | 1,374 | 3.609375 | 4 | class song:
def __init__(self,title,artist,time):
self.title=title
self.artist=artist
self.time=time
self.nextsong=None
self.previoussong=None
def showDetails(self):
print("song name{} artist :{} and time{}".format(self.title,self.artist,self.time))
song1 =s... |
292bc9c3080f0c381b0b038e674c27670d146de7 | DaminduSandaruwan/LearnPython | /OOPs/Types of Variables.py | 413 | 4.09375 | 4 | class Car:
wheels = 4 #class namespace
def __init__(self):
self.mil=10 #Instance Variable
self.com="BMW" #Instance Variable
c1=Car()
c2=Car()
print(c1.com,c1.mil,c1.wheels) #BMW 10 4
print(c2.com,c2.mil,c2.wheels) #BMW 10 4
c1.mil=8
print(c1.com,c1.mil) #BMW 8
#namespace => 1.Class N... |
e2a67436b5c20e27c60915afb3ce630d0aa9afcb | SongofG/Python_Basics | /Range_Q2.py | 124 | 3.84375 | 4 | ## Q2)
def main(num):
tpl = tuple(range(1, num+1))
tpl = tpl + tuple(range(num-1, 0, -1))
print(tpl)
main(100)
|
916e4375c80504c00c7597511c33379d26c98c7d | Totomosic/The-Multiplication | /Classes/Drop.py | 1,155 | 3.5 | 4 | import pygame
from Surface import Surface
class Drop(Surface):
def __init__(self, pos, size, color, alpha, items, lifespan):
super(Drop, self).__init__(pos, size, color, alpha)
self.items = items
self.lifespan = lifespan
self.age = 0
def update(self):
super(Drop... |
e8383fefbd097cdacaac8b8e48f0eae0836e915b | mingyong0915/TestPython | /001.py | 822 | 4.0625 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
@version: v1.0
@author: MingYong
@license: Apache Licence
@contact: 13760182207@163.com
@site: http://blog.csdn.net/mingyong_blog
@software: PyCharm
@file: 001.py
@time: 2017/4/2 22:31
"""
class MyException(Exception):
pass
myException = MyException("出... |
e7acd73e8b2fe52f629d16f5d04a50bbb03ce4b6 | brettaphillips/learning_pygame | /thenewboston/13-change_hardcoding_to_variables.py | 2,483 | 3.546875 | 4 | # Video 13 - Replace hardcoded values with variables
import pygame
game_exit = False
# Define colors using rgb values - can use list or tuple
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# Environment Variables
display_width = 800
display_height = 600
fps = 15
... |
260cfd1bbd7ac9dcaaf8a99bfbcf9ee00c1c061f | ainunfarichah/week-10 | /main.py | 2,148 | 3.6875 | 4 | import os
A = []
B = []
J= []
K= []
menu = ['1.Penjumlahan','2. Pengurangan','3. Exit']
print ("=======Selamat Datang di Operasi Matriks 2x2====")
print ("MASUKKAN MATRIKS A")
print(" ")
for baris in range (0,2,1) :
for kolom in range (0,1,1) :
print ("Baris ke-" , baris+1 ," Kolom ke-",kolom+1)
... |
364aab4d7f1a6868bb6d1f53cf121044cb8820fe | MarkoSijacic/AutomateBoringStuffPython | /FantasyGameInventory.py | 833 | 3.828125 | 4 | #make a dictionary inventory
myInv = {'gold': 24, 'potion': 3, 'sword': 1}
#create and run a function which will show a dictionary inventory in a fantasy RPG formating
def showInv(inv):
print ('Items in inventory')
x = list(inv.values())
y = list(inv.keys())
totalItems = 0
for i in range (len(inv)):
print (x... |
014c6266426b854f32b8bbc55de145f110e2f04f | Akshaypakhle10/ML | /Test/data_preprocessing.py | 1,471 | 4 | 4 | #Importing libraries
import pandas as pd
#Loading the dataset
df = pd.read_csv('purchase_data_class_4.csv')
#Reviewing dataset
df.head()
#Separating features and labels
X = df.iloc[:, :-1].values
y = df.iloc[:, 3:].values
print X, y
#Check for missing data
df.isnull().sum()
#Handling Missing data
from sklearn.pre... |
2d77153d964e5f2cd37458891a16209327bce0f3 | mrinmayig/Python-data-structures-and-algorithms | /coloringproblem.py | 1,086 | 3.71875 | 4 | def minPrice(cost):
lengthofcost=len(cost)
adj=[0]*lengthofcost
adj[0]=cost[0].index(min(cost[0]))
result=min(cost[0])
i=1
while i<lengthofcost:
print(i)
if cost[i].index(min(cost[i]))==adj[i-1]:
print('if',i)
if cost[i].index(mi... |
34c6ac3e7ee41ef3ec25650705e8118ca8479ec4 | LebedevOleg/pylaba1 | /venv/Task3/laba1_3.py | 1,084 | 3.625 | 4 | from tkinter import*
import Queue
def click1():
tempint = txt1.get().split(" ")
tempint = [int(i) for i in tempint]
for i in tempint:
q1.add(i)
lbl1.configure(text = q1)
txt1.configure(text = "")
def click2():
q1.clear()
lbl1.configure(text=q1)
def click3():
lbl3.configure(text=... |
6c665bd031ebedbe735c5c9fd529911bfa5dea7f | ranjithkumar121/Python | /ASSIGNMENT 12/5.IsBalanced.py | 163 | 3.765625 | 4 | def isBalanced(s):
c1=s.count("{")
c2=s.count("}")
if c1==c2:
return True
else:
return False
s=input()
print(isBalanced(s)) |
6bedca08765653e604b60d7b1de4c5b74f0d379c | emildekeyser/tutoring | /fh/opl/oefenzitting_3_opl(1)/E11 replace with self or largest neighbour.py | 1,494 | 4.25 | 4 | #numbers is a list we fill with integers the user provides.
numbers = []
new_number = input("What number would you like to add?: ")
#Keep adding numbers until the user enters the character 'q'.
while(new_number != 'q'):
numbers.append(int(new_number))
new_number = input("What number would you like to add?... |
ac7938bec7001cbf46a10ad969e47f5c5e3f151c | virgilraj/python-interview | /problems/find_element_in_sorted_array.py | 643 | 4.03125 | 4 | #Circular array
def find_ele_sorted_array(arr, X):
left, right = 0, len(arr)-1
while(left <= right):
mid = (left + right)//2
if arr[mid] == X:
return mid
#Right half
if arr[mid] <= arr[right]:
if arr[mid] < X <= arr[right]:
left ... |
98a020cb19236dc093d11a91e363a2273dfd9e2b | AmritaDeb/Automation_Repo | /PythonBasics/Prog_18_12_29/4.LargestNoInList.py | 217 | 3.734375 | 4 | class LargestNoInList:
def findLargest(self,l):
l.sort()
print("The largest No: ",l[-1])
for i in reversed(l):
print(i)
ob=LargestNoInList()
l=[45,65,78,52,98]
ob.findLargest(l) |
9cb70838799bc75a2d28cf96b08f6077f06119e1 | rolinj/my-hackerrank | /python-proficiency/alphabet-rangoli.py | 1,259 | 3.75 | 4 | import string
alphabet = list(string.ascii_lowercase)
def print_rangoli(size):
# your code goes here
if size == 1:
return print("a")
# top section ====================================
print(alphabet[size-1].center((size * 4) - 3, '-'))
for i in range(1, size-1):
top_list ... |
388ea6d22a7e7196a3ba471c1caccc03f5f6a3c1 | brainwaves7/Level-0-coding-challenges | /Task0_10.py | 348 | 3.96875 | 4 | def common_letters(first_word, second_word):
result = []
for element in second_word:
if element in first_word:
result.append(element)
result = ", ".join(result)
print(f"Common letters: {result}")
def main():
common_letters("house", "computers")
if __name__ ... |
f09b295ddd7e7b42d39f4aeae6a2b46db5e15c6a | ykim5470-Lewis/westagram | /Info1110/week02/calculations.py | 93 | 3.671875 | 4 | base = 30
kate = 50
if kate>base:
print("kate is older")
else:
print("base is older") |
fcd6b1a37f043f66574f6a18e43e34665923c291 | john-polvorosa-rogers/PythonAlgorithms | /Exercise Files/1 Introduction/gcd2.py | 465 | 3.84375 | 4 |
# Euclid's Algorithm to find the Greatest Common Denominator
# Two numbers, one greater than the other (a > b)
# Divide a/b, if remainder 0, GCD is b
# else a = b, remainder = b, then repeat until remainder = 0
def gcd2(a, b):
while(b != 0):
r = a % b
if (r == 0):
return b
else... |
9edc855cca2444b4a5df099abe8c1133e550b5f4 | grand719/kolko_krzyzyk | /main.py | 2,627 | 3.59375 | 4 | import random
field = []
def clearField():
if len(field) == 9:
for i in range(0, 9):
field[i] = ' '
else:
for i in range(0, 9):
field.append(' ')
def drawBoard(board):
i = 0
while i < len(board):
print(board[i], "|", board[i+1], "|", board[i+2])
... |
6f76efb6df755f6a81dbb7719430690186462564 | EddylianOrigin/Chapter2_Python | /mypy.py | 245 | 3.875 | 4 | list_a=[10,20,30]
list_b=["Jan","Peter","Max"]
for val_a, val_b in zip(list_a, list_b):
print(val_a, val_b)
print("\n")
for i in range(len(list_a)):
print(i, list_a[i])
print("\n")
for i, val in enumerate(list_a):
print(i, val)
|
e82f19d183d335bb4d25182a4c043e29976aa7e2 | GalyaBorislavova/SoftUni_Python_Fundamentals_January_2021 | /2_Data types and Variables/Exercises and More Excercises/05. Print Part of the ASCII Table.py | 131 | 3.8125 | 4 | start_index = int(input())
end_index = int(input())
for chars in range(start_index, end_index + 1):
print(chr(chars), end=" ") |
e429880fb4e4420a924dba651bb9aa47bf5b235c | Bukurov/all | /Временной ключ.py | 294 | 3.515625 | 4 | a = int(input())
def code_2(a):
list_a =[]
p = 0
b = True
while b:
if a >= 2:
list_a.append(a % 2)
a = a//2
else:
list_a.append(a)
b = False
for i in list_a:
p +=i
return p
g = code_2(a)
print(a+g)
|
dac8ff5803f7cd3ed78c7f5128b1d9ac37a91f2c | mateuszkowalke/sudoku_game | /logic.py | 2,853 | 3.546875 | 4 | import copy
empty_board = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0,... |
fee7ce8942e3212ca57936228d31d2f4ed97e711 | ShivangDave/Python-Programs | /Trie.py | 1,307 | 3.6875 | 4 | # Reference: https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
from typing import Tuple
class Trie:
def __init__(self,char: str):
self.char = char
self.children = []
self.wordFinished = False
self.counter = 1
... |
46dd79f9cde9eedd3eaed3f5332f49e3adb14174 | itsrbpandit/fuck-coding-interviews | /problems/implement_strstr.py | 742 | 3.65625 | 4 | # coding: utf-8
"""
https://leetcode.com/problems/implement-strstr/
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
n_length = len(needle)
for i in range(len(haystack)):
if haystack[i:i + n_length] == needle:
... |
afd5b3d0602bcd7bf2f36fcd24a3f6c1bd1c65bf | rosannahanly/Airline_Program | /classes/flightPlan.py | 5,797 | 3.546875 | 4 | '''
Created on 27 Apr 2018
@author: rosannahanly
'''
from math import sin, cos, radians, asin, sqrt
from classes.airport import Airport
from classes.aircraft import Aircraft
from classes.currencyExchange import CurrencyCode, CurrencyRate
import csv
import sys
class FlightPlan:
'''
Class that finds the best a... |
04f5828866c34140910c432a8beba4c10f32c511 | Tamalika1995/Udemy_Practice | /Practice_100/p37.py | 220 | 4.09375 | 4 | '''Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included)..
'''
def print_list():
L=[i**2 for i in range(1,21)]
print(tuple(L))
print_list() |
24b05096372a02b2801eb901c86804daf40ec534 | Ribosome25/myToolbox | /_top_percentile.py | 1,176 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 16:59:52 2019
@author: Ruibzhan
return the threshold value.
"""
import numpy as np
import pandas as pd
def top_percentage_distribution(data, percentage, pick_highest = True, return_values = False):
'''
Given a dataset, find the top % of this distribution.
... |
3d526c55b2aaed886ce3acb49d435cc50925f317 | jdegreeff/cognitive_model | /src/test.py | 206 | 4 | 4 | #
#i = 3
#if i == (1 or 2):
# print "yes"
#else:
# print "no"
def function(i):
x = 0
while x < i:
print "test"
return x
x += 1
print "end"
print function(5) |
bd899d4d25ca7d215bfc5254ecf6528d6dd2c4ed | PoojaLokanath/PythonCode | /exception.py | 1,841 | 4 | 4 | prompt = "Enter a number"
while True:
try:
x = int(input(prompt))
break
except ValueError:
print("Invalid Input...Try Again...")
print("+++++++++++++++")
while True:
try:
data = input("Enter value")
x = int(data.split(',')[1])
break
... |
9b59481d49d123e4eb3347243a9a4e7b97bfa95b | kirthikartm/guvi | /reverse_player.py | 83 | 3.59375 | 4 | a=int(input(""))
r=0
while(a!=0):
re=a%10
r=re+(r*10)
a=a//10
print(r)
|
c3896fed362986592dc02dbdde2bfb7c8f33e113 | DanielFernandezR/python | /ejercicios_audacity/sudoku/checkNumero.py | 1,333 | 3.6875 | 4 | def checkNumerosEnteros(sudoku):
assert isinstance(sudoku, list)
sudokuSano = True
for fila in sudoku:
for numero in fila:
if not isinstance(numero, int):
sudokuSano = False
break
assert isinstance(sudokuSano, bool)
return sudokuSano
def checkNum... |
fc27b2fdadfa6afcb5061d3651878bd9938e9b82 | skoolofcode/SKoolOfCode | /CodeNinjas/functions.py | 333 | 3.8125 | 4 | def hello(personname, day):
dayOfTheYear = 45
print("Hello " , personname, "Have a happy ",day)
print("Day of the year is ", dayOfTheYear)
return dayOfTheYear
dayToday = "Monday"
name = "Suhas"
dayReturned = hello(name,dayToday)
print("Print the returned day", dayReturned)
name= "Sonakshi"
hello(name,... |
a127badfe6db85f18659fd7d1d3741d8e4e7f4e0 | Kylar42/wvup | /Project Euler/euler13.py | 240 | 3.75 | 4 | def sumDigits(bignum):
cursum=0
while(bignum > 0):
cursum += bignum%10
bignum /= 10
return cursum
numfile = open("bignums.txt", "r")
myList = numfile.readlines()
#sum
mySum = 0
for line in myList:
mySum += int(line)
print mySum |
75b1f6ca232e63ee70331b1257b808368c3f4a93 | bentsmith/itt385 | /NameInLights.py | 346 | 3.9375 | 4 | starCount = 60
line1 = "*" * starCount
line3 = "*" * starCount
name = input("What is your name? ")
spaceCount = starCount - 2 - len(name)
space = spaceCount / 2
space1 = " " * int(space)
if len(name)%2 == 1:
space2 = space1 + " "
else:
space2 = space1
print(line1)
print("*" + space1 + name + spa... |
f0880ae13d96e5c1fb88976e91815bf347493eb1 | caiqinxiong/python | /Django/rbac/day72/luffy_permission - 8 角色和菜单管理 + 权限展示/3. 字典的排序.py | 640 | 3.796875 | 4 | from collections import OrderedDict
dic = OrderedDict()
dic[3] = 3
dic[1] = 1
dic[2] = 2
menu_dict = {
2: {
'title': '财务管理',
'icon': 'fa-usd',
'wight': 10,
'children': [
{'title': '缴费列表', 'url': '/payment/list/'},
{'title': '账单列表', 'url': '/oder/list/'}
... |
850e742b718cff7da925ce73d38108e0df1ef3fb | eugenenuke/Python_lessons_basic | /lesson02/home_work/hw02_hard.py | 7,092 | 4.1875 | 4 | #!/usr/bin/env python3
print("\nЗадание 1\n")
# Задание-1: уравнение прямой вида y = kx + b задано в виде строки.
# Определить координату y точки с заданной координатой x.
equation = 'y = -12x + 11111140.2121'
x = 2.5
# вычислите и выведите y
a, op, b = (equation.split()[2:])
a = float(a[:-1])
b = float(b)
# Вообщ... |
237f15b2201dddf1cccdbb69c44f405a1dd9f849 | SfTI-Robotics/Code-Comparison | /Q-Learning/Roulette-v0/Roulette.py | 1,900 | 3.5 | 4 | import numpy as np
import random
#used to decay epsilon after each step
MAX_EPSILON = 1.0
MIN_EPSILON = 0.01
DECAY_RATE=0.005
#good idea to do to get same "random" values
np.random.seed(1)
#here is the class we use to call our functions, it doesn't take in parameters
class QLearning:
#to make sure initialisation wor... |
58c3fc4796406f4201ce1f30fb50079bf0a3419d | william01424/CodeWarsAnswers | /ArraySplitting.py | 1,075 | 4.1875 | 4 | '''
You are going to be given an array of integers.
Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N.
If there is no index that would make this happen, return -1.
For example:
Let's say you are given the array {1,... |
93f7f3c9b1fe4a87e99f3d599bdc05160e6c85ad | agonzalezcurci/class-work | /10.3.py | 583 | 3.671875 | 4 |
import string
fname = input("Enter the file: ")
try:
fhand = open(fname)
except:
print("File cannot be opened: ", fname)
exit()
counts = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans(" ", " ", string.punctuation))
line = line.lower()
words = line.split()
for word in wor... |
61b73b8c47bfc44898de22c34958746f5a431c5a | moragbl/checkio | /end_of_other.py | 584 | 4.0625 | 4 | #!/usr/bin/python
def checkio(words_set):
if (len(words_set) <2 or len(words_set) > 29):
return False
for word1 in words_set:
for word2 in words_set:
if word1.endswith(word2):
if word1 != word2:
return True
return False
assert checkio({"hello", "lo", "he"}... |
c635827fe1d1b903cefa99aa2af064d1c010a808 | dposlt/blbustky | /nasobky.py | 945 | 3.828125 | 4 | #!/usr/bin/python env
__author__ = 'David Poslt'
class nasobky:
def __init__(self, hodnota, words1, words2, words3):
self.hodnota = hodnota
self.words1 = words1
self.words2 = words2
self.words3 = words3
def multiple(self,first_nasobek, second_nasobek):
self.first_n... |
10eb02f3d812d8539cad62998364a58c797221ef | wilguo/File-Compressor | /huffman.py | 19,303 | 3.984375 | 4 | """
Code for compressing and decompressing using Huffman compression.
"""
from nodes import HuffmanNode, ReadNode
# ====================
# Helper functions for manipulating bytes
def get_bit(byte, bit_num):
""" Return bit number bit_num from right in byte.
@param int byte: a given byte
@param int bit_nu... |
4e9375c26de57c57c2fb4f3188330b68e2f3bc36 | nimra200/caeser-cipher | /cipher.py | 1,486 | 4.375 | 4 | CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LOWER = "abcdefghijklmnopqrstuvwxyz"
def decrypt_message(secret_message:str, key:int) -> str:
""" Decrypt a secret message by subtracting the key from each letter.
Preserve all other symbols in the message.
Precondition: secret_message is a string and key is an integer.
... |
5993b4c593dd6178d29a34f1474e7b20f2825029 | MS642/python_practice | /decorators_generator/generator_and_iterator.py | 684 | 3.75 | 4 | import random
def gen_fibo(n):
a = 1
b = 1
for x in range(n):
yield a
a, b = b, a+b
for x in gen_fibo(10):
print(x)
s = 'hello'
for c in s:
print(c)
it = iter(s)
print(next(it))
print(next(it))
for c in s:
print(c)
print(next(it))
def gensquares(N):
for x in range(... |
f2b268e1aebe7eb0d8b383c0074ed61fb93a899e | zpreator/Engineering | /ME342NumAnalysis/Unit5/Assignment51.py | 2,059 | 3.6875 | 4 | import matplotlib.pyplot as plt
from matplotlib import rcParams
import numpy as np
"""
Zachary Preator
Mastery Level: 10
"""
def x1(t):
return -np.exp((-2+np.sqrt(2))*t)
def x2(t):
return -np.exp(-2*t)
def x3(t):
return -np.exp(-2*t)*(np.cos(2*t)+np.sin(2*t))
def v1(t):
return -(-2+np.sqrt(2))*np.exp... |
23ff44faad83c4830a34bb1933956b2a492753bc | rohanaggarwal7997/Studies | /Python/ifelse.py | 284 | 3.71875 | 4 | import random
import os
import sys
var=15
age=30
if(var>16):
print("rohan")
print ("rohan1")
print("rohan2") #so wherever the indentation is broken ther it ends it
if ((age>=1)and(age<=18)):
print("HI")
elif ((age==1)or(age>=65)):
print("Bi")
elif (age==30):
print("hibi")
|
e361a2522de4230e90b678e081759d872b6734cc | r4ya/Numerical-Analysis | /fixed-point.py | 493 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 14 18:10:35 2020
@author: ryavu
"""
import math
def fixedpoint(function,xo,TOL,MAXN):
i = 0
error=1
print("Iter","Point"," Function","Error",sep=' ')
while((error > TOL) and (i < MAXN)):
x = function(xo)
error = abs(x-xo)
pr... |
92fc458bce3dc27f7553396f12e4fa1f34db825e | Cyan233/DB | /import_csv.py | 450 | 3.59375 | 4 | import csv
with open('customer.csv', encoding='utf-8') as f:
reader = csv.reader(f)
print("header:")
header = next(reader)
print(header)
print(type(header))
listv = header[0].split("|")
print(listv[0])
print(type(listv[0]))
print("reader:")
for row in reader:
listr = row... |
650f4fa1351b9223bea72b7277cb573cc8972878 | bharath-reddy-429/Python-Training | /ListOne.py | 47 | 3.546875 | 4 | l=[1,2,3,4,5]
print(l)
for i in l:
print(i) |
d509337fc6c0afa6b2a2c676981e070300badf65 | C-CCM-TC1028-102-2113/tarea-2-LuisAlbertoHernandez151202 | /assignments/01IdentificaSigno/src/exercise.py | 349 | 3.890625 | 4 | import math
def main():
#escribe tu código abajo de esta línea
print("Dame 10 números")
numero=int(input())
numeros={1:"uno",2:"dos",3:"tres",4:"cuatro",5:"cinco",6:"seis",7:"siete",8:"ocho",9:"nueve",10:"diez"}
print("El numero es:")
for i in range (10):
print(numeros[i+1])
pass
if __name__ ... |
3323fe78f50ec2032109d3a2da37913d29181f22 | dldldlfma/py_tutorial | /sqlite_tutorial/delete_sql.py | 215 | 3.5 | 4 | import sqlite3
conn = sqlite3.connect('./person.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM PERSON_INFO WHERE AGE=29")
conn.commit() #commit을 해줘야 값이 반영됨
cursor.close()
conn.close() |
a90310baef2c33a44c7a06cd8f163cbf889d2b5a | Sergey55/leetcode | /Python/27. Remove Element.py | 1,764 | 4.15625 | 4 | """Solution for problem #27. Remove Element
Description: Given an array nums and a value val, remove all instances of
that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying
the input array in-place with O(1) extra memory.
The order of elements ca... |
10b8a50b8c37ab3eb284633f7c1c3af4646cb324 | jiacai2050/leetcode | /py/342.py | 468 | 3.59375 | 4 | # https://leetcode.com/problems/power-of-four/
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return bool(num > 0 and \
not num & (num - 1) and \
len(bin(num)[2:]) & 1)
if __name__ == '__main__':
s... |
4ce6b83d7ca06c70f3cd60b0dd9cb37b5b7171e3 | PythonRam/Hit-Sort | /Python/hitsort.py | 1,791 | 3.703125 | 4 | #################################################################### supporting functions
def getminimum(array):
sqrt=isqrt(len(array))
mini=[]
for i in range(0,len(array),sqrt):
mini.append(minimum(array[i:i+sqrt]))
return minimum(mini)
def minimum(array):
if array:
... |
4e7ac0678ce9e104ebb924f15805bf75625baa2c | krishanuOP/madlibs | /madlibs.py | 954 | 4.1875 | 4 | adjective= input("enter an adjective:")
nationality= input("enter any nationality:")
name= input("enter a name:")
noun= input("enter a noun")
plural_noun= input("enter a plural_noun:")
number= input("enter a number:")
shapes= input("enter a shape:")
food= input("enter a food:")
person=print("enter a person:")
... |
c3c57a890e0ceb97f1728ab30b385a19acd5a231 | srinskit/LabSem3 | /DSA/7/MinHeap.py | 1,935 | 3.59375 | 4 | class MinHeap:
def __init__(self, in_list=[]):
self.arr = None
self.build_heap(in_list)
@classmethod
def parent_index(cls, index):
return (index - 1) // 2 if index != 0 else None
def left_index(self, index):
return 2 * index + 1 if 2 * index + 1 <= self.last_index() els... |
8f66f154bda2fe0a1538a88c6d23972263a4fa01 | LeenaJawale/MachineLearning | /KernelMethods/kernelMethods_Scikitlearn.py | 3,544 | 3.5 | 4 | #Import libraries
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.kernel_ridge import KernelRidge
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
#read data into dataframe
data = pd.read_csv("C://Users//VISHAL//Pycha... |
9c193635666d2708640fa79d77ac2555ad58e2d4 | GeeB01/Codigos_guppe | /reversed.py | 316 | 4.28125 | 4 | """
Reversed
OBs: Não confundir com reverse() que estudamos nas listas.
A função reverse() só funciona em listas
Já a função reversed() funciona em qualquer iteravel
A função reversed() retorna um iteravel chamado : 'List reverse iterator'
"""
lista = [1, 12, 545, 55, 2, 5, 6]
print(list(reversed(lista)))
|
aca7b67d66d66e199931b6c8b9830f8d57dcb7c8 | Jelle0Bol/papi-gelato | /ijs.py | 2,892 | 3.578125 | 4 | from time import sleep
import os
import sys
ijssalon = 1
stap2 = 1
stap3 = 1
stap4 = 1
aantalaantal = 1
def aantalbolletjes():
global aantalb
while aantalaantal > bol:
hoeveel = str(input("Welke smaak wilt u voor bolletje",aantalaantal,"? : "))
aantalaantal + 1
def smaken():
global smaak... |
596c432e86d57df025673ae464165c1bcc927438 | Medzikarp/PV248 | /04-search/search.py | 3,875 | 3.5 | 4 | import sqlite3
import sys
import json
def create_connection(db_file):
conn = sqlite3.connect(db_file)
return conn
def get_prints(curs, person_id):
prints_info = curs.execute('SELECT print.id, score.name, score.genre, score.key, score.incipit, score.year, edition.name, score.id, edition.id, print.partitur... |
e49c93970d757bf1657c4423c957a59fa50b5d7d | ferhatyeter/Functions | /functions.py | 931 | 4.09375 | 4 |
def input_work_details():
hours = float(input("Please enter your hours worked: "))
pay = float(input("Please enter your pay rate per hour: "))
return hours,pay
def calculate_basic_pay(hours,pay):
total = hours * pay
return total
def calculate_overtime_pay(hours,pay):
overti... |
c03cdce175b9e6078b900449a02235e61c017f74 | erjan/coding_exercises | /erect_the_fence.py | 2,172 | 3.71875 | 4 | '''
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly locat... |
4d6819d6c0d1723ad3b59b35f8274ad7bba39562 | dhfromkorea/aihackers | /jan/pca.py | 715 | 3.75 | 4 | import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
digits = load_digits()
X_digits, y_digits = digits.data, digits.target
print(digits.data[0], digits.target[0])
def plot_pca_scatter():
colors = ['black', 'blue', 'purple', 'yellow', 'white',
'red', 'lime', 'cyan', 'orange', 'gray']
... |
deaa8d0108b929185bc6bd5b5139f3e426eeb503 | YimingXue/leetcode-sword2offer | /leetcode/找树左下角的值.py | 2,293 | 4.125 | 4 | #
# @lc app=leetcode.cn id=513 lang=python
#
# [513] 找树左下角的值
#
# https://leetcode-cn.com/problems/find-bottom-left-tree-value/description/
#
# algorithms
# Medium (64.01%)
# Total Accepted: 2.6K
# Total Submissions: 4.1K
# Testcase Example: '[2,1,3]'
#
# 给定一个二叉树,在树的最后一行找到最左边的值。
#
# 示例 1:
#
#
# 输入:
#
# 2
# ... |
ce9f132079f2868b6505dd31e9e864651987af66 | snarkfog/python_hillel | /lesson_12/sum_num.py | 955 | 4.09375 | 4 | """
3. Написать функцию, которая принимает в качестве параметра целое, многозначное число. Функция должна вернуть сумму
произведений каждой цифры на её порядковый номер. Например:
есть число 874658734
8 именн порядковый номер 1,
7 - 2
4 - 3
6 - 4
5 - 5 и т. д.
необходимо посчитать: 8 * 1 + 7 * 2 + 4 * 3 + 6 * 4 + 5 * 5... |
1556ef3aad08e5fb1e5d79db3af613e041c803ce | TheSuguser/Tensorflow_exercises | /autoencoder.py | 2,854 | 3.59375 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Import training data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
# Training Parameters
learning_rate = 0.01
num_training = 1000
batch_size = 100
# Neural Net... |
21a00705746549826bd7b0ac4d23b25a77cbf62e | ndbhamvani/code-challenges | /selenium/FirstAttempt.py | 1,445 | 3.65625 | 4 | # My very first browser automation script, when learning Selenium.
# The idea was to create a script that will launch Firefox browser, go to google homepage, enter 'spiderman' as a search term
# and then click on following links: 'Images,' 'Videos,' 'News' and 'Shopping' links.
# Once 'Shopping is clicked' then click ... |
2289535c4d653792bcc6c38594c56181ca4b1cfd | willienel/advent-of-code-2015 | /day3/part1/get_number_of_houses.py | 734 | 3.640625 | 4 | import os
def get_number_of_houses(directions):
visited_houses = set()
coordinate_x = 0
coordinate_y = 0
visited_houses.add((coordinate_x, coordinate_y))
for direction in directions:
if direction == '<':
coordinate_x -= 1
elif direction == '>':
coordina... |
b62ec6cb7220805332c9228e6bcbe8a530c40d61 | Jean-Alesi/Exercicios | /ex43.py | 1,214 | 4.03125 | 4 | # Desenvolva uma lógica que leia o peso e altura
# de uma pessoa, calcule seu IMC e mostre seu status,
# de acordo com a tabala abaixo:
# Abaixo de 18.5: Abaixo do peso;
# Entre 18.5 e 25: Peso ideal;
# 25 até 30: Sobrepeso;
# 30 até 40 : Obesidade;
# Acima de 40: Obesidade móbida.
print('-=-' * 15)
print('\... |
7eebe4558483361a834d1ce1e824bd51d97736c4 | devscheffer/Book-Algoritmos-Programacao-Afonso-Inacio-Orth | /Algoritmos e Programacao (Afonso Inacio Orth)/P25/1.py | 220 | 3.703125 | 4 | # Texto
a = 1
b = 2
c = 3
ma = (a + b + c)/3
mh = 3/(1/a + 1/b + 1/c)
mg = (a*b*c)**(1/3)
mp = (1*a + 2*b + 3*c)/(1 + 2 + 3)
print("""
ma: {:.2f}
mh: {:.2f}
mg: {:.2f}
mp: {:.2f}
""".format(
ma,
mh,
mg,
mp
))
|
4c08b15c124ec5a872de6ea0d77ca2ba1c57ff2e | PavanKulkarni/python-code-samples | /code/hard/h_palindrome_pairs.py | 816 | 3.703125 | 4 |
def palindromePairs(words):
d, res = dict([(w[::-1], i) for i, w in enumerate(words)]), []
for i, w in enumerate(words):
for j in xrange(len(w)+1):
prefix, postfix = w[:j], w[j:]
if prefix in d and i != d[prefix] and postfix == postfix[::-1]:
res.append([i, d[pre... |
89d967995c4a0bcefbcdb48a9784f9bbc05b7cd8 | Aestroix/CP_templates | /Dynamic_Programming/lcs/lengthoflcstr.py | 353 | 3.78125 | 4 | # LENGTH OF LONGEST COMMON SUBSTRING
x = 'eekgeeks...geek'
y = 'geeks'
n = len(x)
m = len(y)
result = 0
def lcstr(x,y,n,m,cnt):
if n==0 or m==0:
return cnt
if x[n-1] == y[m-1]:
cnt = lcstr(x,y,n-1,m-1,cnt+1)
else:
cnt = max(cnt,lcstr(x,y,n,m-1,0),lcstr(x,y,n-1,m,0))
return cnt
print('LENGTH OF LONGEST COMMON ... |
094dcd6c4f49ec563a4d366711a41ede547c909e | guilhermemaas/guanabara-pythonworlds | /aulas/world1/modulos.py | 1,020 | 4.0625 | 4 | """
import math
ceil - Arredondar para cima
floor - Arredondar para baixo
trunc - Truncar um valor
pow - potencia (**)
sqrt - rais quadrada
factorial - calcular fator
import math
#from math import sqrt
num = int(input('Digite um numero para calcular sua raiz quadrada: '))
raiz = math.sqrt(num)
print('A raiz quadrada ... |
0b8936159e2facc3947f49d6a36e16cbd6f8be11 | collmanxhu/Python-Books | /Python Crash Course/Chap 7 User Input & While Loop/counting.py | 2,359 | 4.21875 | 4 | # while loop
number_count = 1
while number_count <= 5:
print(number_count)
number_count += 1
# use conditional test to stop the loop
prompt = "\nTell me something, I'll repeat it back to you."
prompt += "\nEnter 'exit' to end the program. "
message = ""
while message != 'exit':
message = input(prompt)
... |
a5d568401a0c5efb535f88cadd7ecfd5d628ccbf | shivamnegi1705/Competitive-Programming | /Leetcode/Weekly Contest 211/1624. Largest Substring Between Two Equal Characters.py | 470 | 3.640625 | 4 | # Question Link:- https://leetcode.com/problems/largest-substring-between-two-equal-characters/
class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
n = len(s)
mex = 0
f = 0
for i in range(n):
for j in range(i+1,n):
if s[i]==s[j]:
... |
203ad6c665b8885201ff91c146a34cd3e107e950 | chafel/chinese-programmer-wrong-pronunciation | /tools/addword.py | 1,787 | 3.5625 | 4 | #!/usr/bin/env python3.8
# -*- coding: UTF-8 -*-
"""
Create the description for a word to be added to the word list
Usage: addword.py <word>
"""
import re
import sys
import urllib.request
from bs4 import BeautifulSoup
def main():
"""Generate the information with pronunciations for a word to be added to the word l... |
15f0fe2cff44c03c94235e521d47a44c8a23c2bc | 0bill0/exercises_python_int_cc_python | /buzz.py | 126 | 3.921875 | 4 | num = int(input('Insira o numero e saiba se ele eh divisível por 5: '))
if(num%5==0):
print('Buzz')
else:
print(num)
|
fd09c09372c32c931833cdd3265e45c6e3a55227 | AllenChenRR/CS162-Portfolio | /XiangqiGame.py | 34,733 | 3.625 | 4 | # Author: Allen Chen (934266694)
# Date: 2/29/2020
# Description: Xiangqi Game
class XiangqiGame:
"""
Chinese Chess Board Game that involves 16 pieces on each side of the board.
Goal: Capture the opponent's general
"""
def __init__(self):
self._game_state = "UNFINISHED"
... |
c52b143963a9b57ecee017a036671f0730f5c0f1 | Liam1809/Testing_Built-in_Python | /Sort.py | 2,048 | 4.6875 | 5 | # Sometimes, we want to sort a list in either numerical (1, 2, 3, …) or alphabetical (a, b, c, …) order.
# We can sort a list in place using .sort(). Suppose that we have a list of names:
# names = ['Xander', 'Buffy', 'Angel', 'Willow', 'Giles']
# print(names)
# This would print:
# ['Xander', 'Buffy', 'Angel', 'Will... |
69c4bdfe74972c2ac157b2831bd55e055c2ad3fd | mandaliyapraful/pythonBasic | /list.py | 783 | 4.09375 | 4 | sqaures = [1, 3, 4, 6, 8, 9]
print(sqaures)
print(sqaures[-1])
print(sqaures[-3:])
print(sqaures[:])
sqaures += [2, 5, 7]
print(sqaures[:])
#Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
sqaures[1] = 10
print(sqaures[:])
sqaures.append(3)
print(sqaures)
prin... |
720a7a12f76cdaa6d3deb5893a4bb1f789ba297b | Baton-Bread/startup | /Second lesson/main.py | 770 | 3.984375 | 4 | def get_imt(weight, height):
imt = weight / (height * height)
if imt < 19:
print("У вас недовес :(")
elif imt > 25:
print ("У вас перевес :(")
else:
print("Ваш вес в норме :3")
def calc():
command = input("Введите команду: ")
num1 = float(input("Введите 1-e число: "))
num2 ... |
9d946d2b8cfbb490a3cb6da3573c6723838cc5fb | drboyer/lmdparser | /lmdparser/download_obs.py | 2,174 | 3.515625 | 4 | from urllib2 import urlopen
from .GLMObservation import GLMObservation
def get_latest_observations(station_type='all'):
"""
Gets the most recent observations from the GLERL CoastWatch website.
By default, observations from all station types are downloaded.
Alternatively, specify a valid station type.... |
f0940af7c0bb190cde5d96f15cfd1a44cf02508b | daynejones/python-aes-password-manager | /.password | 4,108 | 3.875 | 4 | #!/usr/bin/python
""" command line password manager using python and AES encryption
author: Dayne Jones
date: 13-August-2014
"""
import getpass
import hashlib
import pickle
from Crypto.Cipher import AES
from Crypto import Random
class PasswordManager():
""" Password tools and utilities """
def get_pass(se... |
0591a981ff4305a26c404073ae2d2fc8e5491a5e | Adrian0399/AdrianOlveraOrdo-ez-CodigoPython | /Invertir Palabra.py | 113 | 3.90625 | 4 |
Palabra=str(input("Ingrese la palabra que desea invertir: "))
print("La plabra invertida es: ", Palabra[::-1])
|
15ce08b691f9fdd8b250428877ef02328dc8161f | ronnix/meetup-python-demo-ci | /projet.py | 482 | 3.703125 | 4 | def main() -> None:
print(addition(2, 3))
def addition(a: int, b: int) -> int:
return a + b
def soustraction(a: int, b: int) -> int:
return a - b
def test_addition() -> None:
resultat = addition(2, 3)
assert resultat == 5
def test_soustraction() -> None:
resultat = soustraction(42, 3)
... |
934819ebf308909165ed8b58acc848e2530121a2 | briannaf/aoc-2019 | /day2.py | 1,203 | 3.59375 | 4 | #AOC 2019 Brianna Frye
#Day 2
def parse_to_array(base_file):
data_left = True
output_array = []
try:
file = open(base_file)
while data_left == True:
temp = file.readline()
if temp == '':
data_left = False
break
output_array... |
0001675ecb0cdff142b6a711ec848d13c7c4cf0b | NISHIT-RAJANI/Python-Codes | /matrix_mul.py | 563 | 3.84375 | 4 | Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def matrix(d,n):
m=[[0 for i in range(n)]for j range(n)]
for i in range(1,n):
m [i][j]=0
for D in range(1,n-d):
for i in ra... |
7ead0c7d2d1447fde66abbc1a9f239ea32fcb43b | lokeshw24/Breadth_First_Search | /Breadth_First_Search.py | 1,691 | 4.1875 | 4 | #!/bin/python
#list used to represent the graph
#OOP required
#pretty hard-coded
#graph is represented as "adjacency-list"
graph={}
def breadth_first_search():
global graph
#another parallel dictionary for storing the meta-data of the nodes of the graph
meta_data_graph={}
for keys in graph.keys() :
... |
edf695bc7db3ad0e8cf3c3aaaf02f4d3e0275538 | zunigandres26/LAMK | /Código/core/sintax-analysis/grammars/BashGrammar.py | 8,035 | 3.5625 | 4 |
import re
"""
-----------------------------------------------------
Clase Gramatica del Lenguaje Bash
------------------------------------------------------
"""
class BashGrammar:
def __init__(self):
#Variables
self.var = "[A-Za-z][A-Za-z0-9_]*"
#Call Variables
self.cal... |
7453d226c93871f1fbfa4575ac219791432d7a03 | TomEdwardBell/PycharmProjects | /ALevel/GraphTraversal/depthfirst.py | 760 | 4.0625 | 4 | GRAPH = {"A": ["B", "D", "E"],
"B": ["A", "C", "D"],
"C": ["B", "G"],
"D": ["A", "B", "E", "F"],
"E": ["A", "D"],
"F": ["D"],
"G": ["C"]}
visitedList = []
# an empty list of visited nodes
def dfs(graph, currentVertex, visited):
# append currentVertex to list of... |
edb6ca808138f012625e29f2952b7cb6e35984fc | jkfer/LeetCode | /target_sum.py | 710 | 3.890625 | 4 | """
Given a set of non-negative integers (consider them unique with no duplicates), and a value sum, determine if there is a subset of the given set with sum equal to given sum.
Example:
Input: set = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9
"""
# set - the set
# n - number o... |
e50271eeeb1a2cd57fc709264da86aa8c2c5f1d5 | Suryanshg/Python-2.7 | /Matrices/Upper-Lower Triangle.py | 588 | 4.21875 | 4 | while True:
L=[]
m=int(input("Rows:"))
n=int(input("Columns:"))
for i in range(m):
l=[]
for j in range(n):
x=int(input("Elements:"))
l.append(x)
L.append(l)
for l in L:
for x in l:
print x,
print
print"Upper Triangle is:... |
34ff58d02d93860e2d221a3f7471c417280a3392 | ArturPalko/-colloquium | /34.py | 469 | 3.859375 | 4 | '''34. Дано два лінійних масиву однакової розмірності. Скласти третій масив з
добутку елементів перших двох масивів, що стоять на місцях з однаковим індексом.'''
import numpy as np
import random
c=[]
a=np.array([random.randint(1,10) for i in range (10)])
b=np.array([random.randint(1,10) for i in range(10)])
print(a)
p... |
a23fe4e60b17250af6d918c118c3e1568dc98e71 | maruthgoyal/playground | /src/Hailstone Sequence/hailstone.py | 550 | 4.34375 | 4 | def hailstone(num):
"""
If number even, divide it by 2
Else multiply it by 3 and add 1
Repeat till number becomes 1
Conjectured to reach one for all integers (Colatz Conjecture)
"""
nSteps = 0
while(num != 1):
if(num % 2 == 0):
num /= 2
... |
cc0db907db5f4bf823c0ee756a9f8120278a19e3 | urmajesty/learning-python | /ex6.py | 966 | 4.375 | 4 | #the variable is being assigned
types_of_people = 10
# the variable is being called and assigned to x
x = f"There are {types_of_people} types of people."
#some of the variables are being assigned and others are being called
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
#al... |
5cd9215278c16227ea8aef7bd93073b390f149c4 | DannyMireles/Python | /Lab4_Act4.py | 806 | 4.03125 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do."
# "I have not given or received any unauthorized aid on this assignment."
#
# Names: Daniel Mireles
# Jordan Nguyen
# Tan Nguyen
# Fern... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.