blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
815b8d503fb53750f2de4a146b769115fe305659 | marianomayo/Curso-de-Python-Inicial | /datos tipo tupla/listaYtuplaAnidada.py | 682 | 3.5625 | 4 | def cargar_paispoblacion():
paises=[]
for x in range(5):
nom=input("Ingresar el nombredel pais: ")
cant = int(input("Ingrese la cantidad de habitantes"))
paises.append((nom, cant))
return paises
def imprimirPaises(paises):
print("Paises y su poblacion")
for x in range(len(p... |
fdc723deee646053d433ce77bb8174ebed70a76d | Kafka-21/Econ_lab | /Week 4/Python Basics/PY_05.py | 1,403 | 4.03125 | 4 | # learning sklearn
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
#load the diabetes dataset
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
# loading data in array
print(diab... |
60156998e6005ad30cd41ed137423b1015a48e70 | ShakhrizodSaidov/python_solutions01 | /spyderpro14.py | 460 | 3.859375 | 4 | my_father={"name":"Erkin",
"surname":"Sharipov",
"born":1977,
"lives":"Bukhara"}
print(f"My father's name is {my_father['name']}\
and his surname is {my_father['surname']},\
he was born in {my_father['born']},\
he lives in {my_father['lives']} ")
# talaba_0 = {'ism':'murod o... |
0ce8eb014ba3bde265d74c89426cadfbdc5f7681 | chithien0909/Competitive-Programming | /Leetcode/Leetcode - Range Sum Query 2D - Mutable.py | 1,707 | 3.9375 | 4 | """
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example... |
ce558dd7444d0bf453e7d055db8d869bf912fd27 | gasamoma/cracking-code | /Strings/1.3.py | 2,226 | 4.5 | 4 | # URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this opera... |
d311b597c2c3d6290392a1f24be4212ba02e97ae | Karthiga1/CICD_Jenkins | /run.py | 911 | 3.5 | 4 | import requests
import json
import datetime
from datetime import date
def myFunction():
now = datetime.datetime.now()
date_today = date.today()
#print(date_today)
parameters = {
"api_key": "758f54db8c52c2b500c928282fe83af1b1aa2be8",
"country": "IN",
"year" : no... |
9e3b56e731f28f99c628e8a633b11aaf54ea365a | chayabenyehuda/LearnPython | /She Codes/Le9_romania.py | 923 | 4.03125 | 4 | # ex1 program a func that accepts a string representing Roman numeral and returns a number
def romanToInt( s: str):
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
# add all of the values together ignoring special cases like IX or IV
for n in s:
total += d[n]
... |
42ad748206b557425c75319b6d673194bc962393 | yograjshisode/PythonRepository | /LeapYear.py | 750 | 4.0625 | 4 | '''Leap year finder
Description
Leap years occur according to the following formula: a leap year is divisible by four, but not by one hundred, unless
it is divisible by four hundred. For example, 1992, 1996, and 2000 are leap years, but 1993 and 1900 are not. The next
leap year that falls on a century will be 2400.
Inp... |
5200d8cedccac138f7da39723a2c7266b591234c | acharles7/problem-solving | /Vmware/sort_array_by_parity.py | 389 | 4.09375 | 4 | """
Given an array A of non-negative integers, return an array consisting
of all the even elements of A, followed by all the odd elements of A.
"""
def sortArrayByParity(A):
ptr, i = 0, 0
while i < len(A):
if A[i] % 2 == 0:
A[ptr], A[i] = A[i], A[ptr]
ptr += 1
i += 1
... |
40d6b203a69ff547a84a3c30ccaa0112d042b3c6 | daichi0315/VehicleClassifier | /vehicle_cnn_aug.py | 1,945 | 3.625 | 4 | from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D
from keras.layers import Activation,Dropout,Flatten,Dense
from keras.utils import np_utils
import numpy as np
from keras import optimizers
import keras
classes = ['car','forklift','truck']
num_classes = len(classes)
image_size = 50
#メインの... |
2bae2e11e8184e14a951d800c08675603d5f4d5e | Immaannn2222/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/2-cofactor.py | 2,973 | 4.375 | 4 | #!/usr/bin/env python3
"""advanced linear algebra"""
def determinant(matrix):
"""calculates the determinant of a matrix"""
if not isinstance(matrix, list) or matrix == []:
raise TypeError('matrix must be a list of lists')
if any(not isinstance(i, list) for i in matrix):
raise TypeError('ma... |
e2a8b49bb308aa4ef5ca33645ae23e6684cd61c3 | Leeoku/leetcode | /Completed/Puzzle/204_count_primes.py | 2,007 | 3.78125 | 4 | #Count the number of prime numbers less than a non-negative number, n.
#test case, n = 10
class Solution:
def countPrimes(self, n: int) -> int:
#Sieve of Eratosthenes
#Make array for all integers, assume they are prime
#Time = O(nlogn) (inner loop runs fewer runs),
#Space... |
9a772db91b42c8f99c756083c09a49dea8c6947d | shouxie/qa_note | /python/python11_算法与数据结构/1-nodelist.py | 3,202 | 3.765625 | 4 | # -*- coding:utf-8 -*-
#@Time : 2020/5/14 下午7:27
#@Author: 手写
#@File : 1-nodelist.py
'''
数据结构-单链表:
【data, 下一个的指针】 --- data, 下一个的指针】...
'''
# 节点类 【data, 下一个的指针】
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
# 单链表
cla... |
252a2962b8819822684e045f3489405e6195ac4d | GBoshnakov/SoftUni-OOP | /Iterators and Generators/dictionary_iterator.py | 468 | 3.890625 | 4 | class dictionary_iter:
def __init__(self, d):
self.d = d
self.elements = [(key, val) for key, val in self.d.items()]
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index == len(self.d):
raise StopIteration()
current = ... |
0ca59aec9ef6924e05ce6152057ab8ae7332a4bc | daniel-reich/turbo-robot | /C6pHyc4iN6BNzmhsM_19.py | 2,315 | 4.125 | 4 | """
In this challenge, you have to establish which kind of Poker combination is
present in a deck of five cards. Every card is a string containing the card
value (with the upper-case initial for face-cards) and the lower-case initial
for suits, as in the examples below:
"Ah" ➞ Ace of hearts
"Ks" ➞ King of s... |
6b2c04774959ba8611d5262a318aef19ff74b20d | mrifqy-abdallah/python-exercises | /easy/023_meetup/meetup.py | 1,310 | 3.75 | 4 | from datetime import date
from calendar import monthcalendar, setfirstweekday
class MeetupDayException(Exception):
""" Return exception when encountered """
def __init__(message):
super().__init__("No such date exists")
def meetup(year:int, month:int, week:str, day_of_week:str):
setfirst... |
923048f2634fff05fd6665977fedb6404843af79 | DeveloperArthur/Data-Science-Python | /grafico-linha2.py | 175 | 3.6875 | 4 | import matplotlib.pyplot as plt
x = [1,2,5]
y = [2,3,7]
plt.title("Meu primeiro grafico com Python")
plt.xlabel("Eixo X")
plt.ylabel("Eixo Y")
plt.plot(x, y)
plt.show()
|
c799ec86d03b308ee4b8b5852bda24f6ad16e06d | ocoboj/Master-Python | /08-funciones/main.py | 3,024 | 4.4375 | 4 | """
FUNCIONES:
Una función es un conjunto de instrucciones agrupadas bajo
un nombre concreto que pueden reutilizarse invocando a
la función tantas veces como sea necesario.
def nombreDeMiFuncion(parametros):
# BLOQUE / CONJUNTO DE INSTRUCCIONES
nombreDeMiFuncion(mi_parametro)
nombreDeMiFuncion(mi_parametro) -> se... |
86436f130e0f93ad3ced4f94180ad3a9bd7c618a | kaif-rgb/Project-2021-tictactoe | /Project-2021-tictactoe/tictactoe.py | 6,127 | 3.515625 | 4 | from tkinter import *
from tkinter import messagebox
from functools import partial
import random
from copy import deepcopy
global board
board = [[' ' for x in range(3)] for y in range(3)]
sign = 0
def winner(b,l):
return ((b[0][0]==l and b[0][1]==l and b[0][2]==l) or
(b[1][0]==l and b[1][1]==l and b[... |
577bfe770cf7a22d24d8b01c9da965349d491fc4 | 6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion | /CH04/EX4.34.py | 644 | 4.3125 | 4 | # 4.34 (Hex to heximal) Write a program that prompts the user to enter a hex character
# and displays its corresponding heximal integer.
hex = input("Enter a hex character: ")
if '0' <= hex <= '9':
print("The decimal value is", hex)
elif hex.upper() == 'A':
print("The decimal value is 10")
elif hex.upper() ==... |
ac9c7f9898371b9020da8846c062018d5965418d | Nikolay-Pomytkin/cs2 | /python/maddieJin.py | 221 | 3.890625 | 4 | def randomlyDislike(name):
if name == "maddie jin":
return "you dislike katherine yoon"
else:
return "you dont randomly dislike people"
i = input("What is your name?")
print(randomlyDislike(i)) |
3189641113d14513630039b4702e37a02da5fba6 | w1pereira/aurorae | /aurorae/providers/spreadsheet/utils.py | 1,341 | 3.796875 | 4 | from openpyxl import load_workbook
def worksheet_dict_reader(worksheet):
"""
A generator for the rows in a given worksheet. It maps columns on
the first row of the spreadsheet to each of the following lines
returning a dict like {
"header_column_name_1": "value_column_1",
"header_colum... |
f502527a887cc6ab5411799822d38e45bd0b3741 | Phantomn/Python | /study/base64.py | 1,131 | 3.578125 | 4 | def encrypt(plain):
bn = ""
for text in plain:
bn += ("0" * (8-len((bin(ord(text)).split("b")[1]))) + bin(ord(text)).split("b")[1])
out = []
bn += "0"*(6-len(bn)%6)
out += [bn[i:i+6] for i in range(0, len(bn), 6)] # string -> ascii -> 8bit
dict = []
for n in range( ord("A"), ord("Z")+1 ):
dict.app... |
6d8dab473efb9f0c0aa32f5d43fa0e36d3e9c4e2 | emanuelgomes-university/alpP1IFPBGBA | /12 - Questões para implementação/Q3.py | 816 | 3.78125 | 4 | def imc(peso, altura):
return peso / altura**2
def situacao_imc(imc):
if(imc < 16):
return "Magreza grave"
elif(imc >= 16 and imc< 17):
return "Magreza moderada"
elif(imc >= 17 and imc< 18.5):
return "Magreza leve"
elif(imc >= 18.5 and imc< 25):
return "Saudável"
... |
8dbfb1d251cb898f4d1fa2f521f10b1152ae3aff | vkmicro/Person_coding_exercises | /extraTasks/Lecturing.py | 1,802 | 3.796875 | 4 | '''
Author: Vasiliy Ulin
This is a file with test code and explanatory comments which I use to teach my friends basics of programming
'''
import random
"""
block
comment
"""
'''
interchangable
neat eh
'''
'''
var1 = 5
var2 = 2
res = 5/2
print( " res : " + str(res) + "\n hi")
i = 0
for i in range(10):
print... |
61f1571cacb89ca270bc9d595474add78b040827 | EthanWhang/crimtechcomp | /assignments/000/Ethanwhang/000-code/assignment.py | 1,052 | 3.71875 | 4 | def say_hello():
print("Hello, world!")
# Color: Blue
def echo_me(msg):
print(msg)
def string_or_not(d):
exec(d)
def append_msg(msg):
print("Your message should have been: {}!".format(msg))
class QuickMaths():
def add(self, x, y):
return x + y
def subtract(self, x, y):
retu... |
14502ab85732cc557876d0f93a5b2ec1929fa014 | PerlaLunaD/csv-py | /quiz.py | 1,374 | 4.21875 | 4 | name= 'Goreti'
print(f'welcome to {name} choose your own adventure, as you follow the story. Enjoy the play, lets do it.')
print('you will find a room with two doors. The frist door is red and the second door is white')
door_choice = input('What door do you want to choose? \nRed door or White? :')
if door_choice == '... |
1517b6c8035231b6a79f65c8a3e1cb2aac270a73 | vasundhara7/DataStructuresAndAlgorithms | /GreedyAlgorithm/DistributeCandy.py | 976 | 3.578125 | 4 | # There are N children standing in a line. Each child is assigned a rating value.
# You are giving candies to these children subjected to the following requirements:
# 1. Each child must have at least one candy.
# 2. Children with a higher rating get more candies than their neighbors.
# What is the minimum candies yo... |
6a1406ad362042d8ca869a083ee064a25fc19478 | AlejandroPu/budapow | /testspath/matrix_verification.py | 1,328 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 1 20:10:17 2021
@author: retac
"""
def verifications( matrix ):
verification = True
est_col = matrix.keys()[0]=='Estaciones'
tip_col = matrix.keys()[-1]=='Tipo'
square = ( len(matrix.keys())-2 )==len(matrix)
stations = list(matrix.transpose... |
54e9762ec75abf30a844f9791d82ce97bde48821 | SereneBe/chatbot.github.io | /hangman.py | 1,344 | 4.28125 | 4 | word = input("falafel")
# Converts the word to lowercase
word = word.lower()
# Checks if only letters are present (isalpha means it has no numbers)
if(word.isalpha() == False):
print("That's not a word!")
# Some useful variables
guesses = []
maxfails = 7
# make a list of blank spaces
spaces = []
for letter in wor... |
b4404072c1b0d281ad45b614ab5d2ea80df56546 | dustinsnoap/code-challenges | /python/valid_palindrome.py | 573 | 4.40625 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Example 1:
# Input: "A man, a plan, a canal: Panama"
# Output: true
# Example 2:
# Input: "race a car"
# Out... |
5c3babf386e2870a1b93f097a08965e60174a4a7 | jonathanmockostrand/Homework4 | /HW4_Jonathan_Mocko-Strand.py | 2,042 | 3.859375 | 4 | ###########################################################
## ##
## Jonathan Mocko-Strand ##
## Dept. of Geology & Geophysics, TAMU. 2013-10-22 ##
## Python for Geoscientists ##
## Homework Assig... |
bacd3b925693361942403d100e0c5b6c0c6377af | Oihana1/python | /funtzioak.py | 378 | 3.5625 | 4 | def Kenketa(num1,num2):
if(num1>numb2):
ken=numb1-numb2
else:
ken=numb2-numb1
return ken
def Biderketa(num1,num2):
bider=num1*num2
return bider
def Zatiketa(num1,num2):
if(num1>numb2):
zati=numb1/numb2
else:https://github.com/Oihana1/python
zati=... |
d3b62136f4d413240d32a3ed0f44a1e52edaadd2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/29464e89fa7740148084914804c36fa8.py | 477 | 3.890625 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
ANSWER_YELLING = 'Whoa, chill out!'
ANSWER_EMPTY = 'Fine. Be that way!'
ANSWER_QUESTION = 'Sure.'
ANSWER_ANYTHING_ELSE = 'Whatever.'
def hey(what):
what = what.rstrip() # so questions can be properly detected
if what.isupper():
return ANSWER_YELLING... |
f6cf32bbcd7ba63990fb409f0e77d4cab45f9bf6 | TanaseMihaela/Data_wrangling | /sql_queries.py | 6,684 | 3.703125 | 4 |
import sqlite3
import csv
from pprint import pprint
sqlite_file = 'bucharest.db' # name of the sqlite database file
# Connect to the database
conn = sqlite3.connect(sqlite_file)
# Get a cursor object
cur = conn.cursor()
#number of nodes and ways
QUERY = "select COUNT(*) from nodes "
cur.execute(QUERY... |
1dfeabafaf85e2d57f22d2fb715668f47ed4f302 | OmenNXGen/Coding_with_Python-Lists | /content/1-lists/length.py | 271 | 4.25 | 4 |
aString = '12345'
# use the len() function to get the length of a string
print('the string has a length of:')
print(len(aString))
aList = [1,2,3,4,5]
# you can also use the len() function to get the length of a list
print('the list has a length of:')
print(len(aList))
|
ae333d1b58ebc14b108b5f5fb9dfcd7545f0f731 | Dyksonn/Exercicios-Uri | /1133.py | 145 | 3.953125 | 4 | a = int(input())
b = int(input())
if(a > b):
a, b = b, a
for num in range(a + 1, b):
if(num % 5 == 2) or (num % 5 == 3):
print(num) |
10544f4c60b88773dd53ae4e8f51be8feb718ac5 | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/serialization/449_serialize_and_deserialize_BST.py | 2,157 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
if not root:
retur... |
489d79577464ed4eccbf7b9c6d652f1fc7d2a4b4 | ervitis/challenges | /leetcode/range_addition_2/main.py | 742 | 3.578125 | 4 | """
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
"""
from typing import ... |
3d752760c3a10939b299dbed5467d8e94f617a6c | kaizer1v/py-exercises | /alternating_chars.py | 498 | 4.21875 | 4 | def alternating_chars(s):
'''
Given a string like AABABBAB, you need to return how many chars need to be
deleted so that no subsequent letters are the same
Basically, AABABABBA should become ABABABA (return total chars to be
deleted)
'''
toDel = 0
for x in range(1, len(s)):
if s... |
636874fab0a3811cb0ff9357ece4001133c8e462 | ozcayci/01_python | /gun12/starcraft_games.py | 1,615 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
starcraft_games.py
"""
def get_raw_data():
data = """
Game GameRankings Metacritic
StarCraft (PC) 93%[109] (PC) 88[111]
Insurrection 48%[113] —
Retribution —[114] —
StarCraft: Brood War 95%[115] —
StarCraft II: Wings of Liberty 92%[116] ... |
cccfeeb16d38db6e1c3e2172f40d65dcdafb311a | Gera2019/gu_python_algorythm | /lesson_7/task_2.py | 1,593 | 4 | 4 | '''
2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами
на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
'''
import random
def merge_sort(arr, start, end):
''' Сортировка вещественного массива методом слияния '''
if end - start... |
e36423051224c9fc2e2ce9d61e3393486209cdcc | campbelldgunn/cracking-the-coding-interview | /ctci-06-03-dominoes.py | 557 | 3.75 | 4 | #!/usr/bin/env python3
"""
Given an 8x8 checker board with two opposite corners cut out, and 31 domioes
which can each cover two spots, can you cover the entire board?
Completion time: 15 minutes.
Notes
- Tried on 4x4 first, convinced you cannot manually.
- Tried 2x2, obviously not.
- Could not prove it past intuiti... |
0d0e9cb23aacde7b3baa17710c338204439b6b96 | yongfuhu/python.learning | /quadratic.py | 566 | 3.8125 | 4 | a = int(input('请输入ax**2+bx+c=0中的a的值:'))
b = int(input('请输入ax**2+bx+c=0中的b的值:'))
c = int(input('请输入ax**2+bx+c=0中的c的值:'))
import math
def quadratic(a, b, c):
for x in (a, b, c):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
n = b**2 - 4*a*c
if a == 0:
x = - b/c
return x
... |
6daee309a4eacddec5b28982d7a0d1b9f76b6fa1 | nielsenjared/algorithms | /20-recursive-factorial/app.py | 148 | 4.03125 | 4 | def factorial(n):
if (n == 0) or (n == 1):
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) |
5fa92e40799bd358912c8b4cd8910f5effb7b366 | jjmuesesq/ALGORITMOS_2018-1 | /LABORATORIOS/LAB2/punto 2/mergeSort.py | 929 | 4 | 4 | def merge(A, start, mid, end):
p=start
q= mid+1
Arr=[0]*(end-start+1)
k=0
#print(range(start, end))
for i in range(start, end+1):
if(p > mid):
Arr[k]=A[q]
k+=1
q+=1
#print("if1")
elif(q > end):
Arr[k]=A[p]
k+=1
... |
7f0f58aec1f467a2072d582dcd70e5ee28a769d9 | Slothfulwave612/The-CSV-Reader | /csvFunctionFile.py | 64,993 | 3.515625 | 4 | # this is csv's most function file
# the most important file, as it will contain all the option function's code
# we will link this file to our main file and execute the required operation
import csv # importing csv module
import os # importing os module
import ti... |
e0eb11541c31e4b8980e41ec39d274a5ba9980a9 | All-In-Group/DanielDavtyan | /PythonExercises/SectionBasic ExerciseForBeginners/Question8.py | 158 | 3.734375 | 4 | #Print the following pattern
#1
#2 2
#3 3 3
#4 4 4 4
#5 5 5 5 5
i = 6
for num in range(i):
for i in range(num):
print(num, end=" ")
print() |
13e5fd47706fadd3cb4390802eb71f70c1bb5c09 | jikedou/webcrawler | /test1.py | 1,045 | 3.609375 | 4 | # coding:utf-8
import urllib2
import re
import BeautifulSoup
# testUrl = 'https://www.lagou.com/'
testUrl = 'http://example.webscraping.com/'
def download(url, user_agent="wswp", num_retyies=2):
# 设置用户代理
headers = {"User-agent": user_agent}
request = urllib2.Request(url, headers=headers)
# 捕获异常
... |
7b811cb0541bed65dd8dddd4e4f85de9f4e3e9be | abhaykatheria/cp | /HackerEarth/Round Table.py | 249 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 22:32:42 2018
@author: Mithilesh
"""
def round_table(n,x,k):
lst=[i for i in range(1,n+1)]
while(x%k)<len(lst):
t=x%k
list2=list(lst)
for i in range(t):
|
f66d33ae2b26abcf17f27bb817455ab6303f5fa1 | AlecShang/python_lesson | /02.OOP/OOP.py | 2,851 | 3.6875 | 4 | #!/usr/local/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : OOP.py
@Time : 2019/03/16 10:45:00
@Author : Alec Shang
@Version : 1.0
@Contact : shangjingweiwork@163.com
@License : (C)Copyright 2019-2020
@Desc : None
'''
#######################
# import sys
# print('aaa')
# class StudentPytho... |
749b253b421826bc326eabd93df7e39abe0f58c3 | d-mead/AI-Programs | /ATBS practice/chapter2.py | 234 | 3.921875 | 4 | import random
import sys
for i in range(5):
print('hello ')
i = 0
while i < 5:
print('number: ' + str(i))
i = i + 1
for i in range(0, 10, 3):
print(i)
print('')
for i in range(5):
print(random.randint(1, 10)) |
357bb479a78bc033552b2af9db316828df3c5167 | BatiDyDx/MathiPy | /mathipy/functions/quadratic.py | 4,179 | 3.921875 | 4 | import math
from mathipy.math import calculus
class Quadratic(calculus.Function):
"""
f(x) = ax^2 + bx + c
"""
function_type = 'Quadratic'
def __init__(self, a: float = 1, **kwargs):
self.a = a
if 'b' in kwargs and 'c' in kwargs:
b, c = kwargs['b'], kwargs['c']
... |
1bf4b03de2134b2fb532c29bb1129493ad6c7e6f | BenjiFuse/aoc-2020 | /Day13/Part2.py | 1,356 | 3.640625 | 4 | def extended_euclidean(a, b):
"""Implementation of the extended euclidean algorithm for finding gcd
and x,y to satisfy a*x + b*y == gcd"""
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_euclidean(b%a, a)
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
def mod_inverse(a, m):
... |
678842568a88eb671a04813c6247d807f94cdb82 | jaeinkim/Coding_Training | /Pythonic_Example.py | 820 | 3.5625 | 4 | # # acmicpc
# import sys
# input = sys.stdin.readline
# n, m = map(int, input().split())
# answer = 0
# print(answer)
#
#
# # pytest를 활용하기 위한 문법
# class Solution:
# def twoSum(self, nums: List[int], target: int) -> List[int]:
# return [1,2,3]
#
def solution(A):
A.sort() # 주어진 배열을 정렬합니다.
smallest ... |
ff7083eae4c8c31fbf3f80695592b1acc8f5e4fb | epan-1/uni-machine-learning-2018 | /Project_1/dataset.py | 2,519 | 3.671875 | 4 | ###
# Class that represents a dataset that has been stored as a .csv file
# Written by Edmond Pan (841389)
###
from collections import defaultdict
import numpy as np
class DataSet:
def __init__(self, filename):
"""
Reads in the csv file into an appropriate data structure
:param filename:... |
18ee268683d8fc30ff0ff0c46426c79137d81c97 | avdemidov/rosalind | /Partial Permutations/pper.py | 984 | 4.03125 | 4 | '''
Problem
A partial permutation is an ordering of only k objects taken from a collection containing n objects (i.e., k<=n).
For example, one partial permutation of three of the first eight positive integers is given by (5,7,2).
The statistic P(n,k) counts the total number of partial permutations of k objects that c... |
086442a7e13c4c1cc4cae17bd7053d2779f97a27 | sty515253545/pig-papa | /ApiAuto/code.py | 2,538 | 3.90625 | 4 | # coding=utf-8
# def likes(names):
# n = len(names)
# return {
# 0: 'no one likes this',
# 1: '{} likes this',
# 2: '{} and {} like this',
# 3: '{}, {} and {} like this',
# 4: '{}, {} and {others} others like this'
# }[min(4, n)].format(*names[:3], others... |
d0aaa3b720b08ebac8c6fffcfded42a0f0cbb898 | mag389/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 825 | 3.953125 | 4 | #!/usr/bin/python3
"""the island perimeter problem"""
def island_perimeter(grid):
"""finds the total perimeter of the island"""
perimeter = 0
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j] == 1:
if (i > 0 and grid[i - 1][j] == 0) or i == 0... |
f92900e302c6dcf4e5490e444ccfcfdc2b54eea9 | amcharaniya/python_summer2021 | /HW/HW5_AmaanCharaniya | 2,411 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 29 16:21:12 2021
@author: amaancharaniya
"""
class Node:
def __init__(self, _value=None, _next=None):
self.value = _value
self.next = _next
def __str__(self):
return str(self.value)
class LinkedList():
def __in... |
0b5fd5b672b206c0c1748d5c207c122c6de383f2 | michellima28/python | /python_fundamentos_dsa/Cap03/Lab02/calculadora_michel_lima_2.py | 1,013 | 4.21875 | 4 | # mensagem inicial
print('\n ------------- Calculadora Python -------------\n')
# funcoes aritmericas
def soma(x, y):
return x + y
def subtracao(x, y):
return x - y
def multiplicacao(x, y):
return x * y
def divisao(x, y):
return x / y
# variaveis de input
print('1 - soma')
print('2 - subtração')
prin... |
0e4faa4ed617854517dce7047f6a9a8950e7ed93 | gabo32/UniversidadPython | /Leccion02/main.py | 3,630 | 4.1875 | 4 | operandoA = 3
operandoB = 2
# suma
suma = operandoA + operandoB
# interpolacion
print(f'Resultado suma: {suma}')
# Resta
resta = operandoA - operandoB
print(f'Resultado resta: {resta}')
# multiplicacion
multiplicacion = operandoA * operandoB
print(f'Resultado multiplicacion: {multiplicacion}')
# division
division =... |
ba624927c3a34428624f33f43187307fa98b63fa | karanbr/python-projects | /tkinter_args_kwargs/main/kwargs.py | 505 | 3.625 | 4 | # keyword arguments
def calculate(n, **kwargs):
print(kwargs)
# for key, value in kwargs.items():
# print(key)
# print(value)
n += kwargs["add"]
n *= kwargs["multiply"]
print(n)
calculate(2, add=5, multiply=7)
class Car:
def __init__(self, **kwargs):
self.make = kwa... |
7ac669504ee3762a5128a90619ee951015c69fb3 | incememed0/python-notes | /30-ic_ice_fonksiyonlar.py | 3,909 | 3.84375 | 4 | # author: Ercan Atar
# linkedin.com/in/ercanatar/
#######################################################
###
#def greeting(name):
# print("hello",name)
#print(greeting("memed"))
#print(greeting)
#sayHello=greeting
#print(sayHello)
#print(greeting) # 2 adresde aynı
#print(greeting("memed"))
#print(sayHello("ali"))
#... |
8aa3bbd9de2362b23ac49729e32ae886fca6ca75 | girishongit/pythonML | /sigmoidDemo.py | 230 | 3.546875 | 4 | import numpy as np
input = np.linspace(-10, 10, 100)
def sigmoid(x):
return 1/(1+np.exp(-x))
from matplotlib import pyplot as plt
import pylab
plt.plot(input, sigmoid(input), "r")
plt.show()
#print (sigmoid(input))
|
3590acb6e7d4904eabe60763d4e8f60a8db408e8 | anshgandhi4/breadboard_sim | /src/Python/hole.py | 3,017 | 3.953125 | 4 | from tkinter import *
class Hole(Canvas):
def __init__(self, master, coord):
""" Hole(master, coord): creates a new Hole object with given coordinates
Hole object comes with click listener enabled
:param master: (Simulator)
:param coord: (Tuple), coordinates given by Breadboard clas... |
79ba6e211e66b85dd46bcd1ab91afcc6e0035833 | StephenClarkApps/AdventOfCode2019 | /DayFour/DayFour.py | 1,105 | 3.5 | 4 | # Day Four
lines = list(open('input.txt', 'r'))
input_range = lines[0].split('-')
lower_bound = int(input_range[0])
upper_bound = int(input_range[1])
def hasTwoTheSameInARow(a):
last_char = ''
for char in str(a):
if char == last_char:
return True
last_char = char
return False
... |
afdb55a051fbef193c12df9c7e18fb896afde0dc | ASDMGroup/skimap | /Classes/Geomlists/Point2D.py | 3,067 | 4.1875 | 4 | #!/usr/bin/env python3
"""Point2D"""
#Setup plotting and load useful modules
import matplotlib.pyplot as plt
import matplotlib.pylab
import copy
import numpy as np
#Define 2D point class
class Point2D(object):
"""A two dimensional point.
Parameters
----------
x : float
the x coordinate
... |
7b3dd9684c1abf6d577661b5baca2f4d450d1fcb | Airmagic/Lab-5 | /coinFlip.py | 2,938 | 4.21875 | 4 | # some of the code i got from stackoverflow
# importing random to get a random number
import random
# main program so I can call it
def main():
# printing what the program is and what to do
print("Guessing the number of times heads will land.\nPut in the number of flips and then the number of times head will... |
b4bdd0988d5705c006213daae787918aed2b1f77 | Zaidane-E/Labs | /Devoir1_Python/Devoir1Q4.py | 743 | 3.796875 | 4 | #Auteur: Zaidane El Haouari
#Numéro d'étudiant: 300130581
print("Auteur: Zaidane El Haouari")
print("Numéro d'étudiant: 300130581")
bureau=75.9
chaise=50.9
imprimante=32.5
scanneur=28.0
article=str(input("Entrez l'article souhaité: "))
quantite=int(input("Entrez la quantité voulue: "))
def calculPrix(article, qu... |
4b8cbcedc578bad0791514b1f37ae54e17af4f48 | kaustubhvkhairnar/PythonPrograms | /Pattern Printing/Assignment8.py | 446 | 3.984375 | 4 | #8. Write a program which accept one number and display below pattern.
#Input : 5
#Output : 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
def fun(number):
for i in range(1,number+1):
for n in range(1,number+1):
if (i>=n):
... |
d2aa1f4359eef0af7553fd951e578d7c83e63e98 | sgneves/courses | /Data_scientist_in_python/02_Python_for_data_science_Intermediate/02_Python_data_analysis_basics.py | 3,792 | 3.71875 | 4 | #**************************************************************************************************#
# #
# 02_Python_data_analysis_basics #
# ... |
ca7a2f46c11acb00c7cf0e08a88084e7c58615eb | ugaliguy/Python-at-Rice | /Principles-of-Computing/project-1-merge-2048.py | 1,116 | 3.71875 | 4 | """
Merge function for 2048 game.
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = []
merge_line = []
merged = False
indx2 = 0
for indx1 in range(len(line)):
new_line.append(0)
for indx1 in range(len(line)... |
aded423a12d062e75d310f0d6d3534352bb9181b | basantech89/code_monk | /python/MITx/6.00.1x_Introduction_to_ComputerSCience_and_Programming_using_Python/classesBasics.py | 399 | 3.78125 | 4 | class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '<'+str(self.x)+', '+str(self.y)+'>'
def distance(self, other):
return self.x+other.x-self.y-other.y
def yo(self):
return self.__str__().count('3') ... |
e7e0fe4356761323a1dafb876fa57186514c0ccf | Tedigom/Alghorithm_practice | /dfs_practice.py | 551 | 3.6875 | 4 | graph = {'A' : set(['B', 'C', 'E']),
'B' : set(['A', 'D', 'F']),
'C' : set(['A', 'G']),
'D' : set(['B']),
'E': set(['A', 'F']),
'F': set(['B', 'E']),
'G': set(['G'])
}
def dfs(graph, root):
visited = [] #각 꼭지점이 방문되었는지를 기록
stack = [root, ]
while stack: #stack이 비게 되면 탐색 끝
ver... |
a828abdc0e472407e8cb87aaa1d9f7b4bcefba35 | arentaylor/Week3-Py-Me-Up-Charlie | /PyBank/main.py | 2,959 | 4 | 4 | #import OS and CSV libraries
import os
import csv
#create variables for calculations
count_months = 0
total_revenue = 0
total_revenue_change = 0
# create file path and save as file
budgetfile = os.path.join(".", "budget_data.csv")
#open file and create file handle
with open(budgetfile, 'r') as csvfile:
... |
41dcfbd9c5e58850621e13eff6a58dbbde0a908a | Macheing/log_scripts | /user_validations.py | 400 | 3.90625 | 4 | #!/usr/bin/ python3
def validate_user(username):
minlength = 3 # user name should at least be 3 characters long.
assert type(username) == str, 'User name must be of type string not a integer or a list!'
if len(username) < minlength:
return False # minimum length must be at least 3 characters ... |
11a29b3ff03d45bf34af00f767af1a4f3dfe82cb | tuckershannon/pythonSpiralArt | /spiral.py | 3,221 | 3.796875 | 4 | """ Module spiral.py
This python program converts images into an Archimedes spiral type art made by varying
the width of spiral as it travels away from the center
Author: Tucker Shannon
"""
import numpy
from math import cos, sin, pi
from PIL import Image, ImageDraw, ImageSequence
from images2gif... |
249269f1309f2e577a8d3c155ab1785cfb1e4b46 | jfoody/BME547 | /blood_calculator.py | 1,548 | 3.765625 | 4 | def interface():
print('Blood calculator')
keeprunning = True
while keeprunning:
print('make a choice')
print('1-HDL analysis')
print('2-LDL analysis')
print('9 - quit')
choice = int(input('Enter your choice: '))
if choice == 9:
keeprunning = Fals... |
792e4df81d9171c527e0c13f5fbbf286b29268ab | thisconnected/sztucznainteligencja | /test.py | 692 | 3.9375 | 4 | #!/usr/bin/env python
"""Hello World, fizbuzz and 99bottlesofbeer"""
print ("Hello World!\n")
for i in range(1,99):
if not i%15:
print("fizzbuzz")
elif not i%3:
print("fizz")
elif not i%5:
print("buzz")
else:
print(i)
print ("\n99 bottles of beer")
for i in range(0,... |
9c2b7c8f96616b1915e6a8daf9b71e6830e1c841 | SimonFans/LeetCode | /Sliding_Window/L1477_Find_Two_Non_Overlapping_Subarrays_Each_With_Target_Sum.py | 1,951 | 4.125 | 4 | You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two... |
e7df56148fcbc66d75bf50880021eba33e0adbe4 | ahtornado/study-python | /day15/game.py | 639 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author :Alvin.Xie
# @Time :2018/7/15 11:14
# @File :game.py
import random
ch_list = ["石头","剪刀","布"]
win_list = [["石头","剪刀"],["剪刀","布"],["布","石头"]]
prompt = '''(0) 石头
(1) 剪刀
(2) 布
请选择(0/1/2): '''
computer = random.choice(ch_list)
ind = int(raw_input(prompt))
play... |
6ef756a9a42f2883b8a62b8612dfa58c5c469d2f | chalmerlowe/jarvis_II | /sample_puzzles/18_rising_numbers/your_code_here_rising_numbers.py | 706 | 3.640625 | 4 | # TITLE: rising numbers >> empty_rising_numbers.py
# AUTHOR: Chalmer Lowe
# DESCRIPTION:
# Identify and sum all the numbers in the file that have a
# "rising numerical pattern": meaning for each digit in the
# number, the digit is either equal to OR greater than the
# preceding digit (in this order: 0, 1, 2... |
14478c6a3c09b06575d49e76b4c0385d0744dcd9 | MaPing01/Python100 | /二分查找.py | 379 | 3.796875 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Ma Ping
def search(list,t):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
if list[mid] < t:
low = mid + 1
elif list[mid] > t:
high = mid -1
elif list[mid] == t:
... |
82a5d09fdbfa04ba730092057df3c97b7606761d | zhlthunder/python-study | /python 语法基础/d21_线程和协程/线程/4.使用线程锁解决数据混乱问题.py | 1,469 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
"""
两个线程同时工作,一个存钱,一个取钱
可能会导致数据异常
解决的思路:是加锁
"""
import threading
num=0
lock=threading.Lock()
def run(n):
global num
for i in range(1000000):
##加锁的方法1
lock.acquire()
##如果临界区的代码执行异常时,会导致无法解锁,会进入死锁状态,所以我们一般需要使用异常处理的方式,来确保一定会执行解... |
16bec3c5e6508a4cb4d2a05a6619eaf6fd28a23f | yumerov/codewars | /done/kyu-6/goldbachs-conjecture.py | 875 | 3.578125 | 4 | # https://www.codewars.com/kata/goldbachs-conjecture-1/train/python
from unittest import TestCase
primes = set()
def is_prime(num):
if num in primes:
return True
for i in range(2, num):
if (num % i) == 0: return False
primes.add(num)
return True
def goldbach_partitions(n):
if ... |
eb4da1d1c605b1e8fa280671479b10948c09ba8b | nathanfonbuena/python-algorithms | /hacker_rank/athlete_sort.py | 585 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
k = int(input())
def key_sort(elem):
... |
f8023636aa8cce1415e3a8e9ed97ab6341fe50b6 | fabianaramos/URI | /URI/Python/1005.py | 207 | 3.5625 | 4 | A = float(input())
B = float(input())
formatedA = "{:.1f}".format(A)
formatedB = "{:.1f}".format(B)
wghtA = 3.5
wghtB = 7.5
C = (A * wghtA + B * wghtB) / (wghtA + wghtB)
print("MEDIA =" , "%.5f" % C) |
8a14e58ed8785ccad216bdf05019a864fed426fb | Travmatth/LeetCode | /Medium/palindrome_partitioning.py | 1,171 | 3.671875 | 4 | """
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
"""
class Solution(object):
def permute_palindrome(self, s, out, cur):
if not s:
out.append(cur)
elif len(s) == 1:
cur.append(s)
... |
0cdb31dbd37831180026886dbe41a2400477d972 | ARI3L99/EjerciciosPython | /Clase05/estimar_pi.py | 623 | 3.59375 | 4 | import random
def generar_punto(): #genera numeros entre 0 y 1 para x e y
x = random.random()
y = random.random()
return x, y #retorna el valor de ambas variables
N = 100000 #se solicita 100000 veces generar punto
M = 0 #se inicialiaza el contador de M en 0
for i in range(N): #repite N veces
x, y = gen... |
e341970da95bd367925ef7432b74cd8dab703e22 | AlberVini/random-codes | /codes/infos_de_arquivos.py | 1,638 | 3.71875 | 4 | import os
caminho = str(input('Digite em que caminho deseja procurar: '))
termo = input('Digite algo especifico que quer procurar: ')
def formata_tamanho(tam):
base = 1024
kilo = base
mega = base ** 2
giga = base ** 3
tera = base ** 4
peta = base ** 5
if tam < kilo:
texto = 'B'
... |
899c1f8bbff86d7f1778d8396f8ec08ecdcb3096 | parhamgh2020/kattis | /I've Been Everywhere, Man.py | 133 | 3.546875 | 4 | for _ in range(int(input())):
lst = list()
for _ in range(int(input())):
lst.append(input())
print(len(set(lst))) |
6ac3d992a0da1ff34a0220205191486593cf1e5f | cyberskeleton/sandbox | /2020-04-08hw2.py | 613 | 3.734375 | 4 | #20.5
from tkinter import *
root = Tk()
enter = Entry(root, bg = 'cyan', fg = 'blue', borderwidth = 50)
enter.pack()
def delete_brackets():
string = enter.get()
return cut_off(string)
def cut_off(string):
if '(' in string and ')' in string:
string1 = string[:string.find('(')]
string2 = st... |
bca30609f7e0ce7c4d4ea2deec63fec0a4e6d4fc | MaxGosselin/tkinter-tutorial | /bucky/06-bindingFunctions.py | 280 | 3.703125 | 4 | from tkinter import *
def exFunc(Event):
print("This is an example!")
root = Tk()
# first way
# b1 = Button(root, text="What is this?", command=exFunc)
# b1.pack()
# Event
b1 = Button(root, text="What is this?")
b1.bind("<Button-1>", exFunc)
b1.pack()
root.mainloop()
|
e94e7e00f5d959dc29cede1eb6d50aaae0de8f7e | GENARALBOB115/oi | /bob.py | 1,697 | 3.625 | 4 |
import turtle
wn = turtle.Screen()
wn.bgcolor("#00ffff")
bob = turtle.Turtle()
bob.width(0.001)
bob.shape("turtle")
bob.color("red")
bob.goto(0,0)
bob.hideturtle()
bob.speed(0)
for i in range(60):
bob.forward(90)
bob.left(20)
bob.color("gold")
bob.backward(90.5)
bob.right(242)
bob.fo... |
8c0a151dfce332053853236cc9d0ebde5666b6b7 | prithivraj-rajendran/PythonProjects | /atm_machine.py | 591 | 4.1875 | 4 | # This code will tell an atm machine that how many notes at each amount to be given to user.
if __name__=="__main__":
notes = [2000, 1000, 500, 100, 50, 20, 10]
amount=int(input("Enter the amount to withdraw "))
if amount%10==0:
for note in notes:
if amount>=note and amount>0:
... |
5f96be51973fb703e925aa71853e3172919aabf6 | DanJamRod/codingbat | /logic-2/make_chocolate.py | 607 | 4.15625 | 4 | def make_chocolate(small, big, goal):
""" We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.
"""
if (goal - big*5 - small <=... |
71ba5a60f8f711d02f19e698ca9d9373979a076c | Ridhwanluthra/NLMS | /first_traversal.py | 6,195 | 3.65625 | 4 | # code for making the bot move in the grid
# ALL BLOCK COMMENTS ANSWER THE QUESTION "WHAT DO I HAVE AT THIS POINT?"
# take input of the matrix of the image
# store this x,y in a different variable
# take input of the start and the end point
from bot_globals import bot
import bot_movement as bm
from time ... |
fe723810582f183015c00ad7ab70ab8dd3c0037e | guna8897/my-web | /Variables,Numbers,Strings.py | 664 | 3.703125 | 4 | # VARIABLES
text = ("Good evening")
print(text)
#1 variable two message
pet = ("dog")
print(pet)
pet = ("cat")
print(pet)
a = ("hi")
a = ("hello")
print(a)
# Multiline strings
a = '''HI welcome all to "GCIT" '''
print(a)
# Changing case
my_name = "guna"
print(my_name.title())
print(my_nam... |
9af09db794b93b0433af821dbd9ce8ae303b5473 | Michael-Python/pub_lab_week_2_day_3 | /src/pub.py | 836 | 3.53125 | 4 | class Pub:
def __init__(self, name, till, drinks_list):
self.name = name
self.till = till
self.drinks = drinks_list
def add_money(self, amount):
self.till += amount
def drink_count(self):
return(len(self.drinks))
def add_drink(self, new_drink):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.