blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d45d42d81ba4ec38cfd908677cbdae0af2b105a9 | NebelFox/insometric | /temp.py | 1,560 | 3.84375 | 4 | from math import floor
from time import time
# def ray (x0: float, y0: float, x1: float, y1:float):
def ray (x0:int, y0:int, x1:int, y1:int, size:int) -> set:
start = time ()
x0, y0, x1, y1 = x0/size, y0/size, x1/size, y1/size
# print ("Starting time:", start)
ceils = set ()
# dx = abs (x1 - x0)
# dy... |
e85a2055b590e32da28e223dc7a75fc1c02fd5f6 | navneet28/PythonForBeginners | /pythonProTraining.py | 1,496 | 4.0625 | 4 | from statistics import mean as avg
gradeDict={"Dorothy":[98,88,82,78],"Sarah":[87,86,91]}
admins= {"admin":"admin@123","user":"user123"}
def enterGrades():
name=input("Student Name: ")
grade=input("Grade: ")
if name in gradeDict:
print("Adding Grade...")
gradeDict[name].append(float(g... |
b8aa82f476639342d4379387727cc0456b4109fa | xForgot10x/ClimateScraper | /ClimateScraper.py | 6,603 | 3.578125 | 4 | import re
import csv
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
def win_safe_name(cityname):
"""Edit the string so that it can be used as a valid file name in
Windows.
"""
cityname = cityname.strip()
if cityname.endswith("."):
cityname = cityn... |
03a14337bb654ac527c823c136ac5b1c7de52ed0 | bassemaed/HackerRank_TestDome_Practise | /RunnerupScore_py/main.py | 391 | 3.515625 | 4 | if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
MaxVal = 0
Result = 0
arr2 = []
for i in sorted (arr):
arr2.append(i)
MaxVal = arr2[len(arr2)-1]
CheckVal = arr2[0]
for j in arr2:
if(j>CheckVal and j<MaxVal):
CheckVal = j
... |
4f666911627ad075ab4320b22f76ca7813ed7b6b | fancybian/ner-crf2 | /train.py | 4,119 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Main training file for the CRF.
This file trains a CRF model and saves it under the filename provided via an 'identifier' command
line argument.
Usage example:
python train.py --identifier="my_experiment"
"""
from __future__ import absolute_import, division, print_function, unicode_lite... |
de60b0c7ee9c9d9e8fdd7dfd55667c6bb4d4de6d | staypuffinpc/IPT760-F19 | /solutions/constitution_challenge.py | 5,278 | 4.5 | 4 | ### PURPOSE: Show how to solve the constitution challenge problems ###
##-------------------------------------------------------------------------------------------##
#### 1. read the us_constitution.txtPreview the document file into a variable in your python file
# first, define a function to get the text of an exte... |
cad22afca2bc70daa146d16eced38db3a24a7918 | kookkig11/Python_Language | /lab8 เงินทอน.py | 423 | 3.796875 | 4 | def change(money,n) :
change = money//n
return change
money = int(input("Enter total money: "))
b500 = change(money,500)
left = money - b500*500
b100 = change(left, 100)
left = left - b100*100
b20 = change(left, 20)
left = left - b20*20
b5 = change(left, 5)
left = left - b5*5
b1 = change(left, 1)
print("500:... |
25d28962befcf0ef25ee967b1a46e69d8c874d1f | fgaurat/python_07122020 | /tp1/tp4.py | 1,337 | 3.515625 | 4 | #!/usr/bin/env python
l = ['toto','titi','tutu','tata']
num = ['123','456','789','101112']
l1 =[v.capitalize() for v in l if v != 'tata']
print(l1)
l2 = [(name,tel) for i,name in enumerate(l) for i1,tel in enumerate(num) if i == i1]
print(l2)
l3 = list(zip(l,num))
grande_liste = [l,num]
l3 = list(zip(*grande_list... |
b188ccd693297c9268b9613fb17687fc58cb3ff7 | rhaydengh/IS211_Assignment1 | /assignment1_part1.py | 1,824 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Assignment 1, Part 1"""
from __future__ import division
class ListDivideException:
"""class: ListDivideException, raises error
upon testing if the function listDivide doesn't run properly"""
pass
def listDivide(numbers, divide=2):
"... |
a485ac34a929e90c3f235bdc9ad9a13613dfa190 | eviebat/pymealplanner | /mealPlanner.py | 1,755 | 3.75 | 4 | #!/usr/bin/python
#
#title: mealPlanner.pl
#author: Emily VanDerveer
#purpose: This program will assign a random meal from it's
# meal text to the daily meal slot.
import sys
from userInput import getUserSelection #Only imports the used function from each module
from loadmeal import grabMeal
waitToStart = 1
name ... |
77cb70fed75bcae26b6602c4ba38969bfef52432 | DevJames98/INF108_VariousAssignments | /INF108 (Intro To Python)/percentGender2.py | 1,600 | 3.78125 | 4 | #Asks the user for the number of males and females registered in class and display the percentages of males & females in the class
#import everything from the graphics library
from graphics import *
#Create window
newWin = GraphWin("Percent Gender Calculator", 800, 600)
#Ask for user input
numOfMales = Text(Point(20... |
8416fd6c5b538dbf07fe6a5af4825b86722bfc5e | diegoasanch/Programacion-I-Trabajos-Practicos | /TP8 Tuplas, Conj, Dic/TP8.9 Numeros con sus cuadrados.py | 646 | 3.953125 | 4 | '''
Generar e imprimir un diccionario donde las claves sean números
enteros entre 1 y 20 (ambos incluidos) y los valores asociados
sean el cuadrado de las claves.
'''
def numero_cuadrado(hasta):
'Devuelve un diccionario con numeros naturales hasta hasta con su cuadrado'
nums = {}
for i in range(hasta):
... |
4c793dbe9f620061cc34d77821fc0173a9c58a5e | devendermishra/py-segment-tree | /sum-1.py | 2,927 | 3.640625 | 4 | def getmid(start, end):
return start + (end-start)/2
def constructSumUtil(arr, start, end, sum_array, sum_index):
if start==end:
sum_array[sum_index] = arr[start]
return arr[start]
mid = getmid(start, end)
#This operation can be abstracted
sum_array[sum_index] = (constructSumUtil(arr, start, mid, su... |
c27ac0f556dd796ea24d2e55e9c03d7ed6ab44b6 | tisyapruthi/creationqueen | /LMSClub/mycalendar3/mycalendar3.py | 1,120 | 3.96875 | 4 | '''Day Time. Subject
Monday 10:00 - 11:00 AM Period 1
11:30-12:30 AM. Math
Tuesday 9:00-11:00 AM PE
10:00-11:00 AM. Science
'''
def PrintMyPeriod (day, time, subject):
print (day + "\t\t" + time + "\t" + subject)
def PrintAll... |
df1f43b0c13c45bf5e294f2a86e095238215abfa | lucasmvnascimento/trybe-exercises | /exercises/Computer_Science/json-csv-entrada-e-saida-de-dados/exercicio3.py | 537 | 3.859375 | 4 | import random
with open('game_words.txt', mode='r') as game_words_file:
words_list = game_words_file.read().split()
random_word = random.choice(words_list).upper()
scrambled_word = "".join(random.sample(random_word, len(random_word)))
attempts = 0
while attempts < 3 :
print(f"{attempts + 1} TENTATIVA")
... |
07ed8dcc8fee0a38afcada4ba5ed6b60e9dcbfce | bullethammer07/Python_Tkinter_tutorial_repository | /default_blurred_background_on_entry.py | 774 | 4.09375 | 4 | import tkinter as tk
def on_entry_click(event):
# function that gets called whenever entry is clicked
if entry.get() == 'Enter text...':
entry.delete(0, "end") # delete all the text in the entry
entry.insert(0, '') # Insert blank for user input
entry.config(fg = 'black')
def on_focusout(e... |
5f08a83f83d99e0549846ebcba1fb1e920a4565a | xclmj/Lorenz96_and_neural_networks | /Lorenz96.py | 11,375 | 3.71875 | 4 | """This contains code to perform simulations of the Lorenz '96 system (see Lorenz E., 1996, Predictability: a problem partly solved. In Predictability. Proc 1995. ECMWF Seminar, 1-18). It can simulate the full system, the truncated model or use a neural network either alone or in combination with the truncated model, c... |
3134e75ebbaf212d290de16ed10c0a29fe584d25 | kalyons11/kevin | /kevin/tests/leet/test_is_anagram.py | 728 | 3.875 | 4 | """
https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3636/
"""
from unittest import TestCase
from kevin.leet.is_anagram import Solution
class TestIsAnagram(TestCase):
def _base_test_is_anagram(self, s: str, t: str, expected: bool):
sol ... |
ac94e356db71eecc69b4b696fd4fa5961b55f697 | Kalli/project-euler | /python/problem009.py | 487 | 3.875 | 4 | '''
Project Euler - Problem 9
http://projecteuler.net/problem=9
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
for a in range(... |
17bb44470f37f1077e3d05ebf1281dd49e24e9f1 | hscspring/The-DataStructure-and-Algorithms | /CodingInterview2/36_ConvertBinarySearchTree☆/test_convert_binary_search_tree.py | 4,407 | 3.5625 | 4 | from convert_binary_search_tree import convert_bst_to_sorted_doubly_linked_list
from convert_binary_search_tree import convert_bst_to_sorted_doubly_linked_list_with_inorder
from convert_binary_search_tree import BSTNode, travel_linked_list, connect_bst_nodes
def test_full_binary_tree1():
# 10
# 6 ... |
81ecec081ab59e3d4fa17a11d1c9b4dba9281db9 | c0fec0de/anytree | /anytree/walker.py | 2,786 | 3.78125 | 4 | # -*- coding: utf-8 -*-
class Walker:
"""Walk from one node to another."""
@staticmethod
def walk(start, end):
"""
Walk from `start` node to `end` node.
Returns:
(upwards, common, downwards): `upwards` is a list of nodes to go upward to.
`common` top node.... |
ab178cd4791ff700f8d56f81fdbcc75851a4f3e8 | erjan/coding_exercises | /count_elements_with_strictly_smaller_and_greater_elements.py | 1,171 | 3.984375 | 4 | '''
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
'''
#my own solution
class Solution:
def countElements(self, nums: List[int]) -> int:
if len(nums) == 1:
return 0
elif min(nums) == max(nu... |
6dc37e83abe79fbf677a4b191dc85a0c96802ce9 | alaakm1/My-Python-Codes | /String/lowercase_come_first.py | 1,268 | 4.03125 | 4 | """ arrange String characters such that lowercase letters should come first
Given input String of combination of the lower and upper case arrange characters in such a way that all lowercase letters should come first.
Expected Output:
input_String = PyNaTive
arranging characters giving precedence to lowercase letters
... |
753d268e0af831ce9273f10ec6ae6a34f5b6bb73 | Rangxixi/Tedu | /write_file.py | 169 | 3.5625 | 4 |
# 1. 打开文件
f1 = open('myfile1.txt', mode='w') # 'r'->read, 'w'->write
# 2. 写文件
f1.write('我')
# 3. 关闭文件
f1.close() # 释放资源
|
fb26909bd1db9e37e9f0d66c8b025837db63e388 | norbertosanchezdichi/TIL | /Python3/Exercises/Intersection/intersection.py | 127 | 3.734375 | 4 | def intersection(list1, list2):
return list(set(list1) & set(list2))
print(intersection(['a','b','z'], ['x','y','z'])) |
55327754a4c7c4412bddd9892fc330e1c12cd78f | HuangJingGitHub/PracMakePert_py | /leetcode/leetcode_77.py | 583 | 3.59375 | 4 | class Solution:
res = []
def combine(self, n: int, k: int) -> List[List[int]]:
self.res = []
path = []
self.trackback(n, k, 1, path)
return self.res
def trackback(self, n: int, k: int, begin: int, path: List[int]) -> None:
if len(path) == k:
self.res.... |
2947cf8efbea2620b7fcb6bc5db22d6253ab516b | bimri/learning-python | /chapter_14/dict_view_iterables.py | 2,051 | 4.5 | 4 | '''
the dictionary keys, values, and
items methods return iterable view objects that generate result items one at a time,
instead of producing result lists all at once in memory
'''
D = dict(a=1, b=2, c=3)
print(D)
K = D.keys() # A view object in 3.X, not a list
print(K)
# V... |
728ed2acb1213d83a9e366a2f5bec86fa1418025 | 0023jas/Python-Algorithms | /montyHall.py | 1,704 | 3.65625 | 4 | #1. random generate three doors
#2. Set one door to be the correct answer
#3. Select a door that isn't the correct and remove it
#4. Change the answer and see if it is correct
import random
import time
start = time.time()
wins = []
losses = []
def createDoors():
doors = [0,0,0]
doorCreate = rando... |
43824af8f48cb1384826ac067ea0aa8292d74eb9 | Jayamani25/md5 | /md5.py | 168 | 3.6875 | 4 | import hashlib
text = input("Enter Your Name:")
hash_object = hashlib. md5(text. encode())
md5_hash = hash_object. hexdigest()
print("Your Name In MD5 :",md5_hash) |
4919a46c84b301a8e6209bea1fd3f1c156ddc782 | pvmigdalov/random-walk | /my_random_walk.py | 2,445 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
class RandomWalk:
'''Class for generation random walk'''
def __init__(self, num_points=5000, start_point=(0, 0)):
self.num_points = num_points
self.start_point = start_point
def get_points(self, r_distribution=(0, 10), phi_distrib... |
2c01114f98a118992ce0cdac3b4325aa81a2c53f | Hans1140/Calculator-App | /calculator.py | 4,025 | 3.828125 | 4 | from tkinter import*
from tkinter import font
def btnClick(numbers):
global operator
operator=operator + str(numbers)
text_Input.set(operator)
#def pangkat():
#global operator
#operator = operator + str(numbers**2)
#text_Input.set(operator)
def btnClearDisplay():
global oper... |
31acbdd18e35cae16efdac494faf274ef20e530e | MateoPereyra88/DesarrolloDeSistemas6to1raCPOK | /Primera guía (python)/1.d.py | 256 | 3.890625 | 4 | import math
def main():
cat1 = float(input("ingrese el primer cateto (cm): "))
cat2 = float(input("ingrese el segundo cateto (cm): "))
hipotenusa = math.sqrt(pow(cat1, 2) + pow(cat2, 2))
print("la hipotenusa mide ", hipotenusa, "cm")
main() |
b497b59224b2bfa423a9002b3a700c5460cdbd25 | ksgifford/trigram | /src/trigrams.py | 2,559 | 4 | 4 | import io
import random
import sys
def main(source_file, word_count):
"""Call component functions to build paragraph for printing."""
raw_text = read_file(source_file)
parsed = parse_text(raw_text)
trigram = create_trigram(parsed)
paragraph = create_paragraph(trigram, word_count)
return paragr... |
c389fd48415ed69a79c1c88f3a4911d1ab76a943 | nicomatex/TP3AP1 | /equipos.py | 2,332 | 3.53125 | 4 | import random
NOMBRES_EQUIPO = ("Abomyzation","Ansatsu","Banshee","Bloodbane","Collapse","Cyberstein","Darkness","Defussion","Extermination","Flamecaster")
NOMBRES_PARTICIPANTE = ("Carlos","Esteban","Pedro","Gaston","Arya","Mirta","Teresa","Marta","Roberto","Marcelo","Nico","Juampi")
class Equipo:
'''
Representa un ... |
9344df5099b05abc5fbd7ec6044cfc19490f992e | sipakhti/code-with-mosh-python | /Crash_Course/Python standards lib.py | 288 | 3.859375 | 4 | from collections import OrderedDict
fav_lang = OrderedDict()
fav_lang["jen"] = "python"
fav_lang["sarah"] = "c"
fav_lang["edward"] = "ruby"
fav_lang["phill"] = "python"
for name, language in fav_lang.items():
print(f"{name.title()}'s favourite language is {language.title()}. ")
|
885c52af79716d74a0c580f4f5bf8ac1f68a2ce1 | NigrumAquila/RSA_and_LRR-LFSR- | /main.py | 2,730 | 3.734375 | 4 | from src.helpers.fileHelpers import writeKey, readKey
while True:
case = input('Select action: 1 - RSA; 2 - Linear recurrent register; "e" - to exit: ')
if case == '1':
from src.algorithms.RSA import RSA
while True:
case = input('Select action: 1 - Generate keys; 2 - Select public... |
c927d5628d4a866ed468604a90d1ea958bf2f69e | BeeNeal/data_structures | /prison_cells.py | 2,924 | 4.03125 | 4 | # There are 8 prison cells in a row, and each cell is either occupied or vacant.
# Each day, whether the cell is occupied or vacant changes according to the
# following rules:
# If a cell has two adjacent neighbors that are both occupied or both vacant,
# then the cell becomes occupied.
# Otherwise, it becomes vaca... |
f387391c59690fe355aa00f04f4c6c0ac5b69c44 | guimmp92/python | /check_balanced_tree.py | 866 | 4.125 | 4 | #!/usr/bin/python
# vim: foldlevel=0
"""
Write a function to determine if a binary tree is balanced.
"""
from bintree import Node
def is_balanced(node):
if not node:
return 0
left_height = is_balanced(node.left)
if left_height == -1:
return -1
right_height = is_balanced(node.right)
... |
524ca38333b19ada9e7ce91324deee8e3cb4f565 | JLevins189/Python | /Labs/Lab4/Lab10Ex2.py | 297 | 4.1875 | 4 | def max_list(list1):
maximum = list1[0]
for x in range(0, len(list1)):
if maximum < list1[x]:
maximum = list1[x]
print("Max is", maximum)
numbers = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input("Enter"))
numbers.append(ele)
max_list(numbers)
|
7677d3f14d8cc0683d3040a5ed5229915882f6bf | qjatn0120/2020_winter_AI | /source_code/Lecture2/calculator.py | 3,858 | 3.6875 | 4 | """
덧셈, 곱셈 등의 사칙연산을 지원하는 계산기를 만들어 봅시다.
이번 계산기는 메모리에 최근 계산 식 10개를 저장합니다.
__getitem__ 메서드를 이용하여 계산기의 x번째 계산 식에 접근할 수 있도록 합니다.
__str__ 메서드를 이용하여 계산기 최근 계산 식 10개를 모두 출력할 수 있도록 합니다.
"""
class calculator:
# calculator 클래스로 인스턴스를 만들 때 자동으로 실행되는 메서드 입니다.
def __init__(self):
# 먼저 계산 식을 저장할 메모리(리스트)를 생성합니다.
self.memory ... |
fc6775ae6aeae4d20216546e0a2d787048fd4ef6 | Vincentxjh/practice0724 | /012.py | 702 | 3.75 | 4 | #第十二个练习 - 模拟10086查询功能
print("----------10086查询功能----------\n")
print("输入1:查询当前余额\n"
"输入2:查询当前剩余流量\n"
"输入3:查询当前剩余通话\n"
"输入0:退出自助查询系统\n")
judge = True
while judge:
num = input()
if num == "1":
print("当前余额为:999元")
elif num == "2":
print("当前剩余流量为:5G")
elif num == "... |
b5853e9cfcf9ab62839522f88523072148d58e63 | ODelBene/Elite-Qualifier | /main.py | 3,349 | 3.5625 | 4 | import random
from bs4 import BeautifulSoup
import requests
#Simple chat program
#Responds randomly with one of four preprogrammed responses
def generic_response(user_input):
responses = [
"How interesting!",
"Good to know",
"Very cool!",
]
return random.choice(responses)
def hobbies(user_input)... |
bf27222a8acc704bacfcf582d51d01604e503ba2 | darrenzhangcn/mapreducepy | /examples/example_basic.py | 1,686 | 3.84375 | 4 | #!/usr/bin/env python
# coding=utf-8
# This example mapreducepy job is for the infamous Word Counting task with MapReduce
class mapreducejob:
# Data source (mandatory). Can be any dict object, the keys/values will be passed
# to "mapfn" function
datasource = {0: "This is the first phrase",
... |
cec7e403f3923e1bb1d4de59c581a726c7e30e47 | massey-high-school/91883-4-assessment-alis70929 | /QQ_Component8_KeepGoingLoop.py | 1,007 | 3.984375 | 4 | # Quiz Quest Component 8 ask user if they want to play again
# To Do
# - Ask user if they want to play again
# - if yes code loops again
# - if no then code ends
def string_check(question, to_check):
# Loops until a valid answer is given
valid = False
while valid == False:
# Asks question
... |
2531f4a3a987bb1da1d5cc4b668a9c5e273996bd | RLSwanepoel/edsa_packages | /edsa_packages/sorting.py | 3,733 | 4.5625 | 5 | def bubble_sort(items):
'''
Return array of items, sorted in ascending order based on the bubble sort algorithm
Args:
list (items): a list of items of any type
Returns:
list: a sorted list of the items
Examples:
>>> bubble_sort(['apple', 'pear', 'orange', 'pineapple', 'str... |
3be66cd378d15449a4909db02cb472acbef211c5 | lovepreet-013/data_structure | /hashing/Find the only repetitive element between 1 to n-1.py | 206 | 3.609375 | 4 | def findRepeating(arr, n):
s = set()
for i in range(n):
if arr[i] in s:
return arr[i]
s.add(arr[i])
return -1
arr = [9, 8, 2, 6, 1, 8, 5, 3]
n = len(arr)
print(findRepeating(arr, n))
|
939761c2b2c966c86daebd35427c0668aac36f8a | babamsi/py | /turt.py | 1,843 | 3.921875 | 4 | import turtle;
# def draw_square():
# window = turtle.Screen();
# window.bgcolor("red")
# brad = turtle.Turtle();
# brad.shape("circle");
# brad.color("yellow");
# brad.speed(2);
# brad.forward(100);
# brad.right(90);
# brad.forward(100);
# brad.right(90);
# brad.forwa... |
a3a854ddcea244ed6a20b371126e47c7b00951e9 | BloodyPig/PyAlgorithm | /search/binary_search/sence1.py | 682 | 3.90625 | 4 | def binary_search(my_list, element):
low = 0
high = len(my_list) - 1
while low <= high:
mid = low + (high - low) // 2
if element == my_list[mid]:
return mid
if my_list[low] < my_list[mid]:
if element > my_list[mid] or element < my_list[low]:
l... |
8018e8cb46ff55980f5695d307b695154642a78c | Fhernd/PythonEjercicios | /Parte002/ex1064_hacerrank_disenador_puertas_sr_vincent.py | 1,050 | 3.96875 | 4 | # Ejercicio 1064: HackerRank Diseñador de puertas para la empresa del señor Vincent.
# Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
# Mat size must be X. ( is an odd natural number, and is times .)
# The design should have 'WELCOME' wr... |
eee246811d4f1799a7d7ae46bdcbac542511d522 | Lucas-Guimaraes/Reddit-Daily-Programmer | /Easy Problems/151-160/160easy.py | 5,122 | 4 | 4 | # https://www.reddit.com/r/dailyprogrammer/comments/2451r5/4282014_challenge_160_easy_trigonometric_triangle/
import math
# https://www.omnicalculator.com/math/right-triangle-side-angle
# https://stackoverflow.com/questions/32980003/basic-trigonometry-isnt-working-correctly-in-python
def find_angle(a=0, b=0... |
3238acbdb300590fc1d41458a0655e630e46baaa | ykcai/Python_Programming | /homework/week11_homework_answers.py | 1,503 | 4.46875 | 4 | # Python Programming Week 11 Homework
# 1. Create a function that takes a number as an argument and returns True or False depending on whether the number is symmetrical or not. A number is symmetrical when it is the same as its reverse.
# Examples
# is_symmetrical(7227) ➞ True
# is_symmetrical(12567) ➞ False
# is_symm... |
fa9929d01944d6ab7c0d730892bec9b0b59690dd | ch3n-github/Machine_learning | /Linear_regression/sklinear.py | 530 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[18]:
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression as LR
import matplotlib.pyplot as plt
# In[19]:
data = np.genfromtxt('data.csv',delimiter=',')
X = data[:,0]
Y = data[:,1]
plt.scatter(X,Y)
plt.show
data.shape
# In[21]:
x_... |
2a3f4d7ddc5a6048dd9158470917ae650bb969fa | sergioTorres15/Curso_python | /curso_ejercicios/tablas_multplicar.py | 192 | 3.96875 | 4 | numero_tabla = int(input("de que num. quieres la tabla de multiplicar? :"))
for multiplo in range(1,11):
print("{} x {} = {}".format(numero_tabla,multiplo,numero_tabla*multiplo))
|
555e59efd4a4f634898842a0f9436b90b545e336 | k43lgeorge666/Python_Scripting | /basic code/menu1.py | 368 | 3.625 | 4 | #!/usr/bin/python
#lista
lista =[10,7,3,7,2]
suma = 0
nro_elementos = 0
x = 0
while x<len(lista):
suma = suma + lista[x]
nro_elementos = nro_elementos + 1
x=x+1
print("Los elementos de la lista son: " + str(lista))
print("La suma de los elementos de la lista es: " + str(suma))
print("la cantidad de elementos de la... |
804a53c70298d43f098dcf984d5951b620c9a55b | dmjacks/LearnPython | /ex3.py | 1,093 | 4.375 | 4 | print "I will now count my chickens:"
# This line prints the string Hens and the int 30
print "Hens", 25.0 + 30.0 / 6.0
# This line prints the string Roosters and the int 97
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
# This line prints Now I will count the eggs:
print "Now I will count the eggs:"
# This line prints... |
8bc86990547a58969f546245a31d764f470de252 | joseph-mutu/Codes-of-Algorithms-and-Data-Structure | /Leetcode/[面试题13]机器人的运动范围.py | 1,015 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-07 19:42:51
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
class Solution(object):
def movingCount(self, m, n, k):
if m <= 0 or n <= 0 or k == 0:
return 1
node_stack = []
n... |
6c7c584922cc677213875513aa22eef662c5ab9e | erickgust/python-exercises | /mundo-02/ex043.py | 385 | 3.828125 | 4 | peso = float(input('Digite seu peso (Kg): '))
alt = float(input('Digite sua altura (m): '))
imc = peso / alt ** 2
if imc < 18.5:
print('Abaixo do Peso')
elif 18.5 <= imc < 25:
print('Peso ideal')
elif 25 <= imc < 30:
print('Sobrepeso')
elif 30 <= imc < 40:
print('Obesidade')
elif 40 <= imc:
print('O... |
d94f3a69f85babe230a421d15376c59b6ca09896 | buyi823/learn_python | /Python Crash Course/dictionary_job_practice3.py | 766 | 3.6875 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# By Blaine 2021-09-02 17:01
# dictionary practice
users = {
'jordan': {
'first': 'michael',
'last': 'jordan',
'position': 'shooting guard',
},
'kobe': {
'first': 'kobe',
'last': 'bryant',
'position': '... |
9df598235be6f602e57b7c84c1c813be14068ddd | jzaunegger/Pirple-Python | /Homeworks/Homework-9/Homework-9.py | 3,130 | 3.59375 | 4 | import random
class Vehicle:
def __init__(self, make, model, year, weight):
self.Make = make
self.Model = model
self.Year = year
self.Weight = weight
self.NeedsMaintenance = False
self.TripsSinceMaintenance = 0
def __repr__(self):
return "This is an ins... |
513094537483a7550c103f75878b11a5f8ddd8e5 | mbcrocci/Scripts | /python/temp.py | 1,470 | 4.0625 | 4 | #!/usr/bin/env python3
def cel_to_fahr (cel):
return (9.0/5.0) * cel + 32
def cel_to_kel (cel):
return cel + 273.15
def fahr_to_cel (fahr):
return (fahr - 32) * (5.0/9.0)
def fahr_to_kel (fahr):
return (fahr - 32) * (5.0/9.0) + 273.15
def kel_to_cel (kel):
return kel - 273.15
def kel_to_fahr (... |
891f97b137b47d6d2c70bc8e5716c0bbc3f7eed2 | EGESERBES/GCI | /ağaç yükseklik.py | 298 | 3.953125 | 4 | yukseklik=int(input("Çizilecek ağacın yüksekliğini giriniz..:"))
satir=0
while satir<yukseklik:
sayac=0
while sayac<yukseklik-satir:
print(end="")
sayac +=1
sayac=0
while sayac<2*satir+1:
print(end="*")
sayac+=1
print()
satir+=1
|
cf258f62db5d152f6ec638e04ec708de2d820e8f | hiyuricu/NLP_100_Drill | /four/36.py | 305 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
def main(read_file):
before_line = ""
for line in open(read_file):
if before_line == "":
before_line = line
else:
print "%s\t%s" % (before_line.strip(),line.strip())
before_line = line
if __name__ == "__main__":
main(sys.argv[1])
|
0e5be3c74a10316d0a8ae282b8d52b835aff319d | Komei22/play_atcoder | /other/search_method/binary_search.py | 819 | 3.71875 | 4 | # bsのlistは降順にソートされていることが前提。targetは検索する値。
def bs(list, target):
left = 0
right = len(list)-1
# leftとrightが同値のときは、探索を終えたことを意味する。
while left <= right:
middle = (left+right)//2
val = list[middle]
if val == target:
return middle
# 検索する値targetが現在の中央の値valより小さい時、右側には... |
e3be1d058c91c34b33cff7ff81a039c4837f83e5 | shreyasrbhat/PyCon2019 | /Chapter - 6/chap6-2.py | 905 | 3.625 | 4 | y_end = 43000
y_begin = 200000
X_end = 120
X_begin = 0
slope_m = (y_end - y_begin) / (X_end - X_begin)
print("Slope => ", slope_m)
# (y - y1) = m(X - x1)
# y - 200000 = -1308.33(X - 0)
# y - 200000 = -1308X + 0
# y = -1308X + 200000
b_intercept = 200000
print("b_Intercept => ", b_intercept)
new_y = np.array([... |
7f3f2d4b3be47a37b268731a236a7b204d25b8ae | layshidani/learning-python | /lista-de-exercicios/Livro Curso Intensivo de Python/CIP-8.1-display-message.py | 464 | 3.953125 | 4 | # coding: utf-8
print('---' * 20)
print('\033[2mO que estou aprendendo neste capítulo\033[m')
print('---' * 20)
def display_message(name):
'''Mostra uma mensagem sobre o que estou aprendendo neste capítulo'''
print('---' * 20)
print('\nOlá, ' + name + '. Tudo bem?')
print('Neste capítulo estou aprend... |
82544db81e23030a594c60ea399de6f4c8ca73c7 | brianchiang-tw/Python | /Matplotlib/basic.py | 135 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( -5, 5, 100)
y = 3 * x + 2
plt.figure()
plt.plot(x, y)
plt.show() |
ff95149625da48ab0d1692bc19dad54fdaa0326a | sanketha1990/python-basics | /pythonHelloWorld/com/python/learner/PythonTuplesAndUnboxing.py | 328 | 4 | 4 | #Tuples
number=(1,2,3,4)
print(number.index(1))
print(number)
#Unboxing
coordinates=(1,2,3)
#x=coordinates[0]
#y=coordinates[1]
#z=coordinates[2]
#print(x*y*z)
x,y,z=coordinates #Short hand form of above
print(x*y*z)
#Unboxing is not limited to tuples we can use it for List as well
number=[2,4,6,8]
a,b,c,d=number
pr... |
14cf81a9d9056127320d1ca06c7467056fc48a3d | DaikiTanak/Atcoder | /ARC106/b.py | 2,062 | 3.578125 | 4 | N, M = map(int, input().split())
a_li = list(map(int, input().split()))
b_li = list(map(int, input().split()))
# 連結成分の抽出にはunion findで良さそう
class UnionFind():
def __init__(self, size):
# self.parent holds a list of idx for parant node of i-th node
# if i-th node is a root, self.parent[i] holds the - ... |
8864460e51b83fc152489a49d8c65ae027933554 | ranafge/all-documnent-projects | /scrapy_projt/answers.py | 1,734 | 3.8125 | 4 | ## What happens? ##
You grab all the `<li>` and try to print a `title`, but `<li>` do not have a `title`
It is the `<a>` that contains a `title`, so print:
print(b.a["title"])
**Example**
import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup
res = requests.get('http... |
d744966092758f1f2474e1417f22e0b9536bd7cd | dongryoung/Class_Examples | /10. Raspberry Pi/200708_2.py | 1,070 | 4.125 | 4 | #if
name = 'jane'
if name == 'jane':
print("name is jane")
else :
print("name is not jane")
age = 35
if age > 30 :
print('more than 30')
else :
print('less than 30')
a = 5
if a == 5:
print ('True')
else:
print ('False')
if a > 3 and a < 10:
print ('True')
else:
print ('False')
#e... |
e6b6a3549615c48b723450e705be51d8f3858a2e | asilva111/CS3_Lab_1_PythonPlot | /Trees.py | 3,688 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:02:35 2019
@author: Andres Silva
This program will draw tree like structures depending of the levels (n) provided. Each segment vertically is of the same length.
Each center point has 2 children, and each children has 2 children.
We start by having ... |
2dd821dbf4787bf8c2a6ccf90e6c569fc972df37 | hugo-paiva/curso_Python_em_Video | /Exercícios Resolvidos/Desafio094.py | 1,222 | 3.609375 | 4 | pessoa = {}
lista = list()
soma = 0
while True:
pessoa.clear()
pessoa['nome'] = str(input('Nome: ')).strip().title()
while True:
pessoa['sexo'] = str(input('Sexo [F/M] ')).upper().strip()[0]
if pessoa['sexo'] in 'FM':
break
print('ERRO. Digite apenas F ou M.')
pessoa[... |
98a6a19281517efc203946a56bd9e03ebd2e2981 | kumailn/Algorithms | /Python/Reverse_String.py | 296 | 3.984375 | 4 | #Question: Reverse a string
#Solution: Swap left and right pointers
#Difficulty: Easy
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
s = list(s)
for i in range(len(s) // 2): s[i], s[-i - 1] = s[-i - 1], s[i]
return "".join(s) |
76bdea79848ac7afafb74abfe8f863322f60aac4 | bingli8802/leetcode | /1145_Binary_Tree_Coloring_Game.py | 1,196 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 1. 树会被红色节点分成三部分
# 2. 在红色节点的 (父节点 左 右 )节点里面 找一个节点并且这个节点所在连通分量的节点树大于n/2
class Solution(object):
def btreeGameWinnin... |
07fd169c183804529626947b284b336cb276859b | childe/leetcode | /word-search/solution.py | 2,629 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/word-search/
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be ... |
0a4606bef0e74ca0dfe9c4350b0655c923ce8f62 | mollyocr/learningpython | /practicepython/exercise1.py | 1,980 | 4.125 | 4 | #### 2018-10-23 mollyocr
#### practicepython.org exercise 1: character input
## Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
name = input("Hi! What's your name? ")
print("Nice to meet you, " + n... |
6ba880c880d9b64bbce8f5ce1b2fea066508edae | jainrishu95/Machine-Learning | /P5/test.py | 1,810 | 3.5625 | 4 | # class A(object):
# def go(self):
# print("go A go!")
# def stop(self):
# print("stop A stop!")
# def pause(self):
# raise Exception("Not Implemented")
#
# class B(A):
# def go(self):
# super(B, self).go()
# print("go B go!")
#
# class C(A):
# def go(self):
#... |
0a286f81eea91461f80756bf16efa00ea25fc578 | eugeniocarvalho/CursoEmVideoPython | /Python Exercicios/Mundo 2: Estruturas de Controle/3. Repetições em Python (while)/ex062.py | 793 | 3.921875 | 4 | '''
Melhore o desafio 61, pesguntando para o usuario se ele quer mostrar mais alguns termos.
o programa encerra quando ele disser que quer mostrar 0 termos
Desafio 61
Refaça o desafio 51, lendo o primeiro termo e a razao de uma PA,
mostrando os 10 primeiros termos da progressao usando a estrutura while
... |
315734f80ad60150bf45fe0c6f92e2befc5a009c | rockdonald2/studyingPython | /selectionSort.py | 563 | 3.953125 | 4 | def selection_sort(array):
length = len(array)
startIndex = 0
while startIndex < length - 1:
smallestIndex = startIndex
currentIndex = startIndex + 1
while currentIndex < length:
if array[currentIndex] < array[smallestIndex]:
smallestIndex = curr... |
4b1fe9bf63cb8bc3ed027ee0a538bd899de61cd7 | jamesrmuir/python-workbook | /Python Workbook/22. BIGGER OR SMALLER [3].py | 1,427 | 4.28125 | 4 | #BIGGER OR SMALLER[3]
from commonFunctions import *
repeating = True
while repeating:
gettingData = True
while gettingData:
numberOne = float_input("Enter number one: ")
numberTwo = float_input("Enter number two: ")
print("Your two numbers are {} and {}.".format(numberOne, numberTwo))
... |
b8270f0ababd0df5b8d00827107243726ca7fa2a | dfwarden/DeckBuilding | /src/Game/Effects/Conditions/Filters/unique_filter.py | 669 | 3.578125 | 4 |
class UniqueFilter:
""" Represents a filter that returns only unique values """
def __init__(self, field, zoneType):
""" Initialize the filter """
self.field = field
self.zoneType = zoneType
def evaluate(self, context):
""" Evaluate the condition """
... |
c4485105bf6a71c518e568129beb7d476329060d | SaranyaEnesh/luminarpython | /luminarpython1/looping/reverse.py | 153 | 4 | 4 | num=int(input("enter a number"))#123
res=0
while(num!=0):
digit=num%10#123%10=3
res=(res*10)+digit#0*10+3=3
num=num//10#123//10=12
print(res) |
3ce6c3a4204e5f03e2ea084d770a36205b5e2f2a | Ved005/project-euler-solutions | /code/prime_cube_partnership/sol_131.py | 768 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
'''
File name: code\prime_cube_partnership\sol_131.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #131 :: Prime cube partnership
#
# For more information see:
# https://projecteuler.net/problem=131
# Problem Stat... |
ffbffbbfcaa375ca2c7d4a95d20e10d3fba21b05 | arachnidiskandar/Coisas-em-python | /Pegar títulos de artigos de uma página.py | 636 | 3.734375 | 4 | from bs4 import BeautifulSoup
import requests
url = 'http://www.bbc.com/portuguese'
req = requests.get(url)
code_html = req.text
soup = BeautifulSoup(code_html, 'html.parser') #deixa o código HTML da página de uma forma mais legível e guarda na variável.
#Dps disso, descobrir qual é a qual classe dos tít... |
c40e746e93abd8d70bd6fe834fc91f5635bcb5fc | poojatathod/Python_Practice | /vowel.py | 176 | 4 | 4 | def isvowel(char):
list=["a","e","i","o","u","A","E","I","O","U"]
if char in list:
return "true"
else:
return "false"
char="A"
print isvowel(char)
|
49fe99293a761d1af2b9ac60bdc268c4c10b9815 | gabriellaec/desoft-analise-exercicios | /backup/user_139/ch167_2020_06_22_16_59_07_816837.py | 387 | 3.53125 | 4 | def bairro_mais_custoso(dic):
dic2 = {}
for bairros, gastos in dic.items():
semestre = 0
for mes in range(6, 12):
semestre += gastos[mes]
dic2[bairros] = semestre
nome = " "
maior_gasto = 0
for bairro, gasto in dic2.items():
if gasto > maior_gasto:
... |
f31f99a184205436e810c7138bd4b7021e101453 | weak-head/leetcode | /leetcode/p0353_design_snake_game.py | 1,318 | 3.6875 | 4 | from collections import deque
from typing import List
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
self.snake = deque([(0, 0)])
self.snake_set = set([(0, 0)])
self.food = deque(food)
self.width = width
self.height = height
sel... |
39831dc69a97eb256a679804006adabce7165b1d | ArrayZoneYour/LeetCode | /107/Binary Tree Level Order Traversal II.py | 1,053 | 3.796875 | 4 | # /usr/bin/python
# coding: utf-8
# 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 __init__(self):
self.q = []
self.result = []
def levelOrderB... |
df8f7eb2c5c5c4d0c8fc17317681b1f655f3bde7 | franzheidl/ufo4Research | /fileStructureTests/core/plistTree.py | 1,297 | 3.90625 | 4 | def convertTreeToPlist(tree):
"""
Convert an ElementTree tree/element representing
a Property List to a nested set of Python objects.
"""
root = tree[0]
return _convertElementToObj(root)
def _convertElementToObj(element):
tag = element.tag
if tag == "dict":
return _convertElementToDict(element)
elif tag == ... |
731fca158d965092ca59f3f063d1e917fb56a84e | superxiangsx/python-ex | /test.py | 439 | 3.65625 | 4 |
#求绝对值的函数,即两点间距离的函数
'''def abs(x,y):
if x > y:
return x-y
else:
return y-x
'''
# y = |x-1| + 2*|x-2| + 3*|x-3| + 4*|x-4| + ...... + 100*|x-100|
#描述上述函数,min_x和max_x为区间的上下限
def jisuan(x,min_x,max_x):
j = min_x
z = 0
for j in range(min_x, max_x+1):
z = z + j * abs(x - j)
print(f"x = {x}, the resu... |
7e888e32add506ae9ba33925b2709fa4d86adb5c | sumaiya-antara/Relational-DB-Notes-by-princebillyGK | /Python-fake-data-generator/schema.py | 10,935 | 3.53125 | 4 | from json import load as json_loader
from PyInquirer import prompt
with open('datatypes_faker.json') as datatype_file:
datatypes = json_loader(datatype_file)
class DBItems:
def input_unique_obj_index(self, ls_name):
"""Get column index from prompt"""
if getattr(self, ls_name):
qu... |
e05dc2fe9689f95c09384b4d96619b1b4489e924 | Arcane1986/Python-Exercises | /Chapter4Exercises/Q1.py | 158 | 3.9375 | 4 | MessageRepeated=int(input("How many times would you like the message to be repeated? "))
for i in range(MessageRepeated):
print("We like Python's turtles!") |
53397a049b3f994ce75d52190295fab7538fcab8 | bchen528/holberton-system_engineering-devops | /0x16-api_advanced/2-recurse.py | 967 | 3.65625 | 4 | #!/usr/bin/python3
"""
a recursive function that queries the Reddit API and returns a list containing
the titles of all hot articles for a given subreddit. If no results are found
for the given subreddit, return None
"""
from requests import get
def recurse(subreddit, hot_list=[], after=None):
"""returns a list c... |
e201fac4ac8d46332e58b9cf0cf526951607d251 | bucioluis/python-exercises | /maximum.py | 1,061 | 4.34375 | 4 | ################################################################################
# Description: Programs to compare the two integers & see integer which is greater
###############################################################################
# Maximum between the two
def max_of_two(first_number, second_number):
i... |
6b650a9aef5554aaf4306f9a7253c7e9ae67f4b7 | genggng/leetcode | /316-1.py | 1,098 | 3.515625 | 4 | """
6214. 判断两个事件是否存在冲突 显示英文描述
给你两个字符串数组 event1 和 event2 ,表示发生在同一天的两个闭区间时间段事件,其中:
event1 = [startTime1, endTime1] 且
event2 = [startTime2, endTime2]
事件的时间为有效的 24 小时制且按 HH:MM 格式给出。
当两个事件存在某个非空的交集时(即,某些时刻是两个事件都包含的),则认为出现 冲突 。
如果两个事件之间存在冲突,返回 true ;否则,返回 false 。
"""
from typing import List
class Solution:
def haveCo... |
c35f9aac4890dcec80d4d9517676e5b845357e02 | Miguel-Bit-Debug/Curso-em-Video-Python | /ex096.py | 491 | 3.75 | 4 | '''def area():
largura = float(input('Largura [m]: '))
comprimento = float(input('Comprimento [m]: '))
total = largura * comprimento
print(f'A área de um terreno {largura}x{comprimento} é de {total}m²')
area()'''
#codigo curso em video
def area(larg, comp):
a = larg * comp
print(f'A area de um... |
c5bfbf04ffa0fd3c85bf34580dca6dfa34c61717 | LongDallas/data_structures_and_algorithms | /algorithm_analysis.py | 8,583 | 4.09375 | 4 | # Simple approach to study running time
from time import time
start_time = time()
#run algorithm
end_time = time()
elapsed = end_time - start_time
# a 'fairer' metric - measuring number of CPU cycles -- can use
# clock function of the time module, but stil might be inconsistent
#more advanced -- module named timeit
... |
2676db9371b709ca62865a4046932b447bad220d | jessidepp17/hort503 | /assignments/A02/ex16.py | 1,339 | 4.40625 | 4 | # use ex16_test.txt as filename
# import module sys
from sys import argv
# one arg variable
script, filename = argv
# print formatted string with embedded variable; the code will erase the file
# no matter what the user decides
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (... |
bc610a19a01072a3ed943d84887392be36cc4e62 | dudulacerdadl/prototipos | /Curso Python/Exercícios/ex006.py | 200 | 4.21875 | 4 | num = int(input('Digite um número: '))
print('O número digitado foi {}, \n Que tem como dobro {}, \n Sendo o triplo {} \n E a raíz quadrada {:.2f}.'.format(num, num * 2, num * 3, num ** (1 / 2)))
|
b2b7b99261bef001e41dbcc501c4d0cc7a44cdf4 | good5229/python-practice | /1920.py | 616 | 3.78125 | 4 | import sys
def BinarySearch(arr, val, low, high):
if low > high:
return False
mid = (low + high) // 2
if arr[mid] > val:
return BinarySearch(arr, val, low, mid - 1)
elif arr[mid] < val:
return BinarySearch(arr, val, mid + 1, high)
else:
return True
n = int(sys.st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.