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 |
|---|---|---|---|---|---|---|
dd1b36fedafa62b45e9af2156cbfb61f2d141d1c | S-lopez14/cursoPython | /main2.py | 529 | 3.71875 | 4 | """ x = float(input("ingrese dato mi perro: "))
#print(x)
y = float(input("ingrese otro dato mi perro: "))
print(10%2)
a = True
b = False
print(a) """
""" a = 5
if a<4:
print("toes que mi perro")
print ("sisas")
elif:
print("es menor que 5")
else:
print("no es menor") """
""" a = 7
while a==7:
pr... |
ff72ae85afeaa41cbd4235a630a091f40e429458 | SriYUTHA/PSIT | /Week 11/FoodGrade II.py | 410 | 3.53125 | 4 | """FoodGrade II"""
def main():
"""Eat food chicken"""
count = 0
cal = 0
cal2 = []
num = int(input())
chk_1 = input().split()
chk = [int(chicken) for chicken in chk_1]
for i in sorted(chk):
if cal < num:
count += 1
cal += int(i)
cal2.append(int(... |
cce8e7794aae00cc3f1392fcf2127882488b103c | katherine95/Python-tests | /guessTheNumber/guess.py | 943 | 4.09375 | 4 | import random
def get_input():
user_input = input("Enter any number between 0-51: ")
try:
guess = int(user_input)
return guess
except ValueError:
return "Enter an integer please"
def guessNum():
number = random.randint(1,50)
number_of_guesses = 0
while number_of_guesses... |
e97556808a34ad181091c1af6e5b616c37428f53 | p83129/Week7_api_ajax | /Week7/demo_mysql_test.py | 809 | 3.53125 | 4 | import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="qaz4545112",
database='website'
)
#print(mydb)
with mydb.cursor() as cursor:
Name="test1name"
Account= "ply"
Password= "ply"
# 查詢資料SQL語法
command = "Selec... |
cd522c210d1a384e664234eee3061ff345a3c866 | timcopelandoh/KidsMathTest | /create_db.py | 1,036 | 4.0625 | 4 | '''
Script that initializes a sqLite database
SqLite doesn't contain a date data type, so dates are stored as integers. This should be something
we keep in mind when we transition to a production environment and potentially a different DBMS
For the time being, dates should be stored as MMDDYYYY
Year should be stored a... |
dd1ec58cd1a85152edfbea2a0ffab10a0c1260bf | kmgowda/kmg-leetcode-python | /sqrtx/sqrtx.py | 517 | 3.5625 | 4 | // https://leetcode.com/problems/sqrtx
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 1:
return 1
left = 0
right = x
g = (left+right)/2
diff = abs(g**2-x)
while diff > 0.001 and diff < x**2:
... |
3a83ec503c821335e9773564fee90b54fb2ae273 | ardipta/Python-Practice | /Python/operator.py | 1,348 | 4 | 4 | #Arithmetic
x = 10
y = 4
print('x = 10, y = 4')
print('x + y =',x+y)
# Output: x + y = 14
print('x - y =',x-y)
# Output: x - y = 6
print('x * y =',x*y)
# Output: x * y = 40
print('x / y =',x/y)
# Output: x / y = 2.50
print('x // y =',x//y)
# Output: x // y = 2
print('x ** y =',x**y)
# Output... |
ded74d5cbb13253e5654b6c9604e50c6f5ee9079 | jgofman/Adding-Suffixes-Grammatically | /Jacob Gofman_assignment for 12-01, add 'er' properly to end of word.py | 3,805 | 4.375 | 4 | ##Jacob Gofman
##Due December 1st
import re
vowel = ['a', 'e', 'i', 'o', 'u'] ##set of vowels
specific_consonants = ['r', 'w', 'x', 'y'] ##set of consonants that are exceptions
affirmative = ['yes', 'yep', 'y', 'yea', 'sure', 'please', 'mhmm'] ##set of answers for 'yes'
negative = ['no', 'nope', 'n', 'nah'] ##set of ... |
201e7935f5616afa1cd5e3e9f4869f584ff23ab4 | shubhamoli/solutions | /leetcode/medium/380-Insert_delete_O-1.py | 1,308 | 4.0625 | 4 | """
Leetcode #380
"""
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self._nums = []
self._tracker = {}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not alre... |
9c41bdbc15732594c3a69fa741f7377dfde64330 | Min0164/fit1008 | /Week 11/Lecture Code/binary_search_tree.py | 5,016 | 3.796875 | 4 | """ Binary Search Tree ADT.
Defines a Binary Search Tree with linked nodes.
Each node contains a key and item.
"""
__author__ = "Brendon Taylor"
__docformat__ = 'reStructuredText'
from typing import TypeVar, Generic
from list import LinkList
from stack import LinkStack
K = TypeVar('K')
I = TypeVar('I')
class BinaryS... |
9b1642c0a9e1901e7b7e27524ada33b6472dc348 | YGDLycaon/Linked-Lists | /removeDups2.py | 2,509 | 3.875 | 4 | class Node:
def __init__(self, data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def addNode(self,data):
newNode=Node(data)
if self.head==None:
self.head=newNode
... |
c5db98a55ec0fc3acf44e2e8fb1d2c1f53035a53 | Sycoi/bank | /BankSystem/person.py | 1,076 | 3.578125 | 4 | '''
类名:Person
属性:姓名 身份证号 手机号 卡
行为:开户,查询,取款,存款,转账,改密,挂失,解锁,销户,(补卡未实现),销户,退出
'''
# from atm import ATM
class Person(object):
def __init__(self,name,identity,phoneNum,card=None):
self.name = name
self.identity = identity
self.phoneNum = phoneNum
self.card = card
def newA... |
eadc80d290dcf6fccf263f6424201dede6bcceac | ddalma/Python-Practice | /chapter_two.py | 3,260 | 4.375 | 4 | """
//chapter 2.
first_name = raw_input("Enter your first name: ");
last_name = raw_input("Enter your last name: ");
age = input("What is your age?: ");
print 'Hello', first_name, last_name;
print 'You are',age,'years old';
original_price = float(input("Enter the item's original price: "));
discount = original_price ... |
b0ca5a9a106da5bbe889dd28ab4e15496cc87439 | Chunzhen/leetcode_python | /problem_2.py | 1,315 | 3.765625 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
ret... |
cffb4f19e5fb196607bff3d4d9e9fc90475d94d0 | gabrielgamer136/aula-git-gabriel | /Documentos/lista de exercicios 1 python gabriel/exercicios 10.py | 606 | 3.75 | 4 | #GabrielMaurilio
#escreva um programa para calcular a reduçao do tempo de vida de um fumante.pergunte a quantidade de cigarros fumados por dia e quantos anos ele ja fumou.considere que um fumante per 10 minutos de vida a cada cigarro,calcule quantos dias de vida um fumante perderá.exiba o total de dias.
cigarrosfumad... |
a295980d7f2006b2a330c96a0942294babf00fb8 | ssak32/MachineLearning | /ML_Udemy_Courses/Implement ML in Data Mining using Python/Simple Linear Regression/SLR.py | 1,257 | 3.984375 | 4 | # Create Simple Linear Regression
#Importing pandas library to read CSV data file
import pandas as pd
#Importing matplotlib.pyplot library to plot the results
import matplotlib.pyplot as plt
#Reading CSV data file in Python
dataset = pd.read_csv(os.path.join(os.getcwd(), 'Study-Hours.csv'))
#Dividing dataset into X... |
0c1de4834cfd91e7ab017f9d6b6fa0907027d31f | Eric2D/movie_list | /entertainment_center.py | 1,458 | 3.546875 | 4 | # Use the file here to make your favorite movie lists through media
import media
import fresh_tomatoes
# In the three variables below they all call the class movie (in media).
# There are three arguments in the class which are title, image url, and
# youtube video url.
oblivion = media.movie('Oblivion',
... |
5a35c2b15fc5d55b4f0a5c035233ac61b70b80b0 | astiksgithub/list-tuple-and-dictionary | /tup.py | 375 | 3.6875 | 4 | tup1 = ("My", "Name", "Is", "Astik", (1,2,3))
tup2 = ("I", "Study", (3.8, 3.6, 2.6), "Python")
tup3 = ("It", "Is", "Really", "Very", "Fun", (4,5,6))
print(tup1)
print(tup2)
print(tup3)
print(tup1[3]) #prints 'Astik'
print(tup1[4][1]) #prints 2
print(tup2[3]) #prints 'Python'
print(tup2[2][0]) #prints 3.8
prin... |
a599a88fa895bfff29613d23b681536bd0b40327 | emathian/SIR | /agent.py | 1,967 | 3.5 | 4 | import random
class Agent:
#Attribu de la classe
rng=random.Random()
def __init__(self, statut="I", x=0 , y=0 , pi=0.2, pr= 0.4, pd=0.4): #####" On suppose que l'initiation est au depart
############################ Deplacement
self.x= x
self.y = y
#################################### Probabilite
self.stat... |
995910cf34f14417735d5e846f0463834c0fc354 | singhr2/Python101 | /basics/HellowWorld.py | 2,010 | 4.5 | 4 | #HellowWorld.py
# to run,
# cd D:\dev\python\Python101\basics
# python HellowWorld.py
# In Python 3.X, printing is a built-in function
# it doesn’t return any value we care about (technically,it returns None)
print('Hello World')
#When two or more arguments are passed, print function displays each argument separat... |
2c2758ee379431a33a79b4f69524a802d4a195fd | oahahn/MIT-6.01-Intro-to-EECS | /W12-Search-Algorithms/searchAlgorithms.py | 6,673 | 3.609375 | 4 | import search as search
import statemachine as sm
def depthFirstSearch(initialState, goalTest, actions, successor):
"""Models a Depth First Search algorithm"""
agenda = search.Stack()
if goalTest(initialState):
return [(None, initialState)]
# Make root node
rootNode = search.SearchNode(None... |
ba2cca29003b504bb8071792f65c46023ef14f0a | aleksandrikus/python_examples | /calculator.py | 397 | 4.28125 | 4 | while True:
x = int(input("Enter number 1: "))
y = int(input("Enter number 2: "))
operation = input("Choose arithmetic operation symbol: ")
if operation == "+":
print(x + y)
elif operation == "-":
print(x - y)
elif operation == "*":
print(x * y)
elif operation == "/"... |
ac64f20ecabfc29da208272608de55c2fbf8a861 | emisaycheese/Eron-Data | /explore_enron_data.py | 1,395 | 3.671875 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
523a49c87007eddb3ba2e4e8f5577296070bd0fe | stareen/python_mini | /multipliction_table.py | 521 | 4.28125 | 4 | print("\t\t\tMULTIPLICATION TABLES FROM 1 TO 12\n")
for i in range(1,13):
for j in range(1,13):
print(i*j,end="\t")
print('')
#table of 2 to 12
for n in range(1,13):
for i in range(1,11):
print(" %s X %s = %s\n" %(n,i,n*i), end="")
print(' ')
#defining a function to print a ... |
c00c19dc8b5a484762226ac69346e04ce2c421b6 | averroes96/learning-python | /first.py | 269 | 3.5 | 4 | a,b,c = 1,2,3
print(str(b**c))
# floor division : //
print(str(c//b))
a = [1, 2, 3]
b = [3, 4, 5]
c = [6, 7, 8]
a.extend(b)
print(a)
a.extend(c)
print(a)
a.sort()
print(a)
c = a
d = a.copy()
a.append(9)
print(a)
print(c)
print(d)
a.insert(1200,100)
print(a) |
510d3cf11b2f81326030eaf4a39585c66148f51e | llee330/Election_Analysis | /Python_practice.py | 522 | 3.59375 | 4 | counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
for county, voters in counties_dict.items():
print(str(county) + " county has " + str(voters) + " registered voters.")
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"c... |
24b75f252abc2e3af0bce4d3dd7f5a41e0802856 | abybhamra/search_algos | /linear_search.py | 182 | 3.5 | 4 | array = [4, 2, 0, 19, 6, 44]
num = 0
for i in range(len(array)):
if array[i] == num:
print("number [%s] found at [%s] position in the array." % (num, i))
break
|
a7e7ae423de2d9c5eaf8d6271e3959ee3990d1c9 | happy96026/interview-prep | /coding_problems/may/may2.py | 514 | 3.59375 | 4 | from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = set(nums)
longest = 0
for n in nums:
if n - 1 not in nums:
up = n + 1
while up in nums:
up += 1
... |
d0c66373f91c0af6f7a2e2f8791bd2dad7092b75 | KristofferFJ/PE | /problems/unsolved_problems/test_370_geometric_triangles.py | 500 | 3.953125 | 4 | import unittest
"""
Geometric triangles
Let us define a geometric triangle as an integer sided triangle with sides a ≤ b ≤ c so that its sides form a geometric progression, i.e. b2 = a · c .
An example of such a geometric triangle is the triangle with sides a = 144, b = 156 and c = 169.
There are 861805 geometric tr... |
db48011dda47fd7fa0c93ce1982e2241217b9c0e | sidhu177/pythonprog | /quick_sort.py | 691 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 4 22:21:17 2018
Taken from Data Structures and Algorithms using Python
"""
def quick_sort(S):
n = len(S)
if n<2:
return
P = S.first()
L = LinkedQueue()
E = LinkedQueue()
G = LinkedQueue()
while not S.is_empty():
if S.first() <... |
1342981b30c9ed31ec3de3e0ec74ad193fcf2d09 | luizdefranca/Curso-Python-IgnoranciaZero | /Aulas Python/Conteúdo das Aulas/013/Gabarito/Gabarito - Exercicio 1.py | 315 | 4.03125 | 4 | """
Dado um número inteiro positivo n,
calcular a soma dos n primeiros números inteiros positivos.
"""
n = int(input("Digite n: "))
cont = 0
soma = 0
while cont < n:
num = int(input("Digite um número da sequência: "))
if num > 0:
soma = soma + num
cont = cont + 1
print("Resultado:", soma)
|
d68bd7ba033f59702be1cb843650163fb1c1bd9f | ericbaranowski/Python-Programs | /Recursions/binarysearch.py | 573 | 4.03125 | 4 | # Python program to implement binary search on sorted array list using Recursion
def binarySearch(data, target, low=0, high=None):
if high is None:
high = len(data)-1
if low > high :
return False
else:
mid = (low + high)// 2
if data[mid] == target:
return True
... |
acd483af303368dd3f77f7715badf075f77c2f3d | peternortonuk/reference | /python/dataclass.py | 3,361 | 3.75 | 4 | '''
Raymond Hettinger - Dataclasses: The code generator to end all code generators - PyCon 2018
https://www.youtube.com/watch?v=T-TwcmT6Rcw
https://docs.python.org/3/library/dataclasses.html
https://www.python.org/dev/peps/pep-0557/
field specifier supports the following:
default: Default value of the field
... |
7a6dc6220169859df1cbf78041c4861b757f0d88 | Leozoka/ProjetosGH | /pizza.py | 204 | 3.5 | 4 | def fazendo_pizza(tamanhos, *coberturas):
print('\nFazendo uma pizza de ' + str(tamanhos) + ' polegadas, com as seguintes coberturas:')
for cobertura in coberturas:
print('--' + cobertura) |
732727ea13bf14b1eaa4ad7eec94f959c35968f7 | helios2k6/python3_interview_questions | /mergeSortedLists.py | 1,022 | 3.65625 | 4 | def findEnd(a):
i = 0
for e in a:
if not e:
return i
i += 1
return i
def shiftElements(a, i, e):
lenOfA = len(a)
if lenOfA <= i or e >= lenOfA:
return
for m in reversed(range(i + 1, e + 1)):
a[m] = a[m-1]
def mergeSorted(a, b):
endOfA = findEnd(a... |
e3ab5828d703f2e8589000542c3eaf43a40ad7e4 | dreamchild7/python-challenge-solutions | /Ekeopara_Praise/Phase 1/Python Basic 1/Day 3 Tasks/Task 5.py | 232 | 4.46875 | 4 | '''5. Write a Python program to get the volume of a sphere with radius 6.
Tools: input function, math'''
from math import pi
r = 6
vol_sphere = 4/3 * pi * (r **3)
print(f"The volume of sphere with radius 6 is {vol_sphere} m2") |
c796f5fa9038dd4c2cba49ead6db6583968cbcd3 | Joko013/adventofcode | /year_20/day_08/solution_b.py | 1,237 | 3.5625 | 4 | from typing import Optional
from tests import run_tests
def get_solution(puzzle_input: str):
instructions = puzzle_input.splitlines()
for i, instruction in enumerate(instructions):
test_instructions = list(instructions)
if "nop" in instruction:
test_instructions[i] = instructions... |
d2c2378ee8f9265b8fec38b1b70869c94a551913 | athmey/MyLeetCode | /findTarget.py | 1,257 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
... |
5dbc4a64adf940e7cddf09b2bca2eafe21663a35 | NAGESH-KJ/DATA-ANALYTICS-PROJECT | /NaiveBayesModel.py | 4,677 | 3.59375 | 4 |
# coding: utf-8
# In[83]:
import pandas as pd
df = pd.read_csv("D:\DA_ASSIGNMENT\PROJECT\project.csv",parse_dates =["date"],index_col ="date")
# In[ ]:
#we will build a naive bayes classifier for classifying desc into type categories.
# In[109]:
#we will add a column encoding the type as an integer because ... |
a81fe0784684ee116695dcadc3fdd88227e39612 | MEENUVIJAYAN/python | /python lab 5/upper.py | 135 | 4.46875 | 4 | #Program to convert a string with all uppercase and with all lower case.
a = str(input("Enter the string:"))
print(a.swapcase())
|
f55549d43f3abc67e501b4f27e1148c92889cd22 | KoliosterNikolayIliev/Softuni_education | /Programming_basics_2019/Nested Loops - Exercise/03. Coding.py | 292 | 3.765625 | 4 | num = input()
lenght = len(num)
for ind in range(lenght, 0, -1):
current_num = int(num[ind - 1])
if current_num == 0:
print('ZERO')
continue
ascii_char = chr(current_num + 33)
for column in range(current_num):
print(ascii_char, end='')
print()
|
f4dfdbb410ce45eb670fdabeac4e834a77ff9020 | knobay/jempython | /exercise06/h03.py | 722 | 4.28125 | 4 | # A swimmer at position A wants to cross the river of width w. The swimmer can swim with a
# constant velocity v but only along the x-axis. The water itself flows with velocity
# v along the y-axis. Once the swimmer enters the water and starts to cross the river,
# the water will carry him with it and cause him to drif... |
fdbcae0f9ee8c6ce10799ec3085337aed336dbb7 | GabrielFiel/CursoemVideo-Python | /ex012.py | 163 | 3.625 | 4 | preco = float(input('Digite o preço do produto: \n'))
precoDesconto = preco * 0.95
print('O preço do produto com desconto é R${:.2f}.'.format(precoDesconto))
|
8ef1ec42ae22eca4cd74d1b7e5c9498882b3ebaa | byuvraj/Solution_for_python_challanges | /Hacker_rank/Collatz_Conjecture.py | 714 | 4.28125 | 4 | import matplotlib.pyplot as plt
num = int(input("input a number: "))
print(type(num))
highest = 1
highest = max(highest,num)
counter = 0
x = []
y = []
while num !=1:
if num % 2 ==0:
num = (num/2)
x.append(counter)
y.append(num)
highest = max(highest,num)
counter+=1
else:
... |
da4dc8913a769d2bbc6b920af5f45e99d66e6125 | Jamibaraki/adventOfCode2017 | /day4b.py | 1,034 | 3.859375 | 4 | #Passphrases
#Advent of Code 2017 Day 4b
#exclude anagrams
#deal with the file
file = open('input4.txt','r')
input = file.read()
file.close()
lines = input.split("\n")
validLines = 0
def isAnagram(first, second):
if( len(first) != len(second) ):
return False
for x in range( 0, len(first) ):
... |
b3badfae9732a00bb35122e8b3f095d49654e606 | RenegaDe1288/pythonProject | /lesson10/mission2.py | 177 | 3.75 | 4 | num = int(input('Введите число'))
for row in range(1, num + 1):
for col in range(1, num + 1):
if row >= col:
print(row, end=' ')
print()
|
506200dc298c91645ddcd4959235fde72f69007b | FRANC0000/ReposPython006 | /menu.py | 1,489 | 3.984375 | 4 | #menu de opciones
#crear menu con tres opciones
import os
seguir=True
def numeros():
#ingresar n numeros
#mostar cantidad de: n.positivos, n.negativos, n=0
mayor=0
menor=0
igual=0
cantidad=int(input("ingrese cantidad de números a ingresar: "))
for i in range (cantidad):
n=in... |
896852e1402a60e82320470ae37bb4ff5e6c1ddd | NirmaniWarakaulla/HackerRankSolutions | /Data Strctures/Insert a node at the head of a linked list.py | 281 | 3.6875 | 4 | def insertNodeAtHead(llist, data):
# Write your code here
x = SinglyLinkedListNode(data)
if (llist == None):
llist = x
else:
new_node = x
new_node.next = llist
llist = new_node
return llist
// try with python3 language.
|
b89c08e806185058b0dbac55448b1de8410d100f | pritpal1/python-baisc-part2 | /linear.py | 309 | 3.96875 | 4 | def search (arr, n, x):
for i in range(0,n):
if (arr[i] == x):
return i
return -1
arr = [2,3,4,45,60,80]
x= 60
n = len(arr)
result = search(arr, n ,x)
if result== -1:
print("Element is not present in Array")
else:
print("Element is present at index:-",result) |
51bef33cf861ef0e6dbe6b65525ef7ea27f83baa | RenegaDe1288/pythonProject | /lesson17/mission09.py | 144 | 3.5 | 4 | n = [2, 2, 3, 4, 5, 6, 8, 6, 1, 52, 2, 1, 2, 3, 4, 6, 8, 2]
a = 1
b = 7
print(n)
m = [num for num in n[:a]] + [num for num in n[b:]]
print(m)
|
ea6bc0c9b114ee212adf2ee4360c1534a8b1a51d | daniel-reich/turbo-robot | /vSpfEnRHo3hi6ZTRk_10.py | 633 | 3.734375 | 4 | """
What's the probability of someone making a certain amount of free throws in a
row given their free throw success percentage? If Sally makes 50% of her free
shot throws. Then Sally's probability of making 5 in a row would be 3%.
### Examples
free_throws("75%", 5) ➞ "24%"
free_throws("25%", 3) ➞ "2%... |
422ae0eab6acd1b2f8e852da8d80c2c199f5330c | alexforcode/leetcode | /100-199/151.py | 1,170 | 4.375 | 4 | """
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple sp... |
b3d42b754bf5eb7d3ede18029da70881e863fb03 | DamienPond001/Udemy_API | /Datacamp/seaborn.py | 1,435 | 3.828125 | 4 | # Import plotting modules
import matplotlib.pyplot as plt
import seaborn as sns
# Plot a linear regression between 'weight' and 'hp'
sns.lmplot(x='weight', y='hp', data=auto)
# Display the plot
plt.show()
#RESIDUALS
# Import plotting modules
import matplotlib.pyplot as plt
import seaborn as sns
# Generate a green r... |
9c4704ebf86ca0ca7b72ed648f1faaf21bd390dd | AdnCodez/Codewars | /Make_spiral.py | 566 | 3.640625 | 4 | # 3 kyu / Make a spiral
# Details
# https://www.codewars.com/kata/make-a-spiral
def spiralize(n):
if n == 0:
return []
grid_box = [[0] * n for _ in range(n)]
grid_box[0] = [1] * n
s = n - 1
var1x, var1y = 0, n - 1
var2x, var2y = 1, 0
while s > 0:
for i in range(2 if s ... |
6f2d13bcbd1d7743cd775644467e0b6b5b8faeea | AgaK1/codewars_python | /8-Kyuu/Can_we_divide_it.py | 236 | 4 | 4 | #Your task is to create functionisDivideBy (or is_divide_by) to check if an integer number is divisible by each out of two arguments.
def is_divide_by(number, a, b):
return True if (number % a == 0) and (number % b == 0) else False |
5e207cbe6136374bbca4cea6be9f07a48bb58b88 | mtabishk/DataStructuresAlgorithms-Python3 | /graphs/graphs.py | 2,071 | 3.53125 | 4 | class Graph:
def __init__(self, gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
# add connection
def add_connection(self, node, connection):
self.gdict[node].append(connection)
# remove connection
def remove_connection(self, node, connection): ... |
3a77b8a4d5e66d3cf1598e581b6fc3c454776a35 | Vineasouza/til | /python/pandas/pandas-inicial-test/pandas1.py | 910 | 4.21875 | 4 | # pandas.read_csv() opens, analyzes, and reads the CSV file provided, and stores the data in a DataFrame
import pandas
df = pandas.read_csv('hrdata.csv', index_col='Name', parse_dates=['Hire Date'])
print(df)
# If your CSV files doesn’t have column names in the first line, you can use the names optional parameter to... |
54b20edaba4170c0c649c670a787b2cab40c11c6 | gauri05/Assignment5 | /Assignment5_2.py | 280 | 3.9375 | 4 | print("Arecursive program........")
def fun(val):
#if val <=1:
if (val == 0):
return 1
#print (val,end = " ")
fun(val - 1)
print (val, end = " ")
def main():
no = int(input("Enter number:"))
fun(no)
if __name__ == "__main__":
main()
|
23eba719dae9b2b8aabfd707b522655ed1cffd8d | tinkle1129/Leetcode_Solution | /Array/611. Valid Triangle Number.py | 1,128 | 4.03125 | 4 | # - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Valid Triangle Number.py
# Creation Time: 2017/12/26
###########################################
'''
Given an array consists of non-negative integers, your task is to count the number of tri... |
2041ff04be5f6f668598505af33fa4dc05b66a26 | BressettJ21/Monopoly-Analysis | /MonopolyPositionGenerator.py | 1,984 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 6 03:12:59 2020
@author: jackb
"""
import random
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
def roll():
dice = []
for i in range(2):
dice.append(random.randint(1,6))
return dice
#Initialize empty ... |
74ddcc46727059bf166e581b0f02da0be6c19004 | nishanth06/VEBTREE | /Menuproject.py | 2,062 | 4.1875 | 4 | import VebTree form VEBTree
def main():
print("the tree is empty enter the size of the universe you want")
print("HINT: size should be 2^(2^k)")
k=int(input())
v=VebTree(k)
print("Enter the no of elemnts you want to add")
n=int(input())
for i in range(n):
v.Insert(v.root,int(input()... |
d18853b775dcc22c055f7cde59182c748fb993a8 | niteshagrahari/pythoncodecamp | /solve.py | 1,138 | 3.59375 | 4 | def findAll(lst,value):
l=[]
n = len(lst)
for i in range(1, n):
if value == lst[i]:
l=l + [i]
return l
def find(lst,value):
n=len(lst)
for i in range(1,n):
if value==lst[i]:
return i
return -1
output=[]
sweetness=[2,3,7,3,2,2]
bitterness=[5,4,1,4,9,3]... |
d0b3eca764da9e1923ae301151108030b489514e | ROXER94/Project-Euler | /002/2 - EvenFibonacciSum.py | 381 | 3.6875 | 4 | # Calculates the sum of the even terms of the Fibonacci sequence under 4,000,000
cache_fib = {}
def fib(n):
if n not in cache_fib.keys():
cache_fib[n] = fibonacci_uncached(n)
return cache_fib[n]
def fibonacci_uncached(n):
if n < 2: return n
else: return fib(n-1) + fib(n-2)
print(sum(fib(x) for x ... |
eb4c04ec59a789e98f46c76114149c207a11d7d9 | MayankMaheshwar/DS-and-Algo-solving | /leetcode/base7.py | 339 | 3.53125 | 4 |
class Solution:
def convertToBase7(self, num: int) -> str:
if not num:
return '0'
sign = num < 0
num = abs(num)
stack = []
while num:
stack.append(str(num % 7))
num = num // 7
return '-'*sign + '... |
544877742c65e8d5a45442ee17471af38120f735 | WangMingJue/StudyPython | /Test/Python 100 example/Python 练习实例4.py | 697 | 3.859375 | 4 | # 题目:输入某年某月某日,判断这一天是这一年的第几天?
#
# 程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天
year = int(input('年:\n'))
month = int(input('月:\n'))
day = int(input('日:\n'))
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
if 0 < month <= 12:
sum = months[month - 1]
else:
print('data error')... |
69b4e90e94322ea0055d49cd85a9d0eaa236e849 | teejay1O1/Algorithms-and-Data-Structures | /mergesort.py | 868 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 22:41:28 2019
@author: Tanujdeep
"""
def merge(l1,l2):
merged=[]
i=j=0
max1=len(l1)
max2=len(l2)
while(i<max1 and j<max2):
if(l1[i]<l2[j]):
merged.append(l1[i])
i+=1
else:
merged.app... |
3d2dff6cec525f353cdf1a391ba770f89ee6572f | Sreehari78/Snake | /main.py | 1,398 | 3.515625 | 4 | from turtle import Screen
from food import Food
from snake import Snake
from scoreboard import ScoreBoard
from time import sleep
screen = Screen()
screen.tracer(0)
screen.setup(width=610, height=610)
screen.title("Snake")
screen.bgcolor("black")
snape_the_snake = Snake()
snake_food = Food()
my_score... |
5143a3da2fc3e8c0709f49e710b5881b04faa325 | rogersilveiraa/Python | /Semana 7/Quantidade de primos.py | 625 | 3.515625 | 4 | def n_primos (x):
if x < 2:
print(" Tente novamenta com um número maior que 2")
else:
contador_primo = 0
while x >= 2:
teste = teste_primo (x)
if teste == True:
contador_primo +=1
x -= 1
return contador_primo
... |
92eadcbc4fa6595f2e4a833da7314259a822dfee | kphillips001/Edabit-Python-Code-Challenges | /makemywayhome.py | 312 | 4.0625 | 4 | # You will be given a list, showing how far James travels away from his home for each day. He may choose to travel towards or away from his house, so negative values are to be expected.
# Create a function which calculates how far James must walk to get back home.
def distance_home(lst):
return abs(sum(lst)) |
82aac2fa460a2d53660367d86e3012a28306af8d | anshgoyal010/Hacker-Rank-Python3 | /Strings/String Formatting.py | 493 | 3.765625 | 4 | def print_formatted(number):
w=len((bin(number)).replace("0b",""))
for i in range(1,number+1):
#print (str(i).rjust(w,' '),str(oct(i)[2:]).rjust(w,' '),str(hex(i)[2:].upper()).rjust(w,' '),str(bin(i)[2:]).rjust(w,' '))
print(str(i).rjust(w,' '),str((oct(i).replace("0o",""))).rjust(w,' '),str(((h... |
660108333efe7c70f4b67cc45a7630537333a01b | rateterin/GeekBrainsPython | /lesson-4/Ex-5.py | 737 | 4.0625 | 4 | #!/usr/bin/env/python
#
# Written by Teterin Roman
# for GeekBrains Python course
# Python base
# Lesson 4 Exercise 5
#
# Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные
# числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления п... |
e5c8faefb5e0fade3a3cf12a70e351f237ebfa5c | Amina-Yassin/Amina_Yassin_Cashier_Register.py | /Testingbutisworkingkinda.py | 574 | 3.984375 | 4 | def purchase_1(amount_1):
total_1 = 0
for accumulation in range (amount_1):
x = input("Tell me the name of your item.")
x_1 = float(input("Tell me the price of your item."))
total_1 = total_1 + x_1
print (total_1)
total_1=str(total_1)
ans = (total_1,x)
retu... |
96025eca65cc420266fab0eee0b2b08a896eed69 | sudhirshahu51/projects | /Algorithms/Miscellaneous/Insertion_Sort.py | 287 | 3.984375 | 4 | # To sort a list by insertion sort
def insertion_sort(mylist):
my = mylist[:]
for i in range(1, len(my)-1):
key = my[i+1]
j = i
while j > 0 and key < my[j]:
my[j+1] = my[j]
j -= 1
my[j+1] = key
return my
|
2fb0c1454ba9ad737c36ed20906300308a4e4939 | himanshuv0210/Python-Assignment | /q4.py | 523 | 4.25 | 4 | list1=[10,30,20]
list2=[15,5,60]
list3=list()
print("Given List 1 : ",list1)
print("Given List 2 : ",list2)
for i in range(0,len(list1)):
list3.append(list1[i])
for j in range(0,len(list2)):
list3.append(list2[j])
print("Merge list : ",list3)
def sorting(arr):
i=0
j=0
for i in range(0,l... |
89d379e2483ff58edacb9383f8d0f8e185cb64ae | nazarov-yuriy/contests | /yrrgpbqr/p0350/__init__.py | 422 | 3.640625 | 4 | import unittest
from typing import List
from collections import Counter
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list((Counter(nums1) & Counter(nums2)).elements())
class Test(unittest.TestCase):
def test(self):
nums1 = [1, 2, 2, 1]
... |
0ad4c546ffb2398866f31299d7c2ef44730aa006 | Chalmiller/competitive_programming | /python/algorithms/hash_map/jewels_stones.py | 404 | 3.671875 | 4 | # 771 - Jewels and Stones
from typing import *
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
stone_map = set(J)
count = 0
for jewel in S:
if jewel in stone_map:
count += 1
return count
# one liner
# return sum(map(J.... |
11c14b22096447dc35babad8cbd6b22f41caea4c | DavidRDoyle/AdvancedProgramming | /CA3/Attempt1/calculator.py | 3,193 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 22:54:19 2018
@author: David Doyle
"""
'''Calculator Requirements
> Caclculator starts by asking user for input. Input can be a number
> Ten methods:
a. Add. User input will be "number", "operator", "number"
b. Subtract. User input will be "number", "opera... |
6f005e30c9e6a9b01d1509d522c9c1ef4c6832d1 | zilongxuan001/benpython | /ex11.py | 1,260 | 4.5 | 4 | #--coding: utf-8 --
#Date:20170818
#Title:ex11 提问
#打印:你几岁了?
print ('How old are you?')
#输入:岁数
age = input()
#打印:你多高?
print ('How tall are you?',)
#输入:高度
height = input()
#打印:你多重?
print('How much do you weigh?',)
#输入:重量
weight =input()
#打印:因此,你 几岁 ,多高 ,多重。
print("So, you're %r old, %r tall and %r heavy." %(age, ... |
6fa187f734ac5b09fdbda2901704c5d65711a5af | IcySleepingStar/Python | /Analyse/normes dans R2.py | 488 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 19 19:36:32 2018
@author: adrie
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import random
n = 3
fig = plt.figure()
ax = plt.axes(xlim = (-1, 1), ylim = (-1, 1))
plt.axis('equal')
def norme(n,m):
... |
c7baf41629faeb5fec845bc6c90629b2c2266277 | MarkHershey/PythonWorkshop2020 | /Session_01/wordCounter/word_counter1.py | 1,607 | 4.09375 | 4 | import string
# Open text file in reading mode
file = "Doc1.txt"
content = open(file, "r")
# initialise empty dictionary
dict = dict()
# initialise a total word counter
totalWordCount = 0
def stripWord(word):
"""
Make string lower case
Remove leading and trailing whitespeces and Punctuations
"""
... |
600b363e13575858b7e4f3afd8038b9532e53128 | jdh2358/py4science | /examples/skel/convolution_demo_skel.py | 2,176 | 3.921875 | 4 | """
In signal processing, the output of a linear system to an arbitrary
input is given by the convolution of the impule response function (the
system response to a Dirac-delta impulse) and the input signal.
Mathematically:
y(t) = \int_0^\t x(\tau)r(t-\tau)d\tau
where x(t) is the input signal at time t, y(t) is th... |
b8dc3c3fdbc34d01beade6b1107f57d069407c11 | e96031413/Python-Scripts | /searchPPT.py | 1,018 | 3.515625 | 4 | # REF https://stackoverflow.com/questions/55497789/find-a-word-in-multiple-powerpoint-files-python/55763992#55763992
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
import os
path = "./"
files = [x for x in os.listdir(path) if x.endswith(".pptx")]
def CheckRecursivelyForText(shpthissetof... |
c6eb0debdf5ff48a43c5a38f63dffe4c0601e636 | CircularWorld/Python_exercise | /month_01/teacher/day11/demo02.py | 822 | 4.15625 | 4 | """
总结
类与类调用语法
"""
# 函数互相调用:通过函数名直接调用
# def func01():
# func02()
#
# def func02():
# print("func02")
#
# func01()
# 写法1:直接创建对象调
# class A:
# def func01(self):
# b = B()
# b.func02()
#
# class B:
# def func02(self):
# print("func02")
#
# g01 = A()
# g01.func01()
#... |
993edda80c53906675c5bbf871e0557b5903137a | Melwyna/Algoritmos-Taller | /13.py | 205 | 3.671875 | 4 | a=str(input("Escriba el primer valor:"))
b=str(input("Escriba el segundo valor"))
print("Las variables no intercambiadas son:", a, "y", b)
c=a
a=b
b=c
print("Las variables intercambiadas son:", a, "y", b)
|
3d20fa077604c5bea6490c3bfa835fbd7e4fcd50 | cbare/advent-of-code-2020 | /day_04.py | 2,627 | 3.65625 | 4 | """
Advent of Code 2020 - Day 4
"""
import re
def to_dict(txt):
return {
k:v for k,v in
[pair.split(':') for pair in re.split(r'\s+', txt.strip())]
}
with open('puzzle-04-input.txt') as f:
pps = [to_dict(pp) for pp in f.read().split('\n\n')]
fields = {
'byr': True,
'iyr': True,
... |
fbd8daacdc4453406012e3f5ffba039a15ff148d | NapsterZ4/python_basic_course | /admin_archivos/guardar_permanente.py | 1,549 | 3.5 | 4 | import pickle
class Computadora():
def __init__(self, marca, procesador, mouse, teclado):
self.marca = marca
self.procesador = procesador
self.mouse = mouse
self.teclado = teclado
print("Se ha creado un nuevo ordenador de marca", self.marca)
# Convertir en cadena de ... |
cde06678db502c84d5c494a24a6908442ad14877 | tjoloi/CTF | /CSGames/2020_qualification/AI/spellChecker.py | 1,462 | 3.59375 | 4 | import string
global words
def missing_char(arr, word):
for i in range(len(word)):
for c in string.ascii_lowercase:
word_prime = word[:i] + c + word[i:]
if word_prime in words:
arr.add(word_prime)
def added_char(arr, word):
for i in range(len(word)):
word_prime = word[:i] + word[i+1:]
if word_prime ... |
f10384e89a71f577eeadff32daf88b06846e5d75 | Feodor17/tictactoe | /tictactoe.py | 6,768 | 3.921875 | 4 | #Подключаем библиотеку генератора случайных значений
import random
#Функция которая начинает игру.
def start_game():
print('Доброго времени суток! Это игра крестики-нолики!')
ans = input('Начать игру? (Y/N): ')
if ans.upper() == 'Y':
start_new_game()
else:
print('Всего доброго!')
def s... |
7de785e03d84b936007492d65e66e899325a8480 | HSx3/TIL | /algorithm/day07/day7_answer/연습1_스택.py | 190 | 3.96875 | 4 | s = list()
def push(item):
s.append(item)
def pop():
if len(s) == 0:
return
else:
return s.pop(-1)
push(1)
push(2)
push(3)
print(pop())
print(pop())
print(pop()) |
9cd0f0005dd83f00f1497ca66f9c378752e11c35 | gauravpore/Data-structures-algorithms | /Data_structures/binary_trees/tree_traversals.py | 1,718 | 4.1875 | 4 | class Node:
#node class to create a node
def __init__ (self,data):
self.right = None
self.left = None
self.data = data
def insert(self,data): #insertion of new node
if self.data:
if data < self.data: #checking left subtree
if self.left is None:
... |
34e4ad3df559498d143fc4e679c832440f15fed6 | rechardNerd/pythonhooli | /dir_test.py | 1,076 | 4.25 | 4 | # Script Name : dir_test.py
# Author : Craig Richards
# Created : 8th December 2021
# Last Modified : by- Joshua Covinfton 05 October 2021
# Version : 1.0
# Description : Tests to see if the directory testdir exists,
# if not it will creat... |
c693d8ed34dbd09034648e04cd40387199221775 | khaledai/Data-Scientist-Python | /03_Pandas Foundations/10_TS_Creating_And_Using_A_DatetimeIndex.py | 3,485 | 4.15625 | 4 | # The pandas Index is a powerful way to handle time series data, so it is valuable to know how to build one yourself. Pandas provides the pd.to_datetime() function for just this task. For example, if passed the list of strings ['2015-01-01 091234','2015-01-01 091234'] and a format specification variable, such as format... |
f335a352dae317142339c293f08cb21ba8cf0c40 | dhulmul/ds-algo-practice | /check_permutation.py | 375 | 3.84375 | 4 | # Given two strings, write a method to decide if one is a permutation of the other.
def check_permutation(word1: str, word2: str) -> bool:
map = {}
if len(word1) != len(word2):
return False
for ch in word1:
val = map.get(ch, 0)
map[ch] = val + 1
for ch in word2:
if ch not in map:
return False
map[ch... |
2dc44c944ab51bf61cd7000cba75a64339d5aa15 | thippeswamydm/python | /1 - Basics/18-error-handling.py | 771 | 4.21875 | 4 | # Describes using of Error Handling of code in python
# try...except is used for error handling
# 'try' block will be be executed by default
# If an error occurs then the specific or related 'except' block will be trigered
# depending on whether the 'except' block has named error or not
# 'except' can use a named... |
f8279b1e5a1457f85c611dd86b1658e999b67c53 | ncrhynes/Mathematical-Python | /Dice.py | 3,941 | 3.765625 | 4 | import random, math, matplotlib.pyplot as plt
def roll(numSides):
return random.randint(1, numSides)
def rollChoices():
L = []
N = 1
print("Please enter the number of sides for each die to roll.")
print("Enter 0 when finished.")
while True:
N = int(input(""))
if N == ... |
f438f9f7f3bc5a9ff4aed99505f7af3acacc2048 | numanjvd82/python-beginner-course | /guessingGame.py | 436 | 4 | 4 | # Guessing Game
secretWord = "Mr Robot"
guess = ""
limit = 4
while guess != secretWord:
if limit == 0:
print("You have no more guesses left!")
break
userResponse = input(
"Guess the Word: Some Hints are (drama, netflix, hacker, conglomerate, economy): ")
if userResponse == secretWo... |
3e8bd2ff4547e131067f281ddb99c1e5a0e64e19 | rdzotz/Coda-Analysis | /pyCoda/userInput.py | 18,419 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 12 13:37:48 2017
@author: rwilson
"""
import numpy as np
import pickle
import os
import ast
import sys
class utilities:
'''Collection of functions tools applicable to user interaction.
'''
@staticmethod
def query_yes_no(question, ... |
2acb1d381ba428603bebdf81074e1b505da81b0d | xingyunsishen/Python_CZ | /tom.py | 846 | 3.859375 | 4 | #-*- coding:utf-8 -*-
class Cat(object):
def __init__(self, new_name, new_age):
print('\033[0;31;42m ======哈哈哈=======\033[0m')
self.name = new_name
self.age = new_age
def __str__(self):
return '\033[0;33;43m %s 的年龄:%d\033[0m'%(self.name, self.age)
def eat(self):
... |
406f17b1d10cbfe946a1ef7ca7c7ce5b3602202b | alejogq/Intro-Python | /Nivelacion/funciones.py | 1,090 | 3.6875 | 4 |
def ingreso_datos(producto,precio):
temporal=input(f"Ingrese Kilos de {producto} ({precio} el kilo): ")
temporal = temporal.replace("," , ".")
temporal = float(temporal)
return temporal
seguir="s"
pTomate = 2800
pPapa = 1500
while (seguir.lower() == "s"):
kilosPapa = ingreso_da... |
418d96b05ee79551733dc95d318c3cb54fb7ee00 | KonstantinKlepikov/all-python-ml-learning | /python_learning/decorator_closedattr.py | 2,880 | 3.671875 | 4 | # example of realisation of decorator function and class attr
# we close access to that attrs otside of class
traceMe = False
def trace(*args): # code for selftesting
if traceMe:
print('[' + ' '.join(map(str, args)) + ']')
def Private(*privates):
def onDecorator(aClass):
class onInstance: #... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.