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
7d7ece016e2d40272f12d32d32d0dc291c860af3
scaraveos/3dfoo
/restserver/lib/network/facebook.py
2,435
3.515625
4
""" Facebook specific logic. """ import urlparse import urllib import httplib import json class oauth(object): """ The oauth object knows how to authorize a Facebook user. """ api_key = '' api_secret = '' graph_url = 'graph.facebook.com' oauth_suburl = '/oauth/access_token' me_suburl = '/me' authorize_url...
89b8ed1ed7684aee20ebfa70330ceede8b8aade2
D4r7h-V4d3R/Ornekler
/map().py
420
3.515625
4
#Birinci Yol def ikiye(katlan): katlanm=[] for i in katlan: katlanm.append(i*2) return katlanm liste=[3,6,9,13] print(ikiye(liste)) #İkinci Yol (map) lista = [1,2,3,4,5,6,7] print(list(map(lambda x :x**2 ,lista))) keyboards = [("logitech",75),("razer",240),("MSI",140)] ucuz_mu = lamb...
26003c0363ef59d0a28dbc9e3ba40b835c803f09
D4r7h-V4d3R/Ornekler
/class1,__init__,self.py
1,115
4.125
4
#normal OOP Programmlama tarzı (basit programlama) #uninit un self class work: pass emplo1 = work() emplo1.ad = "Hasan" emplo1.soyad = "Kılıc" emplo1.maas = "3100" emplo2 = work() emplo2.ad = "Kemal" emplo2.soyad = "Ok" emplo2.maas = "2300" print(emplo1) print(emplo1.ad,emplo1.soyad) #With init,...
591c8312f8583c9a147eb61c03fc4a04d9445e0c
wps142/PythonLearning
/04_Functional Programming/03_filter.py
3,352
4.15625
4
# Python内建的filter()函数用于过滤序列。 # 和map()类似,filter()也接收一个函数和一个序列。 # 和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 # 在一个list中,删掉偶数,只保留奇数 def is_odd(n): return n % 2 == 1 print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))) # 把一个序列中的空字符串删掉 def not_empty(s): return s and s.strip() print(lis...
35bccdaf15b5f61bbd8847c8609ac03d6dfdf24b
wps142/PythonLearning
/06_OOP/02_使用__slots__.py
1,851
3.71875
4
# 使用__slots__ class Student(object): pass # 给实例绑定一个属性: s=Student() s.name="name1" print(s.name) # 给实例绑定一个方法: def set_age(self, age): # 定义一个函数作为实例方法 self.age = age from types import MethodType s.set_age = MethodType(set_age, s) # 给实例绑定一个方法 s.set_age(25) print(s.age) # 给一个实例绑定的方法,对另一个实例是不起作用的: s2=Student() # s...
536dcf2d28519412dc015986a787659bc2cd8496
wps142/PythonLearning
/03_advanceFeature/03_listComprehensions.py
849
3.75
4
# 高级特性-列表生成式 # 生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)) l1 = list(range(1, 11)) print(l1) # 生成[1x1, 2x2, 3x3, ..., 10x10] l2 = [x * x for x in range(1, 11)] print(l2) # 筛选出仅偶数的平方[4, 16, 36, 64, 100] l3 = [x * x for x in range(1, 11) if x % 2 == 0] print(l3) # 使用两层循环,可以生成全排列 l4 = [m + n for m in 'ABC...
a5454cd3d4ab5e60c5516f53f085e6d7381fe933
wps142/PythonLearning
/04_Functional Programming/07_decorator.py
5,439
3.5
4
# 装饰器 # 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。 # 函数对象有一个__name__属性,可以拿到函数的名字: def now(): print('2015-3-25') print(now.__name__) f = now print(f.__name__) # 现在,假设我们要增强now()函数的功能, # 比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 # 本质上,decorator就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,...
24ce8eee630f5a6200979e6b1a11859e73aed14a
inbarfi/DI_Bootcamp
/week_4/Day_5/daily_challenge.py
3,228
3.8125
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 22 10:37:51 2021 @author: Inbar """ #w4_d5_daily_chaallenge #accepts a comma separated sequence of words as input and prints #the words in a comma-separated sequence after sorting them alphabetically. # =====================================================...
09eb9906e4531f6de85aa8593885c0e2e19df50a
inbarfi/DI_Bootcamp
/week_5/Day_2/xp_3.py
1,081
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 26 19:29:55 2021 @author: Inbar """ #w5_d2_xp # 3 from xp_1_2 import Dog from random import choice class PetDog(Dog): def __init__(self, name, age, weight, trained = False): #adding trained super().__init__(name, age, weight) self.tra...
9c4ddecc93e18f53705f1e8d8c0a8d6e77ddecee
LevequeBenjamin/BenjaminLeveque_P7_11062021
/get_data/get_data.py
742
3.546875
4
"""Contains get_data function.""" # librairies import csv def get_data(file: str) -> list: """Function that allows you to read a csv file. Args: file (string): the path of the csv file. Returns: list (str): a list of information retrieved in the csv file. """ data_shares = [] ...
47c7f247b57ed9a7a114488c427f8005c71ececf
Guyberco/legislation-location-tagger
/src/tests/stringHelperTests/addToString.test.py
2,285
3.609375
4
import unittest import src.stringHelper as stringHelper class TestAddToString(unittest.TestCase): def test_empty_string_addition(self): str = 'Hi' self.assertEqual(str, stringHelper.addToString(str, '', 0)) def test_add_to_empty_string_1(self): str = '' self.assertEqual(str +...
9ebf10a05918f2313a9ba772dd60b229ef5fcf8e
yeruyi0618/python
/if循环.py
203
3.515625
4
# coding=utf-8 user = input("Please input your username: ") psd = input("Please input your passworld: ") if user == 'yeruyi0618' and psd == 'yeruyi@20181225': print ('yes') else: print ('no')
4ff27a89fb2cdb9857d0cb530d7ea43a9f54bed5
Techdread/python-course
/myfunction.py
231
3.921875
4
def minutes_to_hours(seconds, minutes=70): hours = minutes / 60 + seconds / 3600 print(hours) def seconds_to_hours(seconds): hours = seconds / 3600 return hours print(type(minutes_to_hours(300, 200)))
020ce18c50018d43de2710eb5fe540049aed142d
Techdread/python-course
/mprogram.py
78
3.625
4
age = input("Enter your age: ") new_age = int(age) + 50 print(new_age)
9621fb0236eaf16068f246c7bc199679c51c24d2
Snakanter/FunStuff
/rps.py
1,832
4.1875
4
#!/usr/bin/env python3 """ File: rps.py Name: A rock-paper-scissors game against the CPU Concepts covered: Random, IO, if/else, printing """ import random import sys import os def main(): # Code here print("READY FOR A GAME OF ROCK, PAPER, SCISSORS!?") PlayerChoice = input("Choose between optio...
da0dfdfc057f67aa535fed062147951c99d7e673
toobaakram/PYTHON
/date.py
178
3.765625
4
def date(): a=input("Enter date : ") if a[-2]== 'A': print(a) else: b=int(a[0:2])+12 str(b) print(b,a[2:8]) date()
1d7313fe9b0015c48acf5338662386610df1abbf
sidneyriffic/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/4-moving_average.py
367
3.578125
4
#!/usr/bin/env python3 """Calculate weighted moving average of data set""" def moving_average(data, beta): """Calculate weighted moving average of data set""" ema = [0] unbias = [] for idx, dat in enumerate(data): ema.append(beta * ema[idx] + (1 - beta) * dat) unbias.append(ema[idx + 1...
936ae13927543e64f3e7a8cc9a0e015cc0bbe4d0
sidneyriffic/holbertonschool-machine_learning
/math/0x00-linear_algebra/5-across_the_planes.py
351
3.65625
4
#!/usr/bin/env python3 """Add two matrices elementwise""" def add_matrices2D(mat1, mat2): """Add two list-matrices elementwise""" if len(mat1) != len(mat2): return None if len(mat1[0]) != len(mat2[0]): return None return [[ele1 + ele2 for ele1, ele2 in zip(row1, row2)] for ...
f57f5baa9d8b877d74672d49c3f7fd3928d6e72d
hsqStephenZhang/Fluent-python
/使用一等函数实现设计模式/6.1重构策略模式2.py
2,266
3.9375
4
from collections import namedtuple Customer = namedtuple("Customer", "name fidelity") class Lineitem(object): def __init__(self, product, quantity, price): self.product = product # 产品名称 self.quantity = quantity # 数量 self.price = price # 价格 def total(self): # 总价 return sel...
ded6304d80f2401518dc21c39a4a625547682bbb
hsqStephenZhang/Fluent-python
/正确重载运算符/13.2一元运算符.py
1,925
3.78125
4
""" Python的一元运算符有+,-,~,abs等 对于之前的Vector,这里实现几个方法 对于运算符来说,始终返回一个新的对象,而不是在原来的对象基础上修改 """ from array import array import numbers import reprlib import math class Vector(object): typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __neg__(self): ...
f33cb5f201c31a48cd6e231f5eb293c01aa07728
hsqStephenZhang/Fluent-python
/可迭代的对象-迭代器-生成器/14.6生成器表达式.py
370
4.0625
4
""" 生成器表达式只是一个语法糖 完全可以用生成器函数替代,只不过实现起来有时候更方便 对于一些简单的推导式完全可以采用生成器表达式 """ def show1(): a = (i for i in range(5)) # 类似list推导式 print(type(a)) for elem in a: print(elem, end=" ") if __name__ == '__main__': show1()
75a507fe9703d5fb391029bf6e945d55c8d16148
hsqStephenZhang/Fluent-python
/序列的修改散列和切片/10.6Vector类第四版.py
604
4.0625
4
""" 实现hash方法,也就是要在原来Vector2D的基础上写出具有多个分量的__hash__函数 这时候就需要使用functools里面的reduce函数了,而且可以直接使用operator包里面的二元运算符 operator包包含了所有的二元运算符 """ from functools import reduce import operator def myhash(nums1): nums1 = map(hash, nums1) return reduce(operator.xor, nums1) def myeq(nums1, nums2): return len(nums1) == l...
52a19ec7a20ac94d87dd8d26a9492df110792804
hsqStephenZhang/Fluent-python
/对象引用-可变性-垃圾回收/8.4函数的参数作为引用时2.py
2,010
4.375
4
""" 不要使用可变类型作为函数的参数的默认值 """ class HauntedBus(object): def __init__(self, passengers=[]): # python会提醒,不要使用mutable value self.passengers = passengers def pick(self, name): self.passengers.append(name) def drop(self, name): try: self.passengers.remove(name) exce...
baa67284aac469155cfd13d9a5b9a5a2d465fbb5
hsqStephenZhang/Fluent-python
/接口-从协议到抽象基类/11.2Python喜欢序列.py
592
4.1875
4
""" Python尽量支持基本协议 对于一个序列来说,协议要求其实现__getitem__,__contains__,__iter__,__reversed__ index,count的方法 但是,鉴于序列的重要性,在类没有实现__contains__和__iter__方法的时候,只需要定义了 __getitem__方法,也可以实现in,和迭代运算符 """ class Func(object): def __init__(self): self.data = range(0,20,2) def __getitem__(self, item): return self.dat...
de7be08c21a8933afba3503fb97a1e39732ae546
zalak30/terntop
/venv/create_database.py
1,741
3.703125
4
from conn import Connection # create object for class "Connection" connection = Connection() # create database "terntop" try: connection.cursor.execute("CREATE DATABASE terntop") print('database created successfully') except Exception as e: print('Error: ', str(e)) # connect to sql database "terntop" con...
234bb14b6fbf97c49edd17ab5dd926bc57157676
MatePaic/ninjazadaci
/Floyd triangle.py
182
3.796875
4
brojRedaka = int(input('Unesi broj redaka: ')) num = 1 for row in range(1, brojRedaka + 1): for col in range(1, row + 1): print(num,end=' ' ) num += 1 print()
d788483f6803f7e560f5409e8a1e5f0bfafda4a5
ClaremontMBA2020/Homework-for-IST341
/hw2pr1.py
3,833
4.4375
4
# # Intro to loops! # # Name: # def fac(n): """Loop-based factorial function Argument: a nonnegative integer, n Return value: the factorial of n """ result = 1 # starting value - like a base case for x in range(1,n+1): # loop from 1 to n, inclusive result = resu...
4babd18f6552f9c885faac73b0c9f3999129bbf5
chasevanblair/Module7
/fun_with_collections/sort_and_search_array.py
554
3.8125
4
import array as arr def search_array(collection, term): i = 0 for x in collection: if x == term: return i else: i += 1 return -1 def sort_array(collection): new_array = arr.array('i', []) init_len = len(collection) for x in range(0, init_len): ...
68d254a0f0e22a16580126237455d1fe5110564b
khiemjannguyen/Sem4_DB_Projekt
/scraper/main.py
1,387
3.515625
4
from PriceTracker import * def main(url: str, wish_price: float, notify_email: str, openInfluxDB_GUI: bool): print("-------------------------------------------------------------------------------------------------------------------------------------------------") print("Message:") print(f" I will scrap...
64636147c2888308408cb49e42487c05fc6ca95c
stefansilverio/python_improvement
/priority_queue.py
365
3.625
4
#!/usr/bin/env python3 # implement priority queue from heapq import heappush, heappop class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(se...
1bf37586b1315a0c00e69f2902ee8b7a285e67c1
JRBCode/Python
/TKinter/f_text/tk_2.py
533
3.640625
4
# # tk_2.py # @author bulbasaur # @description 在 Text 文本中插入 Button 按钮 # @created 2019-07-24T00:28:03.872Z+08:00 # @last-modified 2019-07-24T00:48:54.034Z+08:00 # from tkinter import * root = Tk() text = Text(root, width=30,height=5) text.pack() text.insert(INSERT, "I love \n") # INSERT 在光标所在位置插入内容 text.insert(END,...
7cc3efabd755c0aba8f2e650dfcf5a043b89b5c1
baki6983/Python-Basics-to-Advanced
/Collections/Tuple.py
328
4.46875
4
#tuples are ordered and unchangable fruitsTuples=("apple","banana","cherry") print(fruitsTuples) print(fruitsTuples[1]) # if you try to assign value to fruitsTuples[1] , it will change because its Unchangeable # With DEL method you can completely List , but you cant item in the list for i in fruitsTuples: pr...
414fc4222b5ffd64f6b437cee32a55f24be5a30d
cbswj/moble
/moble/project_source/자판기/신원진_자판기소스/report_1.py
4,007
3.5625
4
import datetime import time current = 0 # 이자 시간 money = int(input("돈을 입력해주세요 : ")) game = 1 # 게임 지속 유무 sale_name = ["커피","음료수","과자","아이스크림"] sale_money = [100,500,1000,600] loan_money=0 # 빌린 돈 원금 while(game): if loan_money: now = datetime.datetime.now() time_s = (now - current).seconds ...
8a59117fb11a0dba2ade727335f17c342181aa77
ItsRaza/Maze-Assignment-CG
/main.py
492
3.59375
4
from Maze import * import pygame import random import time x, y = 20, 20 # start point of maze on window/canvas build_grid(0, 0, 20) Make_Maze(x, y) Solve_Maze(200, 200) # pygame running loop running = True while running: # keep running at the at the right speed clock.tick(FPS) # process input (events...
f0ed89ec385585eff95f8356d34d0ed524f70b5f
guptavashisht24/VG
/dfstree.py
874
3.890625
4
class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Tree: def __init__(self,root): self.root = root def search(self,target): level = 0 f = 0 stack = [self.root] while(stack): k = s...
89271ea2216fc658a9994b34bc5a10258c576e4a
aakashsheth/humidity_sensor
/remote/remote_test.py
583
3.734375
4
import RPi.GPIO as GPIO import time # GPIO Settings GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Set PIN 17,18 as output GPIO.setup(17, GPIO.OUT) GPIO.setup(18, GPIO.OUT) while True: number = input("Please enter 1(on) or 2(off): ") if number == 1: GPIO.output(17, GPIO.HIGH) time.sleep...
6705d4095c282200d0c3f2ca1c7edfb15cdc7009
akshayreddy/yahtzee
/yahtzee.py
2,427
4.25
4
''' .) Programs creats a list of dices .) ProbailityInfo is used to keep track of the positions of dices which will be used to re rolled in future .) probability contais the list of probanilities ''' from decimal import Decimal from random import randint import sys j,k=0,0 dices,ProbabilityInfo,probaility=[],[],[...
c9519197f10ca554f368e507740dffd37c332496
Pappipapp/LadenhueterBackend_public
/Backend/database/database.py
7,361
3.609375
4
import psycopg2 class Database: """ PostgreSQL Database-Wrapper It should always be instantiated using the keyword 'with', in order to ensure a correct initialization as well as a correct shut down """ def __init__(self, db_name, user, password, host, port=5432): """ Initi...
5c6be00bb23deae43ea19b869ee0536f6d144152
Christopher-Teague/functionsIntermediate1
/get_values.py
497
4.03125
4
students = [ {'first_name' : 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary2(key_name, some_list): for idx in range(0, le...
be122cc41520bbc38050d8b7abfd4423d7ac7a1f
Jeremy-Roux/TP-Bot-Jeu
/dossier_code/Modelisation_Bot_Jeu.py
961
3.890625
4
from random import randint class Game : def __init__(self,nb_bat): self.nb_bat=nb_bat def is_game_finished(self): if self.nb_bat <= 0: return True else: return False def display(self): print(self.nb_bat*"|") def player_remove_stick(self): ...
927b03745e041a669afda190f01217e50d6731b9
IanBurgan/Pong
/Entities.py
2,290
3.65625
4
import pygame from math import tan, radians class Player_Paddle(): def __init__(self, screen, width, height, vy): self.left = screen[0] - (11 + width) self.top = (screen[1] // 2) - (height // 2) self.width = width self.height = height self.ybound = screen[1] self.direction = 0 self.speed = vy ...
7085a6d6351e86ef8cb8eb2cf8f4d9ee15ecc5a5
Junhao-He/PythonUpUp
/Algorithm/maxArea.py
635
3.796875
4
# coding = utf-8 # @Time : 2022/9/8 22:14 # @Author : HJH # @File : maxArea.py # @Software: PyCharm class Solution: def maxArea(self, height) -> int: l = len(height) left = 0 right = l - 1 area = 0 while left < right: cur_area = min(height[left], height[right...
22af7fddc0a03e23689367b90f7677bc8399e867
Junhao-He/PythonUpUp
/Algorithm/MinSubArrayLen.py
1,593
3.71875
4
# coding = utf-8 # @Time : 2020/8/6 13:42 # @Author : 0049003071 # @File : MinSubArrayLen.py # @Software: PyCharm class Solution: # 里层暴力循环,外层二分查找,会超时555 def minSubArrayLen(self, s: int, nums): result = 0 left = 1 right = len(nums) while left <= right: print(left, ...
bae77f5fb3ffaa4c35dc33eb24f6f2ba35255b43
Junhao-He/PythonUpUp
/Algorithm/hasCycle.py
954
3.625
4
# coding = utf-8 # @Time : 2021/7/26 22:25 # @Author : HJH # @File : hasCycle.py 判断链表有环 # @Software: PyCharm class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: sp, fp = head, head sign = 0 # 必须...
d91e91663ee9f3c403bbc37256398b4a6e6982fb
Junhao-He/PythonUpUp
/Algorithm/maxSubArray.py
1,016
3.609375
4
# coding = utf-8 # @Time : 2021/7/2 16:43 # @Author : HJH # @File : maxSubArray.py # @Software: PyCharm class Solution: def maxSubArray(self, nums): backup = [] temp = 0 if len(nums) == 1: return nums[0] if len(nums) == 2: return max(nums[0], nums[1], nu...
5b71531661a8ec8b40c046bd372b96146d212303
Junhao-He/PythonUpUp
/Algorithm/insertsect.py
1,482
3.53125
4
# coding = utf-8 """ Author:hjh Date:07.13 Method:1.最直接的想法,双重循环遍历,并将被查询list的相应元素删除; 2.哈希表存储较小的list """ class Solution: def intersect(self, nums1: list, nums2: list) : result = [] for i in nums1: if i in nums2: result.append(i) nums2.remove(i) ...
9455662e54b6d71e5ce4c89174ae5002936e2e61
Junhao-He/PythonUpUp
/Algorithm/yanghui.py
1,079
3.671875
4
# coding = utf-8 """ Author:hjh Date:07.27 Method:杨辉三角 """ class Solution: def generate(self, numRows): result1 = [1] result2 = [1, 1] if numRows == 0: return [] if numRows == 1: return [result1] if numRows == 2: return [result1, result2...
b1cbcdca4d48b9a86c7004a9bdc3e691e517c17f
defytheflow/cs50
/week1/mario.py
585
4.0625
4
def main(): height = prompt() draw(height) def prompt(): while True: try: height = int(input("Give me an integer from 0 through 8: ")) except ValueError as e: print(e) continue if not (0 < height < 9): continue ...
50a19615d64c0c8e015d625211e2404dd322b0f6
defytheflow/cs50
/week6/caesar.py
1,223
4.375
4
# This program encrypts the given message by a given key using Caesar Cipher import sys def main(): check_args() key = int(sys.argv[1]) % 26 message = input("plaintext: ") encrypt_caesar(message, key) def check_args() -> bool: """ Checks provided command lines arguments. """ if len(sys.argv)...
9adb19ac7cc6b52230616edb92469c19e46e3f8c
AdwaitMhatre/Algorithms-Python
/inssort.py
328
3.953125
4
def InsertionSort(arr): for j in range(1,len(arr)): if arr[j] < arr[j-1]: i = j while i > 0: if arr[i] < arr[i-1]: arr[i],arr[i-1] = arr[i-1],arr[i] i -= 1 print(arr) l = [6,8,1,4,10,7,8,9,3,2,5] InsertionS...
5c965c84d1e4625b7bcdbf58b9469ab435bf4d72
popovale/python-stepic
/kurs2/prim1_6_3_4.py
253
3.640625
4
class EvenLengthMixin: def even_length(self): return len(self)%2==0 class MyList(list, EvenLengthMixin): pass print(MyList.__mro__) print() x=MyList([1,2,3]) print(x) print(x.even_length()) x.append(4) print(x) print(x.even_length())
3310cf12ac5d4a4b21d0435775987c95e4f7342b
popovale/python-stepic
/kurs2/prim1_5_5_2.py
213
3.578125
4
class Counter: def __init__(self, start=0): self.count=start Counter x=Counter() print(x) x1=Counter(10) print(x1) print(x1.count) x1.count+=1 print(x1.count) print(x.count) x.count+=1 print(x.count)
d0169e4b6bef14d963e11ac442577eb3c923d093
popovale/python-stepic
/kurs2/prim1_6_1.py
315
3.921875
4
class MyList(list): def even_length(self): return len(self)%2==0 x=MyList() print(x) x.extend([1,2,3,4,5]) print(x) print(x.even_length()) x.append(6) print(x) print(x.even_length()) # print(isinstance(x,list)) # True Является ли экземпляр х наследником класса list
93f5fe9c8de9affb32447afdd83f601087e214c6
popovale/python-stepic
/zad2_set_chislo_povtorenii.py
608
3.765625
4
# Найти число повторений слова в фразе # ввод строки в сисок с разбитием на слова и переводом в нижний регистр stroka=[str(i).lower() for i in input().split()] # print(stroka) set_stroka =set(stroka) # копируем список в множество set # print(set_stroka) s=0 # обнуляем счетчик for i in set_stroka: # перебираем слова в м...
0c7004e936c09e31cca66c7840454630646d5c9f
popovale/python-stepic
/zad6_vvod_obr_vyv_2massiv_v2.py
680
3.703125
4
a = [] # ввод матрицы while True : s = input() if s == 'end' : break a.append ( s.split() ) #преобразование исходной матрицы в целочисленную n=len(a) m=len(a[0]) for i in range(n): for j in range(m): a[i][j]=int(a[i][j]) # генерация новой матрицы b=[[0 ...
7bc4f5501ba5570ddd2e76e8d6fc02df2c8cb048
frankgh/CS525
/homework1_afguerrerohernan.py
4,981
3.953125
4
import numpy as np def problem1(A, B): """ Given matrices A and B, compute and return an expression for A + B :param A: matrix A :param B: matrix B :return: A + B """ return A + B def problem2(A, B, C): """ Given matrices A, B, and C, compute and return AB - C (i.e., right-mu...
d27ad23f16245f914008fdcb5e45b64b1cf6a4b3
1UnboundedSentience/projecteuler
/eulerlib.py
1,429
3.578125
4
import math def fibonacci(max=None): a, b = 1, 1 while max is None or a < max: yield a a, b = b, a + b def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) def sieve_prime(max=100000000): sieve = range(max + 1) for i in xrange(2, max): ...
5bc1fa978bcca24b8dff5d9c89340f922eafa5a3
1UnboundedSentience/projecteuler
/problem014.py
1,419
3.765625
4
# coding: utf-8 """ The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and f...
d1e2bbd7d438c08ca09a05391e0c1cc8390f722a
GokoshiJr/ejercicios-heavy
/SeriesHeavy/SerieH3.py
1,029
3.71875
4
import math """ Desarrolle la siguiente serie: S = 2X/2! - 3X^2/3! 4X^3/4! - 5X^4/5! + ... En esta serie, se leera el valor de x y epsilon, la misma se desarrollará hasta que el modulo de la diferencia entre el termino anterior y el siguiente sea menor que un epsilon sado osea: |termino anterior - termino siguiente|...
9a4f083a0a58e69cb4cf0fd5ac731073cfb48e29
GokoshiJr/ejercicios-heavy
/SeriesHeavy/SerieA1.py
1,135
3.53125
4
import math """ Desarrolle la siguiente serie: S = - X^1/1! + X^4/1*3 - X^9/3! + X^16/1*3*5 - X^25/5! + ... """ # Declaración de Variables sumatoria = termino = factorial = 0.0 n = factor = final = aux = aux2 = exp2 = 0 estatus = "" signo = True print("-"*30) print(" Serie Heavy A1") print("-"*30) # Entrada de Da...
e26c240fc3b0ed46b98d6ac7e0640d4b5adb2218
SOURABH2227/python-edits
/postive negative no.py
197
4.4375
4
#To check if the entered number is +ve or -ve & display an correct message num=float(input("Enter a number:")) if num >= 0: print("positive or zero") else: print("Negative number")
51b1b9e5e2189e1280acf546c50e7eb2facb9aac
denze11/BasicsPython_video
/theme_14/5_gen_dict.py
281
4.0625
4
pairs = [(1, 'a'), (2, 'b'), (3, 'c')] # класический способ result = {} for pair in pairs: key = pair[0] val = pair[1] result[key] = val print(result) # через генератор словоря result = {pair[0]: pair[1] for pair in pairs} print(result)
f34658ef7cd7cafb3a0cdd67f8c918ca6b4ebd3e
denze11/BasicsPython_video
/theme_14/10_and_true.py
716
4.0625
4
import math # Есть спиок чисел numbers = [4, 1, 2, 3, -4, -2, 7, 16] # Создать список из тех чисел которые имеют квадратный корень меньше 2 [1, 2, 3] result = [] #Обычный способ for number in numbers: if number > 0: sqrt = math.sqrt(number) # квадратный корень меньше 2 if sqrt < 2: result.append(number) p...
180577a343bfe682371b07eb9ef7286a526d0bdc
denze11/BasicsPython_video
/theme_14/17_concrete_exxept.py
235
3.578125
4
number = int(input('Введите число: ')) try: result = 100 / number except ZeroDivisionError: print('На 0 делить нельзя!') except Exception: print('Неизвестная ошибка') print('Конец')
cc35a2f8ef7f5c1c81d6d491abdfb6263c632769
denze11/BasicsPython_video
/theme_4/13_why_range.py
604
4.21875
4
# Когда нам может помочь range winners = ['Max', 'Leo', 'Kate'] # Простой перебор for winner in winners: print(winner) # Что делать если нам нужно вывести место победителя? # использовать while? # или есть способ лучше? # вывести нечетные цифры от 1 до 5 numbers = [1, 3, 5] for number in numbers: print(num...
17b5540da30b3ad865f53ba20cf03c318bea957d
denze11/BasicsPython_video
/theme_14/13_list_in_function.py
251
3.953125
4
numbers = [1, 2, 3] def change_number_in_list(input_list): input_list[1] = 200 # после вызова функции change_number_in_list(numbers) # список в основной программе тоже изменится print(numbers)
2368f20afb3722e8ba9f31b31f64de64947f1481
denze11/BasicsPython_video
/theme_8/17_why_func_param.py
434
3.828125
4
def my_filter(numbers, function): result = [] for number in numbers: if function(number): result.append(number) return result numbers = [1, 2, 3, 4, 5, 6, 7, 8] print(my_filter(numbers, lambda number: number % 2 == 0)) # если нужны нечетные числа print(my_filter(numbers, lambda number: number % 2 != 0)) ...
10be9e035cd80484fcb8a5eef1531a9545f9f30b
denze11/BasicsPython_video
/theme_14/14_copy_list.py
547
4.3125
4
a = [1, 2, 3] # копия с помощью среза b = a[:] b[1] = 200 # список а не изменился print(a) # копия с помощью метода copy b = a.copy() b[1] = 200 # список а не изменился print(a) # Эти способ бы не будут работать если есть вложенные списки a = [1, 2, [1, 2]] b = a[:] b[2][1] = 200 # список а сного меняется print(a)...
e1a3e33058ef5b1a3716e992e31bc3d3bbefa136
denze11/BasicsPython_video
/theme_4/9_in_ex.py
384
3.890625
4
hero = 'Superman' # hero = 'Super' if hero.find('man') != - 1: print('Есть') else: print('Нету') if 'man' in hero: print('Есть') else: print('Нету') goals = ['Стать гуру языка python', 'здоровье', 'накормить кота'] if 'здоровье' in goals: print('Все хорошо') else: print('Все плохо')
20809f6c9792a2db4a74c6a71c551094a6c107a5
denze11/BasicsPython_video
/theme_4/10_winners.py
1,083
4.0625
4
# Пользователь вводит кол-во участников соревнований по python # Пользователь вводит участников и их места в зависимости от кол-ва # 1. Вывод имени участников по алфавиту # 2. Получить 3-х победителей и поздравить их # 3. Победители: ... Поздравляем! print('СОРЕВНОВАНИЯ ПО PYTHON') number_of_participants = int(input('...
aa12e4500bf330344f0ceb4d67beedf9a2fac729
denze11/BasicsPython_video
/theme_8/4_def_func.py
298
3.875
4
# Функция простой разделитель def print_sep(): print('-' * 100) print('Моя функция') print_sep() print('Красивый разделитель') print_sep() print('Что если их будет много?') print_sep() print_sep() print_sep() print_sep()
53f1fb3992694816670222b963a8148445949881
NatheZIm/nguyensontung-homework-c4e14
/Day2/ex4a.py
88
3.59375
4
a n = int(input("Number of star : ")) for i in range(n): print("*",end="") print()
d5d129c657c35a21983e77972370f67e146bdfe7
NatheZIm/nguyensontung-homework-c4e14
/Day4/ex3.py
287
4.25
4
isPrime=0 n=int(input("Enter Number to Check: ")) if n == 1 or n == 0: print(n,"Is Not Prime Number ") else: for i in range(1,n+1): if n%i==0: isPrime+=1 if (isPrime==2): print(n,"Is Prime Number") else: print(n,"Is Not Prime Number")
847cfeb4313e614fd96be92f0de738e5472d214a
aso-learn/python-learn
/pass.py
134
3.53125
4
#! /usr/bin/env python3 #coding:UTF-8 for i in 'helloworld': if i =='o': pass print("pass") print(i,end=",")
57fa092aa77c18fc28f809afb0018f8e87fdc6c4
aso-learn/python-learn
/fbqn.py
139
3.75
4
#! /usr/bin/env python # coding:UTF-8 a = 0 b = 1 n = int(input("请输入数字:")) while b < n: print(b,end=',') a,b = b,a+b
e28d38fdd8c38a640a060f745866eb1f878c534b
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1287.py
720
3.5
4
# coding: utf-8 def main(): while True: try: string = input() numero = processar(string) avaliar_inteiro(numero) except EOFError: break def processar(string): nova_string = '' for i in string: if i == 'l': nova_string +=...
42f80f894e63cde53a5b72b6f3d74c0772d742c2
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1120.py
383
3.546875
4
# coding: utf-8 def main(): while True: d, n = input().split(' ') if d == '0' and n == '0': break else: falha(d, n) def falha(d, n): novo_n = '' for i in n: if i == d: continue else: novo_n += i if novo_n == '':...
812d90e3340a3d1d625f5624b5cd8086306041a6
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1174.py
187
3.59375
4
# coding: utf-8 def main(): for i in range(0, 100): a = float(input()) if a <= 10: print('A[%d] = %.1f' % (i, a)) else: pass main()
e637ca3b7244f85adee869e69a50909fc0c2c801
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1067.py
164
3.59375
4
# coding: utf-8 X = int(input()) l = [] for i in range(1, X+1): if i%2 != 0: l.append(i) else: pass while len(l) > 0: print(l.pop(0))
8470d076c31460964037518280eb30a4be851bd0
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1037.py
347
4
4
# coding: utf-8 # entrada numero = float(input()) # computações e saídas if (0 <= numero <= 25): print('Intervalo [0,25]') elif (25 < numero <= 50): print('Intervalo (25,50]') elif (50 < numero <= 75): print('Intervalo (50,75]') elif (75 < numero <= 100): print('Intervalo (75,100]') else: pr...
e9e114c26f6785593e10ad3723dcc3c4e3c49934
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1039.py
585
3.8125
4
# coding: utf-8 from math import sqrt def distancia_centros(x1, y1, x2, y2): d = sqrt((x1-x2)**2+(y1-y2)**2) return d def contida(d, r1, r2): if d == 0: if r2 <= r1: estado = 'RICO' else: estado = 'MORTO' elif d <= r1-r2: estado = 'RICO' else...
33b09fed8e58fc473406db5dc040a31814a65238
brunomendesdecarvalho/URI-Bruno-Mendes
/uri/u1065.py
252
3.734375
4
# coding: utf-8 # entradas: numeros_pares = [] i = 0 # computações: while i < 5: a = int(input()) if a % 2 != 0: pass else: numeros_pares.append(a) i += 1 # saída: print('%d valores pares' % len(numeros_pares))
1d62f6a708016a46f4ec143529a47ba0fd7fd0a9
MFRoy/pythonchallenges
/python/grade_calculator.py
520
4.1875
4
print("Welcome to average grade calculater ") maths = int(input(" Please imput your Maths mark : ")) physics = int(input(" Please imput your Physics mark : ")) chemistry = int(input(" Please imput your Chemistry mark : ")) average =((maths+physics+chemistry)/3) print ("your percentage is", " ",average,"%") grade= "Fai...
0f3e470f605c044ff0acfc651a96f737b7cba5d8
HomNanThaweHtun/Project
/Assignment 1/A1.py
4,945
4.03125
4
""" Student Name: Hom Nan Thawe Htun Student ID: 13644108 Github: https://github.com/CP1404-2017-2/a1-YeYintThetKhine/blob/master/assignment1.py """ from operator import itemgetter file_name = "songs.csv" in_file = open("songs.csv", 'r') #to display the main menu def main_menu(): prompt = "Menu:\nL - List songs\n...
6a68113be80435c30906625453f65c7950ec0840
Fiverdug/bioptim
/examples/torque_driven_ocp/pendulum_with_fatigue.py
4,615
3.734375
4
""" A very simple yet meaningful optimal control program consisting in a pendulum starting downward and ending upward while requiring the minimum of generalized forces. The solver is only allowed to move the pendulum sideways. This simple example is a good place to start investigating bioptim as it describes the most ...
64eb70ab00fccbcdb96f7ae80b02dda4dd65222a
balazsando/100doors
/100doors.py
100
3.5625
4
print("The following doors are open:", end =" ") for i in range(1, 11): print(i*i, end = ", ")
c7ef09f6a0abfc14f4d624bc97eabb1c390664c1
osaw0405/Dat-119
/Orion_Wille_homework_8.py
4,778
4.1875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 27 19:37:55 2019 @author: orion.wille """ #create empty lists todo_list = [] complete_list = [] def menu_screen(): #display menu print("\n :::Menu::: \n") print("Here are your options: \n") print("1) View Todo List") print("2) View Completed Task...
ba8eee2b4e21b9790a9578b5865f2ab6a2bc575d
mreveil/connect5
/connectFive.py
1,897
3.765625
4
"""connectFive.py General library to calculate the value of a give state of the game and also determine if a player has won. Author: Mardochee Reveil 1/8/2017 """ import constants def getStateUtility(state): #Player 2 is the maximizer (and player 1 the minimizer) totalPoints = 0 for player in [1,2]...
3f8179dc959c98d8a62798a42d51f59107f75de2
Kalva-Swetha/FST-M1
/Python/Activities/Activity6.py
107
3.71875
4
for i in range(7): n=1 while(n<=i): print(i,end=" ") n=n+1 print("\n")
71e92a71b931db2c1d1aff0c573e5b9ff000a992
docjulz/star-program
/tkinter_star.py
923
3.953125
4
# This program creates a Hollywood Star # for the Walk of Fame. import tkinter import tkinter.font class MyStarGUI: def __init__(self): # Main window. self.main_window = tkinter.Tk() # The Canvas widget. self.canvas = tkinter.Canvas(self.main_window, width=400, height=375) ...
2daeebe46ae67bfecf9682f2deabbfb36d1acd89
jordyPineda/python
/python/ejercicio_90.py
638
3.859375
4
import time def main(): h= int(input("ingrese las horas: ")) m= int(input("ingrese los minutos: ")) s= int(input("ingrese los segundos: ")) for i in range(h): for j in range(60): for k in range(60): print("{}:{}:{}".format(i,j,k)) time.sle...
d36f9b924a19735d72b7cb7806184f99a0810856
jordyPineda/python
/python/ejercicio6.py
371
3.90625
4
import math def longitud(r): s= math.pi*2*r return s def area(r): s= math.pi* pow(r,2) return s def main(): r = float(input("ingrese el radio: ")) print("la longitud de la circunferencia es: {}".format(longitud(r))) print("el area de la circunferencia es: {}".format(area(r))...
776a02c28dda3d21fab630b52aa89f62d007f031
jordyPineda/python
/python/ejercicio_34.py
432
3.75
4
def main(): a=1 par=0 impar=0 while a != 0: a= int(input("ingrese un numero: ")) if a<0: a = a * -1 if (a%2) == 0: par = par + a else: impar = impar +a print("suma de los numeros pares {}".format(par)) ...
546fdf1fe55591f18a097d2ca2857ab4eefdd436
Guilli12pm/Word_pring_shapes
/Printword_bounce.py
834
3.6875
4
import time from collections import deque def print_list(li): for i in range(len(li)): if li[i] == None: print(" ",end="") else: print(li[i],end="") print() def printword(word,n): listi = deque([word[i] for i in range(len(word))] + [None for i in range(n-len(word))...
91ca0cb4aa09b64c9f640b316390f80701d11bf0
syurskyi/Python_3_Deep_Dive_Part_3
/Section 7 Serialization and Deserialization/45. Pickling - Coding_001.py
5,165
3.921875
4
import pickle ser = pickle.dumps('Python Pickled Peppers') print(ser) print('#' * 52 + ' We can deserialize the data this way: ') deser = pickle.loads(ser) print(deser) print('#' * 52 + ' We can do the same thing with numerics ') ser = pickle.dumps(3.14) print(ser) deser = pickle.loads(ser) print(deser) print('#...
74a51ebe0841107ea6ff6d37701e2c937d793d12
syurskyi/Python_3_Deep_Dive_Part_3
/Section 3 Dictionaries/18. Custom Classes and Hashing - Coding.py
11,678
4.15625
4
print('#' * 52 + ' Remember the difference between equality (`=`) and identity (`is`): ') t1 = (1, 2, 3) t2 = (1, 2, 3) print(t1 is t2) print(t1 == t2) d = {t1: 100} print(d[t1]) print(d[t2]) print('#' * 52 + ' As you can see, even though `t1` and `t2` are different **objects**, we can still retrieve' ...
a51f73b733192e60671fe400ef60d5ac305e3a52
syurskyi/Python_3_Deep_Dive_Part_3
/Section 3 Dictionaries/14. Dictionary Views - Coding.py
4,926
4.15625
4
print('#' * 52 + ' ### Views: keys, values and items ') s1 = {1, 2, 3} s2 = {2, 3, 4} print('#' * 52 + ' Unions: ') print(s1 | s2) print('#' * 52 + ' Intersections: ') print(s1 & s2) print('#' * 52 + ' Differences: ') print(s1 - s2) s2 - s1 print('#' * 52 + ' ') d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'c': 30,...
dcb6a28c7331e2da2f0ddbe8e889332e441c1bfd
jeetshah0303/MCPneuron
/MCPandNotOr.py
1,231
4.09375
4
#Aim:implementing AND,NOT and OR gate using McCulloch pitts neuron model #Name:jeet Shah #roll number:E024 #Batch: B.Tech CSE BE1 if __name__ == "__main__": w1=1#weights of each node w2=1 x1=int(input("please enter the input1:"))#entered the weight values x2=int(input("please enter the input2:")) ...
e0a5898d45ddec4f1ebea867b9cdd0614c854991
JFernandez1995/misc
/pythonAlgos/queue.py
285
4.0625
4
# Python code to demonstrate Implementing # Queue using list queue = ["Amar", "Akbar", "Anthony"] queue.append("Ram") queue.append("Iqbal") print(queue) # Removes the first item print(queue.pop(0)) print(queue) # Removes the first item print(queue.pop(0)) print(queue)
b505eb417d580c6341ed1e68bcac3bcd66be24ad
shilinlee/reinforcement_learning
/question_task/q1.py
411
3.546875
4
# Structure of your solution to Assignment 1 import pandas as pd import numpy as np def analyze_tf_idf(arr, K): tf_ifd = None top_k = None # add your code here return tf_idf, top_k if __name__ == "__main__": # Test Question 1 arr = np.array([[0, 1, 0, 2, 0, 1], [1, 0, 1, 1, 2, 0], [0, 0, 2...