blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
130b0e7ffbf29b50607f03b190b3637d145492d4 | andonyan/Python-Advanced | /Tuples and Sets - Lab/Parking Lot.py | 409 | 3.921875 | 4 | n = int(input())
parking_lot = set()
for _ in range(n):
(direction, license_plate) = input().split(', ')
if direction == 'IN':
parking_lot.add(license_plate)
elif direction == 'OUT' and license_plate in parking_lot:
parking_lot.remove(license_plate)
else:
if parking_lot:
for ca... |
2d540b404ac7a0e8482ad4dce1173c63616f2719 | danishprakash/courses | /coursera-uom/Part1/p1w7a52.py | 315 | 4.09375 | 4 | #largest = None
#smallest = None
numList = []
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
numList.append(int(num))
#print(num)
except:
print('Invalid input')
print("Maximum is", max(numList))
print("Minimum is", min(numList))
|
ccf6654bd4ec5fd455a879627e49f1cf00e7c3f3 | talibzaz/awesome-py | /dataStructures/ds.py | 342 | 3.578125 | 4 | from collections import deque
fruits = ['orange', 'apple', 'apple', 'pear', 'banana', 'mango', 'kiwi']
print(fruits.count('apple'))
print(fruits.pop())
print(fruits)
queue = deque(['Eric', 'Michael', 'John'])
queue.append('Jerry')
print(queue)
print(queue.popleft())
print(queue.pop())
print(queue)
arr = [1, 5, ... |
a95c390604c50ef42b2c9eeffc4eac37c6bfed22 | Lucian-N/CS50 | /pset6/similarities/helpers.py | 1,622 | 3.828125 | 4 | from enum import Enum
class Operation(Enum):
"""Operations"""
DELETED = 1
INSERTED = 2
SUBSTITUTED = 3
def __str__(self):
return str(self.name.lower())
def distances(a, b):
"""Calculate edit distance from a to b"""
end_range_a = len(a) + 1
end_range_b = len(b) + 1
# Array ... |
9e8e1281973783e03ab2c636672ecd67f11c74df | vlad8130/python9 | /brilliant.py | 1,353 | 4.125 | 4 | # Задача 2. Бриллиант
# Входным данным является целое число. Необходимо:
# написать проверку, чтобы в работу пускать только положительные нечетные числа
# для правильного числа нужно построить бриллиант из звездочек или любых других символов и вывести его в консоли. Для числа 1 он выглядит как одна взездочка,
# для ... |
a50c9e707d23c124f43eb9309664e44904820123 | shirshandu/ExplorePython | /pg3_duplicate.py | 184 | 3.515625 | 4 | prev = None
for line in sorted(open('file')):
line = line.strip()
if prev is not None and not line.startswith(prev):
print prev
prev = line
if prev is not None:
print prev
|
c553adda586c88a671ab74f546c7e3d8d88c0bbf | jmanning1/python_course | /HelloWorld/HelloWorld.py | 322 | 4.09375 | 4 | print('Hello World!')
print(1+2)
print(7*6)
print()
print("The End")
print("Python Strings are easy to use. We can also use 'Quotes' in Strings")
print ("Hello" + "World")
greeting = "Hello"
name = "Bruce"
print(greeting + name)
#If we want a space use a hash for comments/notes
print(greeting + " " + name)
... |
7b1d8a08651291e4a813a4db09603b6b87b56f0b | krohak/Bioinformatics | /Chapter 1/1_4_1.py | 352 | 4.125 | 4 | # Input: A DNA string Pattern
# Output: The reverse complement of Pattern
def ReverseComplement(Pattern):
return Reverse(Complement(Pattern))
def Reverse(Pattern):
return ''.join(list(reversed(Pattern)))
def Complement(Pattern):
complementMap = {'A':'T','T':'A','G':'C','C':'G'}
return ''.join([com... |
691d6be9a77a7608f0c3662ddae4a868690639bd | OlgaLitv/Algorithms | /lesson2/task2.py | 513 | 4.28125 | 4 | """ Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560,
то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). """
n = input('Введите натуральное число\n')
odd = 0
even = 0
for letter in n:
if int(letter) % 2 == 0:
even += 1
else:
odd += 1
pr... |
b5189a0f63422c0af9fff4edde495654e88398d7 | saggarwal98/Practice | /Python/tuples.py | 78 | 3.578125 | 4 | tuple1=("abc","def","ghi")
print(len(tuple1))
print(tuple1)
print(tuple1[0:2]) |
e29b56c230f6e72e9e8f26cb4cd3e94f7f0306b2 | eecs110/winter2021 | /course-files/lectures/lecture14/answers/02a_list_animation_from_class.py | 787 | 3.546875 | 4 | from tkinter import Canvas, Tk
import time
import utilities
import math
import random
gui = Tk()
gui.title('Animation')
canvas = Canvas(gui, width=500, height=500, background='white')
canvas.pack()
########################## YOUR CODE BELOW THIS LINE ##############################
for i in range(1, 101):
x = rand... |
3c2fa1290926bf5ace70583a5b1ca5bf746cf4c0 | maomao905/algo | /sorted-integers-by-the-number-of-1bits.py | 736 | 3.890625 | 4 | """
- how to get the number of 1 bit?
get right-most 1 bit and substruct it
continue this process until the number becomes zero O(32) = O(1)
time: O(NlogN) space: O(1)
"""
from typing import List
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
def count_one_bit(x):
cnt = 0
... |
129845b77a736f553d99e97cff15c7b94c3a741d | Atlasias/Algorithm | /programmers/skill_checks/849.py | 444 | 3.625 | 4 | def solution(n):
answer = ''
while True:
if n == 0:
break
m = n % 3
n = n // 3
if m == 1:
answer = 'a' + answer
elif m == 2:
answer = 'b' + answer
else:
answer = 'c' + answer
answer.replace('a', '1'... |
abdcef196759e872d15d5f8b0e3d4cdfda3a3a85 | AliceTheHive/releases-openstar-Enterprise | /openstar/bash/py/file.py | 1,658 | 3.625 | 4 | #!/usr/bin/env python 2.x
# -*- coding: utf-8 -*-
# version = 1.0
import os
class ScanFile(object):
def __init__(self, directory, prefix=None, postfix=None):
self.directory = directory
self.prefix = prefix
self.postfix = postfix
self.files_list = []
self.dir_list = []
... |
b54e88e134c035a8e04575f16982c7f469470b61 | gavinsyw/CombatDeepfake | /InterceptFace.py | 741 | 3.53125 | 4 | import cv2
def crop_face(imagePath):
# Read the image
image = cv2.imread(imagePath)
# turn the image to Gray
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Create the haar cascade
faceCascade =cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Dete... |
3772936a664ccd3f7ecb8c41a176ecae15c6f1fa | KateDetsyk/see_battle | /canvas.py | 2,689 | 4.1875 | 4 | class Rectangle:
def __init__(self, corner, size, border='*', inside=' '):
"""
Initialize new rectangle.
:param corner: corner coordinates.
:param size: size of rectangle
:param border: symbol that is used to display rectangle border.
:param inside: symbol that... |
cb4985bc00256a6d37a252942c81be46f5e1c20f | vsfh/pyukf_kinect_body_tracking | /src/regression.py | 224 | 3.5 | 4 | import math
import numpy as np
def mean_squared_error(y, t, test_num):
y = np.array(y).reshape(test_num, (int)(len(y)/test_num))
t = np.array(t).reshape(test_num, (int)(len(t)/test_num))
return ((y-t)**2).mean(axis=None) |
abb1a7f3641605ba8c57cf9ad04646423a444a41 | JoannaKielas/testing-with-Robot-Framework- | /code/TC10/TC10_import_csv.py | 335 | 3.921875 | 4 | import csv
def read_csv_file(filename):
list_of_countries =[]
with open(filename) as csvfile:
reader = csv.reader(csvfile)
for line in reader:
list_of_countries.extend(line)
print(list_of_countries, "line")
print(list_of_countries)
return list... |
dc0162c665e3cf8f1479e49561e6f7559b790f9c | beezy12/pythonPractice | /network/pythonhack/sock.py | 942 | 3.828125 | 4 |
# this program creates a simple server. to connect, open Filezilla and connect to the server using localhost on port 1249
# came from my udemy ethical hacking course
# notes in my Bear notebook
# docs here: https://docs.python.org/3.6/howto/sockets.html
import socket
# create a socket object
s = socket.socket()
prin... |
aa7fd0504ca8c075cafbeb43e6c438ace88114a1 | LondonComputadores/Procedural | /orientacao_objetos/classe_e_composicao/oop/pessoa.py | 1,199 | 4.03125 | 4 | class Pessoa:
olhos=2
def __init__(self, *filhos, nome=None, idade=36):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá! {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@clas... |
6f27800bd37d78a4b327a5ac870abd338246b6d0 | punzoamh/StockMarket_MachineLearning | /days.py | 1,950 | 3.890625 | 4 | import time
import calendar
import datetime
from dateutil import rrule
from datetime import date, timedelta
def main():
text_file = open("start_dates.txt", "w")
date_start_obj = date(2014, 3, 17)
date_end_obj = date(2015, 3, 17)
days = 100
"""
Find_dates_cpy() will get the start date
for a g... |
fced51021403b2c1b6ee87cf7f67f5273aa462a6 | JeisyLiu/Repository_Charlie | /VariousFeatures/ComputerVision/geometricTransform.py | 1,862 | 3.671875 | 4 | import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
#####################-------------GEOMETRIC TRANSFORMATIONS IN MATRIX LEVEL-----------------#####################
imgsrc = cv2.imread('resource/bflog.png')
height, width, thickness = imgsrc.shape
# resize/scale the image
alpha = cv2.re... |
91bd2e803e12dae1fb6dad102e24e11db4dfdb03 | ZainabFatima507/my | /check_if_+_-_0.py | 210 | 4.1875 | 4 | num = input ( "type a number:")
if num >= "0":
if num > "0":
print ("the number is positive.")
else:
print("the number is zero.")
else:
print ("the number is negative.")
|
e83307352d949e4f20c8e1c1acb181de0a56a496 | Creater2kTen/Path-Finding-Alogrithms-Visual-Representation | /algorithms/a_star_m.py | 4,543 | 4.1875 | 4 | from queue import PriorityQueue
from algorithms.heuristics import h1
import time
import pygame
def algorithm(start, end, grid, draw, win):
"""
This implementation uses a priority queue for its frontier.
The runtime and space complexity depends on the heuristic.
This is a version of weighted A* search... |
c016fa2ea002e0a0e47d4f37063ea975e6a57166 | MoserMichael/pythoncourse | /turtle-clickme.py | 218 | 3.5 | 4 | import turtle
s = turtle.Screen()
size = s.screensize()
print("screen size {}", size)
def moveme(x,y):
print("moveme {} {}", x, y)
t.goto(x,y)
t = turtle.Turtle('turtle')
s.onclick( moveme )
turtle.done() |
fbf776c80d096a6baa836bc16759f7946454780e | alexheyuzhang/InteractionLogic | /week3_Game.py | 6,775 | 3.75 | 4 | # an object describing our player
import re
player = {
"name": "p1",
"items" : [],
"location" : "start"
}
def sword():
print "Do you want to pick it up?"
pcmd = raw_input("please choose yes or no >")
if (pcmd.lower() == "yes"):
print "OH NO! You accidentally woke up the bear who's p... |
7fd2447f42c990447529f3bb998c85514a825557 | nomihadar/Anastomotic-Leak-Prediction | /Code/utils/defs_functions.py | 738 | 3.828125 | 4 | import pandas as pd
#if string contains Hebrew chars
def containHebrewChars(s):
return any("\u0590" <= c <= "\u05EA" for c in s)
#returns series of Hebrew words in a given df
def getHebrewWords(df):
if (type(df) == pd.Series) or (type(df) == list):
df = pd.DataFrame(df)
hebrewVals = []
... |
d8658563f9d0c93ef9d8636fcf8c05e0a3f5758e | schmidt-jake/socialitics | /proj1/q2/utils.py | 2,362 | 3.671875 | 4 | def scrape(query, n_tweets, lang='en'):
"""
Scrapes Twitter using Tweepy. Returns a dataframe of the most recent tweets that could be found. Also pickles this dataframe as 'raw_tweets/{query}.p'.
Parameters
----------
query: str
Twitter search query.
n_tweets: int
T... |
7f1cef2727c9389bd43bf5dca70acb75be0cceb4 | ssampaleanu/python-challenge | /pyParagraph_SSampaleanu/pyParagraph_SSampaleanu.py | 1,488 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 12:01:29 2018
@author: Stef
"""
words = []
# stores each word's length as element of list
sentences = []
# stores each sentence's length as element of list
pyPar = open('pyParagraphTest.txt','r')
paragraph = pyPar.read()
print("Here is the... |
de1b6587390c72aea50b7c56424c4d751e3c588e | hero24/Algorithms | /python/cryptography/playfair_cipher.py | 2,784 | 3.609375 | 4 | from string import ascii_lowercase
"""
"DON’T WORRY ABOUT THE WORLD ENDING TODAY,
IT’S ALREADY TOMORROW IN AUSTRALIA."
~ CHARLES M. SCHULZ
"""
class PlayfairCipher():
def __init__(self, key=None):
self.mat = [[]]
if key:
alpha = key
else:
alpha = ""
... |
9204d593a5997198b10dbd76265ff09fb3750796 | Midnightbara/COGS-Final-Project | /Tester.py | 789 | 3.578125 | 4 | """
Author: Tracy Pham
PID: A13917165
This file contains a method to test the methods in the Dessert.py file.
"""
import pytest
def test_points():
"""
Description: A unit test to test the function called points() in the Dessert.py file.
"""
# Invalid dessert name input
result = points(["carro... |
aa2744e329c657e00daea0047fe8ac5a01bdcdc6 | kalebjuliu/Fundamentals-PythonExercises | /1/7.py | 388 | 4.3125 | 4 |
#Exercise 7 : Max of Three
a = 1
b = 5
c = 3
def max_three(num_1, num_2, num_3):
if num_1 > num_2 and num_1 > num_3:
print("The first number is the largest")
elif num_2 > num_1 and num_2 > num_3:
print("The second number is the largest")
if num_3 > num_2 and num_3 > num_1:
... |
65cf972045a5ad1c030c8b19ad06a7740d437259 | jdf/processing.py | /mode/examples/Basics/Structure/Recursion/Recursion.pyde | 624 | 4 | 4 | """
Recursion.
A demonstration of recursion, which means functions call themselves.
Notice how the drawCircle() function calls itself at the end of its block.
It continues to do this until the variable "level" is equal to 1.
"""
def setup():
size(640, 360)
noStroke()
noLoop()
def draw():
drawCi... |
fcae7b9b7c3c0ba7a361769637ed544ce25255b8 | big-data-ai/homemade-machine-learning | /homemade/DeepLearn-with-Python/5.1-introduction-to-convnets.py | 2,366 | 3.734375 | 4 | from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64... |
5c604fbb4a46cc704f0d9d73a0c182ccbd8fccc6 | teddymcw/pythonds_algos | /searching_sorting/searches_and_sorts.py | 3,384 | 4.0625 | 4 | def binarySearch(alist, item):
if len(alist) == 0:
return False
else:
midpoint = len(alist)//2
if alist[midpoint]==item:
return True
else:
if item<alist[midpoint]:
return binarySearch(alist[:midpoint],item)
else:
re... |
be5d95f39122b6d0e632f219408e3dbb2d2cd5a8 | mag-id/epam_python_autumn_2020 | /homework_3/tasks/task_1.py | 1,771 | 4.28125 | 4 | """
In previous homework task 4,
you wrote a cache function that remembers other function output value.
Modify it to be a parametrized decorator, so that the following code::
```
@cache(times=3)
def some_function():
pass
```
Would give out cached value up to `times` number only.
Example:
```
@cache(tim... |
e0d307f323f61f45e2a394134483e443cebe863a | odora/CodesNotes | /Python_cheatsheet/statement_example.py | 1,501 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/4/17 23:04
@Author : luocai
@file : statement_example.py
@concat : 429546420@qq.com
@site :
@software: PyCharm Community Edition
@desc :
条件、循环语句
"""
a = 3
# if 语句
if a > 0:
print('a =', a)
# if-else
if a > 2:
... |
715bf396874f157e67a090a3de84e3759f8c4164 | codeAligned/Competitive-Programming-4 | /codeforces/problemset/python_sol/270a.py | 225 | 3.71875 | 4 | def Main():
t = int(input())
for i in range(t):
a = int(input())
if a > 59 and 360%(180-a) == 0:
print("YES")
else:
print("NO")
if __name__ == "__main__":
Main()
|
e2a5dd3fcc8c2069539e88b2edf4b81f4cfbf709 | EslamAmin151/09-21-2018-Remove-Duplicate-and-Pyramid | /pyramid.py | 444 | 3.828125 | 4 | num = eval(input("Enter an integer from 1 to 15: "))
def as_str(i):
s = ""
if i <10: s = " "
return s + str(i)
#num = 15
allrows = ""
for j in range(1,num+2):
#leading spaces
row = " "*3*(num-j+1)
#backward
for i in range(j-1,1,-1):
s = as_str(i)
row+=s + " "
#forw... |
3a12b562893389a93115d515dfd1438d1244917b | harshu232/PythonCode | /quiz.py | 166 | 3.65625 | 4 | counter = 100
loop_run = 0
while counter >= 1 :
print("Loop Variable Value ",counter)
counter = counter - 5
loop_run = loop_run + 1
print(loop_run)
|
07b0e955ec63968fcac59fd7cbc1aa327dcd7224 | Barret-ma/leetcode | /437. Path Sum III.py | 1,990 | 3.921875 | 4 | # You are given a binary tree in which each node contains an integer value.
# Find the number of paths that sum to a given value.
# The path does not need to start or end at the root or a leaf,
# but it must go downwards (traveling only from parent nodes to child nodes).
# The tree has no more than 1,000 nodes and t... |
44ee0bcd14bc6f2dc0cbc010dbde8fcae9b0c0cb | rafaelperazzo/programacao-web | /moodledata/vpl_data/458/usersdata/316/109645/submittedfiles/programa.py | 283 | 3.875 | 4 | # -*- coding: utf-8 -*-
n=int(input('digite a dimensao do tabuleiro: '))
tabuleiro=[]
for i in range(0,n,1):
colunas=[]
for j in range(0,n,1):
colunas.append(float(input('digite o elemento da linhas%d, coluna%d :' %((j+1),(i+1)))))
tabuleiro.append(colunas)
|
04673a56c32021c15acf0b4eec81b6fedf59d8f1 | epassaro/hcc | /06 - Método de Montecarlo/mcpi_parallel.py | 566 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 03:06:42 2018
@author: epassaro
Simplest 'pure' Python Montecarlo approximation of Pi.
"""
#%%
import numpy as np
from numba import njit, prange
@njit
def mc_pi(n):
x = np.random.uniform(-1, 1, n)
y = np.random.uniform(-1, 1, n)... |
12ecd86c6b13299496d10598994286931fac8987 | tiggerntatie/hhs-cp-site | /hhscp/static/exemplars/c09exceptions.py | 2,603 | 3.671875 | 4 | __author__ = 'ericdennison'
class Square(object):
def __init__(self, side = 1.0):
self.b = side
def area(self):
return self.b**2
def _userinputgeneric(self, member, paramname):
inp = input("What is the {0}? ".format(paramname))
try:
self.__dict__[member] = abs... |
da02a8b688d54e39c803c9d8abba3496c1a86632 | R151153/lasya | /addition of sinusoidals.py | 411 | 3.84375 | 4 | import matplotlib.pyplot as plt
import numpy as np
f=float(input("enter the frequency"))
fs=float(input("enter the sampled frequency"))
x=np.arange(0,100,0.5)
y=np.sin(2*np.pi*f*x/fs)
plt.subplot(1,5,1)
plt.plot(x,y)
b=np.cos(2*np.pi*f*x/fs)
plt.subplot(1,5,2)
plt.plot(x,b)
c=y+b
plt.subplot(1,5,3)
plt.plo... |
20787ae11dd9c7a63f53af2f791cdc737f36b05d | andreeavis/python_the_hard_way | /ex5.py | 844 | 4.375 | 4 | name = "Zara Zaraza"
age = 35 #not a lie
height = 74 # inches
weight = 180 #pounds
eyes = 'Brown'
teeth = 'White'
hair = "Brown"
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} kg heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair... |
59480d948c98983ebb8629ea00a1ac214d40b386 | frameworkdartboard/ComeOnFeelTheExercism | /python/hamming/hamming.py | 656 | 3.53125 | 4 | def distance(strand_a, strand_b):
if (strand_a == "" and strand_b != ""):
raise ValueError("strand_a is an empty string but not strand_b.")
elif (strand_b == "" and strand_a != ""):
raise ValueError("strand_b is the empty string but not strand_a.")
lena = len(strand_a)
lenb = len(st... |
2514dac98084ff0c40730731797cff30b2d358f9 | kevinb22/BinarizedNMT | /translation/models/components/binarization.py | 10,177 | 3.5 | 4 | '''
This module implements the binarization of a 1 dimensional convolutional model.
Based on the XNOR net paper: https://arxiv.org/pdf/1603.05279.pdf
Implementation: https://github.com/jiecaoyu/XNOR-Net-PyTorch
The paper and implementation target 2 dimensional convolutions for image classification tasks (MNIST, CIFA... |
abb7083123fdee70c6d00dc657f165d9db40c550 | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1014/FUNCTION05.py | 736 | 3.8125 | 4 | # 사칙연산 함수
def inputValue():
return int(input("Enter Input : "))
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
def printValue(x, y):
print(f"{x} + {y} = {add(x, y)}")
print(f"{x} - {y} = {sub(x, y)}")
print(f"{x} ... |
a2eaee348136d4aeab0b2578332cadfe25883749 | dedekinds/pyleetcode | /base_datastructure/并查集.py | 488 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 14:44:23 2019
@author: dedekinds
"""
def findRedundantConnection(edges):
parent = [-1]*(1+max(sum(edges,[])))
def find_root(x):
if parent[x] == -1:return x
parent[x] = find_root(parent[x])
return parent[x]
for u,v in edges:
... |
3558f9cc638a599a7641c54ed215f0a921c62ec1 | RunzZhang/runze | /Test/python_plot_tutorial.py | 23,765 | 4.03125 | 4 | # Introduction########
# 1.pycharm 的一些技巧
# comment:
# python comment 行以 "#" 开始
# 但是你可以用鼠标多选多行,然后ctrl+/ 键一次commeent多行
# ctrl + F 查找,这个一般程序都有的,但是查找可以锁定大小写
# ctrl + G 跳段落。当报错告诉你某一行出错的时候,用这个快捷键可以快速跳到某一行
# insert 键。这个可能会被误触。知道再按insert键就可以恢复了
"""另外一种办法是英文的双引号,只需要在段落前后加上即可"""
#2 结构
# 一般是:
# import 部分
# 导入包
# function ... |
a937235ef801c6c1515ed047a2eafd4b03d02356 | samyakjain101/DSA | /bit_manupulation/q020_power_of_two.py | 346 | 3.6875 | 4 | """Problem Statement
https://leetcode.com/problems/power-of-two/
"""
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
if n & (n-1) == 0:
return True
return False
if __name__ == "__main__":
num = 16
test = Solution()
prin... |
fa5f70bb6bb03ef0132db5d17b76a54d88982c47 | Aasthaengg/IBMdataset | /Python_codes/p02417/s271430431.py | 290 | 3.625 | 4 | alphabets = "abcdefghijklmnopqrstuvwxyz"
#print(len(alphabets))
#a = len(alphabets)
#print(a)
x = ''
while True:
try:
x += input().lower()
except EOFError:
break
for i in range(len(alphabets)):
print("{0} : {1}".format(alphabets[i], int(x.count(alphabets[i])))) |
d8a5fc6b82b44a8fa362b461748909da75bbbf97 | jaeyoung-cho/TIL_Python | /Basic/pdb/src/example.py | 342 | 4.125 | 4 | import pdb
def calc(operator, num1, num2):
pdb.set_trace()
if operator is '+':
return num1 + num2
elif operator is '-':
return num1 - num2
elif operator is '*':
return num1 * num2
else:
return num1 / num2
pdb.set_trace()
num1 = 100
num2 = 5
result = calc('*', num1... |
54946fd6aeb9d615641b6543f52a9cc8e0bca09d | thegabriele97/python-lab2 | /ex3.py | 1,982 | 3.828125 | 4 | import sys
def main(argv):
lst = []
print("Welcome to note 3000 revolution!")
if len(argv) > 1:
print("Loading from %s.." % argv[1])
load_file(lst, argv[1])
print("Done!")
while True:
print()
selected_int = int(show_prompt())
selected_int -= 1
... |
5d12616f8ceff0ba0ad40a464612932b95bb8a94 | lokeshlk368/Python-Programming | /TableOfNumber.py | 93 | 3.9375 | 4 | num=int(input("Enter a number"))
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i))
|
6065f3a83a2b8a40e7860b4032402930dff7fce1 | PedroRamos360/PythonCourseUdemy | /kivy/aulas/Seção 15 - Funções/Exercicios/Ex14.py | 155 | 3.734375 | 4 | def fatorial(numero):
index = numero
while index > 1:
index -= 1
numero *= index
return numero
print(fatorial(int(input()))) |
59a8707da56060407a32ad9590848232bc305aa3 | Camicam311/Educational-Projects | /Survey of Programming Paradigms /Brute Force Password Cracker/crack.py | 3,092 | 3.84375 | 4 |
from misc import *
import crypt
def load_words(filename,regexp):
"""Load the words from the file filename that match the regular
expression regexp. Returns a list of matching words in the order
they are in the file."""
list = []
with open(filename) as f:
for line in f:
... |
f9be7658465680386db6e86093e7ea8ee1d47b00 | abu6912/codewars | /code/pyscripts/simple_pig_latin.py | 326 | 3.8125 | 4 | text = 'Pig latin is cool'
def pig_it(text):
text = text.split(' ')
out = ''
for word in text:
if word.isalpha():
init = word[0]
rest = word[1:]
out += ' {0}{1}ay'.format(rest, init)
else:
out += ' ' + word
return out.strip()
print pig_it(... |
af2c458ba8c7437c3531923c1f008d53d7704864 | ThomasSelvig/MazeAlgo | /dfsmazegen.py | 1,604 | 3.53125 | 4 | from PIL import Image
import random, sys
def availNodes(x, y, visited, pixels, size):
w, h = size
nodes = [] # ((x, y), (x1, y1)) where x,y is the "destination node" (the one checked) and x1,y1 is the "road node" bridging the dest node and "parameter given" node
# up
if y-2 >= 0 and y-2 < h and pixels... |
700a747086036c6cea939e6735930c2393040fdb | liupy525/LeetCode-OJ | /46_Permutations.py | 779 | 4.09375 | 4 | #!/usr/local/env python
# -*- coding: utf-8 -*-
'''
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
'''
class Solution:
# @param num, a list of integer
# @return a list of lists of... |
b352f0f6f1a1c6f403354b2d5b781cd6c9c2c3f4 | s2e-lab/SecurityEval | /Testcases_Copilot/CWE-117/author_1.py | 400 | 4.21875 | 4 | import logging
def inputConversion():
'''
take a string input from the user
convert it to an integer within try-except block and log the error
return the user input after converting it to an integer
'''
try:
user_input = input("Enter a number: ")
user_input = int(user_input)
... |
598abfb0336a6ed3702817684de046affbd4c32f | shnu2018/python | /第8章/教学案例代码/单元测试.py | 806 | 3.765625 | 4 | import unittest
class HelloWorldTestCase(unittest.TestCase):
"""测试类必须继承自TestCase, 要测试的函数也必须以test开头"""
def setUp(self):
"""每执行一个测试函数之前,都会首先调用这个setUp()方法"""
print('setUp() method will run first!\n')
def test_hello_world(self):
a = 100
self.assertE... |
54b4a59cbbe29bb18492c86e2ac53aed6c6877f4 | casperolesen/my_notebooks | /my_modules/Week_3/Course.py | 477 | 3.65625 | 4 | class Course():
def __init__(self, name, classroom, teacher, ETCS, grade=None):
self.name = name
self.classroom = classroom
self.teacher = teacher
self.ETCS = ETCS
self.grade = grade
def __str__(self):
return 'Name: {name}, Classroom: {classroom}, Teacher: {t... |
32386ed1883f53d2a3928d1660c7a5832e14bd6d | RashlyEndemic/ItalianDay | /ItalianDay.py | 1,530 | 3.859375 | 4 |
#shot = 10
#beer = 5
#wine = 1
def drinking_game():
print("Welcome to Italian Day!")
user = input("What is your name? ")
print("The rules are simple. Don't drink too much.")
import random
sobriety = 0
shot = 0
beer = 0
wine = 0
while sobriety < random.randint(89,121):
drink... |
3747b4d8a5d6ced465b4d59758948ca20de51be2 | OOOIOOOIO/Basic_study_for_Machine_Learning | /BeautifulSoupBasic/CSS03.py | 848 | 3.640625 | 4 | # 스타일시트 연습
from bs4 import BeautifulSoup
# html 파일 열기
fp = open(r"C:\Users\polit\python_MachineLearning\BS\book.html", "r", encoding = "utf-8")
soup = BeautifulSoup(fp, "html.parser")
# 똑같은 표현
print(soup.select_one("ul#itBook > li#DataScience").string) # ul의 id가 idBook이고 그 l 밑에 li id가 DataSciende 인 요소
print(soup.s... |
adec90e1bcd2ef78cd772b602c1e316d2a295e83 | Guilherme2020/ADS | /Algoritmos 2016-1/1-lista(professor_fabio)/6.py | 292 | 3.90625 | 4 | #Leia uma velocidade em km/h,
#calcule e escreva esta velocidade em m/s. (Vm/s = Vkm/h / 3.6)
velocidade_kmh = float(input("Insira a velocidade em km/h"))
velocidade_metros_segundo = velocidade_kmh/3.6
print(" %.2fKm/h equivale a %.2f m/s "%(velocidade_kmh,velocidade_metros_segundo))
|
8c9509866193b9315726ebad1c90883335db789b | brendo61-byte/pythonOnBoarding | /old_Learning_Sets/Learning_Set_1:Entry_Level/3_varbles_basics_pt_2.py | 1,072 | 4.09375 | 4 | """
What you will learn:
- How to add, subtract, multiply divide numbers
- Float division and integer division
- Modulus (finding the remainder)
- Dealing with exponents
- Python will crash on errors (like divide by 0)
Okay now lets do more cool things with variables. Like making python do math for us!
What you need ... |
a2283804176ca7940e72d21d0e249a02c81be3fb | christopherchoe/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 372 | 3.640625 | 4 | #!/usr/bin/python3
class MyInt(int):
"""
rebel class with reversed == and !=
"""
def __eq__(self, other):
"""
inverted eq method
"""
if isinstance(other, int):
return not super().__eq__(other)
def __ne__(self, other):
"""
inverted ne metho... |
bfe1664ff66966824f2b9462097fd48aafae7bcd | jelimy/Practicing-CodingTest | /프로그래머스 Python/0717(level1).py | 781 | 3.65625 | 4 | # 출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
# 코딩테스트 연습 > 연습문제 > x만큼 간격이 있는 n개의 숫자
# 사용언어 Python3
#내 답안
def solution(x, n):
return [i*x for i in range(1,n+1)]
# 코딩테스트 연습 > 연습문제 > 정수 제곱근 판별
# 사용언어 Python3
#내 답안
def solution(n):
a = n**(1/2)
if a == int(a):
return (a+1)**2
... |
0b4c258f0d0d001fa056138b45f81a1bf1136514 | lov2cod/my_playground | /Coding_int/venv/replace.py | 966 | 4.0625 | 4 |
#Python challenge #1 Everybody thinks twice before solving this
message = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj. "
def replaceChars(input, c1, c2):
... |
7c5b45713694013b8af8670a46428faeb9694dca | SimmyZhong/leetCode | /dataStructure/listNode.py | 734 | 3.515625 | 4 | import random
class ListNode:
"""
链表
"""
def __init__(self, v):
self.val = v
self.next = None
@staticmethod
def getListNode(NodeLen):
"""
获取长度为NodeLen的随机链表
"""
TestListNode, ListNodeLen = ListNode(0), 0
curNode = TestListNode
whi... |
2334e384ac7dbb1ec983f7f5e6e0725de680734e | guijavax/algoritmos | /algoritmo-luhn/main.py | 1,222 | 4.09375 | 4 | # This is a sample Python script.
import array
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def reverseNumbers(number):
leng = len(number)
numbers = []
j = leng - 1
for i in range(leng... |
016429c3eaefdc7d9a230def65086507db1b7d79 | ujwalkpl/5thSem_SL_Lab | /SEE/5/A/5a.py | 1,430 | 3.859375 | 4 | import sys
result = []
def celtofah():
cel = int(input("Enter temperature in celcius"))
fah = 9/5*cel+32
result.append((cel,fah))
print(fah)
def fahtocel():
fah = int(input("Enter temperature in fahrenheit"))
cel = 5/9*(fah-32)
result.append((fah,cel))
print(cel)
def keltocel():
kel ... |
253b5d947331fc670aaeb404c1e2213581f27646 | rv404674/Learn-Python3-the-Hard-Way | /ch15.py | 335 | 3.71875 | 4 | #import argv module from sys
from sys import argv
#load script name in argv and filename in filename
script, filename = argv
#open the file
txt = open(filename)
print(f"Here's your file {filename};")
print(txt.read())
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt.... |
a5fc6ecca491828a5596ea51b470c9f0b66ed9a8 | qamarilyas/Demo | /bubbleSort.py | 365 | 4.125 | 4 |
def bubbleSort(lst):
for i in range(len(lst)-1): # outer loop run from index 0 to len(lst)
for j in range((len(lst)-i)-1): # inner loop run from index 0 to omitting i values
if(lst[j]>lst[j+1]):
lst[j],lst[j+1]=lst[j+1],lst[j] # swap each time if second value is greater
prin... |
7ae3adfff82624c85807a12ce0be0f345f36a36c | joowoonk/Python-Intro | /Datastructure Note/binary search tree.py | 1,172 | 4.34375 | 4 | class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# compare the value to the root's value to determine which direction
# we're gonna go in
... |
9d66b8cdb8a2a92db20d4ea7b2de72799f9a2b76 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/preorder-traversal.py | 1,154 | 4.0625 | 4 | """
# PREORDER TRAVERSAL
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
Example 5:
Input: r... |
9ca6689084d09d1d20d028c252c1bf3509f75cc7 | Kjew/Final-Project | /testspace2.py | 331 | 3.875 | 4 | word = "tallie"
#removes letter from alphabet once guessed
def remove_guessed_letter(word): #remove letter once guessed
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for charactors in list(alphabet):
if charactors in word:
alphabet = alphabet.replace(charactors," ")
return alphabet
guess1 = "t"
print remove_guess... |
62ad4f883f66ecee265c6d391f168a85dadf990f | zhangting2/gitp1804 | /p10/dengLu.py | 173 | 3.671875 | 4 | user=123
for i in range(1,5):
passwd=input('请输入 密码')
if user==passwd:
print('登录成功')
break
else:
print('登录失败')
|
8cbd92125880eb6f31ed399ebbe0db96b2d0fa3b | reniass/PythonRecursion | /sum_until.py | 112 | 3.546875 | 4 | def sumUntil(n):
if n == 0:
return 0
else:
return n + sumUntil(n-2)
print(sumUntil(6)) |
f2ecdfb5a6840cc2a10e06073dfdf5799a2881ab | saryamane/python_learnings | /functions.py | 1,817 | 4.375 | 4 | #!/usr/bin/python
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):
print "arg1: %r" % arg1
def print_none():
print "I got nothing!"
"""The variables in your function are not connect... |
232b034eb60701112528ed7f60c35a4c1eee8202 | ibikimam/py4e | /search1.py | 140 | 3.921875 | 4 | print('Before')
for value in [9,41,12,3,74,15] :
if value > 20 :
print(value ,'number is larger than 20')
print('After') |
b02998609aa884a632235d05f4639cb0db58329f | Beardocracy/holbertonschool-interview | /0x0C-nqueens/0-nqueens.py | 2,175 | 4.1875 | 4 | #!/usr/bin/python3
'''
This program show all solutions the N queens problem,
for any given N.
'''
import sys
def print_board(board, n):
'''
Prints the locations of 1s in a n by n matrix
'''
print("[", end="")
for row in range(n):
for col in range(n):
if board[row][col]:
... |
90b1237786315f3922f191e3cc76e88c2d23e884 | anajulianunes/aprendendo-python | /Curso-python-iniciante/Projetos do Curso em Vídeo/aula9/9b - analisador de texto.py | 402 | 3.90625 | 4 | nome = input('Digite seu nome: ').strip()
print('Seu nome em maiúculo é {}'.format(nome.upper()))
print('Seu nome em minúsculo é {}'.format(nome.lower()))
print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' ')))
#print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))
div = nome.split()
print... |
8ce65b73a94fa8047edc183e2e9d8c8162a1e017 | danielchk/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 1,427 | 3.84375 | 4 | #!/usr/bin/python3
"""
module 100-matrix_mul
"""
def matrix_mul(m_a, m_b):
"""
multiplies m_a and m_b
"""
if type(m_a) is not list:
raise TypeError('m_a must be a list')
if type(m_b) is not list:
raise TypeError('m_b must be a list')
lens = len(m_a)
len1 = len(m_a[0])
l... |
d8780b2ae68f465c3a17ebc30e3bbc94e02ec206 | liamcarroll/python-programming-2 | /Exam_papers/marks.py | 636 | 3.71875 | 4 | #!/usr/bin/env python3
import sys
def main():
try:
with open(sys.argv[1], 'r') as f:
for l in f:
l = l.strip()
name, mark = ' '.join(l.split()[1:-1]), l.split()[-1]
if int(mark) >= 40:
print('{:s} passed with a mark of {:d}'.... |
f7176e985dd59a288065ef9250215640f2c9d7eb | jeffaustin32/CSC421-A2 | /monopoly/space.py | 3,653 | 4.03125 | 4 | import random
from spaceType import SpaceType
'Represents a space on a Monopoly game'
'https://en.wikipedia.org/wiki/Template:Monopoly_board_layout'
class Space:
def __init__(self, id, color, name, cost, rent, spaceType):
self.id = id
self.color = color
self.name = name
self.cost =... |
860ea45620d64d4b22e0b8bca5aefa5a3ba1b67d | elafleur3/ENG-122-Intro-to-Programming | /ECE 122/Project 3/bank-app3.py | 3,327 | 4.21875 | 4 | from Bank import BankAccount #imports BankAccount class
def app3(): #defines app3
print("Welcome to App3") #prints intro to app3
print("===============")
print( )
mortgage, rate, monthly = input("Enter amount to borrow, rate, and monthly payment: ").split() #takes user inputs and assigns them to ... |
dd51f2036ffc93f78f6ec2b979b3951a1eca664a | mukhamedzarifovakf/mukhamedzarifova | /Prac11/CW11.5.py | 1,367 | 3.734375 | 4 | class Point:
def __init__(self, parametrs = ('0;0')):
a, b = parametrs.split(';')
self.x = float(a)
self.y = float(b)
def Distance(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def DistanceTo(self, point):
return ((self.x - point.x) ** 2 + (self.y - point.y) ** 2) ... |
e817dfe9d19b3aeedfb4c804d6e8f3e9c3dea72b | laughtLOOL/grok-learning-answers | /introduction to programming (python)/4/ShortLong names.py | 255 | 4.25 | 4 | name = input('Enter your name: ')
if len(name) <= 3:
print('Hi ' + name + ', you have a short name.')
elif len(name) >= 4 and len(name) <= 8:
print('Hi ' + name + ', nice to meet you.')
else:
print('Hi ' + name + ', you have a long name.')
|
26e0d865d649d7c3fa3029760e38c4454a4d2f90 | brijsavla/Project2 | /Part2/Question 5/weightedGraph.py | 705 | 3.546875 | 4 | # Prijesh Dholaria
# CS 435 Section 6
# Question 5
class Node:
def _init_(self, val):
self.nodeValue = val
self.adjacentList = {}
class WeightedGraph:
def _init_(self):
self.nodeList = []
def addNode(self, value):
node = Node(value)
se... |
7b5ff1cd65a26df4bc67d3e5ec8d9d26226334b9 | yoshimura19/samples | /python/kisoen/kisoen/day4/test60b.py | 676 | 3.5625 | 4 | #coding:utf-8
#正規表現でくっつける 最初が"なら or 文字列の終端で終わる。
import re
pat1 = re.compile('^"(.*)",(.*)$')
pat2 = re.compile('(.*),"(.*)"')
rows = []
try:
while True:
s = raw_input()
rows.append(s)
except EOFError, e:
pass
#print(rows)
for i in range(0, len(rows)):
resultpat1 = pat1.search(rows[i]... |
59e1945a28b49c7557af9d98a3c8cc304f60e993 | Anshu-Singh1998/python-tutorial | /twelve.py | 450 | 4.21875 | 4 | # let us c
# Write a program to print out a armstrong number between 1 to 500.
a = int(input("Enter 1st number print armstrong number between two numbers: "))
b = int(input("Enter 2nd number to print armstrong number between two numbers: "))
for num in range(a, b + 1):
s = 0
temporary = num
while temporary... |
ee7fdd5e260c37987c2f81f02c6e013474516989 | mayankkagrawal/machine-learning | /class1.py | 129 | 3.625 | 4 | class Calculator():
def add(self,a,b):
return a+b
def subtraction(self,a,b):
return a-b
s=Calculator().add(2,3)
print(s)
|
c9f3cf9371dd31ab107d830b6280bc89249000c0 | israelbyrd/pdsnd_github | /loadandfilterdata.py | 2,555 | 4.65625 | 5 | #!python
#This is a bit of a bigger task, which involves choosing a dataset to load and
#filtering it based on a specified month and day. In the quiz below,
#you'll implement the load_data() function, which you can use directly in your
#project. There are four steps:
# Load the dataset for the specified city. Index the... |
62388ea8fe272a00539f528fb7cd6f62d47f75c5 | viniciusriosfuck/time-calculator | /time_calculator.py | 4,576 | 4.0625 | 4 | def add_time(start, duration, start_day_of_week=False):
def hours2minutes(hours):
minutes_per_hour = 60
minutes = hours * minutes_per_hour
return minutes
def am_pm2hours(am_pm):
if am_pm == 'AM':
hours = 0
elif am_pm == 'PM':
# add up... |
96e59d76bbe24d7aaa8e04153b73de11b1536b47 | GitPistachio/Competitive-programming | /HackerRank/Print Function/Print Function.py | 435 | 3.546875 | 4 | # Project name : HackerRank: Print Function
# Link : https://www.hackerrank.com/challenges/python-print/problem
# Try it on :
# Author : Wojciech Raszka
# E-mail : contact@gitpistachio.com
# Date created : 2020-07-15
# Description :
# Status : Accepted (169096236)
# Tags : python
... |
3b810eac8491b51fc9411c1a645470cee83c5441 | JaysonSunshine/Portfolio | /Software_Engineering/Python/primes.py | 343 | 4.09375 | 4 | import sys
def isPrime(N):
for i in range(2, N / 2 + 1):
if N % i == 0:
return False
return True
def primes(N):
if N == 1:
return 0
if N == 2:
return 1
count = 1
for i in range(3, N + 1):
if isPrime(i):
count += 1
return count
def main(args):
print primes(int(sys.argv[1]))
if __name__ == "__ma... |
87e256dcc1df83cdd27cdea54762809a6df0c758 | Casmali/inputs | /webapp.py | 2,076 | 3.640625 | 4 | from flask import Flask, url_for, render_template, request
app = Flask(__name__) #__name__ = "__main__" if this is the file that was run. Otherwise, it is the name of the file (ex. webapp)
@app.route("/")
def render_main():
return render_template('index.html')
@app.route("/fir")
def render_page1():
return re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.