blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5c6326a007fd51f2f6fff8887d81dd04c8e1dffc | shuklak13/Python-Notes | /Types_and_Collections/collections.py | 1,328 | 3.78125 | 4 | from collections import *
# Deque: O(1) insertion and removal on both ends
d = deque()
d.append(1); d.pop() # Stack
d.append(1); d.popleft() # Queue
d.rotate(2) # equivalent to d.appendLeft(d.pop()) twice
# Counter: a dictionary optimized for counting
# functions: "most_common", "update" (add), and "sub... |
dccc6ad62cc6bbd375f5624d39836121e7a87dca | robertokondo8496/TechStartPro | /show.py | 432 | 3.53125 | 4 | # this module is responsible for showing data into database
import pymongo
def show(collection, filter = {}):
"""This function is responsible for showing data into database"""
# creates a connection with database
result = []
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
db = myclient... |
d5da1debe4f7d456f2bf6073e2f25f04cfa5c8b3 | da-ferreira/uri-online-judge | /uri/2712.py | 539 | 4.125 | 4 |
casos = int(input())
for i in range(casos):
placa = input()
if (len(placa) != 8) or (not placa[0:3].isupper()) or (not placa[-4:].isnumeric()) or (placa[3] != '-'):
print('FAILURE')
else:
if placa[-1] in '12':
print('MONDAY')
elif placa[-1] in '34':
... |
9141f80eed4510952ce41f8d7fea5b7fe8b19dc8 | tessied/snake_game | /food.py | 467 | 3.59375 | 4 | # A module to generate the food particle for the snake
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.pu()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color("green")
self.speed... |
31b0bfd5d9fb52113a793f2f1451dfd31434f0fe | CiyoMa/leetcode | /wordBreakII.py | 2,945 | 3.890625 | 4 | """
Given a string s and a dictionary of words dict, add spaces
in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
"""
class S... |
d2881fc5dea40152215737d221aa73c05536d3a2 | iverson52000/DataStructure_Algorithm | /LeetCode/0054. Spiral Matrix.py | 959 | 3.796875 | 4 | """
54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix
in spiral order.
"""
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]: return []
res = []
left = 0; right = len(matrix[0]... |
69d7bffa72327e10478cd24cfec340419696eae0 | guolinbuaa/LeetCode | /test.py | 536 | 3.5625 | 4 | s='()'
d = {'(': ')', '{': '}', '[': ']'}
l = ''
if len(s) == 1 or len(s) == 0:
print('false')
# return False
for i in range(len(s)):
print(s[i])
if s[i] in d:
l += d[s[i]]
print(l)
if i == len(s) - 1:
print('false')
# return False
elif s[i] == l[len(l... |
621fc4e5914911597e7571f0637fb00801b247ff | JSebastianP96/intermediate-python-course | /dice_roller.py | 929 | 3.953125 | 4 | import random
def main():
player_n = int(input('Numero de jugadores'))
dice_rolls = int(input('How many dice would you like to roll?'))
dice_size = int(input('How many sides are the dice?'))
dice_sum = []
player_name = []
mayor = 0
player_win = 0
for p in range (0,player_n):
player_name.append("")
... |
d28f4b0dfec576d8074cb284934066c1ce108f00 | shma1664/Project | /Python/runoob/src/com/shma/循环语句/while循环.py | 1,288 | 3.640625 | 4 | '''
Created on 2015年10月15日
@author: admin
'''
from pip._vendor.distlib.compat import raw_input
num = 10;
print("start while");
while(num > 0) :
print("This is count : ", num);
num -= 1;
print("end while");
#使用break,continue
i = -1;
while(i < 10) :
i += 1;
if(i % 2 == 0) :
... |
3758f03aface24522eb22ff4392e41957ab63a39 | jalelegenda/bulkuploadtest | /utility.py | 4,465 | 3.875 | 4 | """Utility classes the app uses"""
import random
import string
import sys
from params import Command, PLATES_NUM
class UserInputValidator:
"""Provides utility functions validating user input for numeric menus"""
def __init__(self, user_options, dbc):
self.__user_options = user_options
self.__... |
9457fa3e812bea651efb39c272dd332fadfdd6af | devDeejay/Python | /Programs/XOR is Mad.py | 232 | 3.5 | 4 | def calculate(x):
n = x
count = 0
for A in range(1,n):
if((A ^ n) == (A + n)):
count += 1
print(count)
testCases = int(input())
for i in range(0,testCases):
X = int(input())
calculate(X)
|
e0e1cbef14504d96d067b872208fb13412a18adb | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4165/codes/1637_2703.py | 124 | 3.640625 | 4 | idade = int(input("idade "))
if(idade > 18):
mensagem = "eleitor"
else:
mensagem = "nao_eleitor"
print(mensagem.lower()) |
114aeb9908f7f700da4e9612d481ce0bcccbfa7b | maximekabel/Advent-Of-Code-2020 | /Day-2/password-philosophy.py | 911 | 3.578125 | 4 | file = open("Day-2/input.txt")
input = file.read().splitlines()
correct_passw1 = 0
correct_passw2 = 0
test_list = []
for i in input:
lower_lim = int(i.split("-", 1)[0])
upper_lim = int(i.split("-")[1].split(" ")[0])
char = i.split("-")[1].split(" ")[1].rstrip(":")
password = i.split(":")[1].strip()
... |
dcde90103b611d9d14154674b860563d23e16acd | Anurag9697/Pythoncodes | /PythonMagicBall-08-01.py | 539 | 3.984375 | 4 | #import modules
import sys,random
#initial variables
#loop variable
#list of responses variable
l=["IT IS CERTAIN","YOU MAY RELY ON IT","AS I SEE IT, YES","OUTLOOK LOOKS GOOD","MOST LIKELY","IT IS DECIDELY SO","WITHOUT A DOUBT","YES, DEFINETLY"
]
#while loop
while True:
#write the code that will recieve... |
32e4e1a50f11f559355436e138cdb00575d0a107 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4153/codes/1638_651.py | 194 | 3.796875 | 4 | h = float(input("Insira kbuvgdhybvkuhd: "))
s = input("uhygdsvcjuysedt: (M/F)").upper()
if(s == "M"):
pi = (72.7 * h) - 58
print(round(pi,2))
else:
pi = (62.1 * h) - 44.7
print(round(pi,2)) |
23a130c56e2291d14b1327f5b7f61734f5e94f61 | Riceyo/QA-Consulting-ONS-Academy | /PySpark/task_calc_student_grades.py | 2,346 | 3.53125 | 4 | from pyspark import SparkConf, SparkContext
def SplitPer(x):
split = x.split(",")
return split[0], split[1], split[2]
def SplitRes(x):
split = x.split(",")
return split[0], split[2] # only keep the student regno (key) and their marks data so we can use the reducebykey method to sum their marks
def Add(x, y):
re... |
8887190f541121b0c758939aca9d4775109e893d | bbsathyaa/PYTHON | /task 8.py | 2,521 | 3.65625 | 4 | #errorTypes:Syntax error,Logical error(Exceptions)
#Syntax error
a,b=1,2
print(a ,b) #SyntaxError: invalid syntax
#Exceptions
print(dir(locals()['__builtins__'])) #list of built-in exceptions
l1=list(range(5))
l1[7] # IndexError: l... |
13ff8935e7aefcad532e884926075ce45a23bc29 | wuxm669/python | /obj.py | 1,450 | 3.9375 | 4 | # a = 1
# b = 1
# c = a+b
# d =a-b
# def add(x,y):
# print(x+y)
# return x+y
# add(1,2)
#声明一个employee类
class Employee:
pay_raist_amount=1.2
#创建一个构造器
def __init__(self,first,last,pay,domin="ersoft.cn"):
self.first =first
self.last =last
self.pay =pay
self.email =las... |
c18a779f4c7ededcb962aa05ae6d3844d12b00de | bakker4444/Algorithms | /Python/leetcode_433_minimum_genetic_mutation.py | 2,819 | 4.21875 | 4 | ## 433. Minimum Genetic Mutation
#
# A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
#
# Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
#
# For examp... |
ec92211831b5ec2c00b887bab22f3f731b9aae37 | Hellofafar/Leetcode | /Medium/542.py | 2,384 | 3.625 | 4 | # ------------------------------
# 542. 01 Matrix
#
# Description:
# Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
#
# The distance between two adjacent cells is 1.
#
# Example 1:
# Input:
# [[0,0,0],
# [0,1,0],
# [0,0,0]]
#
# Output:
# [[0,0,0],
# [0,1,0],
# [0,0,0]]
#
... |
fff02c80f0497eb4a410ce5f2d6ccaee03fc1f28 | boguslaw-chojecki/codewars | /Valid_Parentheses.py | 293 | 3.9375 | 4 | def valid_parentheses(s):
# your code here
check = 0
for i in s:
if i == "(":
check += 1
elif i == ")":
check -= 1
if check < 0:
return False
if check == 0:
return True
else:
return False
|
6c40be694bd4d8b84d5b9e693ecf57319842a78a | cifpfbmoll/practica-5-python-miquel21-hub | /P5EJ5.py | 219 | 3.8125 | 4 | #PRÁCTICA 5 EJERCICIO 5
anchura=int(input("Introduce la anchura del rectangulo\n"))
altura=int(input("Introduce la altura\n"))
for i in range(altura):
for x in range(anchura):
print("*", end="")
print() |
974e4f1a4f6418226ed4a52ded4b07f48504d34f | pongpisut261/CP3-Pongpisut-Choothong | /Exercise5_1_Pongpisut_C.py | 327 | 3.8125 | 4 | input1 = int(input('ระบุตัวเลข :'))
input2 = int(input('ระบุตัวเลข :'))
print(input1 , '+' , input2 , '=' , input1 + input2 )
print(input1 , '-' , input2 , '=' , input1 - input2 )
print(input1 , '*' , input2 , '=' , input1 * input2 )
print(input1 , '/' , input2 , '=' , input1 / input2 ) |
bba2d3f52fb5be3efdf0fb5de4d06a17c53b15fa | RandhirJunior/python_programming | /python-programming-workshop/python_cookbook/src/1/removing_duplicates_from_a_sequence_while_maintaining_order/example.py | 401 | 4.03125 | 4 |
# example.py
# Remove duplicate entries from a sequence while keeping order
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
print(seen) # this is an additional line i added to print the "seen" variable
if __name__ == '__ma... |
f7bef01bc72af50b1ccbe2f3cbc9304265598628 | glissader/Python | /ДЗ Урок 2/main3.py | 608 | 3.96875 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить, к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и dict.
n = 0
while n not in range(1, 13):
n = int(input("Введите месяц от 1 до 12 ").strip())
seasons = {"зима": [12, 1, 2], "весна": [3, 4, 5], "... |
b45b91f1beeece214d96dea903fde88a56f849c8 | robdunn220/THPython | /OOPython/filledlist.py | 309 | 3.59375 | 4 | import copy
class FilledList(list):
def __init__(self, count, value, *args, **kwargs):
super().__init__()
for _ in range(count):
self.append(copy.copy(value))
def __len__(self):
return super(FilledList, self).__len__() + 2
fl = FilledList(3, 2)
print(len(fl))
|
8e942ac0ff9186ffbf352022906ae3a3d159a60b | 7ard1grad3/Snake-turtle-py | /food.py | 316 | 3.796875 | 4 | from turtle import Turtle
from random import randint
class Food:
def __init__(self):
self.food = Turtle("turtle")
self.food.reset()
self.food.goto((randint(-280, 280), randint(-280, 280)))
self.food.color("green")
def pos(self):
return self.food.pos()
|
f2779d883436c15d1ce65f43a13e820bd4da04f7 | KWilliamson90/Term_Project_Ken_Williamson | /Search.py | 1,441 | 3.578125 | 4 | from Database import *
from Management import *
'''
Postcondition1: Connects to Job Database.
Postcondition2: Prompts user to enter a job number.
Postcondition3: Displays list of potential jobs for the user to select.
Postcondition4: Prompts user to select correct job.
Postcondition5: Passes job number to Main... |
11d27007037e7d01d7848ebac6f10fbfce463df0 | Svensson17/python-project-lvl1 | /brain_games/games/brain_even.py | 249 | 3.609375 | 4 | import random
RULE = "Answer \"yes\" if the number is even, otherwise answer \"no\"."
def get_question_and_answer():
question = random.randint(0, 100)
right_answer = "yes" if question % 2 == 0 else "no"
return question, right_answer
|
84d20d185a5fe4993cf5ba868e9dbf71742b85e3 | CodeWithShamim/python-t-code | /Read and write a file/Read and Write a file.py | 999 | 3.875 | 4 | '''
# r for readble, w for writable, r+ for read/write, a for append.............
#use readable..
file = open("name.txt", "r")
#check vale true or false....................
s = file.readable()
print(s)
result = file.read()
print(result)
file.close()
#when use writable then remove all text file..
file = open("name.t... |
3fcdc6c0dfa2c49465527194a47f650f4b7fef58 | xistadi/Python-practice | /it academy/old homework/practice.py | 1,556 | 4.03125 | 4 | a = int(input("Введите число а: "))
b = int(input("Введите число b: "))
c = int(input("Введите число c: "))
#Вывести на экран 0, не если нет ни одного нуля - вывести: "Нет нулевых значений!!!" (без if)
print(a and b and c and "Нет нулевых значений!!!")
#Вывести первое ненулевое значение,но если введены все нули - выв... |
fb1b1e73c7d5311e36eb7f1fd8d2cddd9ad9fb7b | starmap0312/refactoring | /simplifying_conditional_expressions/introduce_null_object.py | 722 | 4.15625 | 4 | # - if you have repeated checks for a null value, then replace the null value with a null object
# - if one of your conditional cases is a null, use introduce null object
# before: use conditionals
class Customer(object):
# abstract class
def getPlan(self):
raise NotImplementedError
# client has a co... |
32c5e1c536f8612465b35801d5349b0765a4060e | rivelez65/Snake-Game_OOP-Turtle | /snake.py | 1,719 | 3.6875 | 4 | from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.snake_sections = []
self.snake_body()
self.head = self.snake_sections[0]
def snake_body(self):
for squa... |
007b7f38d0ef48be92a26362109b03c8aa2189f7 | JoaoBatistaJr/Cuso-Intensivo-de-Python-Projeto-Pygame-Aliens | /ship.py | 1,356 | 3.703125 | 4 | import pygame
class Ship:
"""Classe que controla a espaçonave."""
def __init__(self, ai_game):
"""Inicializa a espaçonave e a coloca na posição."""
self.screen = ai_game.screen
self.settings = ai_game.settings
self.screen_rect = ai_game.screen.get_rect()
# Carrega a ... |
e0646d5163bdc26d2b81d0b08b418267e09ab4ec | AlyoshaS/codes | /startingPoint/01-EstruturasCondicionais/exercicios_propostos/14.py | 2,561 | 4.09375 | 4 | """ 14 - Faça um programa que receba o valor do salário mínimo, o número de horas trabalhadas, o número de dependentes do funcionário e a quantidade de horas extras trabalhadas.
Calcule e mostre o salário a receber do funcionário de acordo com as regras a seguir:
O valor da hora trabalhada é igual a quinta parte d... |
3325622b2c9e2c6b874c59fd7b07d189ad4b60eb | pythonwithalex/Spring2015 | /week6/twitter/4_tweets_to_file.py | 608 | 3.59375 | 4 | # get a Twitter API key
# run this as 'python script.py > output.txt' to store the json data in a file
import tweepy
import json
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_toke... |
a87e543bf4f0eef77929a9d4299bfae4088131bf | MaxRaine/Max_Rain-_TE19D | /programmering/Blackjack/blackjack.py | 1,961 | 3.71875 | 4 | import kortlek
# behöver räkna ut värden på korten
def räknaPoäng(hand):
poäng = 0
for kort in hand:
if kort == "J" or kort == "Q" or kort == "K":
poäng += 10
elif kort == "A" and poäng < 11:
poäng += 11
elif kort == "A" and poäng >= 11:
poäng += 1
... |
4593f273aa303179b363399385c3fea5c43ab4c8 | JessRogeliana/Estudando_Python | /Python 1/Semana 3/fizzbuzz.py | 138 | 4.0625 | 4 | numero = int(input("Digita um número aê: "))
if ((numero % 5 == 0) and (numero % 3 == 0)):
print("FizzBuzz")
else:
print(numero) |
31c2affe0122aad341f05d9752c59c1186d113e0 | Jennysgithub/learn_python_the_hard_way | /working_with_files_1.py | 396 | 3.5625 | 4 | from sys import argv
file_name, from_file, to_file = argv
from_fh = open(from_file)
indata = from_fh.read()
username = raw_input("What is your name?")
to_fh = open(to_file, 'w')
line1 = "Hello {}, here is some text from another file: \n".format(username)
to_fh.write(line1)
to_fh.write(indata)
line2 = "\nGoodbye ... |
f2c892376027f13fb5b7e225ff62ad248d13779d | ArronHZG/algorithm-with-python | /leetcode/binarySearch/154_findMin.py | 1,802 | 3.984375 | 4 | import unittest
from typing import List
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
print(f"left {left} mid {mid} right {right}")
if nums[mid] > nums[right]:
... |
94a852760250df8fccadd14a7136a00cb902caff | wenima/data-structures | /src/binheap.py | 2,959 | 4 | 4 | """Implementation of the binheap data structure.
A binary heap is defined as a binary tree with two additional constraints:
Shape property: a binary heap is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not compl... |
71656850c1d3095179cb45175f1136fb4c503dca | ShuaiWang0410/LeetCode-2nd-Stage | /LeetCode-Stage2/Tricks/Problem_90.py | 970 | 3.609375 | 4 | '''
90. Subsets II
Deepin of Problem 78
这次的集合中元素有duplicate,但不能输出duplicate
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
'''
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = ... |
b2c590ef0417d15ffc7a69abe7914e264ab82803 | ynonp/python3-beginners | /18-datastructures-examples/ab.py | 1,067 | 3.703125 | 4 | import sys
DATAFILE = 'contacts.txt'
def load_datafile():
contacts = {}
try:
with open(DATAFILE, 'r') as f:
for line in f:
words = line.split()
name = words[0]
emails = words[1:]
contacts[name] = emails
exce... |
5f1843c3c7bd53852ab7459c22f459553d8e81d2 | hsclinical/leetcode | /Q03__/22_Coin_Change/Solution.py | 1,484 | 4.03125 | 4 | from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# similar to the question that use combination of substring to build a whole string
# use recursive
if amount == 0:
return 0
else:
coins.sort(reverse=True)
... |
b33d2e95dbc65d1ccc5c2bfecaa28408dc1192cb | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4444/codes/1679_1099.py | 217 | 3.921875 | 4 | area = int(input("Digite a área a ser pintada: "))
litros = area//3
if area % 3 > 0:
litros = litros + 1
latas = litros//18
if litros % 18 > 0:
latas = latas + 1
print("Você precisara de", latas, "latas.")
print(" |
4f9fe3c1b6ccdf7722b02c830ef9fd73c2103514 | paleolimbot/wss | /rras/rstools.py | 16,932 | 3.640625 | 4 |
import json
import random
MAX_ITERATIONS = 10000
def order_choices(choices):
"""Orders the choices used consistently every time"""
order = ["Yes", "No", "Always", "Frequently", "Occasionally", "Sometimes", "Never", "Above Compliance",
"Meets Compliance", "Less than Compliance"]
return list... |
231f6d19572a51af407faf5192d84d58051e02eb | SaeSimcheon/employee_or_farm | /Chapter3/4. 두 리스트 합치기/SH_cht3_4.py | 467 | 3.5 | 4 | import sys
sys.stdin = open("cht3_4_input.txt","rt")
n1 = int(input())
list1 = list(map(int,input().split()))
n2 = int(input())
list2 = list(map(int,input().split()))
list1.extend(list2)
list1.sort()
print(*list1)
# 중복을 없앨 필요도 없고 그냥 두 개 리스트 합칠 방법만 생각하면 됐었음.
# 1개 list를 확장하는 방법으로, 구체적으로 extend를 통하여 두 개 리스트를 하나로 만들어 ... |
e95db27d4c5ae8a3dfcfbe22a240e145e2b77f2c | Taha-Topac/LearningPython | /src/KullanıcıGirişi.py | 337 | 3.5625 | 4 | a1 = "taha"
a2 = 159753
a3=input("Adınızı girin:")
a4=int(input("Şifrenizi şifrenizi:"))
if ( a1==a3) and (a2==a4):
print("Giriş başarılı !!! ")
elif ( a1!=a3) and (a2==a4):
print("Kullamıcı adı yanlış !!! ")
elif ( a1==a3) and (a2!=a4):
print("Şifre hatalı !!!! ")
else:
print("Tekrar deneyin !!! ")
... |
102ead847cc85f2b6ce58bde8c56237d8467dc25 | AbdulMoizChishti/pythonpractice | /guessgame.py | 322 | 4.09375 | 4 | import random
num=0
print("Welcome to Guessing game")
rv = random.randint(1, 21)
for i in range(1,6):
num= int(input("Select number"))
if num<rv:
print("number is less than rv")
elif num>rv:
print("number is greater than rv")
else:
print("your ans is correct")
break
... |
e5bbb0316c486edf53e6447f97891e14b4e095eb | egrabs/DailyCodingProblem | /elyes/139_eg.py | 1,194 | 4 | 4 | # Given an iterator with methods next() and hasNext(), create a wrapper iterator,
# PeekableInterface, which also implements peek(). peek shows the next element that would be returned on next().
# Here is the interface:
# class PeekableInterface(object):
# def __init__(self, iterator):
# pass
# def p... |
265d5b8a99faeb93b29929b1d5bb7c0790fdb043 | secfordoc23/MyFirstRepository | /Assignment1/CelsiusToFahrenheitUtility.py | 731 | 4.0625 | 4 | """
Program: Celsius to Fahrenheit Utility
File: CelsiusToFahrenheitUtility.py
Author: Jason J. Welch
Date: 8/24/2019
Purpose: A utility to calculate the degrees Fahrenheit from entered degrees Celsius
"""
print('*******************************')
print(' Celsius to Fahrenheit Utility')
print('**********... |
a186e23db6e1be81781da4e3a8d5fd2ae4658865 | manojakumarpanda/This-is-first | /sequence/set and list and dict/uper_lower_diognal mat.py | 847 | 4 | 4 | #program to take a n*n matrics and print all the uper matrics and lower matrics and diogna matrics
m=int(input('Enter the number of row and collumn in to the matrixs::'))
mat=[]
i=0
while i<m:
mat.append([])
i+=1
for i in range(m):
for j in range(m):
ele=int(input('Enter a element for the matrxs mat... |
5a895f41f33695f6ea6909b40c034879c22df084 | zingelst/PiecesOfPy | /cmd/argparse_subparse.py | 2,263 | 4.0625 | 4 | # Example of using argparse with sub parsers, useful for
# building interfaces like that of the docker cli
import argparse
def sub1_cmd(args):
"""The command that gets called if user uses the sub1 command on the commandline"""
print("This is sub1")
print("You passed args:", str(args))
def sub2_cmd(args):... |
e112bf1c2729e0e4d808cf65ee06ce22f7f9b676 | topliceanu/learn | /python/algo/src/strassen_array_multiplication.py | 4,068 | 4.125 | 4 | # -*- coding: utf-8 -*-
def op (x, y, op = '+'):
""" Liniar operation over two square matrices.
Args:
x: array of size n*n
y: array of size n*n
op: str with operations to apply on two arrays, can be either + or -
Returns:
A 2D list resulting from applying op to each eleme... |
eaacea6bfecffef36dd39a7ac37780fac1f2eedd | maximusg/Python_Game | /highscore.py | 5,601 | 3.71875 | 4 | #CONSTANTS
MAX_ENTRIES = 20 #Change this to grow or shrink the high score list
class Scoreboard(object):
'''Linked List data structure that contains the High Score List for Day0.'''
class Entry(object):
'''Object representing a single entry within the overall Scoreboard class. Contains:
... |
15284701a1c10cae57f8a2bec7c809833db14f65 | MANC3636/2WeekPython | /4_string_ops.py | 836 | 3.9375 | 4 |
#let's create a string file
file="string_file.txt"
author="Bootsy Collins"
a=open(file, "w")
a.write(f"one nation under a groove, getting down just for the funk of it {author}")
a.close()
#----------2, now let's open it and read it
a=open(file, "r")
listing=[a.readline()]
print("nation" in listing[0])
print(listing[0... |
c83c80a5ae86d94eddaddfa6e6b6d1341a21d4b9 | hyeokjinson/algorithm | /ps프로젝트/DP/파도반 수열.py | 242 | 3.546875 | 4 | if __name__ == '__main__':
padovan=[0]*100
padovan[0:5]=1,1,1,2,2,3
t=int(input())
for i in range(6,100):
padovan[i]=padovan[i-1]+padovan[i-5]
for _ in range(t):
n=int(input())
print(padovan[n-1]) |
4be10d7a0d4dc5755fd74888086a855e79c34336 | ortizp978/Ortiz_P_RPS | /main.py | 1,214 | 4.34375 | 4 | from random import randint
# add player
playerLives = 5
computerLives = 5
# Save the player as a variable called player
# the value of player will be one of three choices to type (input)
player =input("chosse rock, paper or scissors: ")
print("player chose: " + player)
# an array is just a container. It bholds mul... |
1cd19dee209abe9fa959c87b9b38a65c9a02289a | nvasturino52/assignment-9.1 | /cars_pickups.py | 2,559 | 3.9375 | 4 | # CIS 245 Week 8 Car Assignment
class Vehicle:
def __init__(self):
#Initialize Vehicle Attributes
self.make = "make"
self.model = "model"
self.color = "color"
self.fuelType = "fuelType"
self.options = 0
self.optionsList = ["1: cruise control", "2: bluetooth"... |
9144364d0612ea74d32baa4c2d5caa2b793c430c | Ranjana151/python_programming_pratice | /reverse_word.py | 109 | 4.15625 | 4 | #word reversing
word=input("Enter the word")
for i in range(len(word)-1,-1,-1):
print(word[i],end=" ") |
d98ef73f1be22c4fcc58c3c2a537f9aacd66620c | demonlittledog/pythonproject | /newpython/t07同步条件和生产消费模型.py | 1,814 | 3.765625 | 4 | #生产者-消费者模型
import threading
import time
import random
#包子
class Baozi():
def __init__(self, count):
super(Baozi, self).__init__()
self.count = count
def add(self,x):
self.count += x
def sub(self,x):
self.count -= x
#以下为生产者和消费者,都继承了Thread类
#生产者
class Producer(threading.Thread):
def __init__(self, cond, fo... |
5a296025686b84c26d394ec6b261db3bea5ecf6a | madhav9691/python | /lcm_gcd.py | 324 | 4.03125 | 4 | def gcd(x,y):
while y>0:
x,y=y,x%y
return(x)
def lcm(a,b):
return(a*b)//gcd(a,b)
num1,num2=map(int,input("Enter two numbers seperated by\
space:").split())
print("GCD of given numbers= ",gcd(num1,num2))
print("LCM of given numbers= ",lcm(num1,num2))
... |
5b3e88f8a33a006395a893830a6f4ac88032542a | r0meroh/DataStructure_exercises | /game_score_statistics.py | 1,237 | 4.15625 | 4 | """
This program takes in a list of scores from the user. Processes the scores in order to do the following:
Get all the scores from user.
Calculate the lowest score.
Calculate the highest score.
Calculate the average(mean).
Calculate the standard Deviation.
"""
import statistics as stat
def us... |
3b3f692ec325251e5853a67d233441ab921112df | Akashic-Projects/akashic | /akashic/util/type_converter.py | 1,836 | 3.5625 | 4 |
def clips_to_py_type(ctype):
""" Converts CLIPS type to Python type
Parameters
----------
ctype : str
CLIPS type, possible values: "INTEGER", "FLOAT", "STRING"
and maybe "BOOLEAN"
Returns
-------
ptype: type
Coresponding python type
"""
ptype = None
... |
d3ca10fd201cc24daf6574a2a1c488813c0f8e58 | sremedios/AdventOfCode2016 | /day16.py | 1,006 | 3.640625 | 4 | puzzleInput = '00101000101111010'
diskSize = 35651584 # change to 272 for part 1
resultData = puzzleInput
while len(resultData) <= diskSize:
b = []
# reverse order of data in resultData and store in b
for i in range(len(resultData)):
b.append(resultData[-1-i])
# flip bits
b[i] = '... |
79129238e0d5eb7698e016b84fc3a5e3eb0761be | Disguised-Minstrel/Python4Everyone | /13 and before/average_conf.py | 496 | 3.65625 | 4 | fhand = None
while fhand == None:
file_name = input("Enter name of the file: ")
if file_name == "na na boo boo":
print("why?")
try:
fhand = open(file_name, 'r')
except:
print("Invalid filename.")
total = 0
count = 0
for line in fhand:
if line.startswith("X-DSPAM-Confidence... |
f13869f07f79eee6ba2953e736f9ed9a25b9bde7 | dmccoystephenson/Acronym-Maker | /acronymMaker.py | 258 | 4.09375 | 4 | originalString = raw_input("Enter what you want to make into an acronym: ")
list = originalString.split(" ")
acronym = ""
for x in list:
acronym = acronym + x[:1]
print "Your new acronym is %r" % acronym
raw_input("Press 'Enter' to exit the program.") |
a68294d4e47c146198d47ff12a80304fd7e69a24 | MavineRakiro/Reverse_array | /reverse_sentence.py | 502 | 4.3125 | 4 | """Write a function reverseSentence(A) that takes in an array of characters
, A, and reverses the the "words" (not individual characters).
Example:
A = ['t','h','i','s',' ','i','s',' ','g','o','o','d']
reverseSentence(A) A // ['g','o','o','d',' ','i','s',' ','t','h','i','s']
"""
A = ['t', 'h', 'i', 's', ' '... |
fafa1a461e52f9e51d666c2ee759b8c6eca41d1c | 2648226350/Python_learn | /pych-four/4_10to4_12.py | 797 | 4.15625 | 4 | #4-10
ninjas = ["uzumaki naruto","uchiha sasuke","haruno sakura","hatake kakashi",
"nara shikamaru","sai","yamanaka lno","tsunade","yamato"]
print("The first three ninjas in the list are: ")
for ninja in ninjas[:3]:
print(ninja.title())
print("Three ninjas form the middle of the list are: ")
for ninja i... |
ff552b7f3935d4a6aa68443748cb2d8799edf766 | jtbishop/CS506-Fall2020 | /02-library/cs506/kmeans.py | 5,046 | 3.5625 | 4 | from collections import defaultdict
from math import inf
import random
import csv
def point_avg(points):
"""
Accepts a list of points, each with the same number of dimensions.
(points can have more dimensions than 2)
Returns a new point which is the center of all the points.
"""
summation... |
b0c02e9efa43d087e5eaf90f17d3d41ed3d7b3e9 | ashutoshEr/python-code | /basic program/greatest number.py | 219 | 4.1875 | 4 | a=int(input("Please Enter a Number : "))
if(a&1==1):
print("This Number is Odd")
else:
print("This Number is Even")
for i in range(1,101):
if i%3==0 or i%5==0:
continue
print(i) |
2f4a9a5bef04ddfc41f3f303a1c9aa4c4d040f54 | zyj16602159899/lemon_class | /class_1030/function_2.py | 1,482 | 3.609375 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
#@Author:zhuxiujie
#变量作用域
# a = 1 #全局变量
# def add(b):
# a =5 #局部变量
# print(a+b)
#
# add(10)
#全局变量和局部变量
#1.作用范围不一样 全局变量:模块里都能用;函数的局部变量只能用于函数
#2.当全局变量和局部变量同名且同时存在时,函数优先调用局部变量
#3.当局部变量没有时,就优先用全局变量
#4.global
#5.一般情况下,谨慎使用全局变量,优先使用局部变量
# def add(b):
# global a ... |
ce9f9c335952074c67a9961633fc186e0c2208c2 | Rakesh-vcs73/9229580 | /DAY_2_20_12_2020/Task_2_Mettl/4_NoOfPrimeInRange.py | 489 | 3.5625 | 4 | def NoOfPrimeInaRange(input1,input2):
count=0
if(input1==1):
input1+=1
for i in range(input1,input2+1):
flag=0
for j in range(2,(i//2)+1):
if(i%j==0):
flag=1
break
if(flag==0):
#print(i)
count+=1
... |
c156b4d25bd5896ee4f7feaf9cb35d067c7a741b | loust333/python-workspace | /branches.py | 188 | 3.65625 | 4 | humans = 20
dinosaurs = 30
fish = 35
if humans < dinosaurs:
print 'Wow humans less in number than dinosaurs'
elif humans < fish:
print 'More humans than fish'
else:
print 'Nothing'
|
c1c8cb6deb32e19378566ae76096a3dfab1dee73 | LYTXJY/python_full_stack | /Code/src/hellopython/第四章/4.2bool.py | 585 | 3.921875 | 4 | #bool()函数中:非零为True,得零为零
print(bool(0))
print(bool(4))
print(bool(-10))
print(bool("eqw"))
print(bool([1, 2, 3]))
print(bool((1, 2, 3)))
print(bool({1:24, 2:25}))
print("\n")
print(0 == False)
print(1 == True)
print("\n")
print(bool())
print(bool(""))
if -1:
print("-1也是真")
if "":
pri... |
9d38f6c315cb6292b0f3dd07239330ff7e9168d6 | adiboy6/python-practice | /string.py | 670 | 3.796875 | 4 | # add raw string instead of adding backslash(/)
print(r'C:\some\name')
# multi-line string literal can be achieved by using ("""...""") or ('''...''')
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
# String litera... |
4f7aa1ecaf3b11a65d1f7505151c3626b42d74de | hiranomo/dokpro | /3-21/stack.py | 525 | 3.90625 | 4 | class Stack:
def __init__(self):
self.items = []
def is_empy(self):
return not self.items
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(sel... |
b5969b528622cbf952e8d154b99a53f736b5f723 | rashigupta37/tic_tac_toe | /playerMinimax.py | 2,876 | 3.78125 | 4 | from random import randint, seed
#returns best move and best score if max is the player
def getMax(moves,bestScore,scores,bestMove):
#traverse all the moves in the board
for i in range(len(moves)):
#if curretnt score is better than the best score
if scores[i] > bestScor... |
c160ac7cd34eed5e497fd004b0e13e43fbd0db6d | ariscon/DataCamp_Files | /11-pandas-foundations/03-time-series-in-pandas/01-reading-and-slicing-times.py | 664 | 3.625 | 4 | '''
Reading and slicing times
For this exercise, we have read in the same data file using three different approaches:
df1 = pd.read_csv(filename)
df2 = pd.read_csv(filename, parse_dates=['Date'])
df3 = pd.read_csv(filename, index_col='Date', parse_dates=True)
Use the .head() and .info() methods in the IPython Shel... |
649e90039dd35d4c51f165886afcf07a0dfb470c | Oscar1305/Python | /Python/Repaso_Funciones.py | 218 | 3.59375 | 4 | x = 0
def calcularSuma(num1, num2, num3):
suma = num1 + num2 + num3
return suma
while x <= 10:
if calcularSuma(x, x, x) > 20:
break
print(calcularSuma(x, x, x))
x += 1
|
3b43484609397a1aa69cbce58c31371035ad4fb6 | rahularoradfs/euler | /solved/018.py | 2,117 | 3.6875 | 4 | # for this, you should work row-by-row
# there will be several possible ways to get to a number
# of these, only one way will have the maximum total
# store only that maximum total associated with it
# take the example four-row triangle provided
"""
3
7 4
2 4 6
8 5 9 3
"""
# go row by row:
# row 1: only one way ... |
6ef3f7e0f98bed39eba4866863bf1d894811ee3d | D00dGuy07/Minecraft-Coordinate-Tools | /PortalCalculator.py | 1,455 | 3.703125 | 4 | # Portal Calculator takes a file made in locations list and calculates those coordinates in the nether
# By D00dGuy07
import math
name = "Portal Calculator"
description = "Takes a save file made in Locations List and calculates those coordinates in the nether"
def getInfo():
return "{0} - {1}".format(... |
53e9897291cdb38546a8e06f5460f84e52c6ad08 | stcybrdgs/myPython-refresher | /learningPython/basicHTMLparser.py | 1,727 | 3.78125 | 4 | #
# Example file for parsing and processing HTML
#
# import the HTMLParser classs that Python provides
from html.parser import HTMLParser
metacount = 0
class MyHTMLParser(HTMLParser):
# override default implementation of handle_comment
# that's already in the HTML parser class
def handle_comment(self, data):
... |
ad6f765839cb90b1149d702a79f7c1623251d63c | TylerBrock/books | /Learning Python/ch24/formats.py | 466 | 4.125 | 4 | """
Various specialized string display formatting utilities.
Test me with canned self-test or command line arguments.
"""
def commas(N):
"""
format positive integer-like N for display with
commas between digit groupings: xxx,yyy,zzz
"""
digits = str(N)
assert(digits.isdigit())
result = ''
... |
45c3b3ae5842ca22a79124ffa52dc5eab8e38782 | PatrickFang05/PythonToGit | /Homework/turtle_race.py | 940 | 4.125 | 4 | import turtle
import random
numTurtles = int(turtle.numinput('race', 'How many turtles?'))
colors = ['red', 'blue', 'green', 'purple', 'black', 'magenta', 'cyan', 'brown']
turtle.screensize(2000, 2000)
turtles = []
# Create each turtle object and push them to the turtles list
for i in range(numTurtles):
t = turt... |
a882494642f1c36c99e925844c731ec1bba7e416 | yulaimusin/zadachki-na-pythone | /Программочки/palindrome.py | 1,059 | 4.0625 | 4 | """
Программа palindrome.py запрашивает и получает у пользователя число или слово, а затем выводит:
True — если число является палиндромом, или
False — если таковым не является.
Палиндром (https://ru.wikipedia.org/wiki/Палиндром) — одинаково читающееся в обоих направлениях слово, число или фраза.
Например, 8228, A... |
1e9280a0348b92f744031daf29de03db309de10e | dheerucr9/Gase-Search-Engine | /stack.py | 507 | 3.90625 | 4 | class stack:
def __init__(self):
self.s=[]
def isempty(self):
return len(self.s)==0
def push(self,a):
self.s.append(a)
def pop(self):
if self.isempty():
print("Stack is empty")
else:
return self.s.pop()
def top(self):
... |
a81743ac6e33cf9d26cdec0679f3e0f27b488f31 | BhavaSuryaVamsiSrireddy/guvi | /wordpuzzle.py | 1,031 | 3.75 | 4 | import random
sc=0
def puzzle(l,sc):
le1=len(l)-1
i1=random.randint(0,le1)
k=list(l[i1])
le2=len(k)-1
ri=[]
for i in range(2):
rig=random.randint(0,le2)
if rig not in ri:
ri.append(rig)
for i in range(len(k)):
if i in ri:
k[i]='*'
print(''.... |
e1fc4db3f6240ed63e6dfc44c3b89d8f93ca2921 | affinity96/2020PS-python | /Programmers/완전탐색/소수찾기.py | 593 | 3.796875 | 4 | import itertools
def isItSosu(number):
if number < 2 : return False
if number == 2 : return True
if number % 2 == 0 : return False
for i in range(3, number, 2) :
if number % i == 0 : return False
return True
def solution(numbers):
answer = 0
for length,_ in enumerate(numbers):... |
17e8c7a2ffb843d2405b22d77128de1a58f4a076 | Techbanerg/TB-learn-Python | /Exercises/prompting.py | 331 | 3.65625 | 4 | #!/usr/bin/python
def function1():
arg1 = input("\nNiger what's ur Name?\n")
if (arg1!=""):
arg2 = input("\nWhat's your age homie?\n")
print("\nSon of a bitch " + arg1 +" does not look like aged\n"+arg2)
else:
print("\nThis Ahole aint gotta name")
if __name__ == "__main__":
funct... |
25837b59993dfab08722726f5d723f16b422c448 | tied/DevArtifacts | /master/Challenges-master/Challenges-master/level-1/calculateDistance/calculate_distance.py | 679 | 3.5625 | 4 | import sys
import math
import ast
def main(input_file):
output = []
with open(input_file, 'r') as data:
for line in data:
print get_distance(line.strip())
def get_distance(coordinates):
coordinates = list(ast.literal_eval(coordinates.replace(')',... |
399fc64f6e8d7d79c57f3c278873cef9195becc2 | rodrigo129/JuegoBulletHell | /juego/JEFE.py | 4,505 | 3.71875 | 4 | # -*- coding: latin-1 -*-
"""plantilla de objeto python"""
from Armas import ArmaEstandarApuntada
class Jefe1 :
# recordar siempre declarar self en una funcion de objeto
def __init__ ( self , pSpawn , velocidad , alturaAtaque ,info
) :
"""
:type info: list
"""
... |
4dc905bcc09344f838ab7b5c383603892c178bd5 | horia94ro/python_fdm_15ianuarie | /day_2_part_2.py | 3,602 | 4.03125 | 4 | nume_utilizator = input("Introduceti userul: ")
print(len(nume_utilizator))
nume_utilizator = nume_utilizator.strip(str(9))
print(len(nume_utilizator))
sir = input("Introduceti sirul: ")
if len(sir) > 1:
# rez = sir[:2] + sir[len(sir) - 2 : len(sir)]
rez = sir[:2] + sir[-2:]
print(rez)
else:
... |
b80b274f95b407ace8bf851914a89206d9dd1b5c | lizyang95/leetcode | /leetcode4/searchMatrix.py | 1,099 | 3.5 | 4 |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
if len(matrix[0]) == 0:
return False
while(len(matrix)>=1)... |
e8511a009295fdc16b92455e1483f1668606ff39 | smtamh/oop_python_ex | /student_result/2019/01_number_baseball/baseball [2-3 양A].py | 12,239 | 3.75 | 4 | """
숫자 야구 게임 2019.09.23
made by 230* 양**
"""
import random
NUM_DIGITS = 3 # 정답 숫자의 자릿수를 나타내는 상수
NUM_CHANCES = 10 # 문제를 맞추는 전체 기회의 수를 나타내는 상수
ANSWER = "" # 정답 숫자를 문자열로 저장하는 상수
def start_notification():
"""
숫자 야구 게임을 시작하기 전에 실행되는 함수로서, 플레이어의 요구에 따라 숫자 야구의 규칙에 대해 설명하는 함수.
:return: 없음.
... |
57bdcfba21060783b32ef00d361f945576997114 | marcoisgood/Leetcode | /0518. Coin Change 2.py | 1,007 | 3.9375 | 4 | """
518. Coin Change 2
Medium
1513
54
Add to List
Share
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Example 1:
Input: amount = 5, ... |
02829770542910b2814c5391e33c4c4c6fa4874f | Dominique-Cardon/digital-culture | /5_software/demo.py | 342 | 3.921875 | 4 | database = open("first-names.txt")
all_names = database.read().split('\n')
def checkIfName(username):
for name in all_names:
if username == name:
print("Welcome, " + username + "!")
return
print("Error occured!")
username = input("what is your first name? ")
checkIfName(userna... |
0bef130fc89b654d9730fbc9a1b26e3530ee7352 | charlesfranciscodev/codingame | /community-puzzles/horse-racing-hyperduals/horse_racing_hyperduals.py | 468 | 3.671875 | 4 | import math
def distance(vector1, vector2):
return abs(vector2[0] - vector1[0]) + abs(vector2[1] - vector1[1])
if __name__ == "__main__":
n = int(input())
vectors = []
for i in range(n):
vector = tuple(map(int, input().split()))
vectors.append(vector)
min_d = math.inf
for i ... |
b917218609e8b2318d8a627bfd389c63dec9bca7 | eledoro/FreeCodeCamp-Scientific-Computing-with-Python-Assignments | /polygon-area-calculator/shape_calculator.py | 1,529 | 3.78125 | 4 | # ====== class Rectangle ======
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def get_perimeter(self):
perimeter = 2 * self.width + 2 * self.height
return perimeter
def set_height(self, height):
self.height = height
... |
87d3e10b4f5b297bf12b1f64facfd934ef1bb13f | seeinger/OpenCollegePythonWebProject | /session3_20200111/session3-practice1.py | 433 | 3.703125 | 4 | # 코딩해보기
def calc(type, a, b):
if type == '더하기':
return a+b
elif type == '빼기':
return a-b
elif type == '나누기':
return a/b
elif type == '곱하기':
return a*b
a = input('계산정보를 입력하세요: ')
input_list = a.split()
type = input_list[0]
a = int(input_list[1])
b = int(input_list[2])
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.