blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
014dca2ba64c88df58419bd8d54ec52e85fb5a71 | UBC-MDS/tidyplusPy | /tidyplusPy/typemix.py | 3,849 | 4.53125 | 5 | #!/usr/bin/env python
def typemix(df):
'''
The function helps to find the columns in a data frame that contains different types of data.
Python has many data types. The function roughly identifies if an observation belongs to one of the 3 main data types, numbers, booleans, and strings.
Parameters
... |
24393698624ffb0c011a23c9a47ca835082fc20f | ARUNKUMAR0354/python-Files | /Tuples.py | 479 | 4.5 | 4 | Tuple1 = ()
print("To creat the empty tuple1: ")
print(Tuple1)
Tuple1 = ("Arun","kumar")
print("Tuple is using with string:")
print(Tuple1)
Tuple1 = [1,2,3,4,5,6]
print("\nTuple is using with list:")
print(Tuple1)
# Accesing the tuple element.
Tuple1 = (1,2,3,4,5,6)
print(Tuple1)
print("\n Accessi... |
8417e5857389da68ebe17a2c1c94a1a2781caddd | ShanmukhaSrinivas/GUVI-CodeKata | /Beginner/Set-03/problem#24.py | 151 | 3.71875 | 4 | #Sort given data
m = int(input())
l = sorted([int(i) for i in input().split()])
for i in range(len(l)-1):
print(l[i],end = " ")
print(l[len(l)-1])
|
f3072fa2d7d744ae57ea958508080ef13d0bc1de | Allan-Barbosa/respostas-beecrowd | /1012.py | 285 | 3.78125 | 4 | a, b, c = input().split(" ")
a = float(a)
b = float(b)
c = float(c)
at = (a*c)/2
ac = 3.14159*(c**2)
atra = (a+b)*c/2
aq = b**2
ar = a*b
print("TRIANGULO: %.3f" % at)
print("CIRCULO: %.3f" % ac)
print("TRAPEZIO: %.3f" % atra)
print("QUADRADO: %.3f" % aq)
print("RETANGULO: %.3f" % ar)
|
9608ba5aee60cba622ebdc3c514fa4393ba13ab3 | Dpalme/CaesarCypher | /Python/CaesarCypher.py | 4,272 | 3.78125 | 4 | # encoding = UTF-8
import json
import random
# Esta funcion regresa el número de caracter en Unicode.
def num(char):
return ord(char)-97
# Regresa el caracter que se encuentra en la posición "number" del abecedario traducido a Unicode.
def character(number):
return chr(97 + number%26)
def normalizeString(st... |
c7785472c0bc20b45b370ac28f3a65f263ff21bc | LewisPalaciosGonzales/t06_palacios_ruiz | /palacios/multiple_26.py | 426 | 3.90625 | 4 | #PROGRAMA 26
#Ejercicio 26 condicional multiple
import os
tipo_de_empleado=""
categoria=""
#INPUT VIA OS
tipo_de_empleado=os.sys.argv[1]
categoria=os.sys.argv[2]
#processing
#si el tipo de empleado es "aux"
#y su categoria es "tc" moestrar "regular"
#regula=(aux=tc)
if(tipo_de_empleado == "aux") and (categoria == "tc")... |
69604e7cf5b3a26aaae3154c57a8c9cd8ad9c2ea | Raaja6897/100-Days-of-Code-Python | /Day 9/Grading Program.py | 482 | 3.796875 | 4 | student_score = {
"Harry": 81,
"Ron": 78,
"Hermoine": 99,
"Draco": 74,
"Neville": 62
}
for student in student_score:
score=student_score[student]
if score >90:
student_score[student]="Outstanding"
elif score >80 and score <=90:
student_score[student]="Exceeds Expectation... |
a6e5a4643c126c3971cb5702d0c886301ff2262e | mutedalien/CO_Py | /W3/metod.py | 4,302 | 4.46875 | 4 | # Работа с методами экземпляра
class Human:
def __init__(self, name, age=0):
self.name = name
self.age = age
class Planet:
def __init__(self, name, population=None):
self.name = name
self.population = population or []
def add_human(self, human):
print(f"Welcome t... |
e96c8302aa7f90aea8796a575e813f7813913b5f | yoganbye/Kirill-homework | /Part_1/Lesson_2/hw02.py | 3,013 | 3.90625 | 4 |
__author__ = 'Баранов Кирилл Андреевич'
# Задача-1: Запросите у пользователя его возраст.
# Если ему есть 18 лет, выведите: "Доступ разрешен",
# иначе "Извините, пользоваться данным ресурсом можно только с 18 лет"
age = int(input('Введите ваш возраст: '))
if age > 18:
print('Доступ разрешен')
else:
print("Из... |
77ed776df4218a99f5eb760f0c15591edbc1598e | jake-albert/py-algs | /c17/c17p06.py | 4,729 | 3.9375 | 4 | # c17p04
# Count of 2s: Write a method to count the number of 2s that appear in all the
# numbers between 0 and n (inclusive).
#
# EXAMPLE
# Input: 25
# Output: 9 (2,12,20,21,22,23,24,25. Note that 22 counts for two 2s.)
##############################################################################
# I assume for th... |
8781662e202184af4c1ad7a02729452f0cb26f29 | ahirwarvivek19/Semester-3 | /Python Lab/Lab2-A-3.py | 252 | 4.15625 | 4 | # 3) Write a program to enter your birth year. Print your age
#
# Sample input -
#
# Enter your birth year
# 1990
#
# Sample output -
#
# Your age is 30
print("Enter your birth year ")
bYear = int(input())
age = 2020-bYear
print("Your age is ",age) |
34dcbd70f469cdd5caaec34b6e487553e4b88a86 | jmsevillam/LearningML | /projects/Classes/functions.py | 384 | 3.5 | 4 |
def suma(a,b):
a=2.*a
return a+b
def Doble(a):
a=2.*a
def ap(x,b):
x.append(b)
def g(x0,a):
return a*x0+b
import numpy as np
x=np.array([2])
print(x)
suma(x,5)
print(x)
li=[1,2,3]
print(li)
ap(li,3)
print(li)
a=2
b=4
x=np.linspace(0,10,100)
y=g(x,10)
a=1
print(type(a))
a=1.
print(type(a))
a... |
ce2e23cc12d78020ffc38b54a9f7510be1933776 | remixknighx/quantitative | /exercise/leetcode/can_place_flowers.py | 638 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
605. Can Place Flowers
@link https://leetcode.com/problems/can-place-flowers/
"""
from typing import List
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
ans = 0
num = 1
for x in flowerbed:
if x == 0:
... |
c627e919b533046406628ae45ef03539f0728a75 | nss-day-cohort-38/orientation_packages | /appliances/outdoors/airconditioner.py | 457 | 4 | 4 | class AirConditioner:
def __init__(self):
self.set_temp = 68
# A function that calls itself is called a recursive function. See https://www.programiz.com/python-programming/recursion for more.
def run_ac(self, current_temp):
if current_temp > self.set_temp:
current_temp -= 1 # curr... |
b4b1bfdb408ac7878850968fa74c32dce23e5a83 | kevin510610/Book_AGuideToPython_Kaiching-Chang | /unit07/exercise0709.py | 151 | 3.609375 | 4 | end = int(input("p: "))
i = 1
p = 1
while i <= end:
p *= i
i += 1
print(p)
# 檔名: exercise0709.py
# 作者: Kaiching Chang
# 時間: July, 2014
|
164de9ae3ee0bdb71a3c35aa7ad2c68cf1754b2e | navarroruben/RotateMatrix90-python | /main.py | 1,015 | 3.6875 | 4 | # Ruben Navarro
# 12/19/2019
# main.py
# CTCI - Rotate Matrix
# Rotates a NxN Matrix 90 Degrees in place
def rotate90(m):
layers = len(m) // 2
length = len(m) - 1
for layer in range(layers): # loops through for each layer
for i in range(layer, length - layer): # loops through each element
... |
086bb3e2096bab0ad7e091ce57bafaea4471d1e9 | kumarav615/RNN | /MLP/CreateDataSet.py | 1,070 | 3.578125 | 4 | # Multilayer Perceptron to Predict International Airline Passengers (t+1, given t)
import numpy
from pandas import read_csv
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
... |
8899a3f46ff0477cfc1c749a7b9bc69b67177562 | Chetan-verma713/python_program | /checking_password.py | 194 | 4.09375 | 4 | password = "12345678"
print("Hint => 1 to 8")
n = input("Enter password => ")
if n==password:
print("Welcome to python")
else:
print("""Enter a valid password...
Try again""")
|
cdd14557676a20ea58d3d531d742895bae6061db | ssfspu/Learn_Python_The_Hard_Way | /ex15.py | 602 | 4.15625 | 4 | from sys import argv
script, filename = argv
txt = open (filename)
# "open" is a command that reads the text file
# as long as you put the name of the file in
# the command line when you ran the script
print "Here's your file %r:" % filename
print txt.read()
# txt is a variable or object and the . (dot)
# is to ... |
61beed9f74d0ec996b58068c974dccbdb5a87448 | roshan2M/edX--mitX--introduction-to-computer-science-and-programming-with-python | /Week 5/Lecture 9 - Efficiency and Orders of Growth/In-Video Problems/Lec9.1Slide5.py | 123 | 3.78125 | 4 | # Lecture 9.1, slide 5
def linearSearch(L, x):
for e in L:
if e == x:
return True
return False |
d81a31b215f2cbb834f66edf45990335579d8401 | nyanlin-rmg/caeser_cipher_text | /main.py | 533 | 4.15625 | 4 | from encrypt import text_encryption
from decrypt import text_decryption
char = True
while char:
ans = ''
while not(ans.upper() == 'D' or ans.upper() == 'E'):
ans = input("\nEnter 'E' for encryption (or) Enter 'D' for decryption: ")
text = input("Enter text: ")
key = input("Enter key: ")
if ans.upper() == 'E':
... |
07046fffa4adb85bd42553d89af53eb35eab606b | snsd050331/LeetCode_practice | /Homework 1~10/homework1_TWO SUM.py | 436 | 3.5625 | 4 |
class Solution:
def twoSum(self, nums, target):
dic=dict()
for index, value in enumerate(nums):
sub = target - value
if sub in dic:
return [dic[sub], index]
else:
dic[value] = index
if __name__ == '__main__':
nums=[2... |
bc89794eda6e7963ad0936763573036545907d5b | morrrrr/CryptoMasters | /22_schnorr_sign_verify.py | 2,024 | 3.578125 | 4 | from math import sqrt
from random import randint
from sympy import nextprime
# trivial divisors of n
# is 1, -1, n, -n
# because every number will divide be 1 and by itself
# non trivial divisors are all other ones
def non_trivial_divisors(n):
divs = []
for i in range(2, int(sqrt(n)) + 1):
if n % ... |
749776558292c411bf64c731b2b7ff29046b9efc | fredy-glz/Ejercicios-de-Programacion-con-Python---Aprende-con-Alf | /05_Diccionarios/05_DiccionariosPython.py | 534 | 3.546875 | 4 | # JOSE ALFREDO ROMERO GONZALEZ
# 23/11/2020
d_boleta = {'Matemáticas':6, 'Física':4, 'Química': 5}
creditosTotal = 0
for m, c in d_boleta.items():
creditosTotal += c
print(m, "tiene", c, "créditos")
print("Créditos totales: ", creditosTotal)
# SOLUCION DE https://aprendeconalf.es/
course = {'Matemáticas': 6,... |
843dc68a21e83d88318068293f03c3d2fd4218d0 | camellia26/multiml | /multiml/agent/agent.py | 295 | 3.578125 | 4 | """Module to define agent abstraction."""
from abc import ABCMeta, abstractmethod
class Agent(metaclass=ABCMeta):
"""Base class of Agent."""
@abstractmethod
def execute(self):
"""Execute Agent."""
@abstractmethod
def finalize(self):
"""Finalize Agent."""
|
861d8834accea7fab197e8402d1a5f64404f3fd3 | nakanishi-akitaka/python2018_backup | /0629/test1_matplotlib.py | 3,093 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
matplotlib で散布図 (Scatter plot) を描く
https://pythondatascience.plavox.info/matplotlib/散布図
本ページでは、Python のグラフ作成パッケージ Matplotlib を用いて散布図 (Scatter plot)
を描く方法について紹介します。
Created on Fri Jun 29 11:57:44 2018
@author: Akitaka
matplotlib.pyplot.scatter の概要
matplotlib には、散布図を描画するメソッドとして... |
bebfbc9fdf8ee3c9d1ba545489780ab8d1a403c2 | purujeet/internbatch | /tab.py | 82 | 3.828125 | 4 | num=int(input('Enter a number:'))
i=1
while(i<=10):
print(i*num)
i=i+1
|
d76937c713b29e811aafd48c133768af6b740bd9 | Hisokalalala/tic-tac-toe | /tictactoe/tests/test_tictactoe.py | 846 | 3.515625 | 4 | from unittest import TestCase
from tictactoe.tictactoe import turn
from tictactoe.tictactoe import whowin
class Test(TestCase):
def test_turn(self):
self.assertEqual(turn([["?", "?", "?"], ["?", "?", "?"], ["?", "?", "?"]], "M", 1, 1), "○ ? ?\n? ? ?\n? ? ?\n")
self.assertEqual(turn([["?", "?", "?"... |
c957660667c5e3b795fae8e93862d84aec85355f | dawnonme/Eureka | /main/leetcode/92.py | 945 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
dummy_node = ListNode(-1)
dummy_node.next = head
prev, cur = dummy_nod... |
4946dd2834be55dd53ffd06cae73f21f924b6c95 | farhadkpx/Python_Codes_Short | /strings.py | 392 | 4.21875 | 4 |
str = 'We are learning python'
for i in range(len(str)):
pass
#print (str[i],)
for char in str:
print (char)
# any string is always a list
# strings are immutable in python
for word in str.split():
print (word)
#str='We|are|learning|python"
str ='-------------------this----------------------'
print (str)... |
f2e71e3474a4d2a54747d0f2ba5a38e12f61eb78 | SWHarrison/spaceman | /spaceman.py | 11,592 | 4.125 | 4 | '''
Read word from other file, is now the secret word
Display empty spaces for each letter of word and a blank list of letters guesssed
Prompt user for letter, check to make sure only lower case letters are inputted
First check length is only 1 character then try to find it in ascii_lowercase
If input is valid check ... |
9d235ef0a253f696a6a58bea4be1a3f67ee2e9c4 | eliflores/thirty-days-challenge | /challenges/python-solutions/day-9.py | 282 | 3.90625 | 4 | # Euclid's Algorithm for Computing the GCD of two integers
def find_gcd(a, b):
if a == b or b == 0:
return a
return find_gcd(b, a % b)
numbers_from_input = input().strip().split(' ')
gcd = find_gcd(int(numbers_from_input[0]), int(numbers_from_input[1]))
print(gcd) |
787b49688e555a6fd81149fc9546c26d81686d01 | Rishi05051997/Python-Notes | /13-NUMPY/4.py | 444 | 4.09375 | 4 | ### ******Array Matrix********
import numpy as np
arr1 = np.array([
[1,2,3,4],
[5,6,7,8]
])
print("******")
print(arr1.dtype)
##### int32
print("******")
print(arr1.ndim)
#### 2
print("******")
print(arr1.shape)
#### (2, 4) 2 --->> Two rows , 4 --->>> 4 columns
print("******")
print(arr1.size)
#### 8
#### f... |
d94e0c9f0ff5a0c9b130d4ecfbc4a1663d31aca9 | Tometoyou1983/Python | /Python web programs/terminalemailsend.py | 2,066 | 3.6875 | 4 | # Python 3
# this program triggers a selenium script to send out an email thru terminal
#this can be alterted to enter info thru command line as well as copy/paste data using pyperclip
#this asks for email id of recipient, subject and body
# this program also needs to be updated with ur user id and pass for logging int... |
a05ba6316baaeab2c5ccdef1c87b8a1e6e67810d | sourabh-kumar-ML/LeetCode | /BinaryTree/MinimumDepth.py | 1,105 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
"""if not root:
... |
19c00934dba93aa109b615463f878a6d14501625 | lledezma/Algorithms | /Greedy_Algorithms/knapsack.py | 199 | 3.828125 | 4 | def change(cents):
coins = [25,10,5,1]
num_of_coins = 0
for coin in coins:
num_of_coins+= math.floor(cents/coin)
cents = cents%coin
if cents == 0:
break
print(num_of_coins)
# change(33) |
3e023011d8df77df9a788f4b2d4e8a8f2588f1dc | espiercy/py_junkyard | /python_udemy_course/53 inheritance.py | 425 | 4 | 4 | class Father:
money=100
def __init__(self):
print("Inside father constructor")
def show(self):
print("show")
class Mother:
def display(self):
print("Mother")
#specifies parent class
class Steve(Father,Mother):
def __init__(self):
print("Child constructor")
d... |
9ef883ccb5c0cae149c3a9a849f09bc945b36e19 | gavinz0228/AlgoPractice | /LeetCode/82 - Remove Duplicates from Sorted List II/deleteDuplicates.py | 1,811 | 3.96875 | 4 | """
82. Remove Duplicates from Sorted List II
Medium
4279
144
Add to List
Share
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1... |
0e1212a9f9f29798531d89b956485160331bf2ae | smiti5712/Trip-IT-Project | /Weather.py | 3,971 | 3.578125 | 4 | # import dependencies
import requests
import pandas as pd
from datetime import datetime
from config import apiKey, openWeatherAPI
import json
# import pprint
# dictionary of cities and locations
citiesLocations={
"New York City":{"Lat":40.7128, "Lon":-74.0060, "Station":"72502"},
"Washington DC":{"Lat":38.90... |
67986531e4a33a605069727e4f3ff53d3655b3c0 | anton2mihail/Fun-Programs | /UniqueSets.py | 328 | 3.53125 | 4 | class Unique():
def __init__(self, intList):
self._ints = intList
def returnUniqueInts(self):
setsOfLists = []
while True:
temp = []
for i in self._ints:
if i not in setsOfLists:
return setsOfLists
print(Unique([4,5,6]).returnUnique... |
55ce3ebd3fbfe4ef94f62e58b94e1d2edb786668 | markafunke/LGBTQ_NYT | /preprocessing.py | 2,904 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Set of NLP logic that cleans, lemmatizes, and tokenizes dataframe of text
@author: markfunke
"""
import pandas as pd
import numpy as np
import re
import string
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag
fr... |
d1b2bc87953dd4dd3cab6aa3c33cd8848420b60a | vkfukace/Grafos | /TrabalhoImplementação/Trabalho2_RA115672.py | 13,307 | 3.703125 | 4 | # Algoritmos em Grafos
# Trabalho 1
# Geração de árvores aleatórias usando grafos
#
# Aluno: Vinícius Kenzo Fukace
# RA: 115672
from typing import List, Dict, Tuple
from collections import deque
import random
import time
# Definição de Dados
#
# Por convenção, as chaves ligadas aos vértices serão do tipo int.
# Para... |
2f538ce08c5f3dc7248d93e29ca9b20cde1824dc | Marcoakira/Desafios_Python_do_Curso_Guanabara | /Mundo3/Desafio080.py | 445 | 4.03125 | 4 | # desafio080 esse programa recebe 5 numeros. retorna em ordem crescente sem usar a função sort().
alista = []
alista.append(int(input(f'Insira o 1º Numero ')))
for c in range(1,5):
nnovo = int(input(f'Insira o {c+1}º Numero '))
for d in range(0,5):
if nnovo <= alista[d]:
alista.insert(d,n... |
4baab3408deca5463e3afffbc38f51f71e06e9dd | hlfshell/Robot-Framework-RBE3002 | /Framework_Client_Python/SensorClass.py | 886 | 3.515625 | 4 | '''
SensorClass.py
Author: Keith Chester
The parent class for all sensors, sensor class
most importantly creates a standard for grabbing N
bytes of data from the robot based on the sensor it
is updating.
'''
import serial
from Commands import *
class Sensor:
data = None
historyToRemember = 10
bytesPerData = 1... |
b8fcbb413b23de11cfd40a49905c2e98efe00f8c | mandiesitian/python3.6 | /GUI/Canvas.py | 762 | 3.703125 | 4 | #_*_ coding:utf-8 _*_;
# Canvas 画布容器 其中可以放置图形 文字 组件或者帧
#语法:canvas=Canvas(master,option='valur,...)
#master 父窗口 option 画布属性
from tkinter import *;
root=Tk();
root.resizable(0,0);
root.geometry('500x300');
canvas=Canvas(root,width=200,height=100); #设置画布大小
canvas.pack(); #设置布局管理器
#绘制 左上方坐标为 10 10 右下方坐标为 50 50的正方... |
e14ba2591b8229d06af824360812412b6af9b6c7 | Codeology/LessonPlans | /Fall2017/Week1/firstUniqueCharacterInString.py | 1,233 | 3.765625 | 4 | # Given a string, find the first non-repeating character in it and return
# it's index. If it doesn't exist, return -1.
#
# Examples:
#
# s = "leetcode"
# return 0
#
# s = "loveleetcode"
# return 2
#
# Note: you may assume the string contains only lowercase letters
def firstUniqChar(s):
# create the frequency dict... |
3c18bb3c04ce573d2061cbe58b9d5b7978bd1f26 | mikebochenek/learning | /python3/aoc2019/day4.py | 2,178 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: mike - Created on Fri Jun 23 22:22:40 2023
at the start somehow too lazy or can't think of code, but got it eventually..
"""
def mc(i): #meets criteria?
digits = 6
# Two adjacent digits are the same (like 22 in 122345).
adjacent = False
... |
88a9fc130bc4168815db050b5545ea901034c473 | sharmila3/python-for-beginners | /Intermediate/reduce.py | 335 | 3.71875 | 4 | import functools
def mult(x, y):
print(f'X = {x} and Y = {y}')
return x*y
ml = [2, 3, 4]
fact = functools.reduce(mult, ml)
print('Factorial of 3: ', fact)
# def do_sum(x1, x2):
# print(f'X1 = {x1} and X = {x2}')
# return x1 + x2
# s = functools.reduce(do_sum, [1, 2, 4, 4])
# print(f'The... |
8c47c91615e369967c032ff24b5b815803f4db36 | shellytang/intro-cs-python | /01_week5_OOP/integer-set.py | 964 | 3.84375 | 4 | # example class
class intSet(object):
def __init__(self):
self.vals = []
def insert(self, e):
if not e in self.vals:
self.vals.append(e)
def member(self, e):
return e in self.vals
def remove(self, e):
try:
self.vals.remove(e)
except:
... |
536b2e408390ecb3c0366815e1df684cb858c879 | dsawali/Co-Up | /coup/common/utilities.py | 804 | 3.578125 | 4 | import math
def haversine(lat1,\
lng1,\
lat2,\
lng2):
"""
Computes the distance in kilometers
between two coordinates specified
in latitude/longitude.
Formula:
a = sin²(Δlat/2) + cos lat1 ⋅ cos lat2 ⋅ sin²(Δlng/2)
c = 2 ⋅ atan2( √a, √(1−a)... |
39a6466f74fa75d02235b677da6d2d964a9627b2 | ALREstevam/Cats-On-The-Run | /Project4/entrega_final/Novo_gato/cats/catshelper/DistanceCalculator.py | 2,928 | 3.703125 | 4 | from enum import Enum
from math import sqrt
D = 1 #Minimum cost to move in straight line
D2 = sqrt(2) #Minimum cost to move diagonally
def dx(x0, x1):
return abs(x0 - x1)
def dy(y0, y1):
return abs(y0 - y1)
#DIAGONAL DISTANCE - FOR 8 DIRECTION MOVEMENT
def diagonal(x0, y0, x1, y1):
_dx = dx(x0, x1)
... |
c28c6feef8496f318fa52f16328725edf4de2115 | takobell1988/WorldOfGames | /Live.py | 1,947 | 3.78125 | 4 | import time
from MemoryGame import play_memory_game
from GuessGame import play_guess_game
from CurrencyRouletteGame import *
from Score import add_score
def welcome(input_name):
print("\n" + "Hello " + input_name + " and welcome to the World Of Games (WoG)." +
"\n" + "Here you can find many cool games t... |
032cdb2e9fdd54ad5cfd8ee2125473592ffdf524 | Qhupe/Python-ornekleri | /Dosya İşlemleri/SınıfHarfNotu Hesabı.py | 1,516 | 3.703125 | 4 |
def nothesapla(satır):
satır=satır[:-1]
liste = satır.split(",")
isim=liste[0]
not1=int(liste[1])
not2 =int(liste[2])
not3 =int(liste[3])
notort=not1*(3/10)+not2*(3/10)+not3*(4/10)
if(notort<50):
print(" {} \n 1.Vize= {} \n 2.Vize= {} \n Final= {} \n Ortalama= {} \n ... |
8ef49bdfaf4ce4428fe24ea64be5580870cc51d9 | Joyce7Lima/Hello-World | /atividades-exemplo/med-notas-alunos.py | 535 | 3.65625 | 4 | total = int(input('Qual o total de alunos? '))
alunos = {}
for i in range(1, total + 1):
nome = input(f'Nome do aluno {i}: ')
notas = []
for j in range(1, 5):
nota = float(input(f'Nota {j} do aluno {i}: '))
notas.append(nota)
alunos[nome] = notas
print('')
print('Notas dos Alunos')
... |
46975970e83b78dc0849dfd4165897860e2e77a0 | DhruvGodambe/sorting_algo | /selection_sort.py | 255 | 3.640625 | 4 | arr = [7,8,5,4,9,2]
for i in range(len(arr)):
minIndex = i
for j in range(i, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
arr[i], arr[minIndex] = arr[minIndex], arr[i]
print(arr)
# output :
# [2, 4, 5, 7, 8, 9] |
5fa6a7d1f8a0aa1770ef204c4653f98c6a7e5a97 | luizf-crypto/Exercicios | /Estrutura_sequencial/Exercicio_11.py | 295 | 4.15625 | 4 | x = int(input('Digite um numero inteiro: '))
y = int(input('Digite outro numero inteiro: '))
z = float(input('Digite um numero real: '))
a = (x * 2) * (y / 2)
b = (x * 3) + z
c = z ** 3
print(f'\nA resposta da A é {a}.')
print(f'\nA resposta da B é {b}.')
print(f'\nA resposta da C é {c}.') |
826817501ceef4d94ab54491ab8da096ac49069f | snc29654/sqlite_edict | /tkinter_test.py | 2,147 | 3.734375 | 4 | ###### 2021.05.25 文字なしで空白を出力 ######################################################
import tkinter
import json
import sqlite3
from contextlib import closing
dbname = '../ejdict.sqlite3'
root = tkinter.Tk()
def input_key(event):
btn_click(event.keysym)
def getTextInput():
result=textExample.get(... |
c4166a2cda7c28567d01f7ea489abaec7e4ffe39 | Keviwevii/Python-Crash-Course | /Dictionaries/people.py | 454 | 3.671875 | 4 | #Dictionaries in a list
me = {
'first_name' : 'Kevin',
'last_name' : 'Floyd',
'age' : 100,
'city' : 'Neverland',
}
candy = {
'first_name' : 'Candy',
'last_name' : 'Jones',
'age' : 19,
'city' : 'IDK',
}
johnny = {
'first_name' : 'Johnny',
'last_name' : 'Appleseed',
'age' : ... |
25a43bc05d6bae792154f2471224289085410e9d | fanwucoder/leecode | /src/desgin/Codec.py | 2,904 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from queue import Queue
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
... |
11f5eb2c3a65230cad8420ce4c870a3ab35c6142 | adonai-luque/CodewarsPython | /6 kyu/arrayDiff.py | 204 | 3.515625 | 4 | def array_diff(a, b):
#Searching for elements of b also in a
for i in b:
#Repeating removal of repeated elements
for k in range(0, a.count(i)):
a.remove(i)
return a |
03bd7ce2c7fe821393c977118014efaf4d682b2e | CQU-yxy/IntelligentSystem | /Vehicle/VehicleData_delete.py | 1,432 | 3.5625 | 4 | # 车流量数据的删除
# 1.全部删除
# 2.时间段删除
# 删除全部车流量数据 请谨慎操作!!
import sys
sys.path.append('..')
import config
def vehicleData_delete_all():
temp=input('删除全部车流量数据,输入 yes 确认')
if(temp!='yes'):
return
cursor=config.connect.cursor()
sql='''delete from %s
'''%(config.VehicleData.tablename
... |
eb76d4ec38d10ecd1129f4a9a0e5a294ff2de91a | gussvas/Linux-Shell | /round_robin_graph.py | 3,920 | 3.8125 | 4 |
#
# round_robin_graph.py
#
# This program written in Python uses the round robin
# process scheduling algorithm and displays the sequence
# It also displays a graph that compares the average turn
# around time in a quantum interval (between quantum_min and
# quantum_max)
#
# Link with the graph representing ... |
1bbd1ff8e8d35f6b9ac734e759bdb8f7ae768627 | aika810015/guess-num | /guess-num.py | 530 | 3.75 | 4 | import random
start = int(input("ランダム数字を決めてください:"))
end = int(input("ランダム範囲を決めてください:"))
r = random.randint(start, end)
count = 0
while True:
count += 1
num = int(input("数字を考えてください:"))
if num == r:
print("当たり!!")
print("今回は", count, "回目です!")
break
elif num > r:
print("正解より多いですね!")
elif num < r:
print("正解よ... |
9ce16711af723ad3d286455817ee454c0d7551d9 | mlbilodeau/Small-Projects | /Python/QuickSort.py | 1,481 | 3.703125 | 4 | from random import seed
from random import randint
class QuickSort:
def __init__(self, arr):
self.arr = arr
self.left = 0
self.right = len(arr) - 1
self.quick_sort(self.left, self.right)
def partition(self, pivot):
left_ptr = self.left
right_ptr = self.right
... |
aac3505179e6ef1a159a453445a08243ccf10a17 | imulan/procon | /aoj/vol0/0029.py | 303 | 3.546875 | 4 | s=input()
a=s.split(" ")
mp={}
freq=""
longest=""
mx=0
for v in a:
#出現回数カウント
if v in mp:
mp[v]+=1
else:
mp[v]=1
if mx<mp[v]:
freq=v
mx=mp[v]
#最長文字列更新
if len(longest)<len(v):
longest=v
print(freq,longest)
|
ff2ffaff25a2d6d4c213ce04bb022342085b67da | thelouieshi/black_jack_card_game | /main.py | 4,293 | 4.46875 | 4 | # Play Black Jack in the console:. You can play the game here: https://replit.com/@LouieShi/BlackJack-Card#main.py
# Object-oriented programming classes are under the same repository.
# The computer is the dealer and user is the player.
# Ace is 11 when hand is <= 21, Ace is 1 when hand is larger than 21.
# importe... |
19adea2287efeaae9b075813552d14b8e7dcb2a0 | hbwdscj/py_data_alg | /Reverse_ll.py | 8,422 | 3.78125 | 4 | # 1.反转链表
class Node(object):
__slots__ = ('value', 'prev', 'next')
def __init__(self, value=None, prev=None, next=None):
self.value, self.next, self.prev = value, next, prev
class CircualDoubleLinkedlist(object):
def __init__(self, maxsize=None,):
self.maxsize = maxsize
node = Nod... |
e86dfaf00e35e1fa719d879ca0daf87dec5693e4 | Travmatth/LeetCode | /Easy/happy_number.py | 1,313 | 3.828125 | 4 | """
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the
sum of the squares of its digits, and repeat the process until
the number equals 1 (where it will stay), or it loops endlessly
in a cycle... |
278e737e3674b01a63f6bcaa7479128f2dae7934 | mftb/finder | /python/finder.py | 1,322 | 3.546875 | 4 | class Finder():
# returns a tuple with the input string and its char frequency dict
@staticmethod
def _string2dict(string):
if not isinstance(string, str):
raise TypeError
adict = {}
for char in string:
if char not in adict:
adict[char] = 1
... |
7e9dfe18e41bbf6c1367d4e1b1532218a430dc96 | archenRen/learnpy | /leetcode/dynamic_programming/code-312.py | 1,983 | 3.671875 | 4 | #
# 312. Burst Balloons
# Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the bu... |
2ede4a7a5e606d28847565e0138eaa9e67345ebe | bredebjorhovd/breedznet | /Documents/breedznet/layers.py | 2,593 | 4.125 | 4 | """
The neural net is made up of layers.
Each layer needs to pass its input forward
and propagate gradients backwards, for example
a neural net might look like
inputs -> Linear -> Tahn -> Linear -> output
"""
from typing import Dict, Callable
import numpy as np
from breedznet.tensor import Tensor
class Layer:
def... |
9f0e9738076273a28606a53bc8338c0a311ff98f | chinmaydas96/Coursera-Machine-Learning-Python | /python_basic/floor_conversion.py | 103 | 3.53125 | 4 | # converting Europe floors to US floors
euf=input('which floor?')
usf=int(euf)+1
print('US floor',usf)
|
6194c842887ef225629ecce1c4ca792e4279509f | ikonbethel/Python-code | /python for beginners/vowelcounter.py | 309 | 3.890625 | 4 | #vowel counter
#by ikon beth
vowels = "aeiou"
goo = vowels.split()
count = 0
print ("This program counts the vowels in your sentence(s)")
letter = input("Type in your sentence:")
if vowels in letter.lower():
count += 1
print("There are ", count, "vowels in your sentence")
input("Exit")
|
dd9da6acd2b18fb5e79822e9624641cc138bbba9 | Warmriver/part_time_leetcode_record | /find_first_and_last_position.py | 1,063 | 3.609375 | 4 | # 在一个数组中找到第一次出现目标数字,和最后一次出现目标数字的未知,找不到目标数字则结果为-1,把这两个数字组成一个数组返回
class Solution:
def searchRange(self, nums, target):
def binarySearch(x, y):
if x > y:
return -1
mid = (x&y) + ((x^y)>>1)
if nums[mid] == target:
return mid
elif nu... |
9ac0c78e7df280329fc939a03708f823d5d532c0 | kevin-zhq/PythonPractice | /map reduce函数.py | 900 | 3.765625 | 4 | def add(x,y,f):
return f(x)+f(y)
print(add(-5,6,abs)) #将f变量指向abs函数,通过调用,实现高阶函数
r = map(abs,[-1,-2,-3,-4]) #map函数,第一个参数是函数,第二个参数是可迭代对象;返回一个可迭代对象
print(r)
print(list(r))
from functools import reduce #reduce函数,第一个参数是函数,第二个参数是可迭代对象;返回的值作为可迭代对象的第一个值,直到最后
def fu(x,y):
return x*10+y
ad = reduce(fu,[-1,-3... |
ca8e3237950b142e9c8c125d2b210fd5fdde2685 | Sebo-the-tramp/Sebo-the-tramp.github.io | /content/page/photos/canada/rename.py | 328 | 3.5625 | 4 | #rename every photo with integer from 1 to n
import os
import sys
def rename(path):
i = 1
for filename in os.listdir(path):
if filename.endswith(".JPG"):
os.rename(os.path.join(path, filename), os.path.join(path, str(i) + ".JPG"))
i += 1
if __name__ == "__main__":
rena... |
5a31cda3e8b9a2b67da8cdf2c2657fef9091c665 | Icecarry/learn | /day04/用户注册登陆系统v2.0.py | 1,440 | 3.671875 | 4 | '''
用户注册登录系统V2.0
设计一个程序
要求用户可以实现登录、注册、注销登录等功能
用户的用户名(长度6-20)、密码(长度8-20)、昵称、年龄信息保存到字典中
将每个已注册用户的保存到列表中,即将上一步的字典保存到列表中
维护用户的登录状态,每次只能有一个用户处于登录状态,直到选择注销登录
如果不选择退出系统,该程序应当一直运行
'''
# 存放信息的列表
sys_list = []
# 循环输入员工信息
while True:
print("================")
print("1,注册")
print("2,登陆")
print("3,注销登陆")
pri... |
4f28925756181a908841100b8bd44a687b5180d4 | ignasa007/Algorithms | /DFS/Size of SCCs without recursion/DFS - Size of SCCs without recursion.py | 2,844 | 3.578125 | 4 | # Depth First Search in an Directed Graph to find the sizes of SCCs in large graph.
# The idea is to first compute a finishing order in the dfs of a graph and then use the reverse of this order to start dfs
# on the inverted graph.. In the inverted graph, where all the edges have been reversed, the vertices appearing... |
fc419e083d5b22eb47f6b8aa245e12b4a7487918 | mo-dt/PythonDataScienceCookbook | /ch 2/Recipe_3a.py | 986 | 3.625 | 4 | from sklearn.datasets import load_iris,load_boston,make_classification,\
make_circles, make_moons
# Iris dataset
data = load_iris()
x = data['data']
y = data['target']
y_labels = data['target_names']
x_labels = data['feature_names']
print
print x.shape
print y.shape
print x_labe... |
b714da7b9acfe90347b87becb7d3174e48248bd2 | vishaalgc/codes | /Array/kadane.py | 421 | 3.6875 | 4 | def maxSubArray( nums):
"""
:type nums: List[int]
:rtype: int
"""
max_ending_here = 0
max_so_far = 0
for i in nums:
max_ending_here += i
if max_ending_here < 0:
max_ending_here = 0
max_so_far = max(max_so_far, max_ending_here)
if max_so_far ==... |
c2ba773387358c33b89221b2f62a03cddc81a8ac | ldunekac/Pandemic | /src/Level/Deck/deck.py | 501 | 3.515625 | 4 | import random
class Deck:
""""Sets up a deck"""
def __init__(self, deck):
self.deck = list(deck)
self.discardPile = []
def shuffle(self):
""" Shuffles the deck"""
random.shuffle(self.deck)
def draw(self):
if len(self.deck) == 0:
ret... |
a1b5741118b797f861c522b058c6fac7f3d19dd7 | candyer/leetcode | /2020 December LeetCoding Challenge/08_numPairsDivisibleBy60.py | 1,453 | 3.671875 | 4 | # https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/570/week-2-december-8th-december-14th/3559/
# Pairs of Songs With Total Durations Divisible by 60
# You are given a list of songs where the ith song has a duration of time[i] seconds.
# Return the number of pairs of songs for which their tot... |
38f6abbd1bf76cca37dc8532c7ed71b5a4d35b59 | captain-nemo1/BinaryCalculator | /Calculator.py | 5,855 | 3.546875 | 4 | #Simple Binary calculator
import random
import pygame
import sys
import time
#A,B,C,D,x for coordinates
A=100
B=20
C=25
D=30
x=50
E=0
s="" #string to store expression
i=0#check value to clear string
pygame.init()
screen=pygame.display.set_mode((300,300))
black=(0,0,0)
pygame.display.set_caption("Binary Calculator")
sc... |
cddd10d1a259d40c284eaa6c07a3dfe23c6c6e4a | sockduct/CS101 | /daysbetdates.py | 2,037 | 3.953125 | 4 | def IsLeapYear(year):
if (year % 4) != 0:
return 0
else:
if (year % 100) != 0:
return 1
else:
if (year % 400) != 0:
return 0
else:
return 1
def DaysBeforeDate(year,month,day):
daysOfMonths = [31,28,31,30,31,30,31,31... |
1f7a73186b83ef9f70e6f8cbd5026592f82cbe81 | romulorm/cev-python | /ex.062.superProgressaoAritmetica3.py | 503 | 3.890625 | 4 | n = int(input("Digite o primeiro termo da P.A.: "))
r = int(input("Digite a razão: "))
c = 1
print("{} ->".format(n), end=' ')
while c < 10:
n += r
c += 1
print("{} ->".format(n), end=' ')
print("PAUSA")
opcao = -1
while opcao != 0:
opcao = int(input("Quantos termos vc quer mostrar a mais? "))
d = c... |
89af38f3d85b8c5edd4c438b642d35d23c6a4e50 | zhangli709/python_note | /work/flower.py | 196 | 3.671875 | 4 | import math
for num in range(100, 1000):
gw = num % 10
sw = num // 10 % 10
bw = num // 100
if num == pow(gw, 3) + pow(sw, 3) + pow(bw, 3):
print('%d是水仙花数!' % num) |
678f02aaf15a15b2b194eb3d93ef70956683a835 | alaanlimaa/openAccountBank | /conta.py | 1,546 | 3.71875 | 4 | class ContaCorrente:
def __init__(self, numero, titular, banco_numero, banco_nome, saldo, limite, cpf):
self._numero = numero
self.__titular__ = titular
self.saldo = saldo
self.limite = limite
self.banco_nome = banco_nome
self.banco_numero = banco_numero
self... |
e1c3b08c7041fe6fda8d1d49e47865b85ca0f868 | nekacurry/Blackjack-OOP | /devil.py | 510 | 3.640625 | 4 | from player import Player
class Devil(Player):
def __init__(self, name='Satan'):
'''inherits attributes from Player class'''
super().__init__()
self.cards = []
self.value = 0
self._name = name
#------------------------Display Method--------------------------->
def display(self):
print("**... |
a5f0d31329985717574a6da480cba73e15906e19 | ilkelity/PrOCTOR_analysis | /code/drugs.py | 807 | 3.5625 | 4 | import csv
f = open('/Users/jaypearce9/Desktop/Classes/Math_410/drugs.txt')
fda = []
for line in f:
elements = line.split()
if len(elements) == 3:
fda.append(elements[0].lower())
else:
fda.append(str(elements[0] + ' ' + elements[1]).lower())
#print fda
print len(fda)
mydrugs = []
with open('/Users/jaype... |
cff2dbc32bfcc0c42254414ee21f2fcd1667e6f7 | fsgeek/Araneae | /src/Wilbur/Relationship Directory/RelationshipDirectory.py | 2,075 | 4.21875 | 4 | ''' Creates a 'copy' of the Directory specified by the variable 'path' by creating symlinks to files
Files are contained in a folder with the same name as file
This Directory is then acted upon by other programs in this forder to create links to similar files
'''
import os
import operator
import shutil
import magic
#... |
d1dd5ec89afcf482503680ed4db4f2a17d15550b | ramyasutraye/Python-Programming-11 | /Beginner Level/no of digits in integer.py | 119 | 3.96875 | 4 | N=int(input("Enter number:"))
n=0
while(N>0):
n=n+1
N=N//10
print("The number of digits in the number are:",n)
|
c5e0c6331cc080c21f71cb82eb7f58207e104060 | rjchow/adventofcode | /3/calculate_grid_size.py | 584 | 3.546875 | 4 | def calculate_grid_size(program):
length = 0
width = 0
directions = breakdown_directions(program)
left = sum(directions["L"])
right = sum(directions["R"])
up = sum(directions["U"])
down = sum(directions["D"])
return (length, width)
def breakdown_directions(program):
direc... |
23dde8c0132c9364847afc93ceae58a2259c0cbc | kdeholton/AdventOfCode2020 | /day11/day11.py | 420 | 3.578125 | 4 | #!/usr/bin/python3
from waiting_room import *
f = open("input", 'r')
lines = [ line.strip() for line in f ]
width = len(lines[0])
height = len(lines)
waiting_room = WaitingRoom(width, height)
for y, line in enumerate(lines):
for x, seat in enumerate(line):
if seat == "L":
waiting_room.initSeat(x, y)
w... |
ead504c0eae23dda768cbf1ef0168180d1d71413 | CKowalczuk/Python---Ejercicios-de-Practica-info2021 | /C_Rep_05.py | 306 | 3.96875 | 4 | """
5) Solicitar el ingreso de números al usuario y emitir un mensaje para determinar si es par o impar.
El ciclo debe finalizar cuando el usuario ingresa 0.
"""
num = None
while num != 0:
num = int(input("Ingrese un número : "))
if num % 2 != 0:
print("Impar")
else:
print("Par")
|
1f08d37e67fefdf9acafbcbaa5270681dc0795f9 | xin3897797/store | /day2_4.py | 538 | 3.828125 | 4 | # 判断能否形成三角形,什么三角形
import math
a, b, c = int(input()), int(input()), int(input())
if a+b > c > abs(a - b):
print("能形成三角形")
if a == b != c or b == c != a or a == c != b:
print("是等腰三角形")
elif a == b == c:
print("是等边三角形")
elif math.sqrt(a*a+b*b) == c or math.sqrt(c*c+b*b) == a or ma... |
942806c5fd19d8d817d5718db66b9916bb9f4c8e | ALLANKAKAI/HTML-Tutorials | /PYTHON/004Delodd.py | 284 | 3.78125 | 4 | def mylist(x):
evenlist = []
for item in x:
if item % 2 == 0:
evenlist.append(item)
return evenlist
x = [1, 3, 4, 5, 6, 6, 6, 7, 5, 8, 9, 9]
print(x)
print("evenlist:", mylist(x))
def kk(x):
return list(filter(lambda p:p%2==0,x))
print(kk(x))
|
9eb5e54726195f802c610630424ed85c4e2d692a | subramgo/tflow | /02 Regression/02_03_tflow.py | 2,553 | 3.625 | 4 | """
Simple Linear Regression with l2 regularization (RIDGE)
TensorBoard
Gopi Subramanian
16-May-2017
"""
import tensorflow as tf
import numpy as np
from sklearn.datasets import make_regression
np.random.seed(100)
### Make a regression dataset with coeffiecients
X, y, coeff = make_regression(n_samples = 1000, n... |
65caf8b9fa9d08bbab23903c53d3362599a407dc | bazhenovstepan/infa_2020_bazhenov | /Lab_about_balls_modified.py | 5,966 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import pygame
from pygame.draw import *
from random import randint
import os.path
import math
import time
from tabulate import tabulate
pygame.init()
#name=input()
FPS = 3
screen = pygame.display.set_mode((1200, 600))
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255... |
f565df9bd112d6d7660bbac6e7247156245b1ea0 | qmnguyenw/python_py4e | /geeksforgeeks/python/medium/18_19.py | 2,910 | 4.15625 | 4 | Python | Display images with PyGame
**Pygame** is a cross-platform set of Python modules designed for writing
video games. It includes computer graphics and sound libraries designed to be
used with the Python programming language. Now, it’s up to the imagination or
necessity of developer, what type of game h... |
4cc3b46688097d2a7882574312c742a641004157 | Emiyayong/pythonL | /src/test.py | 283 | 3.703125 | 4 | def fib(num):
result=[0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
print(fib(10));
storage={}
storage['first']=[]
storage['second']=[]
storage['third']=[]
my_sister='Anne Lie Heland'
storage['first'].setdefault('Ane',[]).append(my_sister) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.