blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
bab7fb94d222f3f8e2abd64e6e32e9722aaa62da | EchnoX/Coding | /Guess The Number.py | 1,572 | 3.828125 | 4 | import simplegui
import random
guesses = 7
secret_number = 0
def new_game():
global secret_number
global guesses
guesses = int(guesses)
guesses = 7
secret_number = random.randrange(0, 100)
print "WELCOME TO THE GUESSING OF THE NUMBERS GAME!!!"
def range100():
global sercret_nu... |
218aff8471b8f4c4546419e13146a5d89d164a35 | supersonic594/pycse | /pycse/bin/submit.py | 1,690 | 3.515625 | 4 | #!/usr/bin/env python
'''
Script to submit a file to the homework server
files must be text based, and they must contain these lines:
#+COURSE: 06-625
#+ASSIGNMENT: 1a
#+EMAIL: jkitchin@andrew.cmu.edu
'''
import requests
from uuid import getnode as get_mac
import socket
import os
import uuid
import d... |
b69562dd61ba6a1509268f03cbd94f56f0370170 | diegomendieta/projects | /Operations Research/Corn Factory Simulation/classes.py | 26,559 | 3.515625 | 4 | from collections import deque, defaultdict
from functions import *
from parameters import *
from sortedcontainers import SortedList
'''
Clase que representa un evento que ocurre en la simulación.
'''
class Evento:
def __init__(self, tiempo, lote, tipo, descarga=None, sorting=None,
secador=None, mo... |
6d4bfe1ba58483729eca3ac9d766718ba87a089c | Yonatan1P/snakes-cafe | /snakes_cafe/snakes_cafe.py | 1,357 | 3.859375 | 4 | intro = "**************************************\n\
** Welcome to the Snakes Cafe! **\n\
** Please see our menu below. **\n\
**\n\
** To quit at any time, type \"quit\" **\n\
**************************************"
print(f"{intro}\n")
appetizers = ["Wings", "Spring Rolls"]
print(f"Appetizers\n----------\n{app... |
99d4a3e331b02b7dd60a1208593a04c42b30518c | zhouli01/python3 | /gcd.py | 179 | 3.9375 | 4 | def gcd(x,y):
return x if y==0 else gcd(y,x%y)
print ("gcd方法:",(gcd(12,8)))
def gcd1(x,y):
while y!=0:
x,y=y,x%y
return x
print ("gcd1方法结果:",(gcd1(8,12)))
|
9ab8ee8522c32e1559a3fc7c43ad2bfcc3b6e1c8 | zhouli01/python3 | /calender.py | 182 | 3.796875 | 4 |
import calendar
yy=int(input("输入年份:"))
mm=int(input("输入月份:"))
print(calendar.month(yy,mm))
monthrange=calendar.monthrange(yy,mm)
print ("天数:",monthrange) |
43a2c511b10647935ecf0198c212886d08eb371c | zhouli01/python3 | /amusitelang.py | 263 | 3.65625 | 4 | #!user/bin/python
#coding:UTF-8
lower=int(input("请输入比较小的数字:"))
upper=int(input("请输入比较打的数字:"))
sum =0
for num in range(lower,upper):
L=len(str(num))
for n in str(num):
sum+=int(n)**L
if num==sum:
print (num)
sum =0 |
a51f84ba31230e6aa64a24ea55fd1d87c899290f | renegadedme/bitcoinpricenotify | /bitcoinpricenotify.py | 2,786 | 3.53125 | 4 | # This program is a simple bitcoin price notification service
# The program sends the latest bitcoin price to Telegram once every 5mins
# It also sends a direct notification to a mobile device if the price of bitcoin drops below a certain threshold
# It uses Coingecko to get the latest bitcoin price in USD and IFTTT fo... |
e87cbd0ac87db5c6d1f87bbe7e021985c77719dc | AramBoiso/Lenguajes_Automatas_I | /7_sw_alfabeto_cadenas.py | 2,395 | 3.890625 | 4 | # [a-z]+([,][a-z]+)+|[a-z]+
def getString(alphabet):
string = input("Ingrese una cadena par concoer su posicicion: ")[::-1]
n = len(alphabet)
increment = 1
result = 0
for item in string:
result += increment * (alphabet.index(item) + 1)
increment *= n
return result
def getPosi... |
cff9f874f444ee367bdafa4e207cfbe401e8922d | yinwenpeng/FEVER | /cis/deep/utils/misc/__init__.py | 539 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def softmax(M):
"""Calculate the row-wise softmax given a matrix.
Parameters
----------
M : 2d structure (m x n)
Returns
-------
ndarray(m x n)
probabilities according to softmax computation, each row sum = 1
"""
M = np.asarray(M... |
e374a0ea5002d4c88dab482a37fe780aa1a07519 | sd19spring/GeneFinder-Yingzhongjiang | /gene_finder.py | 7,634 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
gene_finder_mini_project
@author: Anne.j
"""
import random
from amino_acids import aa, codons, aa_table # you may find these useful
from load import load_seq
def shuffle_string(s):
"""Shuffles the characters in the input string
NOTE: this is a helper function, you do not
... |
5ea251f96945cb86565b9128910fce21b74b4de1 | chandra-stack/Gitdemoproject | /firstproject.py | 237 | 3.515625 | 4 | class Chandra:
def __init__(self, a, b):
self.a = a
self.b = b
print("i will be calling when object created")
def sum(self):
return self.a + self.b
#obj = Chandra(2, 3)
#print(obj.sum())
|
6fb19f4836ab34de07109d7f65f72fecc05dc26a | emilng/project-euler | /problem0017.py | 1,772 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# Number letter counts
# If the numbers 1 to 5 are written out in words:
# one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
# If all the numbers from 1 to 1000 (one thousand)
# inclusive were written out in words, how many letters would be used?
# NO... |
a65a0dacac46f72c59c6a3084b06f018d7db1958 | emilng/project-euler | /problem0003.py | 696 | 3.890625 | 4 | # Largest prime factor
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
factors = set([600851475143])
iterations = 0
# find largest factor and try to factor that
# repeat until largest factor can't be factored
# start at 3 and add 2 to each number be... |
f8adf85199b31909bccd2e03d9c5f4f5c2247f50 | SvVoRPy/coursera | /Washington_MachineLearningSpecialization/Course03_Classification/Week_03/Assignment2.py | 2,243 | 3.53125 | 4 | import os
path = 'C:/Users/SvenV/Desktop/Coursera Kurse/Machine Learning Spezialization III/Assignments/Week 4'
os.chdir(path)
os.listdir(path)
import pandas as pd
import numpy as np
loans = pd.read_csv('lending-club-data.csv')
loans.columns
loans.head(2)
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1... |
89ab89b1aa761c5980547b42dad415f910ec64bf | burrowdown/exercises | /bank/account.py | 2,190 | 3.859375 | 4 | from datetime import datetime
class Account:
def __init__(self, owner, balance, animal, account_id):
self.owner = owner
self.balance = balance
self.animal = animal
self.account_id = account_id
self.history = [self._write_history(self.balance, "initial deposit")]
def... |
41f4d19c08eb436a56b0a03b4139002eb3e150ab | AMAZINGHARIKRISHNAN/LU-assignments | /LU assignment2.py | 525 | 3.953125 | 4 | #Question 1
#Delete all occurrences of an element in a list
list = [1,2,3,4,5,6,7,8,9,10]
remove= 10
for item in list:
if(item==remove):
list.remove(remove)
print(list)
#Question 2
#Check whether a string is a pangram.
import string
def ispangram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for... |
eb8d20fee99d77092570f7d1eee13fcfd9d3c4b8 | BBBBBzz/DataStructureAndAlgorithm | /SortingAlgorithms/ShellSort.py | 1,041 | 3.921875 | 4 | """
希尔排序:
1. 可以看作是插入排序的简单改进,通过交换不相邻的元素对数组局部进行排序,
并最终使用插入排序将局部有序的数组进行排序。
2. 具体操作是使任意间隔为h的数组的元素都是有序的,这样的数组被称为h有序数组,
一个h有序数组就是h个互相独立的有序数组编织在一起组成一个数组。
复杂度:
1. 时间复杂度:与增量h的大小选择有关
2. 空间复杂度:O(1)
"""
def ShellInsert(arr, d):
n = len(arr)
for i in range(d, n):
# 希尔排序中每组成员是从原来数组中以间隔d提取出来的
j = i-d
... |
1fb9a0139252cd121ac35f2a19ca6fb5e441a75f | BBBBBzz/DataStructureAndAlgorithm | /Array/RemoveDuplicatesInPlace.py | 1,326 | 4 | 4 | """
题目:
给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例1:
输入:nums = [1,1,2]
输出:2, nums = [1,2]
解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。
"""
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> in... |
d967f1f6487aa043bd3e2f0a734287f3f5b0b66b | mgroov/cs471-Programming-Languages | /lab4/python/gausselim.py | 2,950 | 4.0625 | 4 | import random
import time
#Matthew Groover
#9/28/20
#this program is to show the complexity of
#calculating numerical formulas in an
#interpretid language
def forward_elimination(A, b, n):
"""
Calculates the forward part of Gaussian elimination.
"""
for row in range(0, n-1):
for i in range(r... |
57ebee472681027e89e4a2f79a5ec245a7f92df7 | GB071957/Advent-of-Christmas | /Advent of Code problem 1 - expenses add to 2020.py | 683 | 3.546875 | 4 | # Advent of Code problem 1 Program by Greg Brinks
# Find two numbers in the list of 200 that add to 2020 and multiply them together
from timeit import default_timer as timeit
start= timeit()
import csv
num_captured = 0
expenses = []
with open("Advent of Code problem 1.txt") as expense_file:
file_contents =... |
c78fb177089b849773a169e5097d8b7500e13de8 | GB071957/Advent-of-Christmas | /Advent of Code problem 15 part 2 ver 2 - Rambunctious Recitation.py | 862 | 3.53125 | 4 | # Advent of Code problem 15 part 2 - Rambunctious Recitation - Program by Greg Brinks
from timeit import default_timer as timeit
start= timeit()
import csv
#starting_nums = [16,1,0,18,12,14,19]
nums_seen = [16,1,0,18,12,14]
turns_seen = [1,2,4,5,6]
turns = [0]*30000001
for i in range(len(nums_seen)):
if nums... |
d0bed4cbaa51ca82cfe51ba9334c277b94cd359d | baifengbxl/PyhonProject | /PyhonProject/com/Thrid.py | 392 | 3.9375 | 4 | # 分支语句 if if... else.. if..elif ..elif ..else
'''
格式:
if 表达式:
代码段
> >= < <= == in包含
'''
score = 88
list=[90,98,76,88]
# if score in list:
# print("优秀")
if score>=90:
print("优秀")
elif score>=80 and score<90:
print("良好")
elif score>=60 and score<80:
print("及格")
else:
print(... |
77c05445db5276e2dd41aecbf5a5733d65911a14 | baifengbxl/PyhonProject | /PyhonProject/com/Extends.py | 331 | 3.515625 | 4 | #继承
class User:
def method(self):
pass
class Father:
def eat(self):
print("eat")
def sleep(self):
print("sleep...")
class Boys(Father,User):
def playGame(self):
print("game...")
class Grils(Father):
def shopping(self):
print("shopping...")
jack = Boys()
jack.e... |
a7b628b369324b0d3de9ee081b0ab86e0987ec35 | maxwelllee54/TextAnalytics | /stemming.py | 995 | 3.640625 | 4 | #by Jenny GONG
import nltk
from nltk.corpus import stopwords
from nltk import FreqDist
f = open('input_new.txt','r')
raw = f.read()
raw = raw.replace('\n',' ')
#Tokenization
tokens = nltk.word_tokenize(raw)
#Stopwords Removal and only keep text data then change to lowercase
mystopwords = stopwords.words('english')
... |
a6d52b751896f0f73218c5b2ae4accc163162028 | coolstoryjoe-bro/self-taught-journey- | /PersonalPractice/If Statements/If Statements Try Yourself.py | 785 | 4.09375 | 4 | alien_colors = ["green", "orange", "blue", "purple", "yellow"]
if "green" in alien_colors:
print("You have earned 5 points!")
elif "orange" in alien_colors:
print("You have earned 10 points!")
elif "blue" in alien_colors:
print("You have earned 15 points!")
elif "purple" in alien_colors:
print("You hav... |
a09f7b9417baef1b2635f3ba4245b503f493f14d | AaqibAhamed/Python-from-Begining | /ifpyth.py | 419 | 4.25 | 4 | responds= input('Do You Like Python ?(yes/no):')
if responds == "yes" or responds == "YES" or responds == "Yes" or responds== "Y" or responds== "y" :
print("you are on the right course")
elif responds == "no" or responds == "NO" or responds == "No" or responds == "N" or responds == "n" :
print(" y... |
b59ec6d3d3dd88308a5313792be9539a70dd2db0 | 0xpranjal/Databases-with-SQLAlchemy | /Basics of Relational Databases/Selecting_data_from_a_Table.py | 701 | 3.875 | 4 | #Using what we just learned about SQL and applying the .execute() method on our connection, we can leverage a raw SQL query to query all the records in our census table. The object returned by the .execute() method is a ResultProxy. On this ResultProxy, we can then use the .fetchall() method to get our results - that i... |
d0926732039cde4d463a57f833effe85fb656eea | zhangshuyun123/Python_Demo | /function_return.py | 1,129 | 4.125 | 4 | # -*- coding:utf8 -
# 函数返回“东西”
# 函数中调用函数
# 20190510
#加法
def add(a, b):
print("两个值相加 %r + %r = " %(a, b))
return a + b
#减法
def subtract(a,b):
print("两个值相减 %r - %r = " %(a, b))
return a - b
#乘法
def multiplication(a, b):
print("两个值相乘 %r * %r = " %(a, b))
return a * b... |
1e8bd11afef0060a53c21573d5f7b71913ce86ff | extraridder/Checkio | /Power Supply.py | 2,914 | 3.625 | 4 | def power_supply(network, power_plants):
print("Кол-во заводов", len(power_plants.keys()))
if len(power_plants.keys()) == 0:
output = list()
for each in network:
output.append(each[0])
output.append(each[1])
print(list(set(output)))
else:
plants = list... |
66544c8b602a21309392fb689870539bea85d3ee | Archaneos/NLP_Yahoo_QA | /clean.py | 2,964 | 3.546875 | 4 | import csv
# import sklearn
import nltk
import re
from nltk.corpus import stopwords
TOKENS = {"NOUN": "<NOUN>", "URL": "<URL>"}
def tokenize(string):
return string.split(" ") if string != "" else []
def clean_str(string):
"""
Data cleaning. Remove unknown char and space words.
Remove english most c... |
6d5ebfd3a1323bc87e256e27f9ff2f1c194a7730 | mickeybin2211/baitapvenha | /session6 14.52.14/intro3.py | 76 | 3.78125 | 4 | a=0
while True :
print ("hello")
a +=1
if a >= 5:
break
|
8edc0eb992c462337344aa70626431aadee062d1 | mickeybin2211/baitapvenha | /session8/intro22.py | 910 | 3.53125 | 4 | list1=[]
while True :
n=str (input ( """tạo list :nhập thao tác muốn thực hiện ?
C.create
R.read
U.update
D.delete """ ))
if n==str ("c") :
a=input ("nhập thứ yêu thích của bạn ? ")
list1.append(a)
elif n==str("r"):
if len(list1)==0:
... |
c1750a7abcbfcba45e07b8ecc01f00956833126a | mickeybin2211/baitapvenha | /session7/part2_9.py | 143 | 3.9375 | 4 | n=int (input ("nhập n ?"))
if n >13 :
print ("n lớn hơn 13")
elif n==13 :
print ("n bằng 13")
else :
print ("n bé hơn 13") |
8dd72e83e364d450cafab02d2d099a4c3190d5ae | Maker-Mark/python_demo | /example.py | 831 | 4.15625 | 4 |
grocery_list = ["Juice", "Apples", "Potatoes"]
f = 1
for i in grocery_list:
print( "Dont forget to buy " + i + '!')
##Demo on how to look though characters in a string
for x in "diapers":
print(x)
#Conditional loop with a if statment
desktop_app_list = ["OBS", "VMware", "Atom", "QR Generator", "Potato... |
28ed95c7f5b7a1a15256a78c1c766d76ee222044 | chlotod/Exercise-01b-Hello-World | /main.py | 389 | 3.625 | 4 | #!/usr/bin/env python3
import sys
assert sys.version_info >= (3,9), "This script requires at least Python 3.9"
print("Hello, World!")
print("I would like to get to know you.")
n = input("What is your name? ")
if n == "Chloe":
print("What do I need to do to get an A?")
elif n == "Bob":
print("I've got a bad feelin... |
ca3924d8c177a89ad3fc9147c2cc1b2717547b3d | JardelPlk/intro_python_Jardel-Pauluka | /lista-105.py | 3,309 | 4.0625 | 4 | ###
# Exercicios
###
## Usando a lista: ['a','b','c']
# 1) Faca um loop dentro de uma funcao que irah retornar: ['A','B','C']
def maiuscula(lista):
lista2 = []
for i in lista:
lista2.append(i.upper())
return lista2
lista = ['a','b','c']
lista2 = maiuscula(lista)
for i in lista2:
print(i)
## U... |
8400e8c8377f41ce517480c2770c1cafe1b04ce4 | YanaSharkan/Tasks | /task1_chessboard/task1_chessboard.py | 1,315 | 3.515625 | 4 | import sys
import params_validator
from params_validation_error import ParamsValidationError
class ChessBoard:
"""" This class contains properties and methods in order to
create and print chessboard.
"""
def __init__(self, size, symbol, *args, **kwargs):
self.size = size
self.symbol ... |
332e8bb3c8cd2241cd89433fb3070ff2b4707826 | YanaSharkan/Tasks | /task5_num_to_text/task5_num_to_text.py | 1,791 | 3.578125 | 4 | import sys
import numbers
class NumberConverter:
def convert(self, num, skip_zero=False):
res = ''
if num < 10:
res = self.__convert_ones(num, skip_zero)
elif num < 20:
res = self.__convert_teens(num)
elif num < 100:
res = self.__convert_tens(num... |
47b16ea4e98bbfd829566de913da7ef91b0bf246 | 0xchikku/youtubeDownloader | /main.py | 689 | 3.6875 | 4 | from pytube import YouTube
print("YouTube Downloader!\n")
link = input('Link: ')
try:
# YouTube() is a class and it takes the link as argument
file = YouTube(link)
print(
f"Title: {file.title}\nRating: {file.rating}\nDescription: {file.description}")
# File is being filtered
# available is... |
127d9fbf7ffc4bc0d11e0bbdd39da7fbf1b59f7f | AlexKolchin/geekbrains | /pythonProject/Functions/global_local.py | 555 | 3.609375 | 4 | global_var = 1
def my_f():
# локальная переменная
local_var = 100
# мы можем использовать локальную переменную внутри функции
print(local_var)
# глобальная переменная, объявлена в модуле
print(global_var)
# но эту переменную сейчас нельзя изменить
# global_var = 999
my_f()
print(global... |
43415ac9ae1179dd0062ba3a304e396653a48d34 | AlexKolchin/geekbrains | /Files/json_to_format.py | 388 | 3.515625 | 4 | import json
friends = [
{'name': 'Max', 'age': 23, 'phones': [123, 456]},
{'name': 'Leo', 'age': 33}
]
print(friends)
print(type(friends))
# преобразуем список в json
json_friends = json.dumps(friends)
print(json_friends)
print(type(json_friends))
# обратно из json в объект
friends = json.loads(json_friends)
pr... |
431cf8665478f92885c2773f0235c3a66258a7ec | AlexKolchin/geekbrains | /pythonProject/Functions_homework/task4.py | 639 | 3.859375 | 4 | player_hp = 150
player_dps = 50
enemy_dps = 20
enemy_hp = 100
player_armor = 4
enemy_armor = 2
player_name = input('Enter your name: ')
enemy_name = 'Diablo'
player = {
"name": player_name,
"health": player_hp,
"damage": player_dps,
"armor": player_armor
}
enemy = {
"name": enemy_name,
"health":... |
1aaa84537cee63682bd9c18ee49186a1d1befc52 | AlexKolchin/geekbrains | /Lesson2/number_game_levels.py | 985 | 4 | 4 | # компьютер загадывает случайное число от 1 до 100
import random
number = random.randint(1, 100)
print('Вас приветствует игра - "Угадай число!"')
user_number = None
count = 0
levels = {1: 10, 2: 5, 3: 3}
level = int(input('Выберите уровень сложности: 1 - 10 попыток, 2 - 5 попыток, 3 - 3 попытки: '))
max_count = levels[... |
c3bd65d941da22cccb28c90d86f4cf1cec95919a | AlexKolchin/geekbrains | /Lesson2/number_game_players.py | 1,501 | 3.875 | 4 | # компьютер загадывает случайное число от 1 до 100
import random
number = random.randint(1, 100)
# print(number)
print('Вас приветствует игра - "Угадай число!"')
user_number = None
user_count = int(input('Введите количество игроков: '))
users = []
k = 1
for i in range(user_count):
user_name = input(f'Введите имя иг... |
349a8a2864b6958ade644e8bf79e362f94733b29 | dani71153/Tareas-y-Projectos- | /Hola/4.py | 118 | 3.65625 | 4 | indice = 0
numeros = [1,2,3,4,5,6,7,8,9,10]
for numero in numeros:
numeros[indice]*=10
indice +=0
print(numeros) |
f42a483538f0c1404ea3f2d594face9535e57e19 | iramosg/curso_python | /aula04.py | 426 | 4.125 | 4 | import math
num1 = 2
num2 = 5.5
print(type(num1))
print(type(num2))
num3 = num1 + num2
print(type(num3))
divisao = 5 + 2 / 2
print(divisao)
divisao2 = (5+2) / 2
print(divisao2)
verdadeiro = 5 > 2
print(verdadeiro)
falso = 5 < 2
print(falso)
idade = 18
if idade >= 18:
print("Acesso liberado")
else:
print... |
438640fb234665340a8150d973f8f3c84bedd140 | iramosg/curso_python | /aula06.py | 682 | 3.921875 | 4 | igor = {'nome': "igor", "sobrenome": "ramos", "profissao": "programador", "filhos": ['joao', 'maria']}
print(type(igor))
igor['nome']
print(igor['nome'])
print(igor['sobrenome'])
print(igor['filhos'])
print(len(igor))
# del igor['filhos']
# print(igor)
igor['sobrenome'] = "gonçalves"
print(igor)
'sobrenome' in i... |
dbb9a96239455117bb0793a4cf11bad0f3fbcc92 | winnertree/idk-htd | /상속.py | 716 | 3.5625 | 4 | #상속
class Unit:
def __init__(self, name, hp):
self.name=name
self.hp=hp
class AttackUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(self,name,hp)
self.damage=damage
def attack(self, location):
print("{0} : {1}방향으로 공격 {2}damage".format(self.name, loc... |
d3919f473352ef182c7e4e2c7c8bef5f280e8417 | jamiewei-tw/cs50 | /cs50/week1/credit.py | 1,434 | 3.734375 | 4 | #!/usr/bin/python3
def Checktheenter(N):
try:
N = int(N)
if N >= 1000000000000000:
N = str(N)
return N
else:
print("**Please Enter the 16 Numbers of the Credit Card**")
CreditNum = Checktheenter(input("Please Enter YOur Credit Number: ... |
022b843a7beca65f4c49a8f2ec11d4ff97d5d59c | yoworg/code | /set.py | 128 | 3.625 | 4 | import inspect
list1 = [1,2,3,4,5,6,7]
it = list1.__iter__()
print(it.__next__())
print(it.__next__())
print(it.__next__())
|
4136fec32810afa690b0f1c7003f5a242e94a923 | yoworg/code | /gen.py | 121 | 3.875 | 4 | list = [1,2,3,4,5]
def gen():
for i in range(5,10):
yield i
g = gen()
print(g.__next__())
print(next(g)) |
83a421727911eede5685445e709da014384d9c59 | lomaxvogtm/lomaxvogtm.github.io | /Final_Python.py | 4,162 | 3.6875 | 4 | __author__ = 'Madeleine'
import tkinter as tk
class Elevator():
def __init__(self, canvas, num_floors, width, height, vspace, hspace):
self.num_floors = num_floors
self.width = width
self.height = height
self.vspace = vspace
self.hspace = hspace
self.canvas = canva... |
caa6babeeb3ddc71140eb8b7a7187ceb16906565 | zidanebaraba/PythonDasar | /Belajar11-Function.py | 296 | 3.625 | 4 | def Display():
print("hallo")
print("welcome to python")
def Sum(n1,n2):
z=n1+n2
return z
def Min(n1,n2):
x=n1-n2
print("Hasil={}".format(x))
def main():
Display()
Results=Sum(10,20)
print(Results)
Min(20,10)
if __name__ == '__main__':main()
|
f1e155413912b430f2242d07be817beb307321ef | zidanebaraba/PythonDasar | /Belajar10-Control Loop.py | 136 | 4 | 4 | word="Python Program"
for letter in word:
if(letter=='P'):
continue;
elif(letter=='a'):
break;
print(letter) |
5fdb54cd03371c0ee832a8ed6822a75a5925a464 | mexikana/firstclass | /test.py | 355 | 4.09375 | 4 | #print("hello phyton")
num1 = float(input("firstint : "))
num2 = float(input("secondint : "))
symbol = input("+,-,%,*,/")
if symbol == "-":
num = num1 - num2
print(num)
elif symbol == "+":
num = num1 + num2
print(num)
elif symbol == "*":
print(num1 * num2)
elif symbol == "/":
print(num1 / num2... |
fc564da8c5f82d76644ec71a2056898cf3e12d88 | mmmonk/matasano_crypto_challenge | /set1/c2.py | 400 | 3.5 | 4 | #!/usr/bin/env python
def xorss(s1,s2): # xor for strings - non repetitive
if len(s1) > len(s2):
return "".join([chr(ord(s1[i])^ord(s2[i])) for i in range(len(s2))])
return "".join([chr(ord(s1[i])^ord(s2[i])) for i in range(len(s1))])
txt = xorss("1c0111001f010100061a024b53535009181c".decode('hex'),"686974207... |
9b0690bfa3aa792c46e4107b00fc06f45689b99a | xing3987/python3 | /base/基础/_07_tuple.py | 562 | 4.1875 | 4 | single_turple = (3)
print(type(single_turple))
single_turple = (3,)
print(type(single_turple))
# list tuple相互转换
num_list = [1, 2, 4, 5]
num_tuple = tuple(num_list)
print(num_tuple)
num_list = list(num_tuple)
print(num_list)
info_tuple = ("小明", 16, 1.85)
print("%s 年龄是 %d,身高为 %.02f." % info_tuple)
#循环变量
for info in ... |
3002c0c9693c28543e4c5d57ca6e94c458b3d593 | xing3987/python3 | /base/面向对象/_22_classmethod.py | 1,043 | 3.703125 | 4 | # 类属性,类方法,静态方法
class Tool:
# 定义类属性,所有类共用
count = 0
def __init__(self, name):
self.name = name
Tool.count += 1 # 赋值类属性用[实例类.属性名]
# 静态方法不需要传递任何类有关参数,不能使用类属性
@staticmethod
def help():
print("工具的使用帮助。")
# 使用@classmethod注解定义类方法,所有实例类公用,第一个参数为类本身
@classmethod
d... |
48582ae444b69a4788211887a5dc7a23b7ca206a | xing3987/python3 | /base/基础/_14_repeat.py | 264 | 3.734375 | 4 | # 递归:方法调用本身,要有出口防止死循环
def print_num(num):
print(num)
if num == 1:
return
print_num(num - 1)
print_num(5)
def sum(num):
if num == 0:
return num
return num + sum(num - 1)
print(sum(10))
|
ad4f5c5bfdd7e01df252337eecd823b764d1cf16 | xing3987/python3 | /base/基础/_01_type.py | 659 | 3.859375 | 4 | import keyword
print('hello')
print("你好")
name = '小明'
age = 18
sex = True # True算术运行中为1,False为0
height = 1.75
weight = 75
print(age + sex)
print(name * 10) # 得到多个整数
print(type(float(age)))
'''
%s 字符串
%d 有符号的十进制整数 %06d表示显示6位数,不足用0占位
%f 浮点数%.02f表示小数点后只显示两位
%% 输出%
'''
'''
apple = int(input("请输入。。\n")) #input 默认格式为s... |
cacd9750d3c2d5e7920133c2a18aa82846da8d50 | Programming-Hero-01/Projects-2 | /projects/Calculators/Kelvin_Farenheit_Celsius.py | 553 | 4.09375 | 4 | '''F-Fahrenheit
K-Celsius
C-Kelvin'''
choice = input("")
num = float(input(""))
kelvin = ''
celsius = ''
fahrenheit = ''
def f_k_c(choice):
if choice == 'F':
kelvin = (num + 459.67) * 5/9
celsius = (num - 32) * 5/9
return "Celsius is: " + str(celsius) + " , Kelvin is: " + s... |
ac3077cf37ba1f51edd2f728ee425d58e6d00ef0 | neenushoby11/NEENU | /highpkc_code.py | 3,489 | 4.0625 | 4 | import operator
number_employees = 0
found_goodies = 0
goodies = dict()
# store the contents of the input file
input_file = open("sample_input.txt")
input_split = input_file.readlines()
input_file.close()
#print
#print("input list: ", input_split)
#print
# generate the goodies dictionary
for i i... |
64aacf0084eee8ce33647297ff8f22132877220e | Husniya-Sanoqulova/python_3 | /16-dasturcha.py | 105 | 3.515625 | 4 | for i in range(10):
i=i+1
if i==6:
continue
print(i)
print('Datur yakunlandi')
|
dce707766fffe15ebc6702fa82ce9f6148eea612 | JeromeLee-ljl/leetcode | /001~050/_031_next_permutation.py | 1,646 | 3.59375 | 4 | class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
while i >= 0:
if nums[i] < nums[i + 1]:
left, right = i + 1, len(nums) - 1
... |
a3ee4f6a4e0525b079b45b7939f25947dc2de2e8 | JeromeLee-ljl/leetcode | /001~050/_016_3sum_closest.py | 1,215 | 3.765625 | 4 | class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
Return the sum of the three integers.
... |
169bb691778eaf71d5cb6b4ec844ae07577374ce | JeromeLee-ljl/leetcode | /001~050/_033_search_in_rotated_sorted_array.py | 2,652 | 3.78125 | 4 | class Solution:
# 全递归
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def bin_search(nums, left, right, target):
if nums[left] == target:
return left
if left == right:
... |
003a05cd5bc270ac3cafd8a744d8ac00a345132c | JeromeLee-ljl/leetcode | /001~050/_034_search_for_a_range.py | 1,129 | 3.59375 | 4 | class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(nums) - 1
while left <= right:
center = (left + right) // 2
if nums[center] == target:
... |
17428cc9ac5951224e206c015007d6509cbd7bdc | abhisheks-12/hackerrank-python | /019_H_pattern.py | 484 | 3.84375 | 4 | n = int(input())
if n%2 == 0:
print("Plz Enter odd number...")
else:
pass
for i in range(n):
print(("H"*i).rjust(n-1)+"H"+("H"*i).ljust(n-1))
for i in range(n+1):
print(("H"*n).center(n*2)+("H"*n).center(n*6))
for i in range((n+1)//2):
print(("H"*n*5).center(n*6))
for i in ra... |
a53ce6598adfc0615650dc9923b72736d5f7c35d | ziyotek/pythonprojects | /helloworld.py | 95 | 3.515625 | 4 | print("Hello World")
var1=4**2
var2=var1**2
var3=var2 -64
var4=var3/8
print(var4)
import math
|
f255177bd0137e7f208b24296755bf69877e53c7 | shubhu-88/LP3-Module | /coding_quesiton_5.py | 619 | 3.71875 | 4 | '''
Coding Question 5
You have given a string. You need to remove all the duplicates from the string.
The final output string should contain each character only once. The respective order of
the characters inside the string should remain the same. You can only traverse the
string at once.
Input string:
ababacd
... |
2b580b9f6ded29645ea1beda33a59d72dd1f3978 | cavid-aliyev/HackerRank | /itertoolspermutation.py | 316 | 3.890625 | 4 | # Itertools.permutation -> https://www.hackerrank.com/challenges/itertools-permutations/problem?h_r=next-challenge&h_v=zen
from itertools import permutations
name, num = input().split()
num = int(num)
myList = list(permutations(name, num))
myList.sort()
for i in myList:
name1 = "".join(i)
print(name1)
|
bebadc8b0746716b27e43fb8c96d1bccc2a9b6ca | cavid-aliyev/HackerRank | /collectionDeque.py | 476 | 3.828125 | 4 | # Collection deque -> https://www.hackerrank.com/challenges/py-collections-deque/problem
from collections import deque
d = deque()
n = int(input())
for i in range(n):
l = input().split()
command = l[0]
if len(l) > 1:
e = l[1]
if command == "append":
d.append(e)
elif comm... |
30b748c005b0f90374373b1b565954a4de9cdce9 | cavid-aliyev/HackerRank | /incorrectregex.py | 245 | 3.875 | 4 | #Incorrect Regex -> https://www.hackerrank.com/challenges/incorrect-regex/problem
import re
for i in range(int(input())):
a = True
try:
regex = re.compile(input())
except re.error:
a = False
print(a)
|
f839cc7c0a5f7dff9107b10066f0c182150d238c | cavid-aliyev/HackerRank | /zipped.py | 251 | 3.5625 | 4 | # Zipped! -> https://www.hackerrank.com/challenges/zipped/problem
students,subjects = map(int, input().split())
scores = [map(float, input().split()) for _ in range(subjects)]
for student in zip(*scores):
print(sum(student)/subjects)
|
9531c09a52e08a624c95a9102a8c488ef03f2604 | Snigdha171/PythonMiniProgramSeries | /CreatingPythonPackage/compute_numbers.py | 605 | 3.703125 | 4 | """
This is a package in Python that will compute the results of numerical values provided.
A Calculator!
"""
print("Hi There! I have sum, diff, divide and multiply functionality")
""" To get the sum of two numbers """
def sum(n1, n2):
return n1+n2
""" To get the difference of two numbers """
def di... |
e9f52662cd9aef093e442851a189c85b3f40d727 | edfdz/Lab_4 | /BST.py | 4,032 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 11:05:18 2019
@author: eduardofernandez
"""
import matplotlib.pyplot as plt
import numpy as np
class BSTLab(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right ... |
ffc172de327a528fe0b4b6266080d16d0012f23c | sentientbyproxy/Python | /JSON_Data.py | 638 | 4.21875 | 4 | # A program to parse JSON data, written in Python 2.7.12.
import urllib
import json
# Prompt for a URL.
# The URL to be used is: http://python-data.dr-chuck.net/comments_312354.json
url = raw_input("Please enter the url: ")
print "Retrieving", url
# Read the JSON data from the URL using urllib.
uh = urllib.urlopen... |
d8201fce50f4aadbcf1824691dfd5940078d032a | NathanWaddell121107/python_data_science | /simple-linear-regression/simple_linear_regression.py | 1,498 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Import the dataset
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Split into training / test sets
from sklearn.model_selection import train_te... |
ff39b6c284b5177c7e93288a704e6a9578f190cc | LauraPeraltaV85/holbertonschool-interview | /0x06-log_parsing/0-stats.py | 1,065 | 3.546875 | 4 | #!/usr/bin/python3
""" this calculates and prints file logs"""
import sys
if __name__ == "__main__":
a = 1
statusn = [0, 0, 0, 0, 0, 0, 0, 0]
size = 0
statuses = ["200", "301", "400", "401", "403", "404", "405", "500"]
def print_log(statusn, statuses):
"""Method to print file size and stat... |
4222e596b764b3512f35f5eb8ff52540af772e41 | vandosant/flask-spike | /venv/lib/python2.7/site-packages/graphlab/toolkits/diversity/__init__.py | 9,096 | 3.5 | 4 | """
The GraphLab Create diversity toolkit is used to select a diverse subset of
items from an SFrame or SGraph.
Every diverse sampling method uses a measure of intrinsic item quality as well
as a measure of similarity between items. The quality of an item is usually a
single real-valued feature, while the similarity f... |
4c9597269ec4fd29f65eebf8a9921b8cf1d3378a | francofusco/read-the-docs-github-pages | /code/hello.py | 376 | 3.640625 | 4 | #!/usr/bin/env python3
"""Simple module that defines a greetings function."""
def greetings(who="World"):
"""
Function that prints a greetings message on the terminal.
Parameters:
who (str): the "person" to greet.
"""
print(f"Hello, {who}!")
if __name__ == '__main__':
import sys
if len(sys.argv) ... |
d39a72a5414b05e07fd946e995ccaf20b48abe05 | yasmeeen16/python_labs | /lab1/ass5.py | 256 | 3.84375 | 4 |
def dic (names):
result={}
for name in names:
if name[0] in result:
result[name[0]].append(name)
else:
result[name[0]]=[name]
return result
listName=["eman","hend","laila"]
print(dic(listName)) |
2c482ba63ff4acb455741c554cf8f869d32bdba3 | TejasAdiga/United-States-Game | /main.py | 1,094 | 3.734375 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title(" US STATES GAME")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("50_states.csv")
states = data["state"].to_list()
x_coordinates = data["x"].to_list()
y_coordinates = data["y"].to_lis... |
e486088f98599e283895d8508362efe39bb3ac36 | HarryLoofah/grade-data | /grade_data/plot_scores_with_labels.py | 3,619 | 3.515625 | 4 | #!/usr/bin/env python
"""
full_grade_data.py
==========
This is a test script to processes ELD grades from CSV files and plot
overall classroom trends. I'm working on incorporating more information
the imported CSV file, especially dates associated with assignments.
Like grade-data's "main.py", this ... |
9b03290903f617141e132a063e2d038c094c7e1b | blackary/genetic-salesman | /misc/genetics3.py | 8,451 | 3.78125 | 4 | #!/usr/bin/env python
"""
This Python code is based on Java code by Lee Jacobson found in an article
entitled "Applying a genetic algorithm to the travelling salesman problem"
that can be found at: http://goo.gl/cJEY1
"""
import math
import random
import pygame
x = 100
y = 20
import os
os.environ['SDL_VIDEO_WINDOW_PO... |
2c3f82735ee4297f5c88f4ba297b4cfa7a6de943 | bmonroe44/WeatherPy | /starter_code/WeatherPy.py | 6,135 | 4.09375 | 4 |
# Observations
# As expected, the temperature does increase the closer you get to the equator. However, if you notice the higher temps are around the 90° N latitude. This is probably because it is summer in the northern hemisphere and winter in the southern hemisphere. This also results in equivalen... |
67a931750a9eb793613e7203bc373d87ef0cb599 | HYLee1008/Python | /19 Bit Operation/71 Hamming distance/01.py | 142 | 3.875 | 4 | ### Calculate the hamming distance between two given integer number using XOR
###
def hamming_distance(x, y):
return bin(x ^ y).count('1') |
22cbdf98d8ca2c2d6464ab01a94c405f6e377af4 | HYLee1008/Python | /18 Binary Search/69 Search a 2D Matrix II/02.py | 152 | 3.578125 | 4 | ### Find the target value in the sorted 2D matrix
### Pythonic method
def search_matrix(matrix, target):
return any(target in row for row in matrix) |
3c064e22e597f2b1975263207b1e40ec783d8927 | HYLee1008/Python | /14 Tree/45 Invert Binary Tree/03.py | 300 | 3.984375 | 4 | ### Invert every left and right of input binary tree using iterative DFS
###
def invert_tree(root):
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root |
2042bf49a276e97ed0b15ba8d5fd3448b252afa4 | HYLee1008/Python | /18 Binary Search/65 Binary Search/04.py | 179 | 3.84375 | 4 | ### Find the index of the target using binary search by binary search module
###
def search(nums, target):
try:
return nums.index(target)
except:
return -1 |
5310b7fd85d09290acf54086a3ac5fe5c30f7863 | HYLee1008/Python | /22 Divide and Conquer/83 Majority Element/02.py | 306 | 3.984375 | 4 | ### Find majority element using dynamic programming
###
import collections
def majority_element(nums):
counts = collections.defaultdict(int)
for num in nums:
if counts[num] == 0:
counts[num] = nums.count(num)
if counts[num] > len(nums) // 2:
return num
|
4a2ccf9cfba5574086d13ce71f20900d84bf2265 | HYLee1008/Python | /11 Hash Table/29 Jewels and Stones/03.py | 354 | 3.96875 | 4 | ### Calculate how many jewels in stones. Remove calculation part using counter.
###
import collections
def num_jewels_in_stones(J, S):
freqs = collections.Counter(S)
count = 0
# calculate the frequency of jewels(J)
for char in J:
count += freqs[char]
return count
J = "aA"
S = "aAAbbbb"
... |
b849f400be6948a08deec0d1939361352e50dfd4 | HYLee1008/Python | /07 Array/06 Longest Palindrome Substring/01.py | 677 | 4.03125 | 4 | ### Printing longest palindrome substring by two pointer
def longest_palindrome(s):
# determine palindrome and expand two pointer
def expand(left, right):
while left >= 0 and right <= len(s) and s[left] == s[right - 1]:
left -= 1
right += 1
return s[left + 1: right - 1]
... |
c2111f6814e258f9e08eba9c4e4c3372e756f127 | HYLee1008/Python | /07 Array/01 Valid Palindrome/01.py | 608 | 3.96875 | 4 | ### Valid palindrome using list
### pop(0) of list is O(n), which is inefficient.
import time
def is_palindrome(s: str) -> bool:
# get character only
strs = []
for char in s:
if char.isalnum():
strs.append(char.lower())
# determine whether it is palindrome or not
while len(strs... |
18c2fa09cbdc21d7dfa1341c8d46470e50073cb3 | HYLee1008/Python | /08 Linked List/19 Reverse Linked List II/01.py | 661 | 3.9375 | 4 | ### Make linked list reverse from index m to n by iterative
###
from datastructure import *
def reverse_between(head, m, n):
if not head or m == n:
return head
root = start = ListNode(None)
root.next = head
for _ in range(m - 1):
start = start.next
end = start.next
for _ in r... |
72510e3ddc24bec21a2e8f6116ab48e28b0bc1d0 | HYLee1008/Python | /08 Linked List/17 Swap Nodes in Pairs/02.py | 585 | 4.03125 | 4 | ### Swap linked list with pair by iterative.
###
from datastructure import *
def swap_pairs(head):
root = prev = ListNode(None)
prev.next = head
print(id(root), id(prev))
while head and head.next:
b = head.next
head.next = b.next
b.next = head
prev.next = b
hea... |
84af2a9aa641336a69cde00e2f5cb5620ea060b4 | HYLee1008/Python | /07 Array/10 Array Partition I/03.py | 249 | 3.78125 | 4 | ### Calculate the largest number that can be made from the sum of min(a, b) using n pairs by pythonic way.
### Fastest method by slicing.
def array_pair_sum(nums):
return sum(sorted(nums)[::2])
input = [1, 4, 3, 2]
print(array_pair_sum(input)) |
60c66e33f2c18f5615dff7798f8c7cdb655468f4 | afonsonf/ook-modulation | /decode.py | 215 | 3.5625 | 4 | from binascii import unhexlify
file = open('out_bin.txt')
lines = [l.strip() for l in file]
print 'decoding: \n', lines[0], '\n'
n = int(lines[0].encode('ascii'),2)
print 'output: \n', unhexlify( '%x' % n ), '\n'
|
cc80c483dbded8767a52995a8444a73a82c8b623 | pran-av/LearningPython | /split_test.py | 347 | 3.828125 | 4 | lst = ['apple', 'cake', 'cake', 'banana', 'apple']
lst2 = list()
for i in range(len(lst)):
# if i == len(lst) - 1 :
# print("continue trigerred")
# continue
if lst[i] in lst2:
print(i, "already present")
continue
lst2.append(lst[i])
print(lst[i], "added")
print(so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.