blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1c99e8c0b0d564bc126c4250cde363fcd5230c82 | sharkseba/taller-progra | /Ejercicios Control Flujo-condicionales/ejercicio23-parte1.py | 4,881 | 3.6875 | 4 | # Salida --> El equipo que pasa a la siguiente ronda e indicar motivo,
# 1) paso por mayor puntaje
# 2) paso por mayor cantidad de goles realizados
# 3) pasó por mayor cantidad de goles de visita
# 4) pasó por sorteo
# Grupo AAA
# Equipo A
# Equipo B
# Equipo C
# Partido 1: Equipo A vs Equipo B
# goles_a_local y gol... |
55dc16350267b7fe1302d6cdb24eb433e53ec882 | MH10000/Python_Labs | /python_fundamentals-master/13_modules-and-automation/13_04_get_outta_here.py | 566 | 4.21875 | 4 | # Use the built-in `sys` module to explicitly quit your script.
# Include this functionality into a loop where you're asking the user
# for input in an infinite `while` loop.
# If the user enters the word "quit", you can exit the program
# using a functionality provided by this module.
import sys
password = "greentre... |
ecdc61c4c3445422937412512d5131346eb8b198 | FlareJia/-Python | /c2.py | 1,525 | 3.859375 | 4 | #-*- coding: utf-8 -*-
#迭代
#dic也可迭代
d={'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
#因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。
#默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同时迭代key和value,可以用for k, v in d.items()。
#那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
from collections i... |
d2885acc07206c9dd96f729e9c9a94ff8e45683e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2954/60623/308445.py | 137 | 3.65625 | 4 | a=int(input())
l=[]
for i in range(a):
tL=input()
l.append(tL)
if l==['abcdec', 'cdefead']:
print('noway')
else:
print(l) |
20413e2cbaa1a56efce550f9b5f479300e037e28 | stungkit/Leetcode-Data-Structures-Algorithms | /05 Tree/104. Maximum Depth of Binary Tree.py | 2,253 | 4.0625 | 4 | # Given a binary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Note: A leaf is a node with no children.
# Example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 ... |
fc500a19b989c27a8ae01515f9eadc11fda60054 | Pierina0410/t10_palacios.salazar | /palacios/app1.py | 576 | 4 | 4 | import libreria
def agregar_nota():
input("Agregar nota1: ")
print("Se ingreso nota2")
def agregar_nota2():
input("Agregar nota2: ")
print("Se ingreso nota2")
opc=0
max=3
while(opc!=max):
print("######### MENU ##########")
print("# 1. agregar nota #")
print("# 2. nota2 #... |
b1462c479b92001206d9fe1d51473ab3e2cd5117 | lsteiner9/python-chapters-7-to-9 | /chapter8/windchill.py | 1,006 | 3.78125 | 4 | # windchill.py
def chill(temp, speed):
return 35.74 + (0.6215 * temp) - (35.75 * (speed ** 0.16)) + (
0.4275 * temp * (speed ** 0.16))
def main():
print("This program prints out a table of windchill values from 0-50 mph "
"and -20 to +60 degrees Fahrenheit.\n")
print(" % 3.2f % 3.... |
33e0b8a739c1fd0990c560477584d41cabd56591 | Sranciato/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 270 | 3.75 | 4 | #!/usr/bin/python3
"""Returns true if obj is an instance of a class"""
def inherits_from(obj, a_class):
"""Returns true if obj is an instance of a class"""
if isinstance(obj, a_class) is True and type(obj) is not a_class:
return True
return False
|
8822e3fe49324c787d950c3a4c4cb9d3c1e99063 | ikim1991/machine-learning-models | /Python/Linear Regression/univariate.py | 1,096 | 4.25 | 4 | # Simple Linear Regression Model
# Import Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Import Dataset
data = pd.read_csv('Salary_Data.csv')
X = data.iloc[:,:-1].values
y = data.iloc[:,-1].values
# Train/Test set split
from sklearn.model_selection import train_test_split
X_train,... |
2aa50f8d6a0844f68919cf18862c34a45390be28 | lxiaokai/team-learning-python | /取个队名真难-C/day04/logic.py | 815 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
if、while逻辑判断的用法
author: gxcuizy
date: 2018-10-18
"""
# 程序主入口
if __name__ == '__main__':
# 简单if
name = 'big_brother'
if name == 'da_biao_guo':
print('Please take me fly!')
# if……else 的用法
if name == 'da_biao_guo':
print('Please take ... |
66ec7e79c6c6bfc5b684644636aec263d6f11271 | gjersing/interactiveSortVisualizer | /mergeSort.py | 2,439 | 4.125 | 4 | #merge sort implementation for interactiveSorting
import time
def start_mergeSort(data, drawData, speed, size):
merge_sort(data, 0, len(data)-1, drawData, speed, size)
def merge_sort(data, left, right, drawData, speed, size):
if left < right: #Stops when the left index meets the right index (only 1 ite... |
0099056db862c0f341bb1097fa5a0dd38c59d740 | Mookiefer/Calculator | /functions.py | 5,082 | 3.5625 | 4 | from decimal import Decimal, getcontext
numbers = {
"-ZERO-": "0", "0": "0",
"-ONE-": "1", "1": "1",
"-TWO-": "2", "2": "2",
"-THREE-": "3", "3": "3",
"-FOUR-": "4", "4": "4",
"-FIVE-": "5", "5": "5",
"-SIX-": "6", "6": "6",
"-SEVEN-": "7", "7": "7",
"-EIGHT-": "8", "8": "8",
"-... |
4b0fab15f656c4621673cecc1a024e8d39efe9e8 | LucasLeone/tp2-algoritmos | /cf/cf53.py | 382 | 3.90625 | 4 | '''
Se debe calcular e imprimir el producto de todas las X y de todas las Y
de sesenta y tres pares ordenados de números enteros.
'''
for i in range(0, 63):
print('---- Nuevo par ordenado ----')
x = int(input('Ingrese el primer numero entero: '))
y = int(input('Ingrese el segundo numero entero: ')... |
78b03cfa5f08b6843ff85b08cd8b54d7fa119c71 | htl1126/leetcode | /60.py | 727 | 3.578125 | 4 | # ref: https://discuss.leetcode.com/topic/37333/python-i-think-this-is-clean
# -code-with-some-of-my-explanation
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
num = map(str, range(1, n + 1))
... |
080a1a74fe69eca3cf5add4d0200e16d976d1dd7 | protea-ban/LeetCode | /066.Plus One/Plus One.py | 425 | 3.515625 | 4 | class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
# 整数列表转成整数
num = int(''.join([str(t) for t in digits]))
# 加一
num += 1
# 将整数转成列表
return [int(s) for s in str(num)]
if __name__ == '__main__':
... |
8bf37d71fddde157c3a8d959503a491608aec5e9 | juliadejane/CursoPython | /ex005.py | 110 | 4.0625 | 4 | n = int(input('Digite um numero: '))
print('O antecessor é {} e o sucessor é {}'.format((n - 1), (n + 1)))
|
9a052d5dd08938b5d9245865fca79368058fd707 | gabeno/redmond | /problems/sliding_window/4_longest_substring_with_k_distinct_characters.py | 1,841 | 4.28125 | 4 | """
Given a string, find the length of the longest substring in it with no more than
K distinct characters.
Examples:
Input: String="araaci", K=2
Output: 4
Explanation: The longest substring with no more than '2' distinct characters is "araa".
Input: String="araaci", K=1
Output: 2
Explanation:... |
f78f62039ae6f8b98c9964327e5a84d4dcfa2336 | LeonildoMuniz/Logica_de_programacao_Python | /Listas/Lista3_Ex49.py | 204 | 3.625 | 4 | a=1
b=1
result=0
num=int(input('Informe o numeros de termos para serie: '))
for i in range(0,num,1):
result+=a/b
print(f'{i+1} - S = {a}/{b}')
a+=1
b+=2
print(f'Soma total de serie: {result:.2f}')
|
0ad250dac56a35abaf0d14f67e297abb721a981e | Deep455/Python-programs-ITW1 | /python_assignment_2/py13.py | 707 | 4.03125 | 4 |
def binarysearch (arr, l, r, x):
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarysearch(arr, l, mid-1, x)
else:
return binarysearch(arr, mid + 1, r, x)
else:
return -1
n = in... |
c97ca0dbb6d1727593db2c72b4ff89f0cfd96260 | verhovsky/CCC | /contests/2014/juniorSolutions/j4.py | 465 | 3.5 | 4 | how_many_people = int(raw_input())
people = range(1, how_many_people+1) #you're a computer scientist, you should number your friends starting at 0
how_many_rounds = int(raw_input())
rounds = [int(raw_input()) for _ in range(how_many_rounds)]
for round in rounds:
new_people = list()
for i, person in enumerate(... |
62686658d1dfe624428387ce7696da48a81d7377 | swang2000/DSAPractice | /Leet_validParenthesis.py | 287 | 3.59375 | 4 | def minAddToMakeValid(S):
"""
:type S: str
:rtype: int
"""
stack = []
for c in S:
if not stack or c == '(':
stack.append(c)
elif c == ')' and stack[-1] == '(':
stack.pop()
return len(stack)
minAddToMakeValid("()))((") |
3d359283db8549698e8a54b721e354f09f637813 | venkatraj/python-practice | /crash-course/ch03/more_guests_6.py | 539 | 4.53125 | 5 | friends = ['Saravanan', 'Jeevamani', 'Manohar Raja', 'Ravishankar']
for friend in friends:
print(f'Hi {friend}, I would like to invite you to dinner')
print(f'I heard, {friends[-1]} could not make it to dinner!')
friends[-1] = 'Ramlal'
for friend in friends:
print(f'Hi {friend}, I would like to invite you to dinne... |
8869790c1be7e4b328d7063d38282c2e21d17288 | ArtisticPug/GeekBrains_Python | /GeekBrains_Python_Lesson_8/Homework_5.py | 512 | 3.828125 | 4 | class ComplexNum:
def __init__(self, n1, n2):
self.n1 = n1
self.n2 = n2
def __str__(self):
return str(complex(self.n1, self.n2))
def __add__(self, other):
result = complex(self.n1, self.n2) + complex(other.n1, other.n2)
return str(complex(result))
def __mul__(s... |
2b0bab3979926bcb4b6b9a54e9c86689d8edf207 | MohamedSabthar/Algorithms | /Rabin.py | 740 | 3.625 | 4 | def rabin(text,pattern):
textHash = patternHash = 0
prime = 37
dPrime = 13
for i in range(len(pattern)):
textHash = (textHash*prime + ord(text[i]))%dPrime
patternHash = (patternHash*prime + ord(pattern[i]))%dPrime
for i in range(len(text)-len(pattern)+1):
if textHash == pa... |
578ae498d163b983385dbd8cbccd9277091d3f1f | aarti98/RockPaperScissor | /rock_paper_scissor.py | 655 | 4.21875 | 4 | from random import choice
print("Welcome to the game. Player chooses first!")
#ASK INPUT FROM USER
player= input("Choose (r) for rock, (p) for paper and (s) for scissor \n")
print("You chose " + player + "\n")
#GENERATE COMPUTER'S CHOICE
computer= choice([1,2,3])
if computer == 1:
computer = 'r'
elif computer... |
1c3b5db0540617e4865d2c4e04dca5765892c29b | edwinsentinel/pythonbots | /webscraper.py | 546 | 3.71875 | 4 | # import libraries
import urllib
from bs4 import BeautifulSoup
#specify the url
quote_page='http://www.bloomberg.com/quote/SPX:IND'
#query the website and return the html to the variable 'page'
page= urllib.urlopen(quote_page)
#parse the html using beatifulsoup and store in variable 'soup'
soup=BeautifulSoup(pag... |
ab2b0945daace27741ea4f1b6ec28052f6ad7579 | chayes1987/PythonExercises | /sem2/question_one.py | 1,218 | 4.3125 | 4 | __author__ = 'Conor'
""" 1.
a. Write a Python program that generates 10 random numbers between 1 and 100 (inclusive) and calculates and
displays the average of the generated numbers.
(12 marks)
b. Write a function that takes 3 numbers as arguments and returns the value of the largest of the 3 n... |
86f630cad661a11fa816c62c4a4147835044dbb9 | Aasthaj01/DSA-questions | /array/two_sum.py | 868 | 3.75 | 4 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
def summ(nums, target):
listt = []
for i in range(len(nums)):
for j in range(len... |
a7ef1113eb1e4e768172fd9063b56b817acc0667 | LalityaSawant/Python | /DS and Algo in Python/Sort algorithms/merge_sort_complete.py | 814 | 3.953125 | 4 | def merge_sorted(arr1,arr2):
sorted_arr = []
i,j =0,0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
sorted_arr.append(arr1[i])
i += 1
else:
sorted_arr.append(arr2[j])
j += 1
#print(f'sorted arr {sorted_arr}')
while i ... |
01ff49f4c4378db3a1373bbcc1f4aea57386aa0d | melnikovay/U7 | /U7-2v2.py | 1,502 | 3.796875 | 4 | #Отсортируйте по возрастанию методом слияния одномерный вещественный
#массив, заданный случайными числами на промежутке [0; 50).
#Выведите на экран исходный и отсортированный массивы.
import random
MIN1 = 0
MAX1 = 50
SIZE = 10
MASS = [random.randint(MIN1, MAX1) for _ in range (SIZE)]
print(MASS)
def sort_mas... |
53c8a3a3671988d11bab73a9f6cc3564c458bb98 | JeremiahTee/python-games-sweigart | /pygameHelloWorld.py | 1,944 | 3.765625 | 4 | import pygame, sys
from pygame.locals import *
# Set up pygame.
pygame.init() # must do before anything, initializes pygame so it's read to use
# Set up the window
windowSurface = pygame.display.set_mode((500,400), 0, 32) #500 px wide and 400 px tall by using tuple
#set_mode() returns a pygame.Surface object
... |
1224c421cf6a2528e3e3d8054afebeda5e401a75 | mananmonga/Applied-Crypto | /Labs/lab2.py | 9,542 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
################################################################## LAB 2 ##################################################################
"""
List you collaborators here:
Jainam Shah
Your task is to fill in the body of the functions be... |
5eb3aa308d30cd26a380758b902d64dc17c6945f | nicolasalliaume/python-bootcamp | /Module_3/exercises/08-big-mess/exercise.py | 698 | 3.984375 | 4 | #############################################
#
# Please help me solve this big mess!!
# Following there's a list containing elements
# of different types.
#
# Print all the elements following this rules:
# - If it is a number or string, just print it
# - If it is a list, print each of the elements
# - If it es a tuple... |
6597f928f6d4524628b2c7bfe116212501df6e0b | adrianbartnik/ProjectEuler | /037.py | 1,420 | 3.5 | 4 | """
Project Euler Problem 37
========================
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage: 3797, 797, 97, and 7. Similarly we can work from
right to left: 3797, 379, 37, and 3.
Find the sum of ... |
400f898d2d23d1d785412275a9a0c25b9c04ec22 | luzi82/AIND-Sudoku | /nrook.py | 2,463 | 4.03125 | 4 | '''
By luzi82@gmail.com, 2017-01-25
N-Rooks problem:
That is something like "N-Queens problem"
In N-Rooks problem, we are required to put N Rook pieces to a NxN grid.
Each row and col should contain exactly one rook.
Examples:
4-rook problem
1 = True = possible location
0 = False = impossible location
Input: (level... |
12ada9468e9f216b2506af7c2eb6f3ac1dfbaae7 | MarFie93/devopsbc | /python.py/comments.py | 439 | 3.90625 | 4 | # This is a single line comment
# You can write comments like this
print("Hello world")
# comments here
print("Another print call")
"""
You are in a multline comment now :)
That means you can hit enter and separate your
comments
Many lines, make sure your code is clean.
"""
print("You can have comments... |
1d1baf0d1e3b7489c8d451e2b8f3ac0c01296c17 | weih1121/Sort | /radixSort.py | 475 | 3.5625 | 4 | import math
import random
def RadixSort(array, radix=10):
k = int(math.ceil(math.log(max(array), radix)))
bucket = [[] for i in range(radix)]
for i in range(k):
for j in array:
bucket[int(j / (radix ** i) % radix)].append(j)
del array[:]
for z in bucket:
arra... |
22cd96a79d0a22ce120ef3ef5eb6c8ee8dc05197 | Sevendeadlys/leetcode | /108/sortedArrayToBST.py | 721 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not num... |
9f61371a9bc27d960b542e079c38ce45cbda03f7 | irvandenata/Metode-Numerik | /simpson1per3.py | 1,023 | 3.921875 | 4 | a = float(input("Masukkan Nilai a : " ))
b = float(input("Masukkan Nilai b : "))
segment = float(input("Masukkan Jumlah Segment : "))
h = (b-a)/segment
xd = []
data = []
f = a
xd.append(f)
for i in range(3):
f += h
xd.append(f)
xd.append(b)
print("Setiap Nilai X : ",xd)
j = lambda x : (((1/4)*-9.16... |
e753dd5d5719e0a80f9e3587b81baf101687ff9d | drahmuty/Algorithm-Design-Manual | /04-04.py | 1,338 | 4.0625 | 4 | """
4-4. Assume that we are given n pairs of items as input, where the first item is a number and the
second item is one of three colors (red, blue, or yellow). Further assume that the items are sorted by number.
Give an O(n) algorithm to sort the items by color (all reds before all blues before all yellows)
such th... |
250bb9741af33135f46c5027e03d8f3323f440d4 | Rumaia/pcs2_homework2 | /TIMER.py | 1,389 | 3.515625 | 4 |
import timeit
setup = """
from homework2 import quickSort
from homework2 import mergeSort
import random
lst = random.sample(range(50), 10)
lst1 = random.sample(range(500), 100)
lst2 = random.sample(range(5000), 1000)
lst3 = random.sample(range(50000), 10000)
"""
t=timeit.Timer('quickSort(lst)', setu... |
6402ef8bd9c93d30c09627775f457cad12121756 | Niramin/PythonProgrammingTextBookSolutions | /ch7ex6.py | 319 | 4.125 | 4 | def mulist(n):
'''
multiplication tables for 5 multiples for n numbers
'''
l=list()
for i in range(1,n+1):
kl=list()
for k in range(1,6):
kl.append(int(k*i))
l.append(kl)
print(l)
def main():
mulist(5)
if __name__=="__main__":
main() |
3c6b04bed61ac1b17ec3df783d4b94b2e37b8902 | daniel-reich/ubiquitous-fiesta | /g6yjSfTpDkX2STnSX_15.py | 111 | 3.9375 | 4 |
def convert_to_hex(txt):
output=""
for x in txt:
output+=hex(ord(x))[2::] + " "
return output[:-1]
|
e8926b69eb7aa668169a20362b17aaf1c6548c45 | sczhan/wode | /类(class)/str(字符串的简单操作).py | 6,038 | 4.125 | 4 | # + 字符串的连接操作
s1 = "lo"
s2 = "ve"
print(s1+s2)
print("lo"+"ve")
# * 字符串的复制操作
print("#"*20)
# []字符串的索引操作
s3 = "l love you"
print(s3[-1])
print("*"*20)
# [: :] 字符串的切片操作
# [开始索引:结束索引:间隔值] (包含开始,不包含结束)
print(s3[2:6])
print(s3[-8:-4:1])
print(s3[-2:-6:-1])
print("*"*20)
# 切整个字符串
print(s3[:])
print("*"*20)
# 指定开始,不指定结束... |
eb5a4c8548b3c19137a1e89bbbfeb6e3cc128eb2 | trialnerror404/beginner-projects | /mad lib.py | 736 | 4.59375 | 5 | """
# string concatenation (aka to put strings together)
# suppose we want to create a string that says "susbscribe to an youtuber"
youtuber = "a" # a string variable
# a few ways to do this
print ("subscribe to " + youtuber)
print ("subscribe to {}".format(youtuber))
print (f"subscribe to {youtuber}")
"""
name = i... |
c5ab7affd22c71fdc4b4396c9e44427c08cf1a6e | Dududenis/pw1-2021-1 | /aula06/01.py | 319 | 4.09375 | 4 | # Listas servem para armazenar um conjunto de dados de mesmo tipo ou nao
notas=[0,0,0] # alternativa: notas = [0] * 3
soma=0
x=0
while x<3:
notas[x]=float(input(f"Nota {x + 1}: "))
soma += notas[x]
x+=1
x=0
while x<3:
print(f"Nota {x + 1}: {notas[x]:6.2f}")
x+=1
print(f"Média: {(soma / x):5.2f}") |
29085ac6e6e31703d9f5ba71600f64e04cece7fd | byungjinku/Python-Base | /11_IF 문/main.py | 1,427 | 3.828125 | 4 | # if 문 : 특정 조건에 만족할 경우 수행되는 조건문
a1 = 10
# if : 만약 ~ 한다면...
if a1 > 5 :
print('a1은 5보다 큽니다')
if a1 < 5 :
print('a1은 5보다 작습니다')
if a1 < 5 :
print('들여쓰기 테스트')
print('이 부분이 수행될까요? 1')
if a1 < 5 :
print('들여쓰기 테스트')
print('이 부분이 수행될까요? 2')
# else : 조건에 만족하지 않을 경우 수행될 부분
# if ~ else... |
d338f61418293de51cca4b019a13b6c18d20aaaa | Aasthaengg/IBMdataset | /Python_codes/p02391/s230482495.py | 134 | 3.875 | 4 | x=raw_input()
list=x.split()
a=int(list[0])
b=int(list[1])
if a<b:
print 'a < b'
elif a>b:
print 'a > b'
elif a==b:
print 'a == b' |
75faade2c33f824bc7c13912cd955cf65d259545 | patriquejarry/Apprendre-coder-avec-Python | /Module_3/3.5.1b.py | 117 | 3.640625 | 4 | t = int(input())
fn1, fn = 0, 1
if t > fn1:
print(fn1)
while t > fn:
print(fn)
fn1, fn = fn, fn + fn1
|
468701c02a16e45423229f90619d1caae60a8dfd | krushnapgosavi/Rock-Paper-Scissor_Game | /rps.py | 1,643 | 3.890625 | 4 | import random
print("Hi , Friends .This is a game of rock-paper-scissor.Which is a popular game.\nSo let's begin the game")
print("Use this shortcuts :\n\t1)Rock-r\n\t2)Paper-p\n\t3)Scissor-s")
c=[]
def gme(x,y):
#x=user y=cpu
if x == 'r' and y == 's':
print('You win!!')
c.append("Win")
... |
24680dd0cc547755a767c168ed3309e9e0386bc2 | pranayknight/WorkedExamples | /TopicsInBasicPython/Giraffe/dicttype.py | 762 | 4.8125 | 5 | dict1={1:"john",2:"bob",3:"bill"} #a dictionary contains keys and values separated by colon within curly brackets
#both keys or values can be of numeric or string data types as desired by user
print(dict1)
print(dict1.items()) #gives all the keys and values of the dictionary
p... |
c46257d3f07fa78779e83b034b690be1383a568b | yotkoKanchev/Python-Fundamentals-June-2018 | /02. Lists-and-Dictionaries/5Mixed Phones.py | 340 | 3.75 | 4 | data = input()
dict = {}
while data != "Over":
splited_data = data.split(" : ")
name = splited_data[0]
number = splited_data[1]
if number.isdigit():
dict[name] = number
else:
dict[number] = name
data = input()
for key, value in sorted(dict.items()):
print(f"... |
c9dd911ad7df412cea4ef134b68e9e3fd613b42a | Aasthaengg/IBMdataset | /Python_codes/p03273/s424949097.py | 724 | 3.546875 | 4 | h, w = (int(i) for i in input().split())
list_a = [input() for s in range(0, h)]
list_tmp = []
for i in range(0, h):
for j in range(0, w):
if list_a[i][j] == '#':
list_tmp.append(list(list_a[i]))
break
# 転置... https://note.nkmk.me/python-list-transpose/ 参照
list_tmp_t = [list(x) for x... |
98b5d2f8925aad7f853420a2261030621736ff65 | zhangzongyan/python20180319 | /day0c/w1.py | 614 | 3.515625 | 4 |
'这是一个装饰器(deractor)'
# 函数作为另一个函数的返回值(高阶函数)
def lazy_fun():
def newnow():
print("2018-4-4")
return newnow
import functools
# 装饰器:在函数执行的过程中为函数加功能
def log(fun): # "闭包":内部函数可以保存住外部函数的参数变量
@functools.wraps(fun) # 将fun函数的属性赋值给wrapper 包括__name__
def wrapper(*args, **kw):
print("%s is called" % fun.__name__)
retu... |
e923ea8dbde6de81d37b2c72751585b95c4f7d82 | aishwarya-g-thoughtworks/Iris-Flower | /rfc_iris.py | 1,910 | 3.59375 | 4 | # Random Forest classifier for Iris Dataset
import matplotlib.pyplot as plt
# Importing the libraries
import pandas as pd
import seaborn as sns
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import confus... |
7ca15d708771c51abfe7e69c5f4640d991127e39 | RameshTarak/python | /duplcate.py | 148 | 3.65625 | 4 | #write a program to remove duplicates from list
names=["abdul","anil","abdul","mohammed","abdul","sunil","abdul","mohammed"]
print(len(names))
|
e0694f1a728ce3caca8fd688d5aa900a75d60399 | ragvri/python-snippets | /tkinter_snippets/eight.py | 804 | 4.125 | 4 | #creating drop down menu
from tkinter import *
def doNothing():
print("Okay")
root=Tk()
menu= Menu(root) #crete a menu , tells where we want to create a menu
root.config(menu=menu) #tells tkinter that a is Menu , it already has knowledge of menus
submenu= Menu(menu) # this menu is going inside the main menu
#... |
38bc2e330cebb263ea7d6cb17fa2f286008ca8fc | narimiran/AdventOfCode2017 | /python/day03.py | 1,071 | 3.921875 | 4 | PUZZLE = 368078
def find_manhattan(number):
spiral_corner = int(number ** 0.5)
remaining_steps = number % spiral_corner**2
side_length = spiral_corner + 1
towards_middle = remaining_steps % (side_length // 2)
return side_length - towards_middle
first = find_manhattan(PUZZLE)
grid = {(0, 0): 1... |
7cea3969ca822d938f23af29e32035a3e8588c98 | ingiestein/dndme | /dndme/gametime.py | 11,549 | 3.859375 | 4 | import math
from collections import namedtuple
Date = namedtuple("Date", "day month year")
Time = namedtuple("Time", "hour minute")
class Clock:
def __init__(self, hours_in_day=24, minutes_in_hour=60, hour=0, minute=0):
self.hours_in_day = hours_in_day
self.minutes_in_hour = minutes_in_hour
... |
b5100a15ec90079d3e63358e4e3d15b92d2ddef3 | sketchyfish/exercises | /challenge4-easy.py | 529 | 3.59375 | 4 | #!/usr/bin/python
"""
You're challenge for today is to create a random password generator!
For extra credit, allow the user to specify the amount of passwords to generate.
For even more extra credit, allow the user to specify the length of the strings he wants to generate!
"""
import random
c = int(raw_input("Numbe... |
a946f65417cbb79750a67142f094bc5982173f42 | JasonXJ/algorithms | /kmp.py | 4,345 | 3.671875 | 4 | # An implementation of the KMP string matching algorithm.
# NOTE `test_random` might not pass in python2 environment.
def kmp_transition_table(pattern):
# ``table[x]`` is "the position of the last character of the longest
# proper suffix" of "the prefix of the pattern whose last character
# located at x".... |
c7f350f6777f244d39e2139c65f858f86080e500 | yannickkiki/programming-training | /Leetcode/python3/3_longuest_substring.py | 585 | 3.625 | 4 | def lengthOfLongestSubstring(s):
result, current_substring_size, last_cut_idx = 0, 0, 0
char_last_idx = dict()
for idx, c in enumerate(s):
c_last_idx = char_last_idx.get(c, -1)
if c_last_idx == -1:
current_substring_size += 1
else:
last_cut_idx = max(c_last_id... |
4ebf29fb90ffbf313308a21bf2584543995fcdeb | tmcclintock/MonopolyMath | /monopolymath/monopolyroller.py | 3,718 | 4.03125 | 4 | """
The rules for moving a monopoly player via rolling.
This allows for simulating the roll and action matrices.
"""
import numpy.random as rand
class MonopolyRollMover(object):
"""
An object for moving monopoly players via rolling.
Args:
diceroller (:obj: DiceRoller): object for rolling dice
... |
ed8e35fa3b7e57c7b91f683bd896d7753f28d230 | VieetBubbles/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 142 | 3.703125 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
sum = 0
set_list = set(my_list)
for _ in set_list:
sum += _
return sum
|
4687224d00852e27f12e32c3168677c98a5912b2 | ucsd-cse-spis-2020/-spis20-lab04-Sidharth-Theodore | /recursive_tree.py | 1,676 | 3.78125 | 4 | import turtle
t = turtle.Turtle()
turtle.screensize(10000,10000)
t.setheading(90)
t.speed(0)
t.pd()
t.hideturtle()
def tree(trunk_length, height):
"""if(height == -1):
t.setposition(0,0)
t.setheading(90)
t.backward()"""
if height == 0:
return
else:
#making a Y
... |
9245121ae48b7453e4281481c0e4d6e29ad3cf56 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4000/codes/1798_2564.py | 308 | 3.5625 | 4 | from numpy import*
cont = zeros(3, dtype=int)
gm = array(eval(input("Gols marcados: ")))
gs = array(eval(input("Gols sofridos: ")))
for i in range(size(gm)):
if(gm[i] > gs[i]):
cont[0] = cont[0] + 1
elif(gm[i] == gs[i]):
cont[1] = cont[1] + 1
elif(gm[i] < gs[i]):
cont[2] = cont[2]+1
print(cont)
|
3e20833c3dd45c1ce59cf7ab61462ae087e9831f | IlPakoZ/Uniroma1-Informatica | /Fondamenti di Programmazione 1° semestre/Programmi Python/Lezione5/perallenarsi1.py | 554 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 21:18:16 2019
@author: xJ0T3
"""
def check_date(g,m,a):
if (m < 1 or m > 12):
return False
if (m<8 and m%2 == 1) or (m>7 and m%2 == 0):
if(g>31):
return False
else:
if(m == 2):
if(a%4 == 0):
... |
dddb2c1036add043b059cf71ec571566a3786918 | aeberspaecher/simple_cache | /simple_cache/simple_cache.py | 5,387 | 3.890625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
"""Simple caching functionality using decorated functions.
Cached values are stored in a dicitonary. The keys are generated by a callable
given to the decorator. This can e.g. be used to cache expensive calculations
that depend on an object's state. In that case, the key ge... |
9542aeafbb336724537d31c6b8ece42a963555ba | shahed-swe/python_practise | /condition.py | 2,424 | 4.28125 | 4 | #if statement
#syntax of if statement
#if <condition>:
#statement
#example
if int(input("Enter your age: ")) >= 14:
print("You are above 14")
# or
age = int(input("Enter another age: "))
if age >= 18:
print(f"You are above {14}.")
#pass statement
#this use to pass the condition in if or else statement
#exa... |
044fcabdbb871fa37561680e492244c386c0d3f0 | Felix-xilef/Curso-de-Python | /Desafios/Desafio28.py | 297 | 3.796875 | 4 | from os import system
from random import randint
numero = randint(0, 5)
tentativa = int(input('\n\tAdivinhe um número de 0 a 5: '))
if numero == tentativa:
print('\n\tParabéns! Você Acertou!\n')
else:
print('\n\tVocê Errou!\n\tNúmero sorteado: {}\n'.format(numero))
system('pause')
|
c9620627368b67731fc56b08c3d2df4e36fe7f92 | SWE2020/monopoly | /die.py | 521 | 3.609375 | 4 | from random import randrange
import pygame
class Die:
#initializes first roll to [1,1]
def __init__(self):
self.numberRolls = [1,1]
self.double_counter = 0
#randomly selects two numbers between 1-6 to simulate two die rolling and returns the number
def roll(self):
self.number... |
e9d04d51f14d2440cfbadc91eec45fde0908d0f5 | AndrewMicallef/utilitybelt | /time.py | 416 | 3.5625 | 4 | import datetime as dt
import numpy as np
def _timedelta(t0, t1):
"""
uses dummy dates to perform a time
delta operation on two times,
returns number of seconds in interval
"""
dummydate = dt.date(2000,1,1)
try:
t0 = dt.datetime.combine(dummydate,t0)
t1 = dt.datetime.com... |
fc1f0e984dbc203852d921a6065af86139f3fb52 | rafaelperazzo/programacao-web | /moodledata/vpl_data/148/usersdata/271/108779/submittedfiles/testes.py | 363 | 3.921875 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
a = float(input('Digite o valor de a : '))
b = float(input('Digite o valor de b : '))
precisão
#ARIT
def arit (a,b) :
while (a>b) and (a-b>precisão) :
a1 = (1/2) * (a+b)
b1 = (a*b)**(0.5)
a = a1
b = b1
arit = a1
return(arit)
p... |
61fca475e214061ab6f7c4ee86f34f2982458827 | lechodiman/IIC2233-Learning-Stuff | /EDD/defaultdicts.py | 353 | 3.53125 | 4 | from collections import defaultdict
class Integer:
def __init__(self, num=0):
self.num = num
def __call__(self):
return self.num
def __str__(self):
return str(self.num)
dos = Integer(2)
# argument must be callable, eg, int, str, dos, etc
d = defaultdict(list)
if __name__ == ... |
eb2fb4346ad4597ca6f8f62e5a558302bf5d6159 | zhuiyun/python-2 | /propertyTest2.py | 241 | 3.640625 | 4 | class Money(object):
def __init__(self):
self.__money=100
@property
def money(self):
return self.__money
@money.setter
def money(self,num):
self.__money=num
m=Money()
m.money=1000
print(m.money) |
03bd85ae40d2254e38e9671ca680dd644e3e82a5 | pangfeiyo/PythonLearn | /甲鱼python/课程代码/第11讲/列表(数组)2.py | 1,106 | 4.34375 | 4 | #讲列表中的两个元素调换位置
member = ['小甲鱼','牡丹','水仙','花']
print(member)
temp = member[0]
member[0] = member[1]
member[1] = temp
print(member)
#删除元素 .remove
member.remove('牡丹')
print(member)
member.remove(member[1])
print(member)
#删除元素 del语句
del member[1]
print('del:',member)
del member[0]
print('del:',member)
#删除元素 pop() ... |
21311fd1ed2245bef4cb7e17c261dd8b2276abac | IvanChen008/PythonLearnProject | /ControlOfFlow.py | 5,040 | 4.09375 | 4 | # -----------------
# if语句
# 也许最有名的是if语句
# -----------------
# D:\GitHub\PythonLearnProject>python
# Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
# Type "help", "copyright", "credits" or "license" for more information.
# >>> x = int(input("Please enter an integer:"))
# ... |
4138de4ff165d173ba7fd491cda629aae9860bc5 | gjq91459/mycourse | /_Exercises/src/Basic/ex2-3.py | 316 | 4 | 4 | """
Write a program that prints out the square, cubes and fourth
power of the first 20 integers.
"""
format = "%6s"
print (format % "N"),(format % "N**2"),(format % "N**3"),(format % "N**4")
format = "%6i"
for i in range(1,21):
print (format % i),(format % i**2),(format % i**3),(format % i**4)
1 |
948103463469fc6da37381e2f8db879194382f6e | LOG-INFO/PythonStudy | /4_io/3_file_read_write.py | 1,499 | 3.6875 | 4 | # 파일 생성하기
# open('name','mode') mode : ['w', 'w+', 'r', 'r+', 'a', 'a+']
# file.write('str')
# 기존에 파일이 있다면 덮어쓰니 주의!!
print("#" * 50)
print("file.write(data)")
print("#" * 50)
f = open("새파일.txt", 'w')
for i in range(1, 11):
data = "%d ) \n" % i
f.write(data)
print()
f.close()
# file.readline()
# 파일의 ... |
bff18f57884b57ebbc6d2e8d22f12e64a4d5a404 | sreekripa/core2 | /list.py | 388 | 4.03125 | 4 | # list1=["a","b","c",1,2,3,4,5,"apple","mango","grapes"]
# # # # # print(list1)
# # # # print(list1[8])
# # # list1[3]="fruits"
# # # print(list1)
# # list2=["banana","orange"]
# # print(list1+list2)
# print("apple" in list1)
list1=["apple","banana","orange"]
# list1.append("xyz")
# print(list1)
# list1.insert(1,"egg")... |
37c2f76f88902c70c4d5e2c2d833556388abcfa2 | abalulu9/Sorting-Algorithms | /CombSort.py | 967 | 3.96875 | 4 | # An implementation of the comb sort algorithm
# Comb sort compares elements with a certain gap between them and swaps if neccessary
# Repeat this process shrinking the gap until it is of size 1
def combSort(vector, ascending = True, k = 1.3):
# Store the length of the vector
n = len(vector)
# Initialise the leng... |
2937b48cac60e7835d285248795d3c8ba02e1d18 | Pabitra-26/Problem-Solved | /LeetCode/Maximum_Subarray.py | 527 | 3.859375 | 4 | # Problem name: Maximum subarray
# Description: Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
# Strategy: Dynamic programming
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_so_far = nums[... |
7067840a01ff242ae523924c0290d7a6990fd1f6 | victor-erazo/ciclo_python | /Mision-TIC-GRUPO-09-master(16-06-21)/Semana 1/ejercicio5.py | 572 | 3.703125 | 4 | # crear una variable de tipo diccionario
info_persona = {
'nombre':'',
'pr_apellido':'',
'sg_apellido':''
}
info_persona['nombre'] = input("ingrese el nombre ")
info_persona['pr_apellido'] = input("ingresar el primer apellido ")
info_persona['sg_apellido'] = input("ingresar el segundo apellido ")
info_... |
3a986edaeb318445653a66b35627b0c853afb20b | kyeeh/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 576 | 3.515625 | 4 | #!/usr/bin/python3
"""
Function that queries the Reddit API and returns the number of subscribers
(not active users, total subscribers) for a given subreddit
"""
from requests import get
def number_of_subscribers(subreddit):
"""
Suscribers by subreddit
"""
headers = {"user-agent": "kyeeh"}
url = "... |
d47fa7aff3869b2c9a1cb52edcf1740b3132fc88 | aaronthebaron/triple | /triple.py | 3,792 | 3.8125 | 4 | import sys
import string
def clean_string(input_string):
"""We can't simply remove punctuation. We need there to be a count difference in the position because one of the rules is that pairs only count if separated by white space."""
removal_map = str.maketrans({
'\n': ' ignr ',
'\r': ' ignr ',
... |
8a8b2623567dddc7197ccc6ad06c6989e54d7b0c | joooooonson/LOGICnPROG_2017_Fall | /2dchallenge/joonson_w0410150_702_boxOrDiamond.py | 1,864 | 4.1875 | 4 | # Author: Joon Son
# Date: 2017-11-29
# Description: Nested 2D List challenge!
# use nested loop and create 2-D list
size = 0
character = "X"
shape = "box"
def drawing_box(size, character):
side = size + size -1
drawing = []
for i in range(side):
line = [" "] * side
for j in range(side):... |
999087b8c1a10c85cc7033c6c56a546be83aa989 | Mifaou/HackerRank_Solution | /HackerRank/Python/Write a function.py | 278 | 3.875 | 4 | def is_leap(year):
leap = False
if not year%4==0:
return leap
else :
if not year%100==0:
return not leap
else :
if year%400==0:
return not leap
else :
return leap |
f461db4904e95aa11695bfeea6dc1b6fc69cafd3 | marshalloffutt/functions | /user_albums.py | 639 | 4.21875 | 4 | # 8-8
def make_album(artist_name, album_title, number_of_tracks):
"""Return a dictionary"""
album = {'Artist': artist_name, 'Title': album_title, 'No of Tracks': number_of_tracks}
return album
while True:
print("\nEnter artist name, and album title, and number of tracks: ")
print("(enter 'q' to to... |
69a0d8b929df48b531cc89776084b00c62372f9e | chlos/exercises_in_futility | /misc/anagrams.py | 516 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
def get_anagrams(words):
word_groups = collections.defaultdict(list)
for word in words:
word_sorted = ''.join(sorted(word))
word_groups[word_sorted].append(word)
return word_groups
def main():
words = ['a', 'b']
p... |
88e94b4e5d6c3e8855af7159c674f2b489e15325 | sjlarrain/Herramientas | /P03/solucionP03.py | 1,057 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
from copy import deepcopy as dp
def problemaP03(lista,buscado):
def sumar(a,b):
return b+a
def restar(a,b):
return b-a
def numero(a,buscado,b=0):
sol=0
if sumar(a,b)==buscado:
sol+=1
if restar(a,b)==bu... |
18d011df4badddb575d549f17afe53f15a0683a8 | marwafar/Python-practice | /solve.py | 1,683 | 4.09375 | 4 | """
Instructions:
- Implement the function `path_exists` below.
- Save this file as `{first_name}_{last_name}_solve.py`.
Constraints:
- Your solution will be run in a Python2.7 environment.
- Only python standard library imports can be used and they must be imported within `path_exists`.
- ... |
fa0470db97174305cb1ea00849c30bc9fbf927fb | ZYZhang2016/think--Python | /chapter18/Exercise18.2CardGame.py | 1,777 | 3.875 | 4 | #coding:utf-8
import random
class Card(object):
'''reprensts a card game
'''
def __init__(self,suit=0,rank=2):
self.suit = suit
self.rank = rank
suits_name = ['Club','Diamond','Hearts','Spades']
rank_name = [None,'1','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
def __str__(self):
return '... |
2443c5b9dd8e7dd49f14e93d1b2857886ff87647 | amirabed2024/Python_Teacher | /Teach33.py | 687 | 4.03125 | 4 | # Inheritance => class Motor(Car)
class Car:
wheels = 4
def __init__(self, name, speed, price):
self.name = name # Atribute
self.speed = speed # Atribute
self.price = price # Atribute
def show(self): # Method
print(f'{self.name} cost {self.price} and top speed is {self.spee... |
4f6ac4a480ca8e166c17d6d86e48beecc3ca37e6 | zision/Sort-Python | /insert_sort.py | 1,450 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : insert_sort.py
# Author: ZhouZijian
# Date : 2018/9/21
"""插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。
它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
1、从第一个元素开始,该元素可以认为已经被排序;
2、取出下一个元素,在已经排序的元素序列中从后向前扫描;
3、如果该元素(已排序)大于新元素,将该元素移到下一位置;
4、重复步骤3,直到找到已排序的... |
855b6dd08bc7b5251aa045c131fbbd0b69187624 | 1505069266/python- | /函数式编程匿名函数,高阶函数,装饰器/优化装饰器.py | 375 | 3.734375 | 4 | # 优化装饰器
import time
def decorator(func):
# key word
def wrapper(*args, **kw):
print(time.time())
func(*args, **kw)
return wrapper
@decorator
def f1(func_name):
print('this is function' + func_name)
@decorator
def f2(func_name1, func_name2):
print('this is a function' + func_na... |
8e2b5c36a5cac7f4ea616373976d8dc5d70a617b | vykee/-Porta3 | /bono6.py | 167 | 3.765625 | 4 | #Sum of two numbers
n = 0
list = []
sum = 0
n=(input("Digite dos numeros: "))
list=n.split(',')
for i in list:
sum = int(sum) + int(i)
print(sum)
|
98085a43da10432fad1190b96b51414df35f976a | KuR0uSaGi/datatrucgrader | /63010852_Lab04_5.py | 3,826 | 3.78125 | 4 | class Queue:
def __init__(self, ls = None):
self.count = 0
self.count1 = 0
if ls == None:
self.items = []
else:
self.items = ls
self.getTripleCharactor()
def enqueue(self, val):
self.items.append(val)
return ("Add {} index ... |
ade159980337c30b61cf662106bcca38c7926993 | itsdddaniel/POO | /II Parcial/main2.py | 176 | 3.578125 | 4 | #-*- coding: utf-8 -*-
import rep
number = input("")
number = re.sub(r"\D+","",number)
if len(number)==0: number=1
else: number = int(number)
print("Hola Mundo\n"*number) |
9c11c6064853db7bc29c9dc6e354d184dcabf6a8 | miikanissi/python_course_summer_2020 | /week2_nissi_miika/week2_ass4_nissi_miika.py | 1,437 | 4.375 | 4 | print("BMI Calculator")
unit = input("Choose the unit of measure: 1 for Metric, 2 for Imperial: ")
while (unit != "1" and unit != "2"):
unit = input("Choose the unit of measure: 1 for Metric, 2 for Imperial: ")
if (unit == "1"):
while True:
weight = input("Enter weight in kg: ")
try:
... |
8857cbfed8645e5c742f828b0a356532cecf0608 | dmelles/ChessLab | /ChessGUI.py | 7,903 | 3.640625 | 4 | # ChessGUI.py
# Written by: Shasta Ramachandran
# Date: 2/5/2016
# Creates a GUI object for use with Chess
from Square import *
from graphics import *
from Button import *
class ChessGUI:
def __init__(self):
"""Creates a GUI object for use with Chess, complete with Mouse, Square, and Message functionality."""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.