blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
68fe1d060b90470a7fe9d5518c40a3fb3edc964e | flowersw/ultimate-pig | /roomba_simulation.py | 1,687 | 3.640625 | 4 | __author__ = 'willflowers'
class Room:
def __init__(self, length, width):
self.length = length
self.width = width
self.cleaned_squares = set()
@property
def area(self):
return self.length*self.width
def clean_percentage(Self):
return 0.0
def clean(self, ... |
91e3c8fa4db2bdf3810daee883766a1d1fb839bb | babakpst/Learning | /python/101_l_Advanced_Python/7_comprehensions/dictionary_comprehension.py | 710 | 3.953125 | 4 |
# Babak Poursartip
# 12/27/2019
# Advanced python: linkedin
# Dictionary comprehension
def main():
print(" Code starts ...")
print()
CTemps = [0, 10, 15, 20, 25, 30, 35, 100]
# use a comprehension to build a dictionary
tempDict = {t: (t*9/5)+32 for t in CTemps}
tempDict2 = {t: (t*9/5)+32 for t in CTemp... |
1337dff15f2bf105b885fb6b9a74d0e599b92281 | carnolio/task_1 | /isPrime.py | 448 | 4 | 4 |
isPrime = True
try:
test = int(input("Введите проверяемое число: "))
except Exception:
print('Пожалуйста введите натуральное число')
else:
for i in range(2,(test//2)+1,1):
if test % i == 0:
isPrime = False
if isPrime:
print(f"{test} - Простое число")
else:
... |
388f33983178e817c18f3ee871a96c5a579891b2 | LawAbidingPenguin/blackjack-game | /blackjack.py | 8,268 | 3.703125 | 4 | import random
import time
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
'Nine':9, 'Ten':10, 'Jack':10,... |
6eeb74c84c33048f765e568fcd62f744b8e84e15 | ptallrights/python | /oldboy/operator1.py | 1,181 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__ = 'ptallrights'
"""
@version: python 2.7.11
@author: ptallrights
@license: my Licence
@software: PyCharm
@file: operator1.py
@time: 2016/7/28 11:57
"""
from __future__ import division
class Operator(object):
def __init__(self,x,y):
self.x = x
... |
e771851e315f2b521a92700b87a9b65e34420fff | LeonGustavo/exercicios_curso_em_video | /desafio25.py | 173 | 3.953125 | 4 | nome = input("Escreva um nome")
if "SILVA" in nome.upper():
print("Existe silva no nome que você digitou")
else: print("Não existe silva no nome que você digitou")
|
14d0aaf1066aa227b0e5f9de490a5f08abb48844 | ktamilara/sss | /63.py | 96 | 3.59375 | 4 | val=input()
li=[]
for i in value:
if i not in li:
li.append(i)
else:
break
print(len(li))
|
107f1a0fabe21c5828deeb759b1a1b2c831ce8a4 | HansHuller/Python-Course | /ex084 LISTA COMPOSTA recebe lista e mostra mais pesados e leves.py | 1,743 | 3.953125 | 4 | '''
Faça um programa que leia o nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre:
Quantas pessoas foram cadastradas
Uma listagem com as pessoas mais pesadas (mais pesado e mais leve são definidos de acordo com dados recebidos)
Uma listagem com as pessoas mais leves
'''
lpessoas = []
pessoa =... |
f19a404dbb29a33f1fda125746760216f83dd24a | georgevarghese8815/DataScience---DataQuest | /SQL-Beginner/SQL Summary Statistics-181.py | 2,595 | 4.1875 | 4 | ## 1. Counting in Python ##
import sqlite3 as s
conn = s.connect("factbook.db")
query = "Select * from facts;"
facts = conn.cursor().execute(query).fetchall()
print(facts)
facts_count = len(facts)
## 2. Counting in SQL ##
conn = sqlite3.connect("factbook.db")
query = "Select count(birth_rate) from facts;"
data = con... |
7b534e2c09b1ecfdead3db8c8cd871344dc9517b | catalin-enache/gists | /challenges/is_matched/is_matched.py | 616 | 3.765625 | 4 |
def is_matched(seq):
matches = {
'{': '}',
'[': ']',
'(': ')'
}
chars = matches.keys() | matches.values()
stack = []
for c in seq:
if c not in chars:
continue
if c in matches:
stack.append(c)
else:
if len(stack) == ... |
d6da03eb271bfb9aa2809fb0cd583eef5080305c | paduck210/python-basic-practice | /Study/practice/0226.py | 404 | 3.78125 | 4 | #int = integer 정수
#str = character string 문자열
#아래대로 진행하면 n1, n2는 문자열임
n1 = input ('Enter first integer: ')
n2 = input ('Enger second integer:')
print (n1 + n2)
#문자열>정수전환이 필요
#문자 str / 정수 integer
print ("정수변화 int함수 사용")
n1 = int (input ('Enter first integer: '))
n2 = int (input ('Enger second integer:'))
print (n1 + ... |
f64ac79f357a808999118a8ec2e69d193b16cb1a | pawarspeaks/Hacktoberfest-2021 | /Python/calender.py | 188 | 4.1875 | 4 | # Write a python program to print the calender of a given mont and year
import calendar
y = int(input("Input the year:"))
m = int(input("Input the month:"))
print(calendar.month(y,m))
|
ca87f6bc28927a918d250662cfc08378d78491a7 | baerashid/Algorithms_Python_Geekbrains | /lesson5/ans/task1.py | 2,322 | 4.0625 | 4 | """Пользователь вводит данные о количестве предприятий, их наименования и прибыль за четыре квартала
для каждого предприятия. Программа должна определить среднюю прибыль (за год для всех предприятий)
и отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего."""
from collections import name... |
373dcd36281ac060b7b2a1461d88cdb055f9355b | aquibjamal/hackerrank_solutions | /mean_var_std.py | 338 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 02:21:26 2019
@author: aquib
"""
import numpy
numpy.set_printoptions(legacy='1.13')
N,M=map(int, input().split())
x=numpy.array([input().split() for i in range(N)], int)
mean=numpy.mean(x,1)
var=numpy.var(x,0)
std=numpy.std(x)
print(mean)
print... |
010680cbb2436ed4b6927a46cf2835598a392c4f | rachel6854/Python-Projects | /python_functions/exercise1.py | 144 | 4 | 4 | def longest_string(string1, string2):
return string1 if len(string1) >= len(string2) else string2
print(longest_string("hello","world"))
|
495fa820b06ab7a402a1ff813c62897271597eb5 | cvlk/KodlamaEgzersizleri | /Temel veri yapıları ve Objeler/kök bulma.py | 361 | 3.640625 | 4 | a = int(input("a değerini giriniz: "))
b= int(input("b değeriniz giriniz: "))
c= int(input("c değerini giriniz: "))
delta = b**2 - 4* a* c
x1 = (-b - delta**0.5) / (2 * a)
x2 = (-b + delta**0.5) / (2 * a)
"""print( "Birinci kök: {}\nİkinci kök: {}".format([x1],[x2])) //aslında aynı şey"""
print( "Birinci kök: {}\nİ... |
f32b6af01758a4c9e9b3f7dadd8d2ceae0268920 | 15929134544/wangwang | /py千峰/day1函数/func04.py | 2,554 | 4.5 | 4 | # """练习"""
# 1.
#
#
# def func(a, *args):
# print(a, args)
#
#
# # 调用
# func(2, 3, 4, 5) # 2 (3,4,5)
#
# func(2, [1, 2, 3, 4]) # 2 ([1,2,3,4],)
# # !!!不管是字符还是数字还是列表,都会被当作一个元素传进元组里面
#
# func(2, 3, [1, 2, 3, 4, 5]) # 2 (3,[1,2,3,4,5])
#
# func(5, 6, (4, 5, 7), 9) # !!! 5 (6,(4,5,7),9)
# 2.
#
#
# def func(a, b=10,... |
a591c6d09cad0148efe11cb65a2c45f7da1eee06 | Mandar1993/Assignment3 | /3.1.py | 281 | 3.828125 | 4 | #Problem Statement 1:
# Write a Python Program to implement your own myreduce() function which works exactly like Python's built-in function reduce()
#Solution :
def myreduce(l):
s = 0
for i in l:
s = s + i
return s
j=myreduce([1,2,3,4,])
print(j)
#Output:10
|
a730e1c3bd40bccabefad591a88852624b275af3 | taylor-jesse/MovieFundraiser | /01_notblank.py | 323 | 4 | 4 | # not blank function
def not_blank(question):
valid = False
while not valid:
response = input(question)
while response != "":
return response
else:
print("This can't be blank please enter a name")
# ***** Main routine ****
name = not_blank("What is your name? "... |
a463a51ec93d45838b3507ce3147218dfbb87932 | 70monk70/Algorithms-and-data-structures-in-Python | /Homework_2/task_9.py | 725 | 3.8125 | 4 | # Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр.
# Вывести на экран это число и сумму его цифр.
seq = input('Введиие последовательность натуральных чисел через пробел: ').split(' ')
sum_seq = []
for i in seq:
summ = 0
for j in i:
summ += int(j)
sum_seq.append(summ)
p... |
4e61ab9d2c4a4e02061795262b6ade5b0444820a | mhsNSnair/My-Work | /ICS3U/Unit 6/Nsnai1_Forest.py | 14,135 | 4.0625 | 4 | """
course: ICS3U
filename: Nsnai1_Forest
date: 05/22/20
name: Nicholas Snair
description: Go through a Magical forest and see what fun things await.
"""
#Introduction to the forest and what to do
print('Welcome to the Super Happy Magic Forest, where everybody enjoys picnics, fun, and dancing all year round. \n... |
279910ee969e9c02caeaebb2fcf532aa03717912 | EdwardERF/platzi_python_basico | /curso_python/tuples_program/repeated_char.py | 1,289 | 3.84375 | 4 | def first_not_repeating_char(char_sequence):
seen_letters = {}
for idx, letter in enumerate(char_sequence):
if letter not in seen_letters:
seen_letters[letter] = (idx, 1)
else:
seen_letters[letter] = (seen_letters[letter][0], seen_letters[letter][1] + 1)
final_lette... |
05d6229c9816355d0d814f89b93cad895e885ef8 | MassiveNoobie/AI-Poetry | /List-Comprehensions-v2.py | 7,195 | 4.625 | 5 | #The Most Comprehensive Python List Comprehensions Tutorial, Currently
#By Tyler Garrett
#
#Automate generating a list of values using python 2.X - List comprehensions 101
# If you are new, eager to learn quickly, want to learn without having to code, need lots of examples...
# Looking for a lot of sample code, th... |
c430ef2cc2dcc20494136394a7eb3e38ed5271eb | niceNASA/Python-Foundation-Suda | /04_历年复试真题/2021_四道编程题/26239_3.py | 314 | 3.578125 | 4 |
#查找某一个数后面离它最近的比他大的数,如果没有就是none
#[1,3,5] [3,5,none]
#[7,3,5] [none,5,none]
def find_next(L):
a=[None]*len(L)
for index,i in enumerate(L):
for j in L[index+1:]:
if j>i:
a[index]=j
break
return a
|
8de78b297005e2bdc058c29503fb0f2f88c65807 | asariakevin/timetable-comparison-app | /main.py | 2,758 | 3.8125 | 4 | from timetable import TimeTable
timetable1 = TimeTable()
timetable2 = TimeTable()
timetable1.monday = ["7 to 12" , "13 to 15", "16 to 18"]
timetable2.monday = ["8 to 10" , "14 to 16" , "17 to 18"]
NUMBER_OF_HOURS = 11
hour_taken_array = []
# initialize hour_taken_array to zeros
for one_hour_period in range(NUMBER_O... |
2dd723f076dfddef7c574074a39f9ac7b3d83f9b | cs-richardson/presidential-eligibility-4-4-5-albs1010 | /Presidential Eligibility.py | 948 | 4.34375 | 4 | #Albert
'''
this function asks for age, citizen, and residency. If the age is atleast 35,
the person is an American citizen, and years of residency is atleast 14, the
person is elgible to run for president. If these requirements are not met, there
would be text indicating what the person is missing.
'''
def president(... |
4a8003580ab78e92076f050ec6703a73bae33b1c | GanpatiRathia/ML | /deep_learning/deep_learning.py | 3,108 | 3.890625 | 4 | # deep learning / artifical neural network by 2blam
# import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# import dataset
dataset = pd.read_csv("Churn_Modelling.csv")
X = dataset.iloc[:, 3:13].values #column index 3 - 12
y = dataset.iloc[:, 13].values #Exited? 1 ... |
fd4f85df667b95a078948284de6e43b8516a5f57 | HelloImKevo/PyUdemySpaceInvaders | /src/actor.py | 2,322 | 3.796875 | 4 | from __future__ import annotations
import pygame
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
# Workaround for Circular Type Hinting Circular Dependencies
if TYPE_CHECKING:
from world import World
# TODO: Investigate a way to remove the circular dependency on World.
class Actor(ABC):
... |
133df5209c2cca8967f35c3d9902e021b7f3902b | crusaderg/Euler-Project | /quiz5.py | 1,427 | 3.859375 | 4 |
#-----------------------------------------------
def foo1():
val = 739024 * 2520
small_Multiple = 739024 * 2520
lst_Factor = list(range(11,21))
while(True):
isFound = True
if (val % lst_Factor[-1]) != 0:
if (val % lst_Factor[-1]) != 0:
val = val - (val % lst... |
8a0a35d76f6dd1f0ae45f2d9836eb38f9160fa96 | bmstu-iu9/qd-python-tracer | /task_1_square_equal.py | 394 | 3.5625 | 4 | from math import *
def square_equal(a, b, c):
if a != 0:
D = b*b - 4*a*c
if D > 0:
x1 = (-b - sqrt(D)) / (2*a)
x2 = (-b + sqrt(D)) / (2*a)
return [x1, x2]
elif D == 0:
return [-b / (2*a)]
else:
return []
else:
i... |
272c7c07b70485646c7e75f96581dab51c4f7013 | JungLaw/Python_scripts | /Import_Web(Flat file).py | 2,244 | 3.8125 | 4 | """
(1) Import/Download an online flatfile in Python
Task: import a file from the web, save it locally and load it into a DataFrame
"""
# Import a function called urlretrieve from the request subpackage of the urllib package,
from urllib.request import urlretrieve
# Assign the relevant URL as a string to the v... |
b896f866cf3f3afb91236fec5d9427555a2a88c8 | mcow7j/Random-Python | /merge_sort.py | 1,446 | 4.1875 | 4 | """ Module contains 2 functions:
merge: used by mergesort
mergesort: recursive implementation of merge sort algorithm
Running this module will run mergesort with a random sequence
of 8 integers
"""
def merge(L,R):
"""Merge 2 sorted lists provided as input
into a single sorted list
"""
M = []... |
e47ccbdd17f5e1d8770dd2a736c440c4b1017a79 | czs108/LeetCode-Solutions | /Easy/136. Single Number/solution (2).py | 627 | 3.546875 | 4 | # 136. Single Number
# Runtime: 88 ms, faster than 64.02% of Python3 online submissions for Single Number.
# Memory Usage: 16.2 MB, less than 6.56% of Python3 online submissions for Single Number.
from collections import defaultdict
class Solution:
# Hash Table
def singleNumber(self, nums: list[int]) -> in... |
f794ae5a1ff293457b8f3ad30e2f9f137e8ac258 | ZainQasmi/LeetCode-Fun | /Amazon/quora1.py | 2,435 | 3.921875 | 4 | class Node:
def __init__(self, next=None, prev=None, data=None):
self.next = next # reference to next node in DLL
self.prev = prev # reference to previous node in DLL
self.data = data
# Adding a node at the front of the list
def push(self, new_data):
# 1 & 2: Allocate the Nod... |
c2176ba49b0c1dfe757a640c29a7be1c8156a91f | Xerazade/Coding-for-Beginners-Using-Python | /Dare you enter Castle Dragonsnax.py | 728 | 4.0625 | 4 | print ("You are in a dark room in a mysterious castle.")
print ("In front of you are three doors. You must choose one.")
playerChoice = input("Choose, 1, 2 or 3...")
if playerChoice == "1":
print ("You find a room full of treasure. You're rich!")
print ("GAME OVER, YOU WIN!")
elif playerChoice == "2":
... |
c7058c2bd27bd7d0d8260f2e640c4896550cb07e | a-camarillo/record-collection | /util/time_funcs.py | 1,933 | 4.03125 | 4 | '''
This file will be for all time related functions used for this project
'''
class TimeValueError(Exception):
'''Exception raised if illegal time value is passed
Attributes:
time_value -- time value which caused the error
message -- explanation of the TimeValueError
'''
... |
a3e5d004045438ecad1308845c95f816f7fb1eec | Garvit-Kamboj/Maze-Player-pygame | /models/score.py | 1,291 | 4.28125 | 4 | class Score:
""" Simple class to represent a score in a game """
def __init__(self, name, score):
""" Initializes private attributes
Args:
name (str): name of the player (cannot be empty)
score (int): score of the player (cannot be negative)
Raises:
... |
096957d8ffa51cfc10f514021b1f07da43ebea1c | potato16/pythonl | /python101/datastructures.py | 1,953 | 3.65625 | 4 | import sys
if(sys.argv[1]=='0'):
#list
listhang=['con chuot','may tinh', 'loa']
print('I have {} items to purchase.'.format(len(listhang)))
print('These items are:', end=' ')
for item in listhang:
print(item, end=' ')
print('\nI also have to buy VGA.')
listhang.append('VGA DONGKING')
print('My list hang is ... |
0d6b953101006576a0a753f828384ed40a7837e3 | vishrutjai/Codechef | /STRPALIN.py | 583 | 3.609375 | 4 | a = input()
for x in range(a):
str1 = raw_input()
str2 = raw_input()
if str1 == str2:
print 'Yes'
elif len(str1) == 1 and len(str2) == 1:
if str1 == str2:
print 'Yes'
else:
print 'No'
else:
flag = 0
for x in range(1,len(str1)+1):
... |
1ba033176025daa29b881384c9a98bf9e26c160b | voidiker66/hacktx2018 | /airlines/airport.py | 2,297 | 3.5625 | 4 | import enum
import requests
# Possible airport codes for current project
class AIRPORTS(enum.Enum):
DFW = 1
LAX = 2
MIA = 3
PHL = 4
ORD = 5
JFK = 6
LHR = 7
HKG = 8
def get_airport(code):
"""get airport information from airport code.
Parameter
---------
code
typ... |
1845233b0e17e6e0be3800c00263c11678283cd2 | peterzzshi/Digit-Recognition | /model.py | 13,483 | 3.6875 | 4 | import tensorflow as tf
import time
from datetime import datetime
from tensorflow.examples.tutorials.mnist import input_data
import os
import sys
def onelayer(X, Y):
"""
Create a Tensorflow model for logistic regression (i.e. single layer NN)
:param X: The input placeholder for images from the MNIST dat... |
c2a41967bd65cd57b8da1cf73350a25f15c4f984 | panda5566/PythonExercise | /string.py | 93 | 3.578125 | 4 | s1="52"
s2="is good"
s = s1+ s2
print(s)
print(len(s))
print(s2 + s1)
print(len(s2+s1)) |
fb682de2520e248d49d8ae3f4252e0c58c693d59 | Levik451/Python_2021 | /homework_01/task_06.py | 1,198 | 4.375 | 4 | '''
Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
Программа должна принимать значения пара... |
11d5d68b5f98add814c4384bc7f4d990885bcc79 | muhammad-Usman85/gradient-Descent | /gradientDescent.py | 3,556 | 4.03125 | 4 | import matplotlib.pyplot as plt
from numpy import *
def plot_line_on_graph(theta, points):
# draws a line and plots scatter points on a graph given theta values and points
x_plots = []
y_plots = []
for i in range(0, len(points)):
x = points[i, 0]
y = theta[0] * x + theta[1]
... |
8615db8ab398b4cc040187bd21a221b23a3bca03 | salihsarp/CTE_RaspberryPi | /Projects/6_IoT_Camera/IoT_Camera.py | 3,742 | 3.59375 | 4 | """
Raspberry Pi Camera Setup
● Step 1:- First, turn off your Pi and then locate the camera
connector, a long black connector between the HDMI port and
Audio Jack. The connector is marked with ‘CAMERA’ on the
board.
● Step 2:- To connect camera pull up on the ends of the black
plastic connector and insert camera cable ... |
45641a1790e863a510fcfdc433a052eb9fae8764 | BonHyuckKoo/TIL | /test2.py | 413 | 3.671875 | 4 | M = int(input())
N = int(input())
numlist = [i for i in range(M,N+1)]
result = []
def isprime(x):
if x <=1 :
return False
i = 2
while i * i <= x:
if x % i == 0:
return False
i += 1
return True
for i in numlist:
if isprime(i):
result.append(i)
if len(r... |
3390f605bbd03de20b9a653332ddc4909680e6e7 | robalan11/projectchoice | /Files/leveledit/PriorityQueue.py | 854 | 3.75 | 4 | import pygame
class PriorityQueue():
def __init__(self):
self.queue=[]
def put(self, item):
data, priority = item
self._insort_right((priority, data))
def get(self):
if len(self.queue) == 0:
return None
return self.queue.pop(0)[1]
... |
c18d8075093f0aa0359a3e3feb9ae6f7eb6563af | EdgarMartirosyann/Python | /homework2_13.py | 598 | 3.796875 | 4 | #1
def strings(str1, str2):
return sorted(list(str1)) == sorted(list(str2))
print(strings("abvdj", "vjdab"))
#2
def search(matrix, number):
for i in range(len(matrix)):
j = 0
k = len(matrix) - 1
while j <= k:
mid = (j + k) // 2
if matrix[i][mid] < number:
... |
4cc07aeb862d0e6f0e905f31ac786bca715deb97 | hanmaslah/andela_bootcamp | /NotesApplication.py | 2,535 | 4.1875 | 4 | class NotesApplication():
"""
This class creates an application for holding notes and categorises
them according to the author and gives them an index. You can also
search for a word in the notes list.
"""
def __init__(self,author):
self.author=author
self.notes_list=[]
def ... |
025521438dcfeae07064bcf874b27ce86e1ea44a | ChihaoFeng/Leetcode | /55. Jump Game.py | 489 | 3.640625 | 4 | class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
further = 0
for i, num in enumerate(nums):
if i > further:
return False
further = max(further, i + num)
return True
"""
Like a... |
6eb61c2ab5f2b14ae8ee21ab3c19c710662a91f9 | alan199912/Pyhton | /Ejercicios 2/07-listaNombres.py | 660 | 3.8125 | 4 | # Definir una lista con un conjunto de nombres, imprimir la cantidad de comienzan con la letra a.
# También se puede hacer elegir al usuario la letra a buscar. (Un poco mas emocionante)
cantidad = int(input("Ingrese la cantidad de la lista: "))
nombres = []
contador = 0
letra = ""
for i in range(cantidad... |
165a2506f9680e79467c800a28408cf31096ddff | Simon2591990/week_01_functions_lab_2 | /start_code/task_list.py | 2,043 | 3.984375 | 4 | tasks = [
{ "description": "Wash Dishes", "completed": False, "time_taken": 10 },
{ "description": "Clean Windows", "completed": False, "time_taken": 15 },
{ "description": "Make Dinner", "completed": True, "time_taken": 30 },
{ "description": "Feed Cat", "completed": False, "time_taken": 5 },
{ "de... |
8731277c098ec9175379b51a82e4ea91e2525cb4 | varunmaurya/python | /basic/conditions.py | 383 | 4.125 | 4 | # '=' is used to assign the value to a variable whereas '==' is used to compare the value of two variable
# comparision results in boolean represented as True and False ( case sensitive)
# in python every object or variable has a boolean representation eg 0,{},[],None represent 'False'
x = 'abc'
print('abc' == x)
if... |
08e2b0f92151a7d51acf002bc93b1cae5fd95869 | Y-Kuro-u/RSA_python | /rsa_encription.py | 2,055 | 3.546875 | 4 | import random
import secrets
import math
class RSA:
def __init__(self):
self.P,self.Q = self.find_2prime()
self.N = self.P * self.Q
self.L = ((self.P - 1) *(self.Q - 1) ) / math.gcd(self.P-1, self.Q-1)
def judge_prime(self,n):
if n == 2: return True
if n == 1 or n & 1 =... |
f51d62b12d398e158afb800bc072d8caf893bb5f | ngongochoan/PrefixCodeTree | /prefixcodetree.py | 296 | 3.671875 | 4 | class Employee:
def __init__(self, name, id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("Vinh", 101)
emp2 = Employee("Trung", 102)
emp1.display();
emp2.display(); |
f2cadfced9ddd1402825d202af082e83badce116 | pencilEraser/SoftwareDesign | /hw2/fermat.py | 847 | 4.09375 | 4 | #written by neal s. no license.
def check_fermat(a, b, c, n):
if (n > 2):
if ( (a**n + b**n) == c**n ):
print "Holy smokes, Fermat was wrong!"
else:
print "No, that doesn't work."
else:
print "Error! n must be greater than 2"
def m... |
f9a04bb8662dccbfa6a5e3ddc435a44cd9108a48 | Devlious/Multithreading | /Python/abonosWaitNotify.py | 2,193 | 3.640625 | 4 | import threading
import time
import random
class self(threading.Thread):
acctBalance = 50
abono = True
def __init__(self, name, acctBalance):
threading.Thread.__init__(self)
self.name = name
self.acctBalance = acctBalance
def run(self):
# Call the static method
... |
bed2594a9d3c7a61156f4b9995f48881a0b5eafe | samantaProspero/python_guanabara | /mundo2/aula012condicoesAninhadas.py | 8,530 | 4.09375 | 4 | '''
if:
bloco
elif:
bloco
else:
bloco
'''
# 10 desafios 036 em diante:
# 036 Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
# O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
# Calcule o valor da prestação mensal,
# sabend... |
b31913897a53faa4f207149b6f2d080fa50d9a00 | milenatteixeira/cc1612-exercicios | /exercicios/lab 3.2/ex1.py | 528 | 4.125 | 4 |
# coding: utf-8
# In[1]:
letra = input("digite uma letra qualquer: ")
if letra == "a":
print("letra %s: vogal" % letra)
elif letra == "e":
print("letra %s: vogal" % letra)
elif letra == "i":
print("letra %s: vogal" % letra)
elif letra == "o":
print("letra %s: vogal" % letra)
elif letra == "u":
... |
60b5076b550ac0c8534b2ebd9411e2c085abdd00 | mcarifio/interview.py | /interview/repcount.py | 1,802 | 4.125 | 4 | #!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug(logger.level)
import sys
import re
def render_count(count:int)->str:
'''
Used to render the repetition count in the generated string.
If the count is 1, return the empty strin... |
77fa40ea43cd329a5b092edbe1d6c9c53538fe02 | afcarl/pymc-networkx-bdst | /maze.py | 4,441 | 3.78125 | 4 | """ Script to generate mazes using grid graphs and spanning trees"""
import numpy as np
import matplotlib.pyplot as plt
import pymc as mc
import networkx as nx
import random
import models
import views
def random_maze(n=25):
G = models.my_grid_graph([n,n])
T = nx.minimum_spanning_tree(G)
P = models.my_pa... |
264e9468222fb4e6674410eab08618580ed09cf4 | jeonghaejun/01.python | /ch08/ex04_리스트 관리 삽입.py | 743 | 4.1875 | 4 | # .append(값)
# 리스트의 끝에 값을 추가
# .insert(위치, 값)
# 지정한 위치에 값을 삽입
nums = [1, 2, 3, 4]
nums.append(5)
print(nums) # [1, 2, 3, 4, 5]
nums.insert(2, 99)
print(nums) # [1, 2, 99, 3, 4, 5]
nums = [1, 2, 3, 4]
nums[2:2] = [90, 91, 92] # 새로운 값들을 삽입 슬라이싱
print(nums) # [1, 2, 90, 91, 92, 3, 4]
nums = [1, 2, 3, 4]
nums[2] ... |
fa53ab85ffd835978ac90b1ece02ce1443af2928 | DemondLove/Python-Programming | /CodeFights/29. chessBoardCellColor.py | 1,078 | 4.03125 | 4 | '''
Given two cells on the standard chess board, determine whether they have the same color or not.
Example
For cell1 = "A1" and cell2 = "C3", the output should be
chessBoardCellColor(cell1, cell2) = true.
For cell1 = "A1" and cell2 = "H3", the output should be
chessBoardCellColor(cell1, cell2) = false.
Input/O... |
2f9d480e6d2c9e6375bf764d672f301df5240e28 | Bhavyasree95/Largest-and-smallest | /ex5_2.py | 488 | 4.21875 | 4 | largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
number = float(num)
except:
print('Invalid Input')
continue
if smallest == None:
smallest = number
if smallest>= number:
smallest =... |
22faef88a6fb1d8a8bfb688d1edbd4081979fd81 | sanjay2610/InnovationPython_Sanjay | /Python Assignments/Task4/Ques11.py | 545 | 4.25 | 4 | """
Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]
Hints: Use map() to generate a list.
Use filter() to filter elements of a list
Use lambda to define anonymous functions
"""
def square(num):
return num**2
def list_filt... |
a5f4515d8f7a9f13a415c4abd98a041b2c64c7cd | Vutsuak16/random_coding_questions | /array_pair_sum_nlgn.py | 455 | 3.640625 | 4 |
def array_pair(array , k):
if len(array) < 2:
return
array = sorted(array) #nlgn
left , right = 0 , len(array)-1
while left < right:
current_sum = array[left] + array[right]
if current_sum == k:
print(array[left] , array[right])
left += 1 #iterator movement
elif curr... |
08da36a95fe780cfbbaf571c418866caeeee9e3d | Manish-Roy/PythonMain01.py | /Armstrong strong and recursion numbers/AnyArmstrongNo.py | 283 | 3.765625 | 4 | n= int(input("Enter the number"))
sum=0
order=len(str(n))
num=n
while(n>0):
digit=n%10
sum+=digit**order
n=n//10
if(sum==num):
print(f'{num} is an Armstrong no.')
else:
print(f'{num} is not an Armstrong no.')
|
f523fd061eca3b88e95d814eb876f68d462628cb | ash/python-tut | /99.py | 343 | 3.765625 | 4 | print(4 is 4)
print(4 == 4)
print(4 is 5)
print(4 == 5)
x = 4
y = 4
print(x == y) # True
print(x is y) # True
a = []
b = []
print(a == b) # True
print(a is b) # False
c = a
print(a is c) # True
c.append(42)
print(a)
def f(a): # by reference
a[0] = 5
v = [1, 2, 3]
f(v)
print(v)
def g(x): # by value
x = ... |
c1fbb0fe55b65721b03e8902b740c91d2a1a71e2 | seanchen513/dcp | /dcp204 - given complete BT, count number of nodes faster than O(n).py | 5,428 | 4 | 4 | """
dcp#204
This problem was asked by Amazon.
Given a complete binary tree, count the number of nodes in faster than O(n) time. Recall that a complete binary tree has every level filled except the last, and the nodes in the last level are filled starting from the left.
"""
class Node():
def __init__(self, val, ... |
1e5b70b209edd69aafbefcebc50ec3fadb5923d4 | bshaner/gloomhaven-turn-tracker | /round_rect.py | 782 | 3.90625 | 4 | from PIL import Image, ImageDraw
def round_corner(radius, fill):
"""Draw a round corner"""
corner = Image.new('RGBA', (radius, radius), (0, 0, 0, 0))
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)
return corner
def create_rounded_rectangle_mask(s... |
da50608c72529e5f050ac04707331cc5cc3e0b70 | Uttam1982/PythonTutorial | /14-Python-Advance/06-python-regex/01-MetaCharacters/15-Grouping/03-Treating-a-Group-as-a-Unit.py | 2,462 | 3.828125 | 4 | #-------------------------------------------------------------------------------------------
# Treating a Group as a Unit
#-------------------------------------------------------------------------------------------
# A quantifier metacharacter that follows a group operates
# on the entire subexpression specified in th... |
53ee4ded376028e358906c6dfbebed6916e0a0aa | sunwenbo/python | /0.python基础/day08 绘图模块turtle.py | 1,702 | 3.953125 | 4 | """
是一个简单的绘图工具
提供一个小海龟,可以把它理解为一个机器人,只能听得懂有限的命令
绘图窗口的原点(0,0)在正中间,默认海龟的方向是右侧。
运动命令
forward(d) 向前移动d长度
backward(d) 向后移动d长度
right(d) 向右转动多少度
left(d) 向左转动多少度
goto(d) 移动到坐标为(x,y)位置
speed(speed) 笔画回执的速度[0,10] 越大越快
笔画控制命令
up() 笔画抬起,在移动的时候不会绘图
down() 笔画落下,在移动的时候会继续绘图
setheading(50) 改变海龟的朝向
pe... |
5167be5385572144c113939cc6474074c9e54089 | chuwilliamson/PYstar | /astar2017/_Examples/drawablenode.py | 3,472 | 3.8125 | 4 | '''drawable nodes '''
import pygame
class DrawableNode(object):
'''drawable node'''
def __init__(self, graphnode):
# astar vars
posx = graphnode.value[0]
posy = graphnode.value[1]
self.adjacents = []
self.parent = None
self._walkable = True
self._gscore ... |
b5e7926dd491f822a187de53661254f74c4feecb | facup94/AoC2015 | /11/day11_b.py | 1,154 | 4.09375 | 4 | def increment_password(pw):
pass_int = [ord(x) for x in pw]
i = -1
pass_int[i] += 1
while pass_int[i] > 122:
pass_int[i] = 97
i -= 1
pass_int[i] += 1
return ''.join([chr(x) for x in pass_int])
def has_unallowed_letters(pw):
return pw.count('i') > 0 or pw.count('o') > 0 or pw.count('l') > ... |
42fd8027b32dfa790296012543ef36b40f7c2a03 | zulsb/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,678 | 4.1875 | 4 | #!/usr/bin/python3
"""
Module contains Square class.
"""
from .rectangle import Rectangle
class Square(Rectangle):
""" Class Square that inherits from Rectangle.
Args:
Rectangle: Rectangle class.
"""
def __init__(self, size, x=0, y=0, id=None):
super().__init__(size, size, ... |
f7eaa08517519d0adc7681fcf24c1c4dbc137415 | pskhanapur/mininet_topos | /matrix.py | 2,077 | 3.640625 | 4 | """Custom topology example
Creates a matrix of switches with four host connected to each edge
e.g. 2x2 matrix
host --- switch --- switch --- host
| |
host --- switch --- switch --- host
e.g. 3x3 matrix
host --- switch --- switch --- switch --- host
| | ... |
6fd226c692937fd379ee4d7d6e64d592235e6350 | cboopen/algorithm004-04 | /Week 02/id_684/LeetCode_242_684.py | 1,321 | 3.875 | 4 | # -*- coding: utf8 -*-
"""
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
什么是字母异位词?两个单词包含相同的字母,但是次序不同
"""
class Solution(object):
def isAnagram(self, s, t):
"""
排序,时间复杂度O(nlogn)
:t... |
3a0bd0586f0bf824adc3030f3681f2f713c73a2a | Sharplestc98/statMaker | /statMaker.py | 4,315 | 3.875 | 4 | import random
import sys
'''
A simple python program that enables the user to make some simple
dnd dice rolling functions simpler. Such as rolling for attributes
or your next amount of hit points
Author: Thomas Christopher Sharples
'''
class statMaker:
space = 9
'''
Class constructor, prints out the starting s... |
a842a7f484ccdb22a8c4b214b82ff99a146f1781 | jualshe/python | /nested_lists.py | 922 | 4.0625 | 4 | nested_list = [['HTML', 'Hypertext Markup Language forms the structure of webpages'],
['CSS' , 'Cascading Style Sheets give pages style'],
['Python', 'Python is a programming language'],
['Lists', 'Lists are a data structure that let you organize information']]
first_concep... |
142b4782c58bab3b8c8713517accbc3bc1f91ecf | oshin0703/python | /intermediate-9.py | 809 | 3.84375 | 4 | import datetime
class TestClass:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
#クラスメソッド
@classmethod
def sample_classmethod(cls,date_diff=0):
today = datetime.date.today()
d = today + datetime.timedelta(days=date_diff)
... |
07fa4f52a960bf4b19527964e6fd61fcd4016376 | a-angeliev/Python-Fundamentals-SoftUni | /11. Fruit Shop.py | 1,219 | 4.09375 | 4 | fruit = input()
day = input()
quality = float(input())
if day == 'Monday' or day == "Tuesday" or day == "Wednesday" or day =='Thursday' or day == "Friday":
if fruit == 'banana':
print(f"{quality * 2.50:.2f}")
elif fruit== 'apple':
print(f"{quality * 1.20:.2f}")
elif fruit=='grapefruit':
... |
4e0b534a0719177b16da9906161e725975619dac | SoeRatch/codingpractice | /Python/depthFirstSearch.py | 543 | 3.65625 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSutil(self,v,visited):
visited[v]= True
print(v)
for x in self.graph[v]:
if(visited[x] == False):
self.DFSutil(x,visited)
def DFS(self,v):
visi... |
790780220513a823b65eede6ec88a5dad3e0f162 | anandpgm/python | /w3resource/List/38_Python program to change the position of every n-th value with the (n+1)th in a list.py | 219 | 4.15625 | 4 | """
Python program to change the position of every n-th value with the (n+1)th in a list. Go to the editor
Sample list: [0,1,2,3,4,5]
Expected Output: [1, 0, 3, 2, 5, 4]
"""
my_list = [0,1,2,3,4,5]
print(my_list[0:2])
|
d2fd857768b784b5d412fcfde44b925623531940 | Jose-Humberto-07/pythonFaculdade | /exers/notas.py | 827 | 3.984375 | 4 |
#funcao
def media(ap1, ap2):
m = (ap1 + ap2) / 2
return m
nome = []
ap1 = []
ap2 = []
print("===============controle de notas=============")
#=[0,1,2,3,4,5]
for c in range(3):
print("Qual o nome do ",(c+1),"° aluno? ")
nome.append(input())
print("Qual a nota AP1 do " + nom... |
320f09861ab87e8e5391f5d537e5ec74ce7c3b85 | HaykBarca/Python | /dictionaries.py | 519 | 4.4375 | 4 | # Dictionaries - mutable containers which maping one object to another (key: value)
my_dict = dict()
print(my_dict)
my_dict_lit = {}
print(my_dict_lit)
# Key: value pairs
fruits = {
"Apple": "Red",
"Banana": "Yellow"
}
print(fruits)
print(fruits["Banana"]) # Access to value
# Dictionaries are mutable
words = dic... |
601b067ffb91a9f04e8508afc8a2491321b6e56d | ricek/lpthw | /ex4/ex4-1.py | 986 | 4.125 | 4 | # Write comments above each of the variable assignments
# An integer value of 100 assigned to the variable named cars
cars = 100
# A floating point number for space in a car
space_in_a_car = 4.0
# Integer, number of drivers available
drivers = 30
# Integer, number of passengers
passengers = 90
# Integer, number of car... |
4abbd3d58dafd2001dc5613a0688dc6f83981a5f | supervehacker/Homework | /session 3 home work 28042017/turtle excercise.py | 226 | 3.6875 | 4 | from turtle import *
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
speed (-1)
n = 2
for mau in colors :
print(mau)
n += 1
color ( mau)
for x in range (n):
forward (100)
left (360 / n )
|
ade7f6d133e8c9b689c61c1393778df4f600d28d | priatmoko/basic-python | /17.py | 146 | 3.84375 | 4 | #Nested looping
index = 1;
while index <=20 :
i=1
while i<=index :
print "#",
i +=1
print "\n"
index +=1
|
120e0d6305451c9325989948f212bc5581c1cb4b | medvedodesa/Lesson_Python_Hillel | /Lesson_10/task_lesson_10/task_26.py | 1,139 | 4.34375 | 4 | # Задача №26 (Конвертер чисел)
"""
Написать функцию для перевода десятичного числа в другую систему исчисления (2-36).
В качестве параметров, функция получает десятичное число и систему счисления.
Возвращает строку - результат перевода десятичного числа.
"""
def convert_numeral_system(number, to_numeral_system=None)... |
9b57a1dadf048a569d47256883e4c16baf12902d | TianyiZhang0315/LeetCodeNote | /4_4.py | 3,009 | 3.65625 | 4 | #反转链表
#递归
#判断归的条件为下一个节点为空,则返回当前节点
#或当前节点为空,对应特殊例子,只有一个空节点
#每一层归的目标,当前节点和下一节点的关系,由指向下一节点
#变为下一节点指向自己 1->2变为1<-2
#再将当前节点next设为none,在链表中间的节点其实没有必要,但是方便把开头节点指向none(None<-1)
def reverseList(self, head: ListNode) -> ListNode:
# 归
if head == None or head.next == None: return head
# 递
p = self.r... |
448ddb1488e21f16c89773c79b6f4b89cf9107ca | dillon4287/CodeProjects | /Python/stock_script.py | 942 | 3.765625 | 4 | #!/usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import json
import pandas as pd
def get_jsonparsed_data(url):
"""
Receive the content of ``url``, parse it as JSON and retu... |
7fed03b2e37f80e0f391cba442349d30bffcad0c | sujithk/Think-Python-Solutions | /chap6/Untitled Document 1 | 104 | 3.765625 | 4 | def compare(x,y):
if x==y:
return 0
elif x>y:
return 1
else:
return -1
print compare(5,6)
|
882b11bf08ab5f2f087470e287b7c264b34a1ade | diegofregolente/30-Days-Of-Python | /24_Day_Statistics/Checking data types.py | 599 | 3.546875 | 4 | import numpy as np
numpy_int_arr = np.array([1, 2, 3, 4])
numpy_float_arr = np.array([1.0, 2.0, 3.0, 4.0])
numpy_bool_arr = np.array([-3, -2, 0, 1, 2, 3], dtype='bool') # 0 false / int negative or positive true
# print(numpy_int_arr.dtype)
# print(numpy_float_arr.dtype)
# print(numpy_bool_arr.dtype)
# int to float
i... |
2dcb1b5695c732400f8e57c4ab573d5c4701f2d5 | RRCHcc/python_base | /python_base/day06/exercise07.py | 451 | 4.15625 | 4 | """
练习:在控制台中显示矩形
for r in range(3):
for c in range(5):
print("*", end="") # 在一行输出
print()# 换行
"""
def rectangle(line,column,char):
"""
:param line: 矩形的高度(行
:param column: 矩形的宽度(列
:param char: 矩形的字符
:return:
"""
for r in range(line):
for c in range(column):
... |
27ab28bb12b0fe9ae4f03af44c4c6769ebbadd2b | wang264/JiuZhangLintcode | /Intro/L4/optional/493_implement_queue_by_linked_list_ii.py | 3,275 | 4.09375 | 4 | # 493. Implement Queue by Linked List II
# 中文English
# Implement a Queue by linked list. Provide the following basic methods:
#
# push_front(item). Add a new item to the front of queue.
# push_back(item). Add a new item to the back of the queue.
# pop_front(). Move the first item out of the queue, return it.
# pop_back... |
5feac949d4138a1c3ab395346c7f669536ea0feb | hawlette/intesivepython | /July21/EssentialPython/classesandobjects/prime.py | 153 | 3.734375 | 4 | def is_prime(number):
for index in range(2, number):
if number%index == 0:
return False
return True
print(is_prime(9)) |
3dcd2a0eb0704852c8b99b0940a8dbae82abad29 | Omupadh/python3 | /Desafios/desafio014.py | 117 | 3.78125 | 4 | c = float(input('Informe a temperatura em ºC: '))
f = ((9*c)/5) + 32
print('A temperatura em ºF é: {}'.format(f))
|
df6d7515f16d9fea3b2134960bc00d215d412180 | luise7932/hyuk | /CS/test10.py | 258 | 3.8125 | 4 | a = [1, 2, 3, 4]
result = []
for num in a:
result.append(num*3)
print(result)
result = [num*3 for num in a]
print(result)
result = [num*3 for num in a if num % 2 == 0]
print(result)
result = [x*y for x in range(2,10) for y in range(1,10)]
print(result) |
ebcd88018899fe8b0c003a934ca540e8446f5b14 | cxxacxx/udacity_AI_for_Robotics | /Search/first_search.py | 1,959 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[19]:
# ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the go... |
4f7dd2c13d0505a5957ad12de991eee1a168b278 | thippeswamydm/python | /1 - Basics/22-complexnumbers.py | 1,068 | 4.1875 | 4 | # COMPLEX NUMBERS
# https://en.m.wikipedia.org/wiki/Complex_number
# Usage and behaviour in python codes
# Complex numbers end with a 'j' key in the end of the integer/float
# Inbuilt function complex() creates a complex number
# USAGE
# complex(real, imag)
# You can add two complex numbers but there will be represent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.