blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
080f20f81e01b51c18369cf95af339d985d16cb5 | vivekanand-mathapati/coding-for-interviews | /python/binarytree.py | 780 | 3.78125 | 4 | class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
root = Node()
def insert_node(data):
root = insert(root, data)
def insert(root, data):
if root is None:
root = Node(data)
return root
if... |
b76f0012e2010c0d9899879dfff0b013071c36fb | rpereira91/interview-questions | /Mock Interviews/mock_1.py | 2,200 | 3.625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
L, R, an... |
84176f794536d7e4e80222954d1ca16ef031683a | Aasthaengg/IBMdataset | /Python_codes/p02255/s169369447.py | 242 | 3.734375 | 4 | def insertionSort(a):
for i,v in enumerate(a):
j=i-1
while j>=0 and a[j]>v:
a[j+1]=a[j]
j-=1
a[j+1]=v
print(*a)
n = int(input())
a = list(map(int,input().split()))
insertionSort(a) |
7eed6f9370819084e9bf0f4893ada67d7c5daf9b | lawrel/unilabs | /lab4.py | 800 | 3.671875 | 4 | import sys
import random
def Rselect(x,k):
if k == 0: return "Invalid K"
def select(array,s,e,k):
if e==s: return array[s]
else:
pivot = random.randint(s,e)
array[s],array[pivot] = array[pivot],array[s]
index = s
for j in range(s+1,e+1):
if array[j] < array[s]:
index += 1
... |
917d904f2729c0650410048416d3180d0d67f03e | elvarlax/python-masterclass | /Section 03/03 - Printing tabs/coding_exercise3.py | 272 | 4.1875 | 4 | """
Coding Exercise 3 - Printing tabs
Write a program that will produce the following output.
All the text should appear in your program's output.
Number 1 The Larch
Number 2 The Horse Chestnut
"""
print("Number 1\tThe Larch")
print("Number 2\tThe Horse Chestnut")
|
0b8384bb89b5cf922391c8b81e0b707fc7c82fa4 | Linkin-1995/test_code1 | /day09/exercise05(sep指定分隔符).py | 376 | 3.953125 | 4 | # 练习:体会print函数参数
# 星号元组形参 , 命名关键字形参
# 实参数量无限 , 关键字实参
# def print(*values, sep = " ", end="\n")
print()
print("你好")
# 还可以打印多个数据
print(1, 2, 3) # 1 2 3
# 还可以指定分隔符
print(1, 2, 3, sep="-") # 1-2-3
print(1, 2, 3, sep="-", end=" ") # 1-2-3
# print(1, 2, 3,"-"," ")# 1-2-3 |
f0ed459cd85b81958c22b169b090713a5ba53164 | henryvu25/630-Final | /630FinalProjectCode.py | 10,491 | 4.40625 | 4 | """
These classes are for a POS at a grocery store. The Food class is the base class
and Produce, Alcohol, and Frozen are subclasses. Each inherit name and unitPrice from
the base class. Depending on the situation, each subclass has its own specific
methods for the POS to deal with.
The 3 design patterns used here are... |
b84478127c1f73fb4bc344f5ed4ba7eb170a86ac | HenriTammo/Koolitus | /tund1/teegid.py | 185 | 3.546875 | 4 | import math
import random
arv1 = 144
ruutjuur = math.sqrt(arv1)
print (ruutjuur)
arv2 = random.randint(1, 6)
print(arv2)
if arv1 != arv2:
print (arv1, "on alati suurem kui", arv2) |
4601faf68e5abaaea6b59cafb4c2705fc35dacc0 | slamatik/codewars | /5 kyu/Perimeter of squares in a rectangle 5 kyu.py | 231 | 3.828125 | 4 | def perimeter(n):
fib = [1, 1]
while len(fib) < n + 1:
fib.append(fib[-1] + fib[-2])
return sum(fib) * 4
print(perimeter(5))
print(perimeter(7))
print(perimeter(20))
print(perimeter(30))
print(perimeter(100))
|
aaa7a6409f62075705d5b971fe8227770dcec8bf | dvminhtan/python_core | /source/lession_2/baitap7.py | 748 | 3.625 | 4 | """
Tìm và in lên màn hình tất cả các số nguyên trong phạm vi từ 10 đến 99 sao cho tích của 2 chữ số
bằng 2 lần tổng của 2 chữ số đó. Ví dụ: Số 44
"""
a = int(input("Nhap a: "))
b = int(input("Nhap b: "))
while True:
try:
if a < 10 or a > 20:
print("Nhap sai. Nhap lai")
a = int(input... |
9aff6a6b092ff3f0eb176e86c019c72a0fc924f3 | gustkust/More-advanced-Python-exercises-for-university | /Physics of perfect elastic ball collisions.py | 9,026 | 3.859375 | 4 | # imports
import pygame
from math import sqrt
from random import randint, uniform
# some variables
SCREEN_WIDTH = 720
SCREEN_HEIGHT = 720
FPS = 60
BACKGROUND_COLOR = (255, 255, 255)
BALLS_COLOR = (31, 132, 155)
BALLS_SIZE = 30
NUMBER_OF_BALLS = 10
BALLS_SPEED = 5
RED_LAUNCH_TIME = 100
STOP_TIME = 3600 + RED_LAUNCH_TI... |
33da3242309a86ac25cb65c52755c2b95b6de0a1 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2535/60606/284125.py | 469 | 3.8125 | 4 | #如果位置和原数组一样,那么就说明可以分割
array = input()[1:-1].split(",")
array = [int(x) for x in array]
origin = array.copy()
origin.sort()
set_origin = set()
set_array = set()
count = 0
for i in range(len(array)):
set_origin.add(origin[i])
set_array.add(array[i])
if len(set_origin.difference(set_array)) == 0:
count... |
fd12201bd93001316255752a17fdb64998497f37 | luismichu/Python | /ej4.py | 772 | 4.125 | 4 | from random import randint
max_num = int(input('Hasta que numero quieres adivinar: '))
intentos = int(input('Numero de intentos: '))
adivinar = randint(0, max_num)
num = input('\nAdivina: ')
if num.isnumeric():
intento = 1
dic = {intento:int(num)}
while intento < intentos and num.isnumeric() and int(num) != adivi... |
24818c3f54452988320a34588987345f69e068b9 | yaoyu2001/LeetCode_Practice_Python | /309. Best Time to Buy and Sell Stock with Cooldown.py | 1,248 | 3.875 | 4 | # Say you have an array for which the ith element is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
#
# You may not engage in multiple... |
8ef99bcf38165e4588313dad50c151958907739f | qjm100/password | /veiji.py | 2,399 | 3.625 | 4 | #作者:qjm
#鸣谢:Kevil
import getopt
from string import ascii_lowercase as lowercase
import sys
import pyfiglet
def En(p, key):
p = get_trim_text(p)
ptLen = len(p)
keyLen = len(key)
quotient = ptLen // keyLen # 商
remainder = ptLen % keyLen # 余
out = ""
for i in range(0, quotient):
fo... |
e069bee1fe8f23513246a822a032a12a5a9d85fa | yao76/Coding-Dojo-Python | /Week_3/python/OOP/classes_practice.py | 995 | 4.03125 | 4 | # class User: # declare a class and give it name User
# def __init__(self):
# self.name = "Michael"
# self.email = "michael@codingdojo.com"
# self.account_balance = 0
# guido = User()
# monty = User()
# monty.name = "Monty"
# print(guido.name)
# print(monty.name)
class User:
def __ini... |
cd413b1ca6492c3652972210a91b99c0f5da8db4 | rjcate/Pressure_sensor_use | /single_pressure_plot_and_stats.py | 3,667 | 3.5625 | 4 | '''
Calculate statistics and generate graphs for raw sensor data
using a variety of window sizes. Generates one plot using each
window size per data file input.
Inputs:
sys.argv[1] - directory containing raw data. Generated images also save here
sys.argv[2] - name of the sensor being t... |
40036b195cb472d18d827d0c3bf1829704db07f0 | Saqlainrocks7/Rock_Paper_Scissors | /ro_pa_sc.py | 1,179 | 3.8125 | 4 | from art import rock, paper, scissors
import random
user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper and 2 for Scissors.\n"))
comp_choice = random.randint(0, 2)
game_images = [rock, paper, scissors]
if user_choice == 0 and comp_choice == 2:
print("You chose:\n{}".format(game_i... |
21bf82dca5fcf782509c9dc4bd17d807c6c79d53 | danielhp02/Pong | /code/objects.py | 5,096 | 3.5 | 4 | import random
class Ball():
def __init__(self, startX, startY, pygame, surface, radius):
self.startPos = (startX, startY) # This is where the ball will return to after a point is scored
self.x = startX
self.y = startY
# These are so the bats can interact with the game without pyga... |
53ae25d696254bbb425e80d5106fa94decf85f6c | TheGoldenShark/Advent-Of-Code-2020 | /D6/D6.5.py | 401 | 3.515625 | 4 | import string
with open("input.txt","r") as f: data=f.readlines()
data = [x[:-1] for x in data]
dataProcessed = []
temp=set(string.ascii_lowercase)
for i in data:
if i== '':
dataProcessed.append(temp)
temp=set(string.ascii_lowercase)
else:
temp = temp.intersection(set(i))
dataProcessed.... |
07b5de946f56b449de717373ccc4863348fa882a | abhishekdwibedy-2002/Spectrum_Internship_Task | /prgm9.py | 294 | 4.0625 | 4 | n = int(input("Enter number of elements : \n"))
lst=[]
print("Enter",n ,"Elements")
for i in range(0, n):
element = int(input())
lst.append(element)
idx=int(input("Enter the value To Find The Smallest no. :- \n"))
lst.sort()
print("Your " ,idx,"th smallest no. is: ",lst[idx-1]) |
e902c1b74c79d2e277248505c38019dfec282d6c | kgerg2/Imperativ | /2.ora/ropzh.py | 187 | 3.796875 | 4 | def fizzbuzz():
a = int(input("Add meg a számot:"))
eredm = ""
if a % 5 == 0:
eredm += "Fizz"
if a % 3 == 0:
eredm += "Buzz"
return eredm
|
8cfa77fdb730918b71d52f8e4eb078462b5c955e | fatihunal78/Python_Assignments_CodeInPlace | /Assignment2/khansole_academy.py | 867 | 4.1875 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
import math
MIN_NUM = 10
MAX_NUM = 99
def main():
count = 0
while count < 3:
number_1 = random.randint(MIN_NUM, MAX_NUM)
number_2 = random.randint(MIN_NUM, MAX_NUM)
total = number_1 + nu... |
1045ec6dd515836aa0c1d6ebc72ee665512ccca9 | vins89/Assingment1_math | /Assignment 2/evenodd.py | 447 | 4.1875 | 4 | var1= raw_input("enter a number: ")
if int(var1) % 2 ==0:
print "The number is even"
else:
print ' the number is odd'
if int(var1) % 4 ==0:
print " the number is a multiple of 4"
else:
print " the number is not divisible by 4"
num = int(raw_input("enter number a "))
check = int(raw_input("enter number ... |
cc229dbd60bfc347cc468e20e518a81b5678f327 | guyuzhilian/Programs | /Python/project_euler/problem30.py | 547 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: lidajun
# date: 2015/7/31
# time: 10:23
def get_nth_digit(num, n):
return (num / pow(10, n-1)) % 10
def sum_of_fifth_power(num):
total = 0
for n in xrange(1, len(str(num))+1):
digit = get_nth_digit(num, n)
total += pow(digit, 5)
... |
5d781a52fb550a565c625739228f90eb61d6db48 | maryferivera14/The-New-Age | /The new age -code.py | 810 | 3.9375 | 4 | def temperatura():
#Aqui recibiria la temperatura de forma automatica al estar conectado el sensor de calor
#Los estados del ventilador seran representados como ON = 1 y OFF = 0
vent=0
cal=float(input("CANTIDAD DE GRADOS: "))
if cal>37:
print("VENTILADOR ENCENDIDO")
vent=vent+... |
6b58a1e4b9dea5565193c27f8a72a6eeb113fbc4 | sainihimanshu1999/Leetcode---Top-100-Liked-Questions | /intersectionoftwolinkedlist.py | 588 | 3.65625 | 4 | '''
using dictionary
'''
def intersection(self,headA,headB):
dic = {}
curr1 = headA
curr2 = headB
while curr1:
dic[curr1] = curr1.val
curr1 = curr1.next
while curr2:
if curr2 in dic:
return curr2:
dic[curr2] = curr2.val
curr2 = curr2.next
'''
u... |
8dbbbb32e1ddabf29571ab1ec3bd89415146537d | LittleFee/python-learning-note | /day06/04-class-inherit.py | 3,461 | 4.46875 | 4 | # 一个类继承(inherit)另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,
# 而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法
class Car():
"""描述小汽车,包括年份、制造商和型号"""
def __init__(self,maker,model,year):
"""初始化汽车属性"""
self.maker=maker
self.model=model
self.year = year
self.odometer_reading=0
# 给一个路码... |
cc43a518cf27e37dbd7bdfa7b4fc7db4b4973152 | tux-linux/Python-works | /CalculatriceAléatoire.py | 1,228 | 3.9375 | 4 | import random
from math import sqrt
nombres = range(1, 100000)
operations = ["*", "/", "+", "-", "sqrt"]
print("Calculatrice aléatoire Python")
_init_ = 1
while _init_ == 1:
nombre1 = random.choice(nombres)
nombre2 = random.choice(nombres)
operation = random.choice(operations)
if operation == "*":
... |
89357603502974a6d0ecbc82d30660372353f5e6 | eymkarla/gitpy | /dictionary.py | 326 | 4.0625 | 4 | thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
thisdict["apple"] = "red" #change green to red
thisdict = dict(apple="green", banana="yellow", cherry="red")
thisdict["damson"] = "purple" #insert another value in the dict
del(thisdict["banana"]) #delete
print(len(thisdict)) #length of di... |
351809d6e886b851498b573d3849c5015668db6c | zhaohj2017/nnreach-nsfc | /pipes.py | 477 | 3.53125 | 4 | import numpy as np
import superpara
import activation
import ann
#the neural network weight computed for the ith (i >= 0) step is stored at index i in PIPES
PIPES = []
#after training, add the final value of weights to pipes
def addpipe():
global pipes
w_matrix = ann.weight_matrix.copy()
w_h_o = ann.weight_h_o.cop... |
7b0c521ac7a5983b72b3916d5444d81aa8cfdc50 | pedroeml/t1-fcg | /CrowdDataAnalysis/graph/node.py | 1,287 | 3.671875 | 4 | from graph.edge import Edge
class Node:
def __init__(self, item):
"""
:param item:
:param edges:
:type edges: dict
"""
self.item = item
self.edges = {}
def add_edge(self, node, weight):
"""
:param node:
:type node: Node
... |
13047359d89a6d146937d62c4461eb0bc2c89a49 | mHernandes/pad-like-game | /button.py | 1,100 | 3.65625 | 4 | import pygame
from settings import Settings
class Button:
""" A Class to manage the button """
def __init__(self, game):
""" Initializes the Class """
# Settings instances
self.settings = Settings()
# Assign the screen from pinball.py to Button in order to access it and get rect
self.screen = game.scree... |
df95751c57869fb3260b76e2de6e9e8f95f15689 | Andor-Z/My-Learning-Note | /ThinkPython/code/widget_demo.py | 3,660 | 4.5 | 4 | """Solution to an exercise from
Think Python: An Introduction to Software Design
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
This program requires Gui.py, which is part of
Swampy; you can download it from thinkpython.com/swampy.
This program demonstrates how to use the Gui ... |
71ee82791a257bcf420dd47070b8b7a6463e10b6 | jayhebe/w3resource_exercises | /Basic - Part2/ex5.py | 104 | 3.6875 | 4 | numbers = []
for num in range(1000):
num = str(num).zfill(3)
numbers.append(num)
print(numbers)
|
71c415f2a7105e25dfcae9038151e91925144255 | Song2017/Leetcode_python | /Leetcode/226.invertTree.py | 988 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def invertTree0(self, root: TreeNode) -> TreeNode:
'''
翻转一棵二叉树
'''
# 当前节点不存在或不存在子节点时返回
if not root or not ... |
15f47ffa83ab3c0eb6e0cc2c150daa272aadbad3 | Smoow/MIT-UNICAMP-IPL-2021 | /solutions/p2_5.py | 1,586 | 4.34375 | 4 | from string import ascii_lowercase, digits
def handle_letter(char, shift):
"""
Helper function for Caesar Cipher. Handles the case the character is a letter.
Args:
char: length-one string, letter character
shift: shift value of caesar cipher
Returns:
new letter that should be... |
ff2660c9e4fe9f9db0cc002381a5bb618377d016 | schatzke/Dailyexercise | /exercise 17 - Decode A Web Page.py | 695 | 3.6875 | 4 | '''
Exercise 17 Decode A Web Page
Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the New York Times homepage.
Discussion
Concepts for this week:
Libraries
requests
BeautifulSoup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#output-formatters
''... |
c697b2494bc80202d8c07ac71e3641657955b129 | ben-holland-young/learn | /diff2/calculator.py | 104 | 3.5625 | 4 | calc = input("Input your calculation")
print(eval(calc))
#eval turns a string into runnable python code
|
bd0cbf93feffea1467e470315478b4050c2b3a85 | llpuchaicela/Proyecto-Primer-Bimestre | /NumeroPositivoNegativo.py | 328 | 3.90625 | 4 | print ("Ejercicio7")
print ("Lilibeth Puchaicela")
print("Programa para cálcular si un número es positivo o negativo")
#Declaracion de variables
n = 0
srt = ""
#Datos
n=int(input("Ingrese un número diferente a cero : "))
n = int(n)
#Proceso
if n > 0:
print("El numero" ,n, "es positivo")
else:
print ("El numero" ,... |
073166a38495c621121ed73c4d7ecc44e69d2e3f | colo1211/Algorithm_Python | /기초 알고리즘 100제/6027. 값변환03.py | 259 | 3.546875 | 4 | a=int(input())
print('%x'%a)
#10진수->16진수로 변환
#print('%x'%변환할10진수)
# 10진수 형태로 입력받고
# %x로 출력하면 16진수(hexadecimal) 소문자로 출력된다.
# (%o로 출력하면 8진수(octal) 문자열로 출력된다.) |
f7ad55c8694b08f61b8ce4767ce5a9da600330f7 | ujjvalchauhan/python-challenge | /PyBank/code/main.py | 1,170 | 3.78125 | 4 | import os
import csv
bank_csv_path = os.path.join( "..", "Resources", "budget_data.csv")
totaltrans =[]
months=[]
average=[]
profchange=[]
with open(bank_csv_path, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
next(csvreader,None)
for row in csvreader:
... |
08ec943c18b1a38f2c17b50f5a52d224c8baebd5 | jaap3/sourcebuilder | /sourcebuilder/pysourcebuilder.py | 2,537 | 3.75 | 4 | from __future__ import with_statement
import textwrap
from contextlib import contextmanager
from sourcebuilder import SourceBuilder
INDENT = ' ' * 4
TRIPLE_QUOTES = '"' * 3
DOCSTRING_WIDTH = 72
class PySourceBuilder(SourceBuilder):
"""
A special SourceBuilder that provides some convenience context managers
... |
965670759666c8237775eda5c657ec2d4f8c075a | shivanshrai13/python-sep-batch | /string_suggestion.py | 425 | 3.734375 | 4 | #This problem was asked by Twitter.
'''Implement an autocomplete system. That is, given a query string s and a set of all
possible query strings, return all strings in the set that have s as a prefix.
For example, given the query string de and the set of strings [dog, deer, deal], return
[deer, deal].'''
a = ['dog', 'd... |
f216eb3533679ea28b02e21f4a03cb68d4048b03 | s19013/my_program_python | /class/shopping.py | 1,425 | 3.78125 | 4 | import math
class CalcFee:
def __init__(self):
"""初期化"""
self.shipping_fee=1000 #送料
self.tax_rate= 0.08#税率
self.value = 0#合計
self.sppedy =500 #速達
def additem(self,price):
"""商品の値段を加算"""
self.value+=price
def calc(self,ques):
"""最終的 金額"""
self.ques=ques
total=self.value +... |
ec8ebb8d88ea5047f935282acb20648a1bfd7dde | Vikas6206/PythonBasics | /home/sample/After3Hours/ClassConstructor.py | 435 | 3.75 | 4 | class Point:
#defininng the constuctor via init method
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
point = Point(10, 20)
print(point.x)
class Person:
def __init__(self,name):
self.name=name... |
e4e085bec2fd382183fd9747120af7149669b890 | mocaco/dev236x | /final.py | 1,337 | 4.21875 | 4 | # def main function adding_report()
def adding_report(arg):
print('Input an integer to add to the total or "Q" to quit.')
# init default values
loop = True
total = 0
items = ""
# while loop to provide multiple input
while loop:
# default prompt
check = input('Enter ... |
ee853617dc0be4b097a6b476156e36de97007eb5 | sanjogj43/Test_Project_1 | /main.py | 836 | 3.9375 | 4 | # print("Hello World")
def print_something(name="Sanjog", age=20):
print("my name is ", name, "and my age is ", age)
# print_something()
def print_inf(*people):
for person in people:
print("Person is ", person)
# print_inf("John", "Smith", "Rog")
def do_math(num1, num2):
return num1 + num2
... |
3cd6b874a651344fd8125af262d2b36b4f660a93 | FelipeKonig/ExerciciosPython | /107Exercicios.py | 1,208 | 4.03125 | 4 | # 1) Imprima os metodos disponiveis para uma lista e para uma tupla.
# 2) Faca um metodo para retornar apenas as diferencas entre as duas de metodos
# 3) Adicione as coordenadas (latitude, longitude) para os dicts professor1, professor2 e professor3. Copie os dicts do arquivo 106.py
professor1 = {'id': 42, 'name': 'Al... |
9cdd2c3447e1217d39e8ef682f3fc68972cbfd21 | cs-fullstack-2019-fall/python-coding-concepts1-weekly-5-Kenn-CodeCrew | /question2.py | 372 | 4.15625 | 4 | # ### Problem 2:
# Ask the user for a string. If they enter “Kenn”, “Kevin”, “Erin”, or “Autumn” print “Hello Teacher”. Otherwise print “Hello Student”
userInput = input("Enter a string")
if (userInput == "Kenn" or userInput == "Kevin" or userInput == "Erin" or userInput == "Autumn"):
print("Hello Teacher")
else:... |
249d8e81049ab0ab108b6c76d823c0b70927647f | ChenLaiHong/pythonBase | /test/myself/TestStr.py | 4,482 | 4.0625 | 4 | # 字符串切片操作
# 字符串下标可以为负数但是不能超过长度减1
name = "abcdefgbhk age name"
print(name[0])
# 下标为负数就是从字符串后面开始数
print(name[-1])
# 获取字符串片段:name[起始:结束:步长],获取范围[起始,结束),默认步长为1
# 步长> 0,从左到右;步长< 0,从右到左。注意:不能从头部跳转到尾部,也不能从尾部跳转到头部
print(name[0:3])
print(name[4:1:-1])
# 反转字符串
print(name[::-1])
# len(x):计算字符串的字符个数,转义字符占一个
print(len(name))
# ... |
ffbeca9acc56785f04fe937960409337042309fe | XxSlowMOxX/ProjektUnikot | /gameclass.py | 686 | 3.65625 | 4 | class Game:
def __init__(self, Players):
self.Players = Players
def addPlayer(self,player):
self.Players.append(player)
def getMPos(self):
return [self.Players[0].x, self.Players[0].y, self.Players[0].rep]
def setOPos(self, opos):
# TODO
self.Players[1... |
e8a3b0b2506fb964820d64b6fe2b37350b111465 | Jordan-Rowland/oop-practice | /notebook/notebook.py | 2,197 | 3.546875 | 4 | import datetime
# Store the next available ID for all new notes
last_id = 0
class Note:
"""Represents note in the notebook. Match against a string in searches and store tags for
each note."""
def __init__(self, memo, tags=''):
"""Initialize a note with memo and optional space-separated tags. Aut... |
a4908d1ebe0bbc9d5dc817cfc71c0373b2cbe184 | EltonZhong/leetcode | /middle/PrefixTree.py | 2,747 | 4.09375 | 4 | # coding=utf-8
"""
https://leetcode.com/problems/implement-trie-prefix-tree/description/
"""
from typing import Any
class Trie:
"""
trie
"""
class Node:
"""
node
"""
def __init__(self, ch: Any):
self.children = []
self.char = ch
se... |
8d07c12136d2831cc08935bb89266ddb6f62c947 | gumityolcu/Binari | /Code/syllabliser.py | 3,972 | 3.875 | 4 | """
Türkçede kelime içinde iki ünlü arasındaki ünsüz,
kendinden sonraki ünlüyle hece kurar: a-ra-ba, bi-çi-mi-ne, in-sa-nın, ka-ra-ca vb.
Kelime içinde yan yana gelen iki ünsüzden ilki kendinden önceki ünlüyle,
ikincisi kendinden sonraki ünlüyle hece kurar: al-dı, bir-lik, sev-mek vb.
Kelime içinde yan yana gelen üç... |
03ed5477761ec59a0e7f02c18d80f21e44617ad6 | doctone/myKatas | /piglatin.py | 731 | 4.375 | 4 | '''
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !
'''
def pig_it(text):
#create empty list of new words
new_words = ... |
d14a8253d21e1cb306b5f3805b5e189bb685322c | opavelkachalo/phoneCallsApp | /main.py | 1,035 | 3.890625 | 4 | from src.classes import Abonnent
import time
def main():
while True:
number = input("Enter your phone number (or press RETURN to exit): ")
if not number:
break
abonnent = Abonnent(int(number))
time.sleep(1)
if abonnent.enter_status:
while True:
... |
8e76fe2a8c6d40facc9be2b5a59a2f2ac0f844e9 | melissa1824-cmis/melissa1824-cmis-cs2 | /cs2quiz2.py | 1,713 | 4.15625 | 4 | import math
#PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) 3 == 3 #point
#b) 5 != 8 #point
#c) 45 > 23 #point
#
#2) What does 'return' do?
# returns/prints the value/result of the function. #point
#
#3) What are 2 ways indentation is important in python code?
#a) It knows that the next line is pa... |
b2481f42ba00f5d6f1ca8d23e92c40aee235ef4b | fpavanetti/python_lista_de_exercicios | /aula23_explicação.py | 2,067 | 3.984375 | 4 | '''
Aula 23 - Tratamento de erros e exceções
----- ERROS ACONTECEM: SEMPRE -----
Existem erros de diferentes tipos
> primt(x), por exemplo, é um erro de sintaxe
O programa estar escrito corretamente não quer dizer que ele está "certo"
print('Oi')
print(x) -> x não foi inicializado. Erro semânetico
Qua... |
23cc9b0343cf4491611295f2a52e9affcfcb7d01 | TheMoira/PythonLearning | /first_file/arithmetics.py | 285 | 3.9375 | 4 | import math
print(10/3)
print(10//3)
print(10**3)
x = 2.9
print(round(x))
print(math.ceil(x))
is_night = True
if (math.floor(x) > 1):
print("x is big")
elif is_night:
print("night")
else:
print("day" + "*" * 20)
if is_night and x:
print("shit") |
9bd2f9e19daa516be1ebe72a793f7057590a9ae5 | alcazar007/python-challenge | /PyBank/main_Second_Attempt.py | 4,109 | 4.375 | 4 | ## PyBank
'''
* In this challenge, you are tasked with creating a Python script for analyzing
the financial records of your company. You will give a set of financial data
called [budget_data.csv](PyBank/Resources/budget_data.csv).
The dataset is composed of two columns: `Date` and `Profit/Losses`.
* Your task is... |
ddb1a8d6ee748a4efaaf3d9fe160ae24417754ab | kolo-abb/Graph_segmentator_app | /segmentation_app/utils.py | 414 | 3.875 | 4 |
def convertToBinaryData(filename):
#Convert digital data to binary format
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def writeTofile(data, filename):
# Convert binary data to proper format and write it on Hard Disk
print(filename)
with open(filename,... |
80731a463c41a7484990e26e8eafc6f011909b18 | harshath2017/psp-manual_17B37 | /matrix.9.py | 519 | 3.953125 | 4 | def matrixmulti(X, Y):
# X dimension is M x N
# Y dimension is N x P
M = len(X)
N = len(X[0])
P = len(Y[0])
# resultant matrix dimension is M x P
Z = [[0] * P for row in range(M)]
if N != len(Y):
print ("Incorrect dimensions.")
return
for ... |
1044b6463b9d0db8531df31aeb3f50af57b1a8e4 | rmcarthur/acme_labs | /Lab16v1.py | 2,954 | 3.5625 | 4 | import numpy as np
import math
import scipy as sp
from matplotlib import pyplot as plt
## Problem 1 ##
def Newton(func, error, maxiter, guess, prime = None):
h = 1e-6
converge = True
iterations = 0
change = np.inf
x0 = guess
def NoPrime(xold, func):
deriv = (func(xold+h)-func(xold))/h... |
0969c35f3081cf507a8000199978d43fc88e2b9e | sahilkumar171193/mycodes | /swap2number.py | 137 | 3.859375 | 4 | a=6
b=5
temp=a
a=b
b=temp
print(a)
print(b)
a=a+b
b=a-b
a=a-b
print(a)
print(b)
a,b=b,a
print(a)
print(b)
|
beb22c5ae57e61e41953fe68ee5cec3c08ea18bd | knut0815/Book | /Part 2/Chapter 11/Multinomial_logistic_regression_using_iris_dataset(Listing_13).py | 1,282 | 3.59375 | 4 | #import the required libraries for model building and data handling.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score,confusion_matrix
from sklearn.model_selection import train_test_split
#Load the dataset and generate the train and t... |
1f2262d497bd7b4046de491f8a6187f45abc06c9 | wxyBUPT/leetCode.py | /dp/Solution_309.py | 2,681 | 3.765625 | 4 | #coding=utf-8
__author__ = 'xiyuanbupt'
# e-mail : xywbupt@gmail.com
'''
309. Best Time to Buy and Sell Stock with Cooldown Add to List QuestionEditorial Solution My Submissions
Total Accepted: 31636
Total Submissions: 80223
Difficulty: Medium
Contributors: Admin
Say you have an array for which the ith element is t... |
dc74bf4ad3eeacfbccded9f2a210940ca67a0911 | vishalikannan96/python-solution | /problemset3/proset3_8.py | 814 | 3.984375 | 4 | #Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical
# order (double letters are ok). How many abecedarian words are there? (i.e) "Abhor" or "Aux" or "Aadil"
# should return "True" Banana should return "False"
'''def is_abecedarian(word):
word=list(word)
if ... |
719b2648bc2848890cf516de7983b163c2847829 | ShenTonyM/LeetCode-Learn | /Q410SplitArrayLargestSum.py | 915 | 3.578125 | 4 | class Solution1(object):
def isValid(self, nums, m, max_sum):
"""
:rtype: bool
"""
count = 0
accumu = 0
for i in range(len(nums)):
accumu += nums[i]
if accumu > max_sum:
count += 1
if count >= m:
... |
1a47efcb48e7ffa277ad6b572d6dfc345091037c | juda/scheme | /mutual_with_text.py | 2,811 | 3.53125 | 4 | '''mutual with text'''
import numbers
from pair import *
import sys
def parentheseBalance(statement):
res=0
for i in statement:
if i=='(':
res+=1
elif i==')':
res-=1
if res<0:
raise SyntaxError('Unmatched parentheses')
return res==0
def isnumber(... |
e4a6f924056974ed1d4eff0bd7bd6e976e284486 | spgeise/Restaurant-Selector | /Main.py | 4,964 | 3.53125 | 4 | from Files.GetRestaurants import RestaurantList
import time, sys, os
from random import randint
rest_dict = {}
final_options = []
def select_restaurants():
x = list(map(int, input("Make your selections: ").split()))
print('\n')
for i in x:
print(rest_dict[i])
final_options.... |
75232280bf665d972c8fe61e39650c81bb36189f | pylinx64/sun_python_18 | /sun_python_18/pic3.py | 376 | 3.6875 | 4 | import turtle
t=turtle.Pen()
#-------------
t.shape('turtle')
t.forward(100)
#t.write('Hello Киберпанк 2030', align='right', font=('Minecraft Rus Regular', 5))
t.speed(0.5)
colors = ['red', 'cyan', 'brown', 'lime', 'white', 'blue']
for color in range(500):
t.pencolor(colors[color%6])
t.left(45)
t.forw... |
d0834883d1701d05a452e2fe3d12d69b7e8c2e19 | Tussi/autosendemail | /Sendmail/randCont.py | 11,294 | 3.765625 | 4 | # 读取指定文件随机生成邮件内容
import csv
import random
def randCont():
csv_file = csv.reader(open('./Resource/contents.csv'))
columnNa = []
columnSu = []
columnCon = []
for row in csv_file:
columnNa.append(row[0])
columnSu.append(row[1])
columnCon.append(row[2])
colNameS = random.cho... |
5c3788167dbdba7206a3e284ea001cb68527e405 | mpolis2/CodingNomads-PythonLabs | /02_basic_datatypes/2_strings/02_09_vowel.py | 787 | 4.1875 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
# get user sentence
sentence = input("type a sentence: ")... |
a8052b0769540b33a51c572d38e528d7cb7c293f | kedard1995/Summarization-comparison | /wiki_sum.py | 2,356 | 3.703125 | 4 | import wikipedia
def summarize(content,num):
#Step 1: Make an intersection function which forumulates the intersection between two sentences, as in, takes two sentences and finds the number of common words between them.
#Step 2: Split the content into sentences, and find the intersection of each sentence with all t... |
a397d26a1166dce8f8797fec6ad607142dd2d895 | ike1212/python-assignments | /3.4.3/ikesimage.py | 1,711 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
This code provides a solution to the
change_pixels.py project.
change_pixels.py modifies an image's pixels using
nested for loops.
by Gabriel A Pass 2020
"""
import matplotlib.pyplot as plt
import os.path
from itertools import chain # allows chaining of ranges for iterative operations
impor... |
8e0e1a064afe0050e0527f3a6e552bc49ac11113 | viviyin/bdpy | /demo31_python_dict_default.py | 201 | 3.5625 | 4 | lists = ['s', 's', 'm', 'l', 'xl', 's', 'm', 'l', 'l', 'xl', 's', 'ss', 's', 'm', 'l', 'xl']
total = {}
for item in lists:
total.setdefault(item, 0)
total[item] += 1
print(f'total={total}')
|
b4d49cf2e745445b472f7a6ce49e25844c871dae | WenhaoChen0907/Python_Demo | /01_hellopython/hn_12_evenSum.py | 211 | 3.65625 | 4 | # 计算 0 ~ 100 之间 所有 偶数 的累计求和结果
result = 0
i = 0
while i <= 100:
# print(i)
result += i
i += 2
print("0 ~ 100 之间 所有 偶数 的累计求和结果: %d " % result) |
35d5d557378a2e6fb0225a2eae89557dcfc08b08 | fastdft/eular | /116.py | 892 | 3.59375 | 4 | import os
import sys
def count_recur(cnt, length, cnt_dict):
if cnt < length:
return 1
#because the tiles may not replace at all, so there should be 1 more case
ret = 1
# i means the number of titles been eaten, the cnt+1 means all titles have been eaten
for i in range(length, cnt+1):
... |
abb8ada9025a2b604871913447552d370305eebf | nathan-chappell/unios-machine-learning | /linalg.py | 8,804 | 4.21875 | 4 | # linalg.py
#
# python refresher and introduction to doing linear algebra with numpy
# begin standard imports
import pdb
import numpy as np
import numpy.linalg as linalg
hr = lambda: print('\n'+40*'-'+'\n')
def _print(*args,**kwargs):
print(*args,**kwargs)
hr()
# end standard imports
## Exercise 1: basic operat... |
3d9741e42e3d761a4b8a34f3dadcad28f8e56256 | smkr9000/IMDB- | /movies.py | 438 | 3.546875 | 4 | #!/usr/bin/env python
from rotten_tomatoes_scraper.rt_scraper import MovieScraper
movie_name = input("Enter_movie name: ")
web_api = 'https://www.rottentomatoes.com/m/%s' % movie_name.replace(" ", "_")
movie_scraper = MovieScraper(movie_url=web_api)
movie_scraper.extract_metadata()
data = movie_scraper.metadata
prin... |
1980918ca57f2b49d2ad923ead1e7246b27a2a19 | nicefuu/leetCode-python3 | /66.py | 846 | 3.765625 | 4 | """给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
"""
class Solution:
def plusOne(self, digits):
"""
:param digits: list[int]
:return: list[i... |
24d725858654c730324fd794010a0ef3e4e04081 | mohitKhanna1411/COMP9021_19T3_UNSW | /pascal_nth_line.py | 277 | 3.796875 | 4 | from math import factorial
result = list()
def nCr(n, r):
result.append( int((factorial(n) / (factorial(r)
* factorial(n - r)))) )
number = int(input("Input a number"))
for i in range(number):
nCr(number - 1,i)
print(str(result).replace(',','')) |
856fd6f42fa31e8a0bec17972273e526607706b2 | raychangCode/Python-projects | /Photoshop I/mirror_lake.py | 1,220 | 3.625 | 4 | """
File: mirror_lake.py
Name: Ray Chang, 2020.08
----------------------------------
This file reads in mt-rainier.jpg and
makes a new image that creates a mirror
lake vibe by placing the inverse image of
mt-rainier.jpg below the original one
"""
from simpleimage import SimpleImage
def reflect(filename):
"""
... |
44518b0bd21c75c3cb41abd4b637b0bcd4dd831d | milind-okay/source_code | /python/continue.py | 176 | 3.890625 | 4 | num = 0
den = 0
while den != 1:
print("enter num")
num = float(raw_input())
print("enter den")
den = float(raw_input())
if den == 0:
continue
print(num/den)
|
6b199c745ccfdfb192810340996629ae27a2cac3 | acenelio/curso-algoritmos | /python/notas.py | 251 | 3.734375 | 4 | nota1: float; nota2: float; notafinal: float
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
notafinal = nota1 + nota2
print(f"NOTA FINAL = {notafinal:.1f}")
if notafinal < 60.0:
print("REPROVADO") |
f258277d59ff9095f8cfdbabed74b74a065465bf | robertsmukans/DMI | /python/sin_caur_summ6.py | 497 | 3.625 | 4 | # -*- coding: utf-8 -*-
from math import sin
def mans_sinuss(x):
k = 0
a = (-1)**0*x**1/(1)
S = a
print "a = %6.2f S0 = %.2f"%(a,S)
while k< 3:
k = k + 1
R = * (-1) * x**2/((2*k)*(2*k+1))
a = a * R
S = S + a
print "a%d = %6.2f S%d = %6.2f"%(k,a,k,S)
... |
145c263077c2ea26f3649913d538d04debdb5a93 | amolsatsangi/Codedhef | /Practice/FLOW004.py | 605 | 3.875 | 4 | '''First and last digit
If Give an integer N . Write a program to obtain the sum of the first and last digits of this number.
Input
The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.
Output
For each test case, display the sum of first and last d... |
d24231ebb167d82b96d2f1b6d25d246fefeb9d2e | nicol337/python-exercises | /Trees/trie.py | 741 | 3.96875 | 4 | def insert(word, trie):
currNode = trie
for letter in word:
if letter not in currNode:
currNode[letter] = {}
currNode = currNode[letter]
currNode[None] = None
def find(word, trie):
currNode = trie
for letter in word:
print(letter)
if letter in word:
currNode = currNode[letter]
else:
return Fals... |
5a42f14af6e57411dd97612302b9ddbe62f45850 | Matheusrsm/Graduacao-CC | /Programação 1/Atividades-LP1/Diversas Unidades/area/area.py | 231 | 3.625 | 4 | # coding: utf-8
# Área e perímetro de um Círculo
import math
diametro == int(raw_input())
raio = diametro/2
area = (math.pi*raio**2)
perimetro = (2*math.pi*raio)
print "A: ", ("%.5f" % area)
print "P: ", ("%.5f" % perimetro)
|
501852bd7442b0b597455f1662ee0e0572e966e5 | PriceLab/STP | /chapter2/aishah/math.py | 790 | 3.765625 | 4 | # math functions
length = 4
w = 10
d=math.sqrt(length**2 + w**2)
x = 10
y = 10
z = x + y
a = x - y
z
a
2**2 # exponent equivilent to 2^2
14%4 # remainder
13//8 # integer division
13/8 # division
8*2 # multiplication
7-1 # subt
5+7 # add
# conditional statements
if x== 10:
print("true")
# example 1
home = "U... |
b3d8bce8df83983b070748c451cb8881c9cadd73 | daniel-reich/ubiquitous-fiesta | /ozMMLxJRPXBwm3yTP_17.py | 165 | 3.8125 | 4 |
def is_factorial(n):
from math import factorial
x=[i*factorial(i-1) for i in range(1,7)]
if n in x:
return True
else:
return False
|
c957772d371f6f04da31ec4d022295e8d804ee9f | jingxiufenghua/algorithm_homework | /leetcode/leetcode690.py | 1,433 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :algorithm_homework
@File :leetcode690.py
@IDE :PyCharm
@Author :无名
@Date :2021/5/1 12:17
'''
from typing import List
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
... |
a146a54ad63c9744649e47ed023c41fd0a9d6311 | J-Younkin/python-assignments | /car.py | 553 | 3.859375 | 4 | class Car:
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
def display_all(self):
print("Price:", self.price, "Speed:", self.speed, "Fuel:", self.fuel, "Mileage:", self.mileage)
car1 = Car(2... |
99f92df5049183809b9a363999c9da11ae166a90 | 112EasonLu/Python-Practice | /ShareBack Python_Fundamental Course/HW1.py | 3,985 | 3.796875 | 4 | import math
#------------Basic questions and identifications-----------
def set1():
tyPe={"a":"紅茶","b":"綠茶","c":"奶茶"}
size={"a":"中杯","b":"大杯"}
sugar={"a":"全糖","b":"少糖","c":"無糖"}
ice={"a":"全冰","b":"半冰","c":"去冰"}
more={"a":True,"b":False}
return [tyPe,size,sugar,ice,more]
def problems():
Q0="請問你要什麼飲料:a:紅茶,b:綠茶,c... |
9d3d239a52d9ef7d1e9e268459f90f90ee2813a9 | Artakharutyunyan120/Python-lesson | /homework.py | 343 | 3.65625 | 4 |
#import random
# x=random.randint(1,20)
# while x>10:
# print('true')
# if x<=10:
# break
# x=0
# for x in range(0,50,5):
# x+=1
# print(x)
# for i in range(1,10):
# if i == 5:
# continue
# print(i)
import random
random.randint('qar','tuxt','mkrat')
random.randint('qar','tuxt','mkrat')
for x in pc:
for ... |
746f4ab401d62181416179a5a9c43d8532647ae3 | KapowFreshGitHub/IAN-S-PROGRAMMING | /while loops.py | 416 | 4.0625 | 4 | #DECLARE password: STRING
#DECLARE guess: STRING
password = "BramPT0n"
attempt = 1
guess = input("Enter password")
while (guess != password) and (attempt < 3):
if guess == password:
print("Correct.")
else:
print("Incorrect")
attempt = attempt + 1
guess = input("Enter password")
... |
0a42bb20710f10533fe50e875785a8e3c1eee4bd | Arin-py07/Python-Hashing | /SubArrayGivensum.py | 273 | 3.734375 | 4 | N = 10
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sum = 14
Output:
1
Solution:
def sumExists(arr, N, sum):
#Your code here
dict = {}
for k,v in enumerate(arr):
if (sum - v) in dict:
return 1
dict[v] = k
return 0
|
2f65c0626f0c58653f35fff661772cc4ccc89de6 | antoine-moulin/MVA | /graphs_ml/PW1/code/build_similarity_graph.py | 6,618 | 4.1875 | 4 | """
Functions to build and visualize similarity graphs, and to choose epsilon in epsilon-graphs.
"""
import numpy as np
import matplotlib.pyplot as pyplot
import scipy.spatial.distance as sd
import sys
import os
from sklearn.metrics import pairwise_distances
from utils import plot_clusters
from utils import plot_grap... |
c2fda1f0cd577414996a4fd8550e86a152a0653f | tariqdaouda/pyGeno | /pyGeno/tools/io.py | 757 | 3.515625 | 4 | import sys
def printf(*s) :
'print + sys.stdout.flush()'
for e in s[:-1] :
print e,
print s[-1]
sys.stdout.flush()
def enterConfirm_prompt(enterMsg) :
stopi = False
while not stopi :
print "====\n At any time you can quit by entering 'quit'\n===="
vali = raw_input(enterMsg)
if vali.lower() == 'quit' :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.