blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
390f57d2c837f417e52753f171d749226217a8fa | kaviyasriprabhakaran/python_programming | /player/larger.py | 273 | 4.0625 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=int(input("enter the number"))
if ((num1>num2)and(num1>num3)):
print("num1 is large")
elif ((num2>num1) and(num2>num3)):
print("num2 is large")
else :
print("num3 is larger")
|
452a5383989ac83702cfbee8c83c1727d74321d6 | zhengwei223/thinkstats | /numpy_case/np_reshape.py | 191 | 4.0625 | 4 | import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a)
# 所有的行的第三列,本身组成一个行,reshape成三行一列
ak = a[:, 2].reshape(3, 1)
print(ak)
|
19177899477590cccac4d04e74dc1bcad5b3a0ff | Valery780/lesson_10 | /task_2.py | 233 | 3.734375 | 4 | word = str(input("Enter a word: "))
x = len(word)
i = 0
x = x - 1
k = 0
while x - i >= i:
if word[x - i] == word[i]:
i += 1
else:
k = 1
break
if k == 1:
print("No")
else:
print("Yes") |
aa5107fed1b824eec6d34e7abdb138552ca99fad | minhthangtkqn/PythonWorkSpace | /FirstProject/412FizzBuzz.py | 417 | 3.65625 | 4 | def fizz_buzz(value):
for i in xrange(value):
if (i + 1) % 3 == 0 and (i + 1) % 5 == 0:
print 'FizzBuzz'
else:
if (i + 1) % 3 == 0:
print 'Fizz'
else:
if (i + 1) % 5 == 0:
print 'Buzz'
else:
... |
da25bb167f6026648eb8759d62757374485c0608 | vip7265/ProgrammingStudy | /leetcode/july_challenge/pow/sjw.py | 458 | 3.625 | 4 | """
Problem URL: https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3392/
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
# return self.pow1(x, n) # 60ms
return self.pow2(x, n) # 28ms
def pow1(self, x, n):
# python nativ... |
88303e497cd889342e20ab7f27dba5bce5c4b974 | zwcdp/torecsys | /torecsys/layers/ctr/position_embedding.py | 1,727 | 3.578125 | 4 | import torch
import torch.nn as nn
class PositionEmbeddingLayer(nn.Module):
r"""Layer class of Position Embedding
Position Embedding was used in Personalized Re-ranking Model :title:`Changhua Pei et al, 2019`[1],
which is to add a trainable tensors per position to the session-based embedding features
... |
2ace9ec445387837e2f51ad43ca1e119c9483571 | GauravS99/answers | /q5.py | 687 | 3.84375 | 4 | # Time Complexity: O(n)
# Space Complexity: O(1)
def estimate_e(n):
"""
In 2004, using series compression, Brothers proposed
$$ e=\sum_{n=0}^{\infty} \frac{2n+2}{(2n+1)!} $$ (use latex to visualize)
to calculate the value of *e*. Implement a function that performs this estimation given an posit... |
67ce9e34783bc34f679ec0bc0f8c48b3c07aad0f | intaschi/Python-course | /Estruturas de repetição/Ex 058.py | 937 | 3.84375 | 4 | import random
cont = 0
print('Acabei de pensar em um número entre 0 e 10. \nSerá que você consegue adivinhar qual foi?')
e = random.randint(1, 10)
acertou = False
while not acertou:
n = int(input('Qual é o seu palpite?'))
cont += 1
if n == e:
acertou = True
else:
if n > e:
... |
c2364396548202b5d9d23a2af0f12002db4ecc46 | frankieliu/problems | /leetcode/python/199/sol.py | 1,535 | 3.921875 | 4 |
5-9 Lines Python, 48+ ms
https://leetcode.com/problems/binary-tree-right-side-view/discuss/56064
* Lang: python3
* Author: StefanPochmann
* Votes: 45
Solution 1: **Recursive, combine right and left:** 5 lines, 56 ms
Compute the right view of both right and left left subtree, then combine them. For very unbal... |
376428613d394d17799fa0917df6d3f7c8991b9e | ignaciomartinez96/Primeros_pasos_en_Python | /Hangman.py | 9,538 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Project #2: Hangman
For this assignment, we want to play hangman in 2-player mode.
The game should start by prompting player 1 to pick a word.
Then the screen should clear itself so that player 2 can't see the word.
After the screen is clear, the "gallows" and the empty letter sp... |
d7d2d09b9a69f965020eac8575c846b0fb85fb2f | gatinueta/FranksRepo | /python/challenge/equality.py | 203 | 3.625 | 4 | import re
import fileinput
for line in fileinput.input():
ms = re.finditer('[A-Z]{3,}[a-z][A-Z]{3,}', line)
for m in ms:
if len(m.group()) == 7:
print(m.group())
|
15a176b3c98828cbcfc84f1c1cc34e4a3d6db5bb | w5802021/leet_niuke | /Linked_list/234.回文链表.py | 893 | 3.96875 | 4 | from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseList1(head):
# 初始化res=None代表反转链表的尾结点
p, res = head, None
while p:
p,res,res.next=p.next,p,res
return res
def isPalindrome(head):
if not head or... |
41d03dddd4eba73900011fec087fb00b2a22ee4f | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/csdotson/lesson02/print_grid.py | 914 | 4.25 | 4 | # Lesson 2 Assignment - Grid Printer
def print_grid(n):
"""Print 2 x 2 grid with cell size n"""
horizontal = ("+ " + ("- " * n)) * 2 + "+"
vertical = ("|" + (" " * (2 * n + 1))) * 2 + "|"
# Do the printing
print(horizontal)
for j in range(2):
for i in range(n):
print(vertic... |
1249c8eb97b2c8f8751bb944fa61eefcd91ae559 | luismvargasg/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 5,493 | 3.84375 | 4 | #!/usr/bin/python3
"""Defining the Base class"""
import json
import turtle
class Base:
"""This class will be the base of all other classes in this project."""
__nb_objects = 0
def __init__(self, id=None):
"""class constructor for Base.
Args:
id: is an integer, if id is not No... |
766a58d6b9654ab62fdb1ff60249965919348641 | pvolnuhi/CPE-202 | /lab1/lab1.py | 2,181 | 4.34375 | 4 | #
#Polina Volnuhina
#014302388
#4/07/2019
#
#lab 1
#CPE 202-13
#Practising recursion through finding max number, reversing numbers, and binary search.
def max_list_iter(int_list): # must use iteration not recursion
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, r... |
34205ebc4c7ebad3362efe312530292e7dccb216 | mmore500/hstrat | /hstrat/_auxiliary_lib/_anytree_cardinality.py | 495 | 3.5625 | 4 | import anytree
from ._AnyTreeFastPreOrderIter import AnyTreeFastPreOrderIter
def anytree_cardinality(node: anytree.Node) -> int:
"""Count the number of nodes in an anytree tree rooted at the given node.
Parameters
----------
node : anytree.Node
The root node of the Anytree tree to compute th... |
2dc3d5a4bc4f0a4b74fe460ec404164c97ad6688 | Legoben/DailyProgrammingProblems | /10.py | 1,012 | 3.5 | 4 | # Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
from collections import deque
import time
store = deque() # linked list
def hello():
print("hello1")
def hello2():
print("bye")
def add_job(f, n):
i = 0
for t in store:
if t['time'] =... |
18f3ec1f64bea9739b2c1967e6975d7262ec1bf2 | A0pple/PPNS | /PrimeChecking.py | 698 | 4.25 | 4 | import time
while(True):
print("How many numbers do you want until the machine stops?")
a = input("")
print("How many times do people need to wait to the script to occur again?")
b = input("")
# import time is to make the script slower
for n in range(1,int(a)):
time.sleep(int(b)) #() = the amount of se... |
6c11959063a9717a24cafc3692264d433679092c | johnspiel99/compute | /project marks.py | 380 | 4.21875 | 4 | #= float(input("marks_number: "))
def grade(marks):
if marks < 50:
return "fail"
elif marks >= 60 and marks <= 70:
return "pass"
elif marks >= 61 and marks <= 80:
return "fair"
elif marks >= 81 and marks <= 90:
return "excellent"
else :
return ("distinction")... |
288791b5773aca165a0e5e028b4104ba9ce46b10 | NkStevo/daily-programmer | /challenge-001/easy/survey.py | 388 | 3.71875 | 4 | import sys
def main():
name = input("Input your name: ")
age = input("Input your age: ")
username = input("Input your reddit username: ")
result = "Your name is " + name + ", you are " + age + " years old, and your username is " + username
print(result)
f = open("easy-result.txt", "w")
f... |
6efba8e32831926082a41998edc5c70a6b91273d | prachi39/acad | /module asn.py | 767 | 4.40625 | 4 | #1
print("time tuple is the usage of a tuple(list of ordered items/functions) for the ordering and notation of time. "
"the tuple used for time in python based systems can be largerly summarized by year,month,day,hour,minutes,"
"seconds,day of the week,day of the year,and finally a DST(daylight savings time... |
1b60c15e36dffde7562e5e9fbef9677b97e3e971 | spettigrew/cs2-codesignal-practice-tests | /web-logger.py | 3,787 | 3.890625 | 4 | """
Web Logger
"""
"""
Setup
We are building a new website, and we want to know how many visitors we are getting to the website. All we care about is how many visits we've gotten in the past 5 minutes, nothing more. Your job is to build this system, but implementing two functions:
# This function gets called every ... |
fcea316a1c4e15eb7533a16cca5dabeaaf2c7581 | 815382636/codebase | /python/foundation_level/my_caculate.py | 558 | 3.734375 | 4 | """
1.使用 and 、 or 时,尽量将每一小部分用()括起来,利于和他人配合工作,防止歧义等
"""
"""
数值之间做逻辑运算
(1)and运算符,只要有一个值为0,则结果为0,否则结果为最后一个非0数字
(2)or运算符,只有所有值为0结果才为0,否则结果为第一个非0数字
"""
print(0 and 1)
print(2 and 3)
print(0 or 0)
print(0 or 1)
print(2 or 3)
"""
算数运算优先级:
混合运算优先级顺序: () 高于 ** 高于 * / // % 高于 + -
""" |
c4160338545d6e0f858bb8669cbab48282fac20f | qchui/qchui | /剑指offer/数组中出现次数超过一半的数字.py | 745 | 3.734375 | 4 | """
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
"""
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
total_array=len(numbers)
half_array=int((total_array+1)/2)
dict={}
for i in numbers:... |
e74e2c02e9b1fbf361c0445929b4dd5d06055a29 | thiagosantos1/AI_Pac_Man | /Classes/bonus.py | 3,167 | 3.53125 | 4 | # Copyright by Thiago Santos
# All rights reserved
import pygame
from tiles import Tile
from random import randint
from maze import Maze
# This Class is used to set and control where the bonus(fruit, coins, etc) is. It's the goal of the survivor to get it
class Bonus(pygame.Rect):
bonus_img = [ pygame.image.loa... |
b45a9b5a3e1de5d9bae040f77d8e67ed8a36b4f1 | sebastianrcnt/cshomework | /lab12_2018199061/lab12_p2.py | 328 | 4.03125 | 4 | def moderateDays(mydict):
'''Returns a list [...] of the days for which the average
temperature was between 70 and 79 degrees.
'''
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
# return list of days whose temperature is between 70 and 79
return [day for day in days if 70 <= mydict[day... |
6855c05acc331cfe77c08470854f941042c09ef9 | Gracekanagaraj/positive | /pro40.py | 143 | 3.765625 | 4 | string3='dhoni'
in3=input()
list31=list(in3)
list31.sort()
lst3=list(string3)
lst3.sort()
if(lst3==list31):
print("yes")
else:
print("no")
|
83502c5a8db76a0c08f716657df875596b26aae4 | klistwan/project_euler | /41.py | 715 | 3.6875 | 4 | def is_prime(n):
if n in prime_sieve(n+1):
return True
return False
from math import sqrt
def prime_sieve(limit):
lop = []
cur_num = 2
l2g = range(2,limit)
while cur_num < sqrt(limit):
lop.append(cur_num)
l2g = filter(lambda n: n%cur_num != 0, l2g)
cur_num = l2g[1]
lop.extend(l2g)
... |
42808ce13d648930741e6be7131b559d6cdb624c | Error57nk/Python-codes | /For_loop#1.py | 168 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 22:47:03 2019
@author: nkkum
"""
#For loop
print('Printing 1 to 12 ')
for i in range(1,11):
print(i) |
78024de7257eb2c7ab1756a476f251256f45106f | haichao801/learn-python | /7-文件处理/f_read.py | 715 | 3.75 | 4 | """
语法格式:
f = open(file='d:/练习方式.txt', mode='r', encoding='utf-8')
data = f.read()
f.close
* f = open(file='d:/练习方式.txt', mode='r', encoding='utf-8') 表示文件路径
* mode='r'表示只读(可修改为其它)
* encoding='utf-8'表示将硬盘上的010101按照utf-8的规则去断句,再将断句后的每一段010101转换成Unicode的010101,Unicode对照表中有010101和字符的对应关系
* f.read()表示读取所有内容,内容是已经转换完毕的字符串
... |
49be4ac9e3c94dd52bce45b8fcfc929358a81702 | valen280/fundamentos_programacion | /fundamentos de programación/ordenamiento_burbuja_juntas.py | 1,296 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 23 08:34:07 2021
@author: Luz Dary Prada
"""
# FUNCIÓN DESARROLLADA POR EL PROGRAMADOR
# ORDENAMIENTO BURBUJA DESCENDENTE
print("FUNCIÓN DESARROLLADA POR EL PROGRAMADOR")
def ordenamientoBurbuja(unaLista,tipo):
if(tipo=="ascendente"):
for numPas... |
68c2c00a74cc36c4743cd45c88cfe31ecfbf8828 | stamp465/01204111-Computer-and-Programming | /quiz/20_08_20.py | 1,055 | 3.78125 | 4 |
'''
#1
def printt(ans) :
if len(ans) == 0 :
print("A minus B: empty set")
else :
print(f"A minus B: {ans}")
def minus(a,b) :
Set_Minus = []
lena = len(a)
lenb = len(b)
for i in range(0,lena) :
if a[i] in b :
pass
else :
Set_Minus.append(int(a[i]))
return Set_Minus
a = input("... |
8ce40de5bd3b213f6d54ce348862f623f5a75ac1 | chaofan-zheng/tedu-python-demo | /month01/all_code/day12/demo08.py | 691 | 3.8125 | 4 | """
需求:老张开车去东北
变化:飞机/轮船/骑车....
思想:
封装:将需求分解为多个类
人类 汽车 飞机 轮船 自行车 ...
"""
class Person:
def __init__(self, name=""):
self.name = name
def drive(self, pos, vehicle):
print("去", pos)
vehicle.transport()
class Vehicle:
def transport(self):
... |
8baa1bd56d234cd612bd91097f639d537b79bd13 | theymightbepotatoesafter/School-Work | /CIS 210/p34_sscount_sol_W21.py | 1,585 | 4.34375 | 4 | '''
Find all substrings of a string (CS Circles Unit 8) - two solutions
CIS 210 Winter 2021 Project 3-4
Author: CIS 210
Credits: N/A
'''
import doctest
def sscount0 (needle, haystack):
'''(str, str) -> int
Given a "needle" string to search for in a "haystack" string,
return the count of the number occu... |
776c834b70ec15c285729b410c5c7e1f25bfa8ce | nefra298/python-base | /lesson03/hw_3_2.py | 1,114 | 3.703125 | 4 | def tonumeric(inp):
try:
val = int(inp)
return val
except ValueError:
try:
val = float(inp)
return val
except ValueError:
val = None
return val
def input_check_int(inp, msg=False, id=""):
x = tonumeric(inp)
if type(x) is i... |
82fc8e4bfb12d79f3caeb48c3b2a45daf03f5827 | kamaleshkumar7/Twitter-Sentiment-Analysis | /sentiment.py | 867 | 3.515625 | 4 | import tweepy
from textblob import TextBlob
import csv
consumer_key= ''
consumer_secret= ''
access_token=''
access_token_secret=''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#Step 3 - Retrieve Tweets
keyw... |
32c3e7fabe277989caf901aac8fcc12623e17a78 | vanishh/python-tutorial | /oop/08debug.py | 593 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 6 23:36:25 2018
@author: Administrator
"""
# 调试程序方式:
# 1.在程序中使用print()打印中间变量值
# 2.使用assert 断言
# 启动解释器时,可以使用-0参数关闭assert
def foo(s):
n = int(s)
assert n != 0, 'n is zero!' # 如果assert为true则继续执行,为false则抛出AssertionError
return 10 / n
def main():
foo('0')
... |
7d3a40f1c2f5161048769c04f471e84740c9270b | lizKimita/Password-Locker | /user.py | 1,599 | 4.21875 | 4 |
import pyperclip
class User:
'''
Class that generates new instances of the user.
'''
user_list = []
def __init__(self, first_name, last_name, user_name, password):
'''
init__helps us to define our users' properties.
Args:
first_name: New contact first name.
... |
ca3c8f89a29855f35102e8972aadf648cd5a4b29 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2444/49823/300149.py | 96 | 3.515625 | 4 | import random
n=int(random.random()*2)
if n==0:
print('true')
elif n==1:
print('false')
|
27091efc6c7aaa7ee488b4ce223df4cb683b4a54 | turo62/exercise | /exercise/codewar/lowest_product.py | 482 | 3.921875 | 4 | def lowest_product(input):
lst_nums = list(input)
prod_lst = []
product = 0
if len(input) < 4:
return "Number is too small"
else:
for i in range(len(lst_nums) - 3):
prod_lst.append((int(lst_nums[i]) * int(lst_nums[i + 1]) * int(lst_nums[i + 2]) * int(lst_nums[i + 3])))
... |
5759bf30a5b36f20a9184bd34ad36bd8df2a8f55 | DavTho1983/List_comprehensions | /list_comprehensions2.py | 1,090 | 3.625 | 4 | movies = ["Star Wars", "Gandhi", "Casablanca", "Shawshank Redemption", "Toy Story", "Gone with the Wind", "Citizen Kane", "It's a Wonderful Life", "The Wizard of Oz", "Gattaca", "Rear Window", "Ghostbusters", "To Kill A Mockingbird", "Good Will Hunting", "2001: A Space Odyssey", "Raiders of the Lost Ark", "Groundhog Da... |
05d90d7252e157357b748e52eb8dfa313cce754c | vladimirpecerskij/vvp- | /linked list.py | 1,424 | 4.03125 | 4 | def add_at_end(self,data):
if not self.head:
self.head = node(data = data)
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = node(data=data)
def delete_node(self,key):
... |
f16138e4adf8dbd4535ad4cb15c58a915a232938 | wagnersistemalima/Mundo-3-Python-Curso-em-Video | /pacote de dawload/projeto progamas em Python/Aula 19 Dicionarios parte 1.py | 513 | 3.59375 | 4 | # Aula 19 Dicionarios. É assim que tratamos os dicionarios
pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(pessoas['nome'])
print(pessoas['idade'])
print(pessoas['sexo'])
print(f'{pessoas["nome"]} tem {pessoas["idade"]} anos') # Utilizar aspas duplas para a localização [" "]
print(pessoas.keys()) ... |
694ff1d23f5f436aa0605a34cc6183cd0ad26cb3 | rafacab1/1daw-python-prog | /Primer Trimestre/03 Bucles/3.py | 1,263 | 4.28125 | 4 | # 3. Algoritmo que pida caracteres e imprima ‘VOCAL’ si son vocales y ‘NO VOCAL’
# en caso contrario, el programa termina cuando se introduce un espacio.
#
#
# Autor: Rafael Alberto Caballero Osuna
#
#
# 22/10/19
#
# Algoritmo
# Mientras que una variable sea distinta de " "
# Pido un número
# Si es igu... |
a75c2be32d91de1aa33d7589830fda39744e6075 | URI-ABD/clam | /py-clam/abd_clam/core/dataset.py | 7,153 | 3.75 | 4 | """This module defines the `Dataset` class."""
import abc
import pathlib
import random
import typing
import numpy
class Dataset(abc.ABC):
"""A `Dataset` is a collection of `instance`s.
This abstract class provides utilities for accessing instances from the data.
A `Dataset` should be combined with a `M... |
ed786f016c70c4423d9255cabd667abbc17aa4c9 | aritraaaa/Competitive_Programming | /Number_Theory/Primality Test/Sieve_of_Eratosthenes.py | 980 | 4.25 | 4 | '''Python program to print all primes smaller than or equal to n using Sieve of Eratosthenes'''
def SieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True fo... |
1cb5343471295e8b4f7c76670a75ca45be4de466 | AnastasioNieves/Python- | /Cursos/Mastermind/Ejercicio Grados.py | 146 | 3.84375 | 4 | print("bienvenido a mi conversor")
a = float(input("Escriba los grados fahrenheit"))
b = (a-32)*5/9
print("Equivalen estos celcius: " + str(b)) |
c2cc637ee9bd12a707076201fafe98d35db5fa5f | daniel-reich/turbo-robot | /jyGco3e82sNfYKvCj_2.py | 431 | 4.03125 | 4 | """
Create a function that takes an integer `n` and reverses it.
### Examples
rev(5121) ➞ "1215"
rev(69) ➞ "96"
rev(-122157) ➞ "751221"
### Notes
* This challenge is about using two operators that are related to division.
* If the number is negative, treat it like it's positive.
"""
... |
8457c7b14938e17c2db036a814ff6855bafc8408 | jragbeer/Project-Euler | /ProjectEuler31.py | 1,322 | 3.515625 | 4 | import cProfile
import io
import itertools
import pstats
# Project Euler Problem 31
#
# In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
#
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
# It is possible to make £2 in the following way:
#
... |
ef824c4eedf00958c523011a38c401a7d896844e | eduardomezencio/tsim | /tsim/core/units.py | 1,270 | 4.0625 | 4 | """Units, values and functions for space and time."""
from __future__ import annotations
from datetime import time
from math import floor
Timestamp = float
Duration = float
SECOND = 1.0
MINUTE = 60.0 * SECOND
HOUR = 60.0 * MINUTE
DAY = 24.0 * HOUR
INT_SECOND = int(SECOND)
INT_MINUTE = int(MINUTE)
INT_HOUR = int(HOU... |
246f45427a272ba44ac78d256c95096d63c5475a | xiaochideid/yuke | /7-12/3.列表 元组 字符串 集合之间的转换.py | 1,733 | 4.34375 | 4 | # 重点内容:
# 将类型一转化成类型二:命名=类型2(类型1)特殊:转化为字符串string1=''.join(list or tuple or set)
# 列表:list []
# 元组:tuple ()
# 字符串:string {}
# 集合:set {}
# ..................列表转化成元组 字符串 集合...............
# 列表转换成元组
list1=['a','b','c','d']
tup=tuple(list1)
print(type(tup))
print(tup)
# 列表转化成字符串
string=''.join(list1)
print(type(strin... |
1ef1f340963813e34ae4bc344aa45e5344d0d774 | jefersonmz78/cursoemvideo | /ex044.py | 990 | 3.6875 | 4 | print('{:=^40}'.format(' Lojas Guanabara '))
preço = float(input('Preço das compras: R$'))
print('''FORMAS DE PAGAMENTO
[1] à vista dinheiro/cheque
[2] à vista cartão
[3] 2x no cartão
[4] 3x Ou mais no cartão''')
opção = int(input('Qual é a opção ? '))
if opção == 1:
total = preço - (preço * 10 / 100)
el... |
24a00e26367bd1f85243880f1148c9efdd6ec58d | avengerryan/daily_practice_codes | /five_sept/programiz/seven.py | 297 | 3.828125 | 4 |
# shuffle deck of cards
# importing modules
import itertools, random
# make a deck of cards
deck= list(itertools.product(range(1, 14), ['Spade', 'Heart', 'Diamond', 'Club']))
random.shuffle(deck)
# draw five cards
print("You got: ")
for i in range(5):
print(deck[i][0], 'of', deck[i][1]) |
c6ace24d2f27534f6d81146f2fd835ff4b30ed1f | tylerlorenzen/python-guessing-game | /pythonNumberGuessingGame.py | 1,480 | 4.125 | 4 | #Guessing the Random Number Game.
import random
import time
import numpy as np
import sys
#Delay printing
def delay_print(s):
#print one character at a time
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.1)
print('Hello and welcome to my Random Number game! What is your... |
cc1f3e9e625cac5ffcb3b8cb5c5bdbafaf132604 | hasnatosman/30days | /break.py | 122 | 3.796875 | 4 | for number in range (1, 11):
if number == 5:
continue
if number == 9:
break
print(number) |
b36086b538967c79a423af4b5f7c113f74283d77 | DebugConnoisseur/practice-programs | /sajibot.py | 293 | 3.84375 | 4 | a=2
b=7
c=10
d=2
e=14
if a>b:
print('Guddu CHildu')
else:
print('Worst Fellow')
if c<b:
print('Guddu Childu')
else:
print('Worst fellow')
if a==d:
print('Guddu Childu')
else:
print('Worst fellow')
if a*b==e:
print('Guddu Childu')
else:
print('Worst Fellow')
|
a116d816cb0d49c507fe9db34e939c6b97f811d3 | Candeladlf/UnsungInsistentDrupal | /main.py | 458 | 3.703125 | 4 | # Actividad 2 - Ejercicio 3
kilometros = float(input("¿Cuandos kilometros ha recorrido? "))
litros = float(input("¿Cuantos litros ha consumido? "))
print(f"El consumo ha sido : {round(100*litros/kilometros,2)} litros cada 100 kms")
# Actividad 2 - Ejercicio 4
IVA = float(input("¿Cuanto IVA vas a pagar (sin porcentaje)... |
6bf71e9ccd9981e27eb6ddba4f4fc63a5431efdb | tammyen/python | /prog5.py | 1,041 | 4.0625 | 4 | ##Lesley Tam Uyen Tran
##September 7, 2018
##ECS 10 Eiselt
##
##prog5.py
#Problem 1
def addTables(table1, table2):
"""function will ask for two arguments, both being a 2 dimmen-
sional tables. each value in the first table will be added with
a value in the second table with the same index and the... |
f57e23e713579878a1d5ebea8a2147ea20483a51 | anvesh2502/Leetcode | /Tree_RightView.py | 802 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self) :
self.level=dict()
def buildRightTree(self,root,index=0) :
if root==None : ret... |
f1ed4032b5e383e2fcc43c8c405e1067901736cf | ClearlightY/Python_learn | /top/clearlight/algorithm/sort/bubble_sort.py | 483 | 3.859375 | 4 | def BubbleSort(lst):
n = len(lst)
if n <= 1:
return lst
for i in range(0, n):
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
(lst[j], lst[j + 1]) = (lst[j + 1], lst[j])
return lst
x = input("请输入待排序数列:\n")
y = x.split()
arr = []
for i in y:
arr.app... |
e50a11206db0f499a130059cf554f49fd246aa97 | waynekwon/Python_Data | /helloworld.py | 323 | 3.671875 | 4 | # print('100+200')
# print('hello world')
# #helloworld exercise
# print('The quick brown fox','jumps over', 'the lazy dog')
# print('100+200=', 100+200)
# name=input()
# print(name)
# x=input()
# y=input()
# print(int(x)+int(y))
# z=input('Enter Your Name: ')
# print('hello', z)
x=1024
y=768
print('1024 * 768 = ', x*y... |
73545d4680598d57971d981c6d2f437c378a3d99 | jabibenito/pynet | /learnpy_ecourse/class4/Javi/ex3.py | 2,652 | 3.546875 | 4 | # III. Create a program that converts the following uptime strings to a time in seconds.
# uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
# uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
# uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
# uptime4 = 'rtr1 uptime is 5 years, ... |
8dfdcfa1d39999d822c55d2efa9d53e7e7b4245c | AdamZhouSE/pythonHomework | /Code/CodeRecords/2500/60636/258870.py | 355 | 3.546875 | 4 | def pancakeSort(A):
"""
:type A: List[int]
:rtype: List[int]
"""
res = list()
for i in range(len(A), 1, -1):
A = A[:A.index(i)-1] + A[:A.index(i)]
res += [A.index(i)+ 1, i]
return res
A=eval(input())
a=pancakeSort(A)
while(1 in... |
bcd41fbc9ea976689cecb6136d45d5ada188635a | anketlale/ML_AZ | /Machine Learning A-Z/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/datap.py | 2,247 | 3.84375 | 4 | # importing library
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('C:/Users/Anket Lale/Desktop/Machine Learning A-Z/Part 1 - Data Preprocessing/Data.csv')
print("dataset:",dataset)
print()
print()
#------------------------------------------------------------
... |
338cd1464110abf63183720311610577fd8615ba | Dimk000/Labs | /Semestr tasks/Dichotomy/Py/main.py | 473 | 4.125 | 4 | from math import fabs
def F(x):
return x*x*x-3*x+1
c = float()
a = float(input("Введите 1-ую границу интервала: "))
b = float(input("Введите 2-ую границу интервала: "))
eps = float(input("Введите точность: "))
while fabs(a - b) >= eps:
c = (a + b) / 2
if F(c) * F(a) < 0:
a = c
else:
b =... |
b6b6ac69765b56fc710064ee39a214b2d61469d5 | gcifuentess/holbertonschool-higher_level_programming | /0x0B-python-input_output/12-student.py | 821 | 3.671875 | 4 | #!/usr/bin/python3
"""Student to JSON module"""
class Student():
"""Student class"""
def __init__(self, first_name, last_name, age):
"""Student constructor"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
'''... |
570c23d660eba7c93504ed0472928aef9d62a053 | Melv1nS/CS313E_Projects | /Assignments/Assignment 5/Office.py | 3,350 | 3.5 | 4 | # Input: a rectangle which is a tuple of 4 integers (x1, y1, x2, y2)
# Output: an integer giving the area of the rectangle
def area (rect):
width = rect[2] - rect[0]
length = rect[3] - rect[1]
area = width * length
return area
# Input: no input
# Output: a string denoting all test cases ... |
71a67870d97a9605486871417b7f6a2342e416b6 | nss-cohort-40/c40-keahua-arboretum-lava-dodgers | /actions/cultivate_plant.py | 9,812 | 3.828125 | 4 | import os
import copy
from plants import *
def choose_plant():
os.system('cls' if os.name == 'nt' else 'clear')
print("1. Mountain Apple Tree")
print("2. Silversword")
print("3. Rainbow Eucalyptus Tree")
print("4. Blue Jade Vine")
print("")
try:
plant = int(input("Choose plant to cu... |
5deee4cfca0fb430299af44ccb3f7e99528d2d16 | pythonebasta/lab | /provaEreditarietaMultipla.py | 623 | 3.5625 | 4 | class madre:
def __init__(self):
pass
def parla(self):
print("Parla la classe madre")
class figlia(madre):
def __init__(self):
pass
#def parla(self):
#print("Parla la classe figlia")
class figlio(madre):
def __init__(self):
pass
def parla(self):
... |
682c65aa59bd11b213ea110266e4eea435012d62 | Enokisan/AtCoder-History | /AtCoder/ABC204/A/A.py | 152 | 3.53125 | 4 | a = list(map(int, input().split()))
if (a[0]==a[1]):
print(a[0])
elif not (0 in a):
print(0)
elif not (1 in a):
print(1)
else:
print(2) |
42594999794886d07edfb8f061a81112c017545f | balazsczap/adventofcode2019 | /1a.py | 573 | 3.703125 | 4 | import math
from functools import reduce
from input_1 import task_input
def calculate_basic_fuel(mass):
return math.floor(mass / 3) - 2
def add_extra_fuel(extra):
new_fuel = calculate_basic_fuel(extra)
if (new_fuel <= 0):
return 0
return new_fuel + add_extra_fuel(new_fuel)
def calculate_all... |
a1f540295270989f0d3d615f1711a2d1108728c5 | Mayym/learnPython | /2-Python高级语法/2-2 函数式编程/1-3.py | 893 | 4.3125 | 4 | # 定义一个普通函数
def my_func(a):
print("In my_func")
return None
a = my_func(8)
print(a)
# 函数作为返回值返回,被返回的函数在函数体内定义
def my_func2():
def my_func3():
print("In my_func3")
return 3
return my_func3
# 使用上面定义
# 调用my_func2,返回一个函数my_func3,赋值给f3
f3 = my_func2()
print(type(f3))
print(f3)
f3()
pri... |
dd111751dc79151cd7ad7ebd8d69d15ab8de91b1 | shivangi-prog/leetcode | /generateParenthesis.py | 569 | 3.515625 | 4 | class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
# 不用穷举组合+剪枝+堆栈判断,直接设定规则来生成就行
result = []
def generate(left, right, s):
if left == 0 and right == 0:
result.append(s)
return
... |
2eae74ab9edf88f0723a08b0f52c8f580337abeb | stephenchenxj/myLeetCode | /391_Perfect Rectangle.py | 2,673 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 15:17:58 2020
@author: chen
391. Perfect Rectangle
Hard
323
68
Add to List
Share
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bot... |
ff29d73189d1a5b638ddf1e61e0cece41948fc46 | trinhgliedt/Algo_Practice | /2021_06_14_merge_two_sorted_lists.py | 1,735 | 4.21875 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
# Example 1:
# Input: l1 = [1,2,4], l2 = [1,3,4]
# Output: [1,1,2,3,4,4]
# Example 2:
# Input: l1 = [], l2 = []
# Ou... |
a61c710abbe43fdb1c1d315091bb33477044738d | Krishnom/python-udemy-course | /src/functions/excercise/master_yoda.py | 242 | 3.9375 | 4 | # MASTER YODA: Given a sentence, return a sentence with the words reversed
def master_yoda(text):
reversed_text = text.split()
# print(reversed_text)
reversed_text = reversed_text[::-1]
return " ".join(reversed_text)
pass
|
c63ebd3b8d5d02aba09c2425b95107118836b8ac | VainateyaDeshmukh/Python_DataStructure | /Python Practics.py | 10,587 | 3.921875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plot
import scipy as sc
#assignment no.1 (Question A) TM1817154
# Company can spend maximum 70,000 on training. Training will be approved for each employee in the same order as mentioned in Nomination1dictionary below.
# Following
# data is given:
# Fe... |
5f5141f8985e0d1d11d4be85c555d287eb721939 | append-knowledge/pythondjango | /1/exam/cal.py | 705 | 4 | 4 | def add(num1,num2):
print(num1+num2)
def sub(num1,num2):
print(num1-num2)
def mul(num1,num2):
print(num1*num2)
def div(num1,num2):
print(num1/num2)
def expo(num1,num2):
print(num1**num2)
print("calculator")
x=print('1)ADDITION\n2)SUBTRACTION\n3)MULTIPLICATION\n4)DIVISION\n5)EXPONENT')
print()
y=int(... |
462458fd63d7d98a8016c632764da4c111877bce | wereii/simple-raspi-rc | /client.py | 1,203 | 3.53125 | 4 | # python3
import sys
import socket
import keyboard
import time
DELAY = 0.1
UDP_IP = ""
UDP_PORT = 6666
if not UDP_IP:
# Pokud neni zadana IP, nastav na localhost
UDP_IP = "127.0.0.1"
if not UDP_PORT:
# Pokud neni zadan port, nastav na 8008
UDP_PORT = 8008
sock = socket.socket(socket.AF_INET, socket... |
6c103ea08f35adcb390584b53d661188cf5ae622 | Davestrings/PythonCode | /consecutivesum.py | 190 | 4.0625 | 4 | number = int(input("Enter a number: "))
num=1
total = 0
# while num <= number:
while num <= number:
total = total + num
num += 1
print(total)
if total % num == 0:
print(total)
|
52de584817f5c5f763f3a12721fcdab4d796f239 | roopish/csv_report | /Python/csv_report.py | 775 | 3.796875 | 4 | #!/usr/bin/env python
def main():
csvfile = open('test.csv', 'r')
input_dict = {} # dictionary to store names, events and avg time
mean=0.0
for line in csvfile.readlines():
cols = line.split(",")
names = cols[0].title() #capitalize first letter
time = cols[1]
city = cols... |
70cc764305b915f31e9661034f598333b09560f5 | edevaldolopes/learning | /04 - stringsList.py | 628 | 3.953125 | 4 | txt1 = 'The best code'
list1 = ['one', 'two', 'three']
print(txt1)
print(list1)
print(txt1[0])
print(list1[0])
# slice
print(txt1[0:3])
print(list1[0:2])
# slice, step
print(list1[0:3:2])
# negative
print(list1[-1])
# add
list1.append('four')
list1.insert(0, 'zero')
print(list1)
# remove
list1.remove('one')
del l... |
d45f36617d30097b343495ceb641fce508e3c392 | ZinollinIlyas/python | /18/classwork/example.py | 414 | 3.59375 | 4 | class Cat:
def __init__(self, name, age=None, color="White"):
self.name = name
self.age = age
self.color = color
def meow(self, something):
print("Meow", something)
def purr(self):
print("Purrr")
def ask_food(self):
for i in range(3):
self.m... |
5e05c2170523529aee4e56239f335f2ced135a62 | lishuchen/Algorithms | /leecode/26_Remove_Duplicates_from_Sorted_Array.py | 400 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
idx = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
... |
628d238e9c033a7ab2c8d5661098a1e07866e3d2 | gabriellaec/desoft-analise-exercicios | /backup/user_102/ch41_2019_09_03_22_24_47_823991.py | 188 | 3.96875 | 4 | senha = true
while senha:
x = str(input("Tenta acertar minha senha:"))
if x==andre:
print("desisto")
else:
print("Você acertou a senha!")
senha = false |
7e8ef4c22515967e6e981ebbc6c77a2953d4d49f | pigswillfly/advent_of_code_2019 | /1_solution_a.py | 150 | 3.546875 | 4 | f = open('1_puzzle_input.txt', 'r')
total_fuel = 0
for line in f.readlines():
fuel = int(int(line) / 3) - 2
total_fuel += fuel
print(total_fuel)
|
4dbd78e0f3fdffe0d847c60e60501de5c860dab2 | provoke01/Python-Programs | /Typecasting.py | 298 | 3.9375 | 4 | name = "Bill"
count = 1234
floaty = 95.9500
stranger = str(count)
intfloat = float(count)
print("Integer: ", count)
print("String: ", name)
print("Float: ", floaty)
print("Integer to String: ", stranger)
print("Integer to Float: ", intfloat)
print("Thats the basics of typecasting primitive types") |
acf59533b034956b615a5fd7fafdedfb4652465f | 11EXPERT11/pythonProject | /Start.py | 483 | 3.703125 | 4 | from random import randint
print("угадай число от 0 до 50 которое я загадал")
user = int(input())
num = randint(0, 50)
while user != num:
user = int(input("повторите попытку"))
if user < num:
print("ваше число меньше загаданного")
elif user > num:
print("ваше число больше загаданного")
... |
9c12c141f69093bf17c00988aed93c8928572471 | Timur1986/work-with-FILE | /io_conor.py | 430 | 3.734375 | 4 | # Копировать файл с новым названием (способами без with)
x = input('Укажите имя файла для копирования: ')
y = input('Введите новое имя файла: ')
n_conor = open(x, 'rb')
n_chicken = open(y, 'wb')
n_chicken.write(n_conor.read())
n_conor.close()
n_chicken.close()
print('Файл с новым именем успешно создан!')
|
e5460f8fea63034afd4e2454b728e8752f31bbb1 | grodrigues3/InterviewPrep | /Leetcode/symmetricBinTree.py | 1,885 | 4.03125 | 4 | """
Symmetric Tree Total Accepted: 66661 Total Submissions: 210965 My Submissions Question Solution
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \... |
d1f09e2d52ca12134467857590e76101caa47802 | zerformza5566/CP3-Peerapun-Sinyu | /assignment/Exercise8_Peerapun_S.py | 1,440 | 3.515625 | 4 | userName = input("Id : ")
password = input("Password : ")
if userName == "admin" and password == "1234":
print("Login completed.")
print("----FPStore----")
print("-------Product list--------")
print("1. Leather bag : 150 THB")
print("2. Backpack : 199 THB")
print("3. Wallet ... |
1fc51b04dc63b9c87e0062405298b371c72ff793 | Tharnickanth/Python-For-Beginners | /ControlFlow/TernaryOperator.py | 107 | 3.96875 | 4 |
age = int(input("Enter you age :"))
message = "Eligible" if age >= 18 else "Not Eligible"
print(message)
|
639fbdb1856bda615837fb5124df84b202a687bf | YJL33/LeetCode | /current_session/daily_challenge/find_nearest_right_node_in_binary_tree.py | 819 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
import collections
from typing import Optional
class Solution:
def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optiona... |
f11bc41703e34183643e6064c7d982ec18c18f62 | jbub/spy-data-types | /strings.py | 1,248 | 4.6875 | 5 | # lets define some strings
my_string = "hello there!"
# accesing individual characters by indexes
my_string[1]
# slicing also works for strings
my_string[1:4]
# string concatenation
my_string + ' hello ' + ' world '
# concatenation of other types (explicit conversion is needed)
number = 3
'My number is = ' + s... |
b63161d220b2066182b0baf591d11e67affa1bae | nwthomas/code-challenges | /src/daily-coding-problem/easy/find-friend-groups/test_find_friend_group.py | 674 | 3.546875 | 4 | from find_friend_groups import find_friend_groups
import unittest
class TestFindFriendGroups(unittest.TestCase):
def test_returns_two_groups(self):
"""Takes in an adjacency list of friends and returns 2"""
adj_list = {0: [1, 2], 1: [2], 2: [0], 3: []}
result = find_friend_groups(adj_list)
... |
78217df7c72e3745b091d8e986aa397389502f76 | amantaya/Image-Processing-Python | /image-processing/09-connected-components/InvContours.py | 953 | 3.875 | 4 | '''
* Python program to use contours to count the objects in an image.
'''
import cv2
import sys
# read command-line arguments
filename = sys.argv[1]
t = int(sys.argv[2])
# read original image
img = cv2.imread(filename)
# create binary image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,... |
189c5653ecfd297a60c6f1bcadc38794f4754a52 | matkins1/Project-Euler | /P23.py | 3,720 | 4 | 4 | ## Problem 23
## A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
## For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
## A number n is called deficient if the sum of its proper divisors is... |
812efd2e2f99e0de1588171c5f8b198859eefae2 | Melifire/CS120 | /Projects/Short 1/swap.py | 458 | 4.09375 | 4 | ''' File: swap.py
Author: Ben Kruse
Purpose: Swap the first half and second half of an input,
leaves the middle character if applicable
'''
import math
def main():
inp = input('Please give a string to swap: ')
length = len(inp)
print(inp[math.ceil(length / 2) : ] + #takes the last chars
... |
c0e5eac05c5e860915f5913619cd8a11db4c7ae1 | jbmenashi/python-course | /functions/basic_functions.py | 335 | 3.59375 | 4 | def say_hi ():
print("Hi")
say_hi()
def print_square_of_7():
return 7 * 7
print(print_square_of_7())
from random import random
def coin_flip():
if random() > 0.5:
return "heads"
else:
return "tails"
print(coin_flip())
def generate_evens():
return [num for num in range(1, 50) i... |
86a45b7671abb488d1bebb64b4bb4479b2b4ae2d | abhishekparakh/Matasano-Challenges | /P3-alt.py | 1,957 | 3.765625 | 4 | #Single-byte XOR cipher
import binascii
import sys
from bitstring import BitArray
#using only the two few characters to check for frequencies
vowels = ['e', 't', 'a', 'o', 'i', 'u']
englishLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', \
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', \
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.