blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
42d57a786631846aeae01a0cd15b229e4da04634 | ranjit-kr-nair/CodeForces | /Watermelon_4A.py | 111 | 4.0625 | 4 | x = int( input() )
if x > 3:
if x % 2 == 0:
print("YES")
else:
print("NO")
else:
print("NO")
|
082ce250d75b41d933dcbb8525953742e9f1e646 | jdogg6ms/project_euler | /p005/p5.js | 427 | 3.546875 | 4 | #!/usr/bin/env python
//Project Euler Problem #5
//find smallest number that can be evenly divided by 1-20
function test_factor(n){
for (var i = 11; i <= 20; i++){
if (n % i !=0)
return false;
}
return true;
}
var i = 0;
var result = 0;
while (result == 0) {
i +=20;
if (test_f... |
9f4076c731a9547ff88e6066be5ead88190863ff | newbieeashish/DataStructure_Udacity | /stackinpython_list_demo.py | 970 | 4.21875 | 4 | '''
push is when you add an element to the top of the stack and
a pop is when you remove an element from the top of the stack.
Python 3.x conviently allows us to demonstate this functionality with a list.
When you have a list such as [2,4,5,6] you can decide which end of the list is
the bottom and the top o... |
20128535e10a41eac0610193688a8ee8b52f0c95 | swayamsudha/python-programs | /fibbo.py | 198 | 4.28125 | 4 | ##WAP TO TO DISPLAY FIBBONACI NUMBERS UPTO NTH TERM
n = int(input("Enter the Nth term:"))
f=0
print("Fibbonaci numbers up to {0}th term = ".format(n))
for i in range (1,n+1):
f=f+i
print(f)
|
d1296bb2df6449d80fb58fe513ca1f625878515f | fatiharslanedu/PythonNotes | /Chapter 7-8-9/script.py | 2,465 | 3.703125 | 4 |
#? ------------ Section 7.1: Creating an enum (Python 2.4 through 3.3) --------?#
from enum import Enum
class Color(Enum):
red = 1
green = 2
blue = 3
# print(Color.red) #todo: Color.red
# print(Color(1))#todo: Color.red
# print(Color['red'])#todo: Color.red
# print([c for c in Color])#todo: [<Color.... |
09c27afb90c984f3d9bd2e7ad289ea5009ce263c | lmdpadm/Python | /aula17.2.py | 487 | 4.1875 | 4 | '''valores = list()
for cont in range(0, 5):
valores.append(int(input('Digite um valor: ')))
for c, v in enumerate(valores):
print(f'Na posição {c} encontrei o valor {v}!')
print('Cheguei ao final da lista')'''
a = [2, 3, 4, 7]
#b = a
#b[2] = "pizza" # O Python cria uma conexão entre uma lista e ou... |
df58c831f993f533acfe30520eb7198641ecf901 | mardeldom/data_science_student_nov_2020 | /SQL/Exercise/EXERCISE AUSTRALIA/src/src_libs/eda_lib/eda.py | 310 | 3.546875 | 4 |
def choose_x_y(df, col_name, col_name2, col_name3, col_name4, col_name5, col_name6, target_col=None):
x_data= df.drop(columns=[col_name,col_name2, col_name3, col_name4, col_name5, col_name6])
if target_col:
y_data = df[target_col]
return x_data, y_data
else:
return x_data |
ec244b378f1e4c90c891c9d0a7d0efde4792899a | mutse/desgin-patterns-gossip | /proxy/proxy.py | 1,262 | 3.75 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 mutse <yyhoo2.young@gmail.com>
#
# This program is a proxy demo of the Design Pattern Gossip Series.
#
class SchoolGirl:
def __init__(self, name):
self.name = name
def getName(self):
return self.name
class AbstractProxy:
de... |
d8d65161f83dac8f7c4d030d629e0a37cbf10cf8 | Scary-Terry/TextGame | /textgame.py | 17,941 | 3.8125 | 4 | """
Sam Ruchti
Text Adventure
4/3/18
"""
import time
class Creatures:
def __init__(self, name):
self.name = name
def health(self, health):
self.health = health
class Hostile_Monster(Creatures):
""""""
print ('To restart the game, type "restart" and hit enter at anytime.\n'... |
1dcdf7b6236997cedae8a3eb2c885585ebdaac7b | Shengliang/language | /python/passwd/menu.py | 2,082 | 3.984375 | 4 | verbosityLevel = 2
class Menu:
def __init__(self):
self.menuChoiceString = ''
self.menuChoiceInt = -1
self.validateMenuChoice = False
# Hash Table: 1 to 8 options
self.option = {}
self.option[1] = "Enter User Data"
self.option[2] = "Validate Entered Pass... |
7e55c46c83352eba31b4075867c8239068b376d5 | chenuratikah/GoQuo | /model.py | 1,356 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
class Model:
def __init__(self, adult, child, infant):
self.adult = adult
self.child = child
self.infant = infant
def calculateRoom(self):
#Calculate room count
biggestPax =max([self.adult, self.child,... |
b7a099deefd59736896b2871ccb3dced4d66af28 | AmanPandey0320/Differentivity | /N_LargestEle.py | 293 | 3.59375 | 4 | n = int(input("Enter value of n"))
list1 = list(map(int,input("\nEnter list:").strip().split()))[:n]
new_list = []
for i in range(0,n):
mx = 0
for j in range(len(list1)):
if (list1[j] > mx):
mx = list1[j]
list1.remove(mx)
new_list.append(mx)
print(new_list) |
14239b6427e9127330f1deba8018cbe91950b79f | liuyang2239336/xuexi | /PythonTest/demo1.py | 764 | 3.84375 | 4 | # a = input("请输入舒展是不是直男,1:是;0:不是:")
# a的变量类型
# 判断; == 判断语句:判断a是否等于1,如果a等于1:打扰了!如果不等于1:你好呀
# 缩进:if/while/for/def/class/try...
# if a == "1":
# print("打扰了!")
# else:
# print("你好呀~")
# 不等于
c = 10
if c != 18:
print("这个c不是18!")
if c > 18:
print("这个c就已经成年了!")
if c < 18:
print("这个c未成年!")
c = ... |
b5a04ddce9c03523b4b2e1bb19454da3df323379 | yuenliou/leetcode | /226-invert-binary-tree.py | 1,572 | 3.859375 | 4 | #!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
from datatype.tree_node import TreeNode, pre_order_travel, in_order_travel, post_order_travel
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
#递归交换左右节点
if not root: return root
root.left, root.right = root.right, root.left... |
158c2c883efd3cbccdc0302150d90e7cca5d1cab | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_55/50.py | 1,381 | 3.546875 | 4 | #!/usr/bin/python
# google code jam - c.durr - 2010
# Theme Park
# N numbers seen circularly
# ride: a mapping from i (being the first on the queue) to j<=i such that
# total number of persons from i (incl) to j (excl) does not exceed k
# we use the rapide exponentiation trick
import sys
def fit(i):
'''given... |
b62535abdbcb7d226089cff88b5ea0e6ab07a304 | JasminSantana/Patterns-Design | /Patterns/strategy.py | 909 | 3.703125 | 4 | import types # Import the types module
""""Author: Santana Mares Jasmin
gmail: sant.mar.1997@gmail.com
date: 12/11/2017 """
'''Determina cómo se debe realizar el intercambio de mensajes entre
diferentes objetos para resolver una tarea.'''
class Strategy:
"""The Strategy Pattern class"""
... |
d8eaa7f851f19973f83acb383e77ffedf59bb58d | AndersonHJB/PyCharm_Coder | /Coder_Old/早期代码/lesson_f.py | 721 | 3.84375 | 4 | def while_function(judge):
while True:
if judge == '男' or judge == '女':
break
elif judge.isdigit():
break
else:
print('输入错误')
while_function(input('请重新输入:'))
user_gender = input()
while_function(user_gender)
user_age = input()
while_function(user_age)
def while_functi... |
0a054d02258fd6f346778d959aae13e39d2089f9 | a3345/LearnPython_In8Day | /Hello.py | 257 | 3.75 | 4 | import time # 这里需要导入包;
name = input("your name:");# 这里不需要var;
tel = input("your tel:")
print("系统正在计算中...")
time.sleep(5) # 5s延时;
print("你的名字是:%s"%(name))
print("你的电话是:%s"%(tel))
|
303d357614c46235a46c1478c34cb58c2e0dd67c | anversa-pro/ejerciciosPython | /diccionarios.py | 3,286 | 4.03125 | 4 | #!/usr/bin/python
# # -*- coding: utf-8 -*-
print("""Un diccionario es una colaeccion de datos agrupados por clave valor,
donde la calve es el indice puede no solo ser numero si no que puede ser una
cadena, tuplas o una mezcal entre ellos """)
print("")
print("""al crear un diccionales las partes de clave valor se pa... |
645c8e08ef29bf8ecdfc8579ebe3b90b0898cf81 | eduardosacra/learnpython | /semana6/exercicios/3primos.py | 611 | 3.671875 | 4 | # Exercício 3 - Primos
#
# Escreva a função n_primos que recebe um número inteiro maior ou igual a 2 como parâmetro
#e devolve a quantidade de números primos que existem entre 2 e n (incluindo 2 e, se for o caso, n).
def isprimo(valor):
fator = 2
while fator < valor:
if valor % fator == 0:
... |
7b4ecf8edf2dc4d75328298a07e7657eebafdc24 | OhadSrur/JupyterTradingAnalysis | /source/basicTradingFunctions.py | 2,883 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
def normalize_data(df):
"""Normalize stock prices using the first row of the DF"""
return df / df.iloc[0,:]
def plot_data(df, title="Stock Prices"):
"""Plot stock prices with a custom title and meaningful axis labels."""
ax=df.plot(title=title, fon... |
068f13d535b37dbe1fe7896365b5efa46a123f84 | HenriqueMartinsBotelho/steiner | /showcross.py | 929 | 3.53125 | 4 | import plot
def printAresta(e1):
print([(e1[0].x, e1[0].y), (e1[1].x, e1[1].y)])
def cross_product(p1, p2):
return p1.x * p2.y - p2.x * p1.y
def direction(p1, p2, p3):
return cross_product(p3.subtract(p1), p2.subtract(p1))
def intersect(p1, p2, p3, p4):
d1 = direction(p3, p4, p1)
d2 = direction(p3,... |
752eaf3e57c9eceb7139e1484fecf82849f5104c | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/26-apply.py | 698 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 21:06:43 2020
@author: baysan
"""
import pandas as pd
df = pd.DataFrame({
'degisken1':[10,23,33,22,11,99],
'degisken2':[100,253,333,262,111,969]},
columns = ['degisken1','degisken2'])
"... |
df46f230332ca3fc8b7e44755ad62b9a9eec71c7 | gaurav112007/press_me-game | /press__me.py | 1,246 | 3.671875 | 4 | from Tkinter import *
import pygame
from random import *
score=0
timeleft=30
root=Tk()
def startGame(event):
if timeleft == 30:
countdown()
def event1(event):
print("{},{}".format(event.x,event.y))
def jump(event):
mygame.abc.place(relx=random(),rely=rando... |
449b0a1c5cc14f9c0b481f80daf1fb40bec446b9 | Farubegum/intnumber | /leaapppp.py | 163 | 3.796875 | 4 | while True:
try:
sam=int(input())
break
except:
print("invalid input")
break
if sam%400==0 or sam%4==0 and sam%100 !=0:
print("yes")
else:
print("no")
|
62fda3bb8992b5ed638afe2fb2309e1f541bf7a2 | andrewn488/5061-entire-class | /Week 03/tw4_low_high.py | 244 | 3.859375 | 4 | """
Week 3 Team Work Assignments
TW4_Low_High
9/30/2020
Chequala Fuller
Austin Bednar
Andrew Nalundasan
"""
# user inputs and variables
low = int(input('low: '))
high = int(input('high: '))
# while loop
while low <= high:
print(low)
low += 1
|
9f7ceee8887017d2f2d42b9a067ae08972b6a6a4 | mmncit/cracking-the-coding-interview-solutions | /data-structure/binary_search_tree.py | 1,173 | 4.125 | 4 | class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, data=None):
self.root = None
if data:
self.root = TreeNode(data)
def insert(self, data):
current = self.root # a ... |
fc2997eaa6d4b1771dac40200c96afd21a93bcca | OwenWong0627/CCC | /Python/CCC17J3.py | 618 | 3.71875 | 4 | Start = str(input())
End = str(input())
Battery = int(input())
StartCoordinate = [int(e) for e in Start.split()]
Endcoordinate = [int(e) for e in End.split()]
def determineNumberOfSteps(startlist,endlist):
steps = 0
steps = steps + abs(startlist[0]-endlist[0])
steps = steps + abs(startlist[1]-endl... |
6bf8ad98a81d4851fea8c8e2fc9f8ec578dd8130 | kolyasalubov/Lv-568.1.PythonCore | /codewars/Tsokh/ClassyClasses.py | 301 | 3.609375 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.info = f"{self.name}s age is {self.age}"
def getInfo(self):
i = 0
self.info = f"{self.name[i]}s age is {self.age[i]}"
i += 1
return self.info
|
80722f3fccac3b4b0016210212bd9a9667c769e5 | RahulK847/day-3-1-exercise | /main.py | 241 | 4.3125 | 4 | # 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if number%2==0:
print("Its even")
else:
print("Its Odd")
|
c7603ab5b94f3b8c95743a892ad1f16ba3f77b35 | RiccardoBefi/Programming2020_Project | /Console Game/ventuno.py | 2,522 | 3.765625 | 4 | from Deck_creation import draw, listed, deck, game
l = listed()
game_deck = deck(1)
total_players = game(3)
player_1_hand = total_players[0]; player_2_hand = total_players[1]
# Turn base
stop1 = True
stop2 = True
result1 = 0
result2 = 0
active_player = 1
def winner():
print("Player 1 had a tot... |
0a0e2e667b3899e52e0486bdd4d64cba6af312cd | edsonb0rges/python_work | /2_listas/ordenando_elementos/sort.py | 358 | 4.28125 | 4 | carros = ["bmw", "audi", "toyota", "subaru"]
carros.sort()
print(carros)
# o método sort() altera a ordem dos elementos de uma lista em ordem alfabética
carros.sort(reverse=True)
print(carros)
# o método sort(reverse=True) altera a ordem dos elementos de uma lista em ordem alfabética inversa. Cuidado!!! O True deve s... |
4d7db87e99715b8225dcce99d1bfa9b16e887b54 | tz2614/rosalind | /interwoven_motifs.py | 2,678 | 3.5625 | 4 | #! usr/bin/env python
"""
Problem: Finding Disjoint Motifs in a Gene
URL: http://rosalind.info/problems/itwv/
Given: A text DNA string s of length at most 10 kbp, followed by a collection of
n (n <= 10) DNA strings of length at most 10 bp acting as patterns.
Return: An nxn matrix M for which Mj,k = 1 if the jth and ... |
c4842063ea6ea7b39fb7beeb5e16b0c6348515ee | nguyenjessicat/python-games | /hangman.py | 1,925 | 4.28125 | 4 | import random
from words import words
import string
#get the computer to generate a word randomly
def get_valid_word(words):
word = random.choice(words) #computer will choose a random word from list "words" we imported
#since some words have spaces and dashes within the word, this while loop will keep going un... |
116ed29e5b101c213cfab09b22604ee39a3e45fb | daniel-reich/ubiquitous-fiesta | /8rXfBzRZbgZP7mzyR_24.py | 66 | 3.640625 | 4 |
def is_last_character_n(word):
return word[-1].lower()=='n'
|
3fddfe5414c703a74dc3177b7a9a2c98359fa5a3 | nptit/Check_iO | /Elementary/pangram.py | 403 | 3.859375 | 4 | from string import ascii_lowercase
def check_pangram(text):
return set(a.lower() for a in text if a.isalpha()) == set(ascii_lowercase)
if __name__ == '__main__':
assert check_pangram("The quick brown fox jumps over the lazy dog."), "brown fox"
assert not check_pangram("ABCDEF"), "ABC"
assert check_pa... |
c8d3e5b7a19c349affb6d13b8b82ef81600a3d5b | dzakub77/python_basics | /zadania_domowe/zadanie11.py | 210 | 3.578125 | 4 |
x = int(input("Wprowadz liczbe: "))
for i in range(2, 100):
if x % i == 0 and x != i:
print(f"{x} nie jest liczba pierwsza")
break
else:
print("Liczba pierwsza")
break |
b1a9409af98b8dbd48972ee4d1c8ceb52515aba1 | ironllama/adventofcode2017 | /advent02a.py | 776 | 3.90625 | 4 | # Advent of Code 2017
# Day 2 - Part I
# Python
f = open("advent02.in", "r")
allLinesList = f.readlines()
sumTotal = 0
for thisLine in allLinesList:
highest = -1 # Just using -1 as a placeholder for "no value", though I probably could have used "". Maybe next time.
lowest = -1 # Just using -1 as a placeho... |
81d58c17ae063129a882fca1b11351c126f44996 | Himanshu-Gurjar/Hybrid_Encryption | /Cryptography/generate_key_pair.py | 4,146 | 4 | 4 | import random
from Cryptography import cryptomath
# Pre generated primes
first_primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139,
... |
02a6a4dd9b2fe3712a02a725cf37eb90635691b5 | Arifuzzaman-Munaf/KC_assessment | /BIG_NUMBERS.py | 865 | 3.890625 | 4 | def sum_large(number1, number2):
len1 = len(number1)
len2 = len(number2)
"""
If the length of numbers are not same , then it will add leading zeros to equalize the numbers
"""
number1 = {True:('0' * (len2-len1) + number1), False:number1}[len2 > len1]
number2 = {True:('0' * (len1-len2) + num... |
beed5108dc1764765770f7629c8c2764561d7e89 | withinfinitedegreesoffreedom/datastructures-algorithms | /linkedlists/return_kth_to_last.py | 957 | 3.875 | 4 | import unittest
class Node:
def __init__(self, val=None):
self.value = val
self.next = None
class LinkedList:
def __init__(self, val):
self.head = Node(val)
def kth_to_last_element(head, k):
if head is None:
return None
fast = head
slow = head
for i in r... |
b9cc3c011686c9f4e4704769a2d7690609cecca8 | garyyli/Unit2 | /movie.py | 299 | 4.21875 | 4 | #Gary Li
#9/13/17
#movie.py- tells user the most scandalous type of movie they can watch based on age
age=int(input('Enter your age: '))
if age>=17:
print('You can watch R movies')
elif age>=13:
print('You can watch PG-13 movies')
else:
print('You can watch PG movies (with a parent)')
|
7389d725d448a22a44a51e579c2c7e2b473691ef | yashbg/6w6l | /python/mkdir.py | 520 | 3.78125 | 4 | import argparse
import os
import sys
parser = argparse.ArgumentParser(description='Make an empty directory')
parser.add_argument(
'path',
metavar='path',
type=str,
help='the path to the new directory'
)
args = parser.parse_args()
input_path = args.path
if os.path.exists(input_path):
if os.path.... |
b0bbd3d9eb3b13c3566640d6d148cc3256ddb38c | ikuklos/home_work | /task_8_3.py | 1,173 | 3.78125 | 4 | # Написать декоратор с аргументом-функцией (callback),
# позволяющий валидировать входные значения функции и выбрасывать исключение ValueError, если что-то не так, например:
# def val_checker...
# ...
#
# @val_checker(lambda x: x > 0)
# def calc_cube(x):
# return x ** 3
#
# >>> a = calc_cube(5)
# 125
# >>> a = ... |
39fe09af6f969c237d52d1f6754b6126bce85df5 | yiming1012/MyLeetCode | /LeetCode/回溯法/294. 翻转游戏 II.py | 1,406 | 3.78125 | 4 | """
294. 翻转游戏 II
你和朋友玩一个叫做「翻转游戏」的游戏。游戏规则如下:
给你一个字符串 currentState ,其中只含 '+' 和 '-' 。你和朋友轮流将 连续 的两个 "++" 反转成 "--" 。当一方无法进行有效的翻转时便意味着游戏结束,则另一方获胜。
请你写出一个函数来判定起始玩家 是否存在必胜的方案 :如果存在,返回 true ;否则,返回 false 。
示例 1:
输入:currentState = "++++"
输出:true
解释:起始玩家可将中间的 "++" 翻转变为 "+--+" 从而得胜。
示例 2:
输入:currentState = "+"
输出:false
提... |
5d0605e16f07895974c5441f0ced3a15481ee205 | MichaelLenghel/python-concepts-and-problems | /comprehensions/comp.py | 1,279 | 4.1875 | 4 | # Code adapted from Corey Shafer
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Rather than doing a for each loop and appending to the list, this is a comprehension
my_list = [n for n in nums]
print(my_list)
# For the same thing, but multipling each value by itself:
my_list = [n*n for n in nums]
print(my_list)
# Using a ... |
861880e02ca40f0dcaf822e1a4c331ba12823b39 | muhammadpauzi/python-tutorial-with-kelas-terbuka | /24 - Operator Bitwise/main.py | 358 | 3.59375 | 4 | a = 4
b = 6
# and ( & )
print("4 & 6 : ", a & b)
print("4 & 4 : ", a & a)
# or ( | )
print("4 | 6 : ", a | b)
print("4 | 4 : ", a | a)
# xor ( ^ )
print("4 ^ 6 : ", a ^ b)
print("4 ^ 4 : ", a ^ a)
# Negasi/kebalikan ( ~ )
print("~4 : ", ~a)
print("~4 : ", ~a)
# Left Shift ( << )
print("4 << 6 : ", a << b)
# Right Sh... |
861c5c83b9ba1130bd799e823612bc7967bd16b0 | RMSpratt/Python-Programs | /RecordListManagerDB/RecordEditFunctionsDB.py | 16,603 | 3.828125 | 4 | import csv
import mysql.connector
"""
Name: addRecord
Description: This function adds a new record to the database table, or updates an existing record's quantity
if it already exists in the table.
Parameter: dbConnection The connection the the database
Parameter: dbCursor ... |
414e45d6b4bb1f63c75861df350c538b8367497c | sychris/PyGVisuals | /pygvisuals/src/widgets/border/roundedborder.py | 2,678 | 3.703125 | 4 | # -*- coding: cp1252 -*-
import pygame
import coloredborder
class RoundedBorder(coloredborder.ColoredBorder):
"""
Border with rounded corners
"""
def __init__(self, width, height, color, radius):
"""
Initialisation of a RoundedBorder
parameters: int width ... |
e611ca8973816c9d844a43b427b6b8b8aee0b34e | JuDaGoRo/grup05 | /ejesumapromedio.py | 390 | 3.90625 | 4 | suma = 0
contador = 0
# Es un while que nunca va a terminar siempre y cuando no se rompa on break
while (True):
print ("Ingrese un numero")
numero = int(input())
if (numero < 0):
break
# Forma resumida "suma = suma + numero
suma += numero
contador += 1
promedio = suma/contador
if ... |
7b4e1168b7ff66f642e98dcba4cf097612bc27f5 | JHorlamide/Python-tutorial | /tuple.py | 389 | 3.515625 | 4 | from typing import Coroutine
list_numbers = [1, 2, 3]
tuples_numbers = (1, 2, 3)
print(type(list_numbers))
print(type(tuples_numbers))
# Index of an item in a tuple
print(tuples_numbers[0])
# Unpacking
coordinates = (1, 2, 3)
x, y, z = coordinates
print('Tuple')
print(x)
print(y)
print(z)
print('List')
coordinat... |
a089ad73dd935fc795ee0522b09a6574f0e0adc7 | AlejandroSotoCastro/practicing_python | /ejerciciohoja3.py | 136 | 3.859375 | 4 | a=int(input("Cuántos números se van a introducir"))
num=0
for n in range(a):
x=int(input("Introduce un numero"))
num+=x
print(num)
|
8d17058220d91b1302be4e7764d8729b431ef879 | UpendraDange/JALATechnologiesAssignment | /pythonExceptions/program_9.py | 280 | 3.53125 | 4 | """
Write a program to generate ArrayIndexOutOfBoundException
"""
def pyException():
try:
pyList = [10,20,40,30]
print(pyList[2])
print(pyList[6])
except IndexError as ie:
print("Error:",ie)
if __name__ == "__main__":
pyException()
|
e3681f33cce377af26062301c82bf75eb22f9c79 | romangomezmarin/Platillas-para-python | /04-estructuras-datos/stacks/ejemplo_uso_Stack.py | 1,408 | 4.1875 | 4 | # una lista es un ejemplo de stack(pila en español),
# es un tipo de dato LIFO(Last In Firt Out)
# El stack es un tipo de dato abstracto que se usa en muchos lenguajes
# de programacion y cumple unas funciones especificas.
# sus metodos principales son append() en python o push() en otros lenguajes de programacion
# e... |
5179b45500b4a28e9bf751ab623da0c0fdcf726c | Lucas-Severo/python-exercicios | /mundo02/ex036.py | 741 | 4.34375 | 4 | '''
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
- Pergunte o valor da casa,
- o salário do comprador
- e em quantos anos ele vai pagar.
A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
'''
precoCasa = float(input('Valor da casa: R$'))
salarioC... |
c20885af04d6a7ddf35a1a6e8731ea0763034548 | evgranato/Python-Course-Code | /Dictionaries/dictionary_practice.py | 344 | 3.5 | 4 | playlist = {
"playlist" : "chill",
"songs" :
[
{"title" : "number 41", "artist" : "dave matthews band", "duration" : 4.55, "album": "Crash"},
{"title" : "crash", "artist" : "dave matthews band", "duration" : 2.32, "album" : "ants marching"}
]
}
for val in playlist["songs"]:
total_l... |
dd65dff2a71d3c597908f6a5272bf7aafd46a9a9 | arpitaga04/simple-rsa | /brute_force_rsa_privatekey.py | 386 | 3.890625 | 4 | def mod_pow(x,y,p):
res = 1
x = x % p
while(y > 0):
if((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x*x)%p
return res
n = int(input("Enter n : "))
c = int(input("Enter cipher text to decrypt : "))
m = int(input("Enter message to encrypt : "))
... |
04f98a6b74ac4de4ec5950ff0a6633fae28c9cda | sheikhusmanshakeel/leet_code | /linked_list/61.py | 1,216 | 4.03125 | 4 | # https://leetcode.com/problems/rotate-list/
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
len_of_list = 0
curr = head... |
983d20dfa5b1045917cdcc4095dd4c64516fba4e | VivekAdmuthe/python-program | /OOPS_sum_2Numbers.py | 442 | 4.0625 | 4 | # oops concept code to write sum of two numbers
class Number:
def sum(self):
return self.a + self.b
num = Number()
num.a = 12 #you can take this values from inputs also
num.b = 34
s = num.sum()
print("sum is equal to ",s)
#normal code in python to add two numbers
# a = 12
# b = 34
# print("The ... |
78c107e98d2ec820045441ac811f8cdca111e38d | loveyinghua1987/algorithm014-algorithm014 | /Week_01/Leetcode.25翻转链表-分析.py | 4,524 | 3.703125 | 4 | #Leetcode 25. Reverse Nodes in k-GroupK 个一组翻转链表
#https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
#方法1:迭代解法
#思想:
#把链表结点按照 k 个一组分组,所以可以使用一个指针 head 依次指向每组的头结点。这个指针每次向前移动 k 步,直至链表结尾。
#对于每个分组,我们先判断它的长度是否大于等于 k。若是,我们就翻转这部分链表,否则不需要翻转。
#Q1:如何翻转一个分组内的子链表
# 参见:Leetcode 206. 反转链表(https://leetcode-cn.com/problems/r... |
f5141ef93b768a9bbe0cf8aff0a7ac0ed2e93e4e | DominoCode154/Code-Inverness-Python | /Mastermind v4.py | 2,021 | 3.75 | 4 | import random
MasterNumList = []
ImputList = []
VerdictList = []
print ("Welcome to MasterMind, my friend!")
for r in range(4):
MasterNumList.append(random.randint(1,8))
#for q in MasterNumList:
# print (q) #Temporary for Testing and debug
print ("If a number is right, % appears. If a number is nearly right... |
b4165ea2edb9316ddd5bf0693ace03f7941bdab2 | joaoDragado/web_scraping | /tumblr/tumblr_image_scrape.py | 1,555 | 3.546875 | 4 | import requests, bs4
'''
script that scrapes the links to all the images on the nameOfSite tumblr, and :
- saves it to a text file,
- downloads the image in a folder named "images".
Saving the links before downloading is advisable, to check and filter out avatar & non-pertinent images.
'''
images = []
posts = []
b... |
26e28a10807d2ce858ea947366f0600c4a78ad2a | HKassem7/PYTHON | /homework4b_hamzakassem.py | 732 | 4.09375 | 4 | # Homework04B hamza kassem
# Uses a for intVariable in [ ] loop
# Uses a for intVariable in range() loop
sales1 = int(input("Enter today's sales for Store 1: "))
sales2 = int(input("Enter today's sales for Store 2: "))
sales3 = int(input("Enter today's sales for Store 3: "))
sales4 = int(input("Enter today's sales for... |
1a0ea2220bf86a1390f7b769d51aa1081aae8ba0 | lukerucks/ProjectEulerSolutions | /p071.py | 348 | 3.734375 | 4 | from fractions import Fraction
def p071():
result = Fraction('3/7')
to_subtract = 0
delta = 0.1**8
while result == Fraction('3/7'):
to_subtract += delta
new_fraction = Fraction('3/7') - Fraction(to_subtract)
result = new_fraction.limit_denominator(max_denominator=1000000)
r... |
da42da4d902573f1514066d61972a474cfdb69b0 | giselemanuel/programming-challenges | /100DaysOfDays/Dia02/ex07.py | 348 | 3.96875 | 4 | """
Exercício Python 7:
Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
"""
print("-" * 40)
print(f'{"Calcula média":^40}')
print("-" * 40)
nota1 = float(input("Insira a primeira nota: "))
nota2 = float(input("Insira a segunda nota: "))
media = (nota1 + nota2) / 2
print(f"Sua ... |
dc8e567933041ac6b1dd524541fe920630d98c40 | epetrel/python | /04-entrada-salida/main.py | 72 | 3.765625 | 4 | nombre = input("¿Cúal es tu nombre?")
print (f"Tu nombre es {nombre}") |
6432d888236a7135cabf693a34936eb85b7b7907 | Vivston/-Coffee_Machine | /Coffe_Machine.py | 4,435 | 4.15625 | 4 | class CoffeMachine:
money = 550
water = 400
milk = 540
coffe_beans = 120
disposable_cups = 9
def main(self):
while True:
action = self.input_text("Write action (buy, fill, take, remaining, exit):")
if action == "exit":
break
... |
49d89b4541d7e3dff41580448378849c01c90faa | AdMoR/sozy-face-embedding | /databricks_jobs/jobs/utils/face_processing.py | 2,256 | 3.609375 | 4 | import face_recognition
import os
import wget
def extract_face_emb(path):
"""
Given an image, we can find multiple faces
Each face will generate one 128-sized embedding
To go back to a format spark understand, we need to transform np array into lists
:param path: path of the image
:return: L... |
877b24a953b80fcbd67eb57dbce9429c39130178 | PravinSelva5/LeetCode_Grind | /Stacks & Queues/ValidParenthesis.py | 1,235 | 3.96875 | 4 | '''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
---------
RESULTS
---------
Time Complexity: O(N)
Sp... |
5babc6cba8faeed0cc696b00e2bf665acc1ee8ad | ktandon91/DataStructures | /6. Random/random1.py | 878 | 3.796875 | 4 | from copy import deepcopy
def get_variables():
dic1 = {
'a':1,
'b':2,
}
return deepcopy(dic1)
a=get_variables()
b=get_variables()
b.update({'c':3})
print(a,b)
# from copy import deepcopy
#
#
# a = False
#
# if a :
# print("a")
#
# if not a:
# print("not")
# def function2(a):
# ... |
accb2508bbd2183e5db4c4ae86cd92e81c85d9b6 | jeanmizero/SWDV-610 | /WEEK-5/selection_sort.py | 698 | 4.40625 | 4 | def selection_sort(list_value):
for i in range(0, len(list_value) - 1):
# Find the minimum value from list by using linear search
minimum_value = i
# Find the new smallest value
for j in range(i + 1, len(list_value)):
if list_value[j] < minimum_value: # use ascending ord... |
95147102f65fe967b97e1108b56c51dced51232d | bretonne/workbook | /src/Chapter2/ex35.py | 980 | 3.90625 | 4 | # Exercise 35: Dog Years
# (22 Lines)
# It is commonly said that one human year is equivalent to 7 dog years. However this
# simple conversion fails to recognize that dogs reach adulthood in approximately two
# years. As a result, some people believe that it is better to count each of the first two
# human years as 10.... |
9873d20e649d580ec5ee50820c2293cb1f71916c | DanielSantin1/Phyton-1--semestre | /buscar sequencial.py | 456 | 3.75 | 4 | def busca_sequencial(v,chave):
p=0
while(p<len(v)):
if(chave==v[p]):
return(p)
p=p+1
return(-1)
vetor=[0]*10
for i in range(10):
vetor[i]=int(input('Digite valor: '))
valor=int(input('Digite o valor a ser procurado no vetor: '))
posicao=busca_sequencial(vetor,valor)
... |
d51ce96aa0e56368c2268e6f4396ea013257f04c | abhimanyupandey10/python | /ask.py | 515 | 3.875 | 4 |
print('LET ME ASK YOU SOME QUESTIONS!')
x = str(input('Q1) What is the thing that is without hairs and has 3 sons? : '))
if x == 'fan':
print('Great!'),
else:
print('Opps, try again!')
k = str(input('Q2) 3 + 3 = ? (unlogical) : '))
if k == '8':
print('Great!')
else:
print('Opps, try again!')
l = ... |
27b043ec38e59f23471d8d6f186c368a8162f37a | DikranHachikyan/python-20201012 | /ex13.py | 325 | 3.796875 | 4 | def main():
num = int(input('num='))
m = 0
# (condition)? true-expr:false-expr класически формат
# true-expr (condition)? false-expr Python
m = num if num > 0 else num ** 2
# if num > 0:
# m = num
# else:
# m = num ** 2
print(f'm = {m}')
main() |
0facec0d97edb13bcb6d4a448e8f4a7f2b8792eb | MAX70709/CSCircles | /Auto-Decryption.py | 2,393 | 3.71875 | 4 | value = []
goodList = []
S = 0
#Adds the message into a temporary list and checks for alphabeticals or spaces
def caesarCode(code):
tempList = []
for letter in code:
tempList.append(letter)
return goodList[value.index(goodness(tempList))]
#Determines value of each message.
def goodness(... |
8cd6b74830f8f0387e803eac68a8abc25aad95cf | kcpedrosa/Python-exercises | /aula21c.py | 672 | 3.765625 | 4 | cores = {'fverde':'\033[42m',
'fciano':'\033[46m',
'limpa':'\033[m'}
def fatorial(n=1):
f = 1
for c in range(n, 0 ,-1):
f = f * c
return f
def par(n=0):
if n % 2 ==0:
return True
else:
return False
n = int(input('Digite um valor para n: '))
print(f'O fat... |
2fd64411e2c190033d1dfd020c67590ea190d51b | kachnu/my_script | /python_project/e1_sdh.py | 2,837 | 3.75 | 4 | #!/usr/bin/python3
error_message = '''
!!!!!!!!
Введены неверные данные!
help - для получения справки
exit - для выхода
!!!!!!!!
'''
help_text='''
********
Номер потока Е1 - целое число от 1 до 63,
Адрес в структуре STM - a.b.c, где a,b,c - цифры (1<=a<=3, 1<=b<=7, 1<=c<=3)
или x.a.b.c, где x - номер STM-1 (1<=x<=4)
... |
988c1f1eea7e6dd755bc3b86dc2a1b07ea1f79d5 | peinanteng/leetcode | /mergeKSortedList.py | 2,233 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
dummy = preNode = ListNode(0)
preNode.next = None
self.heap = []
self.MAX = 2 ** 31
... |
a44e2c52213613b09cf183d3d4271f21a41bcf28 | LABETE/Python1_Homework | /final.py | 6,857 | 4.1875 | 4 | #!/usr/local/bin/python3
""" Program for extract information of a document txt"""
import sys
exit_options_lst = ["Yes","No"]
menu_lst = ["Size of the word and number of words(1: 20)","Word and number of times that it is displayed(and: 15)","Words that are from the same size(3: and, the)","Exit from menu selection"]
t... |
cd8599a995182c6edc63630cb473b561b816276d | BrandaoDeSerra/python | /Exercicio IA/python Init/condicoes.py | 542 | 4.09375 | 4 | idade = input("Qual sua idade : ")
try:
val = int(idade)
print("A idade digitada foi: ", val)
except ValueError:
print("Digite uma idade!")
exit()
idade = val
if idade >= 18:
print("Maior Idade")
else:
print("Menor")
# 3 condições
if idade > 18:
print("Maior que 18")
elif idade < 18:
... |
84833042706180216fc90a6b0b3b558c292c148e | Netekss/CipherProgram | /cipher/decode.py | 2,349 | 4.3125 | 4 | def decode_cipher(string, key):
"""Function to decode given string. Decoding is composed by following steps:
1. Check length of key, decode true value of a key and split giver string by odd and even index.
1.1 Skip first two characters
1.2 Get correct order
1.3 Get shifts... |
c1caed743cb543fcf828af1693f064ba0f9614f1 | dyegosl11/Aprendendo-Python | /Módulo 1/split_join.py | 609 | 3.921875 | 4 | frase = 'Olá, bem-vindo a este treinamento!'
print(frase.split())
print(frase.split(','))
print(frase.split('-'))
nomes = 'jhonatan, rafael, carol, amanda,jefferson'
print(nomes.split())
print(nomes.split(','))
hashtags = '#music #guitar #gamer #coder #python'
print(hashtags.split())
print(hashtags.split('#'))
print(... |
533df361fc463a475b67711ce47cab29f889ea56 | saurify/A2OJ-Ladder-13 | /22_petya_strings.py | 180 | 3.703125 | 4 | def main():
a=input().lower()
b=input().lower()
if a>b:
print(1)
return 0
if a==b:
print(0)
return 0
if a<b:
print(-1)
return 0
if __name__ == '__main__':
main()
|
7bb1bc5bc21f5ec5bb71269eb6074a3ce362880a | matthewzung/IntegrationProjectPycharm | /activity 10.py | 142 | 3.9375 | 4 | height = int(input("Enter height: "))
for row in range(1, height+1):
for column in range(row):
print(row, end=" ")
print() |
e0ac51ed369a469d7513777c180112291c12cbda | aronhr/SC-T-111-PROG-Aron-Hrafnsson | /Hlutaprof 1/7. Meðaltal margra talna.py | 246 | 4.125 | 4 | u = ""
arr = []
while u != "n":
number = float(input("Please enter a real number: "))
arr.append(number)
u = input("Do you wish to enter another number (y=yes): ")
m = sum(arr) / len(arr)
print("Average of all numbers: " + str(m))
|
9515353c3a34edc87722a4103a766aaa37799028 | prabhushrikant/Python-DataStructures- | /Arrays/search_in_rotated_sorted_array.py | 2,971 | 3.8125 | 4 |
# this solution is good for repeated as well as non repeating numbers in the list.
# time complexity average case O(lg(n)) , worst case O(n)
# Note: all these while loops are required for skipping the same numbers, because it's not changing condition
class Solution(object):
def search(self, nums, target):
... |
507e2d1c40f6f8c2af3e034aa063c7a932ece45e | grantgasser/curriculum-database | /Project/queries.py | 8,315 | 3.71875 | 4 | #############################################################################################
# Authors: Zee Dugar, Grant Gasser, Jackson O'Donnell
#
# Purpose: Host the functions to obtain data from the database for the user
##########################################################################################... |
dce8597dec302d65a9f5b338cede7263316776ab | udaypandey/BubblyCode | /Python/findMean.py | 149 | 3.703125 | 4 | def aMean(list):
sum = 0
for item in list:
sum += item
return sum / len(list)
list2 = [2, 65, 23]
print(aMean(list2))
|
1b92475b8c59bcc30b85863a82a7d02262049ef1 | hunj/hpc-pi | /digits/Monte-Carlo/pi_monte-carlo.py | 956 | 3.953125 | 4 | # Monte-Carlo Method for approximation of Pi
import random
from decimal import *
import datetime, time
import sys
import math
def is_in_unit_circle(x,y):
return(x**2 + y**2) <= 1
def main():
iterations, num_hit, calculated_pi = Decimal(0), Decimal(0), Decimal(0)
#expect number of corr... |
0ff03b17377b69ffbb3b2d817d1f8ed68de7bbef | ysachinj99/PythonFile | /Covid.py | 525 | 3.53125 | 4 | import covid
import matplotlib.pyplot as plt
covid=covid.Covid()
name=input("enter the country name::")
virusdata=covid.get_status_by_country_name(name)
remove=['id','country','latitude','longitude','last_update']
for i in remove:
virusdata.pop(i)
all=virusdata.pop('confirmed')
id=list(virusdata.keys())
... |
3e9ba4fff30053623a7cabc15f242214cb2d2399 | jO-Osko/adventofcode | /2015/problems/day13.py | 5,752 | 3.578125 | 4 | DAY = 9
from collections import defaultdict as dd
from functools import lru_cache
def solve(data, wall=False):
graph = dd(dict)
for line in data:
fro, would, gain, change, *_ , to = line.split()
change = ([-1,1][gain=="gain"]) * int(change)
to = to.strip(".")
graph[fro... |
18732f0176ea68e2e4a7bc22bb090e3636594f2a | Zakir887/Python1 | /string/12udalit_kazhd_3.py | 210 | 3.828125 | 4 | # Дана строка. Удалите из нее все символы, чьи индексы делятся на 3.
s = input()
n = ''
for x in range(len(s)):
if x % 3 != 0:
n += s[x]
print(n)
|
81710e346e5d1a6aab47a772286c229582eb2b36 | sashaobucina/interview_prep | /python/medium/top_k_frequent_words.py | 1,029 | 4.09375 | 4 | import heapq
from typing import List
from collections import Counter
def top_k_frequent(words: List[str], k: int) -> List[str]:
"""
# 692: Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same fre... |
4f431d5eded3b45f5b774f1ce39b4b429144248a | alfonsomartinez/sets | /main.py | 2,058 | 4.125 | 4 | # File split into two parts. Part 1 will import a file and streamline the input to give
# a variable N, and an array of all the cards given. Also, this part will assert that the
# conditions from the specification are true. Part 2 takes the N and array of cards from part 1
# and will print the number of SETs, Disjoint... |
3eddf24f7b411acb8e1d50231792e7f1a759486d | cavandervoort/Project-Euler-001-to-100 | /Euler_005.py | 415 | 3.78125 | 4 | # Problem 5
# Smallest multiple
divisors = []
for num in range(1,21):
tempNum = num
for divisor in divisors:
if tempNum % divisor == 0:
tempNum /= divisor
if tempNum > 1:
divisors.append(int(tempNum))
# print(f'new divisor ({int(temp_num)}, from {num}) added to divisors... |
a24ea4de086f7a7852142ff11d5ff0fc11e0c1c8 | MatiasToniolopy/numpy_list_cmp_python | /profundizacion_1.py | 1,644 | 4.3125 | 4 | # Numpy [Python]
# Ejercicios de profundización
# Autor: Inove Coding School
# Version: 2.0
# NOTA:
# Estos ejercicios son de mayor dificultad que los de clase y práctica.
# Están pensados para aquellos con conocimientos previo o que dispongan
# de mucho más tiempo para abordar estos temas por su cuenta.
# Requiere ... |
476702f035b3f30aaefb6d1f1685023de6aca3a4 | hep-gc/cloudscheduler | /lib/html_tables_to_dictionary.py | 4,541 | 3.5625 | 4 | """
Extract HTML tables from a URL, file, or string and return a dictionary:
{
'table1': {
'heads': [ 'col_hdg1', 'col_hdg2', ... 'col_hdgN' ],
'rows': [
[ 'col_val1', 'col_val2', ... 'col_valN' ],
[ 'col_val1', 'col_val2', ... 'col_valN' ],
... |
b8912ed39f52e17d674e8af6fad7aadb2c814b07 | andy-pi/berrybot | /motor.py | 1,520 | 3.53125 | 4 | #!/usr/bin/python
# Title: intermediate function for using UKonline2000's motorHat
# Author: AndyPi
from Raspi_MotorHAT import Raspi_MotorHAT, Raspi_DCMotor
import time
import atexit
# create a default object, no changes to I2C address or frequency
mh = Raspi_MotorHAT(addr=0x6f)
# recommended for auto-... |
ba0dc96f9bcf9cdf04043cc7f1dc35cf87b97b16 | idnbso/cs_study | /data_structures/tree/heap/min_binary_heap.py | 2,936 | 3.5 | 4 | class MinBinaryHeap:
def __init__(self, value=None):
self.values = []
if value:
self.values.append(value)
def insert(self, value):
self.values.append(value)
self.bubble_up(len(self.values) - 1)
return self
def bubble_up(self, index):
cur_index = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.