blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
5c96d7745ba921694275a5369cc4993c6bb5d023 | inmank/SPOJ | /source/AddRev.py | 2,292 | 4.3125 | 4 | '''
Created on Jun 20, 2014
@author: karthik
The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies.
Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies.
Obviously, this work is very hard because the basic s... |
967398078bc5e25cee9baefc88674681dca3d1bb | jimuyang/use-python | /liaoxuefeng/function/ReturnFunction.py | 1,537 | 3.671875 | 4 | # encoding: utf-8
"""
@file: ReturnFunction.py
@user: muyi-macpro
@time: 2018/4/3 下午10:37
@desc: 返回函数
"""
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
# 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数:
f = l... |
5a0b202736bf8665de6efda294f9daaae729fc25 | jimuyang/use-python | /skills/datastructure_algorithm/dict_sort.py | 714 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Jimu Yang'
sorted([1, 5, 0, 9])
from random import randint
dic = {x: randint(60, 100) for x in 'xyczaowv'}
sorted(dic) # ['a', 'c', 'o', 'v', 'w', 'x', 'y', 'z']
(97, 'a') > (97, 'b')
for x in zip(dic.values(), dic.keys()):
print(x)
zip(dic.values... |
1f678c57eed56787339abdf585dfbf06880e712b | jimuyang/use-python | /skills/datastructure_algorithm/use_deque.py | 260 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Jimu Yang'
# 队列的使用 双向队列
from collections import deque
que = deque([], 5)
for x in range(0, 10):
que.append(x)
print(que)
que.appendleft(10)
print(que)
s = ''
print(s | 'sasd') |
5e28e338899f6063864d5f3157aff908bc0dbd32 | jimuyang/use-python | /skills/handle_string/string_align.py | 357 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Jimu Yang'
# 对字符串进行左、右、居中对齐
# 1:str.ljust() str.rjust() str.center()
# 2: format() 传入:'<20' '>20' '^20'
str1 = 'abcde'
print(str1.ljust(10, '='))
print(str1.rjust(10, '='))
print(str1.center(10, '='))
print(format(str1, '>20'))
print(str1.__format__('^20... |
c86c82044d131784afd2cba6d125f2e02d8ffc60 | jimuyang/use-python | /liaoxuefeng/Generator.py | 1,048 | 3.8125 | 4 | # encoding: utf-8
"""
@file: Generator.py
@user: muyi-macpro
@time: 2018/4/1 下午9:34
@desc: python高级特性——生成器
"""
# 第一种方法:把[] 改为 ()
# 创建L和g的区别仅在于最外层的[]和(),L是一个list,而G是一个generator。
L = [x * x for x in range(1, 11)]
print(L)
G = (x * x for x in range(1, 11)) # 类似于一个状态机
print(G)
print(next(G))
print(list(G))
# print(nex... |
5ceb18ad2d95aa3c229b73b9fb5924cb6b876187 | Papashanskiy/testing | /find_full_periods_in_range.py | 4,779 | 4.03125 | 4 | from datetime import datetime, timedelta
import calendar
def find_full_month_in_period(_start: datetime, _end: datetime) -> list:
"""
|This function takes two arguments start of period and end of the period
|It returns list of tuples: month start date, month end date, 'year.month' string
"""
def ... |
4df2f9598334409ea9e09f7df9f6a61c7fce490f | Pretty-19/Coding-Problems | /MagicStick.py | 670 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def fittingAnalysis(height_of_locker ,length_of_locker,width_of_locker,length_of_magic_stick):
if height_of_locker length_of_magic_stick:
digonal = pow(height_of_locker, 2) + pow(length_of_locker, 2)+ pow(width_of_locker,2)
... |
604c5557cc1ddd60623e4d60302e5a2f95dc3f7f | tjbwp-ComputerVision/facial-detection-and-recognition | /faces-and-eyes-detection/tutorial-2/tutorial-2.py | 3,657 | 3.84375 | 4 | # Facial Detection and Recognition
# Faces and Eyes Detection - Tutorial #2
# Description:
# - A simple tutorial for Faces and Eyes Detection,
# using frames in shape of circles for each detected component,
# during a video capture;
# Authors:
# - Ruben Andre Barreiro
# Import future versions' libraries
from __... |
d8cfc9798f3479110809dc408f42ea946a66a7cd | jwjimmy/fast-SVD | /assembly/binaryprinter.py | 683 | 3.546875 | 4 | ##num = 0b11
##print num
##print bin(num)
##
num2 = 0xffffffff
print num2
##print bin(num2)
##
##o = "0"
##s = "1"
##num3 = int(s*32, 2)
##print num3
##print bin(num3)
##
##print bin(0b1110+0b1111)
##
##num4 = int(o*15+s+o*16,2)
##print bin(num4)
##print num4
def invert(i):
bins = bin(i)[2:l... |
3513235d2bde1fc5ada6725dbbd89ef116131b64 | abhinandanchakraborty/datascience_test | /airquality.py | 595 | 3.6875 | 4 | import pandas as pd
#(1.) Download the dataset from https://archive.ics.uci.edu/ml/datasets/Air+quality and save .csv file into /data
#(2.) Load the dataset into pandas data frame
df = pd.read_csv('data/AirQualityUCI.csv',sep=";")
#(3.) Create a timeseries data frame
df['Date'] = pd.to_datetime(df['Date'])
df.inde... |
963757d9b8200684173efc9ed2e25f6e9757dbc3 | matheusmcz/Pythonaqui | /Aula10/ex031.py | 321 | 3.78125 | 4 | print('--' * 5, 'Bem-Vindo a AEROP', '--' * 5)
distanciaviagem = int(input('\nDistância em Km da viagem: '))
print('----' * 5)
if distanciaviagem <= 200:
print('O valor da passagem será de: R$ {}'.format(distanciaviagem * 0.50))
else:
print('O valor da passagem será de: R$ {}'.format(distanciaviagem * 0.45))
|
1e0936e3421d590d78dcc852ba674b4527fd3971 | matheusmcz/Pythonaqui | /Aula09/ex025.py | 156 | 3.75 | 4 | print('-' *5, 'TEM SILVA?', '-' *5)
nome = str(input('Insira seu nome macho: ')).strip().lower()
print('Seu nome contem silva? {}'.format('silva' in nome)) |
71b08031cf691fbab98779c4d31c558143f1ce99 | matheusmcz/Pythonaqui | /Aula07/ex010.py | 148 | 3.71875 | 4 | # Conversão de Moeda
print('-' *5, 'CONVERSÃO DE MOEDA', '-' *5)
dollar = float(input('Valor em reais:R$ '))
print('U${:.2f}'.format(dollar/3.27)) |
c415bf6e18b5343578c03242ae659b3f8a37ebcb | matheusmcz/Pythonaqui | /Mundo2/ex039.py | 428 | 3.96875 | 4 | import datetime
idade = int(input('Informe seu ano de nascimento: '))
periodoalismento = datetime.date.today().year - idade
if periodoalismento < 18:
print('Você ainda vai se alistar!')
print('Faltam {} anos.'.format(18 - periodoalismento))
elif periodoalismento == 18:
print('Está na hora de se alistar!')
... |
54368499b5a35f60348bac46dae1d71b97c658f9 | matheusmcz/Pythonaqui | /Mundo2/ex49.py | 147 | 3.578125 | 4 | print('{:=^40}'.format('TABUADA!'))
numero = int(input('NÚMERO: '))
for c in range(1, 11):
print('[{} x {} = {}]'.format(numero, c, numero*c))
|
3d4db8f63937fe075289367c4662ed6647c0889f | matheusmcz/Pythonaqui | /Mundo2/ex038.py | 303 | 4.09375 | 4 | numero1 = float(input('Insira um número: '))
numero2 = float(input('Insira outro número: '))
if numero1 > numero2:
print('{} é maior que {}'.format(numero1, numero2))
elif numero2 > numero1:
print('{} é maior que {}'.format(numero2, numero1))
else:
print('Os dois número são iguais.')
|
dfb314c0bd28e8c2408dfaf3fa4c3b341f94010a | matheusmcz/Pythonaqui | /Aula09/aula09.py | 987 | 4.0625 | 4 | # Fatiamento str
# [] serve para lista.
# [9:13] seleciona uma fatia da str. começando no 9 terminando no 13, sem mostrar o ultimo.
# [9:21:2] saltando de 2 em 2.
# [:5] começa do '0' até o 5, eliminando o ultimo.
# [5:] começa do '5' vai até o final.
# [5::3] começa do '5', vai até o final pulando de 3 em 3.
# Analise... |
4460060d3b57d8156296ae00ffc96078d7b38332 | matheusmcz/Pythonaqui | /Mundo2/ex063.py | 286 | 3.890625 | 4 | quantidade = int(input('Quantos termos você deseja ver? '))
t1 = 0
t2 = 1
contador = 0
print('{} → {} '.format(t1, t2), end='')
while contador < quantidade:
contador = contador + 1
t3 = t1 + t2
print('→ {} '.format(t3), end='')
t1 = t2
t2 = t3
print('→ FIM')
|
6e26ac4583906c2d4a2c73ff073b4a6888ea4ef1 | matheusmcz/Pythonaqui | /Aula06/teste.py | 149 | 3.890625 | 4 | print('TABUADA DE 0 A 9:')
for a in range(1, 10):
print('--' *5)
for b in range(1, 11):
print('{:2} x {:2} = {:2}'.format(a, b, a*b)) |
ac726dc0ff5df0b10c81e0850063be8ecd12b441 | klssmith/advent | /2020/day_03_ex_02.py | 722 | 3.5 | 4 | #! /usr/bin/env python
import math
with open('./data.txt') as f:
lines = f.read().split()
def count_trees(horizontal_movement, vertical_movement):
horizontal_position = 0
vertical_position = 0
tree_count = 0
while True:
if vertical_position >= len(lines):
break
hori... |
e52e9e249e6fd8864bec873ca38ec6439cff579e | klssmith/advent | /2018/day_1_2.py | 466 | 3.546875 | 4 | #! /usr/bin/env python
from itertools import cycle
with open('./data.txt') as f:
data = f.readlines()
data = cycle(data)
frequency = 0
things_seen = []
while True:
instruction = next(data)
if frequency in things_seen:
result = frequency
break
else:
things_seen.append(frequ... |
0de239e2a149d02ea2b889c9648442b4f8924263 | metehangelgi/python-Repo | /selfStudy/dictionaryStudy.py | 590 | 3.796875 | 4 | dersler= {"mete" : ["Veritabanları" , "işletim sistemleri"], "oğuz": ["java","php"], "kerem": ["linear algebra","math"]}
mete= {1,2,3}
ahmet=(1,2,3,4)
aaa=[1,2,3,4]
print(type(mete),type(ahmet),type(aaa))
print(type(dersler))
print(dersler["mete"])
for i in dersler.items():
print(i)
'''
for i,j in dersler.i... |
b2793d8465306a05393ade34a0132e21f4365b2a | metehangelgi/python-Repo | /inclass/inclass8.py | 2,413 | 3.90625 | 4 | import numpy as np
import pandas as pd
import datetime
import time
'''
eski dosyaları okuma işlemini yap. Lazım görüyorsan
epoch-1970 1 january=t0
datetime:
today()
second(milisecond)<->date
time:
BASİC DATETİME.py koduna bak genelde
'''
time.time()
#time.asctime([t])
time.localtime()
date... |
3a833a4a81585411319d7acedc23204d142d5bfc | metehangelgi/python-Repo | /selfStudy/ogrenciIO.py | 4,688 | 3.9375 | 4 |
## python calisan arkadaslar icin bir ogrenci uygulaması yazdım
## dosyaya ogrenci ekleyen ogrenci silen ve goruntuleyen bir uygulama
## merak edenler bakabilirler
import os
dizi = ["ad", "soyad", "yas", "okul", "bolum"]
index = 0
devam = True
def ara(dict, katar):
global dizi
global devam
global inde... |
c091a5828d6968a93dfecfa7bce735a5f188c4bb | metehangelgi/python-Repo | /exercises/exercise1.1.py | 788 | 3.59375 | 4 | '''
A)
1-
a)it is waiting for finish my code(for forget second paranthesis)-invalid syntax
b)missing paranthesis error
2-interpreter think that i will continiue my string
3-gives 4 (2++2=4)----- (2+-2=0)----- (2+2=4)
4-SyntaxError: invalid token (4+001)
5-SyntaxError: invalid syntax (2 3)---- 2,4->(2, 4)
2-
a)(42*60... |
100e8ac6009baf189c1e9dca70853370991f1ce0 | shanikalakshani/CS5617-PROJECT-01 | /linear_regression.py | 1,614 | 3.53125 | 4 | import csv
import pandas as pd
import matplotlib.pyplot as plt #Data visualisation libraries
from sklearn.linear_model import LinearRegression
def column(matrix, i):
return [row[i] for row in matrix]
data_set = pd.read_csv('population_by_district_in_census_years.csv')
prediction_years = pd.read_csv('prediction... |
4ac739496cade252ee0cec0a9eb0c4e2968c40e5 | dang-jing/python | /test/rice_dumpling.py | 2,036 | 3.578125 | 4 | import math
from turtle import *
# 画粽子
def rice_dumpling():
pensize(2) # 画笔宽度
pencolor(2, 51, 12) # 画笔颜色
fillcolor(4, 77, 19) # 填充色
begin_fill()
fd(200) # 向前
circle(15, 120) #画圆弧
fd(200)
circle(15, 120)
fd(200)
circle(15, 120)
fd(200)
circle(15, 60)
fd(100)
circl... |
d86de679bfc98b7312bc33977fa1cd3c1d872aee | bitmarc/api-load-data | /app/main/services/data_cleaner_service.py | 1,499 | 3.53125 | 4 | """
Methods to manage files processing
"""
import pandas as pd
def parse_xlsx(file_path):
""" Method to load file xlsx into dataframe object and prepare it to iterate """
COL_NAMES=[
"code",
"name",
"birth_date",
"naturalization_date",
"contract_date... |
4c209b1e3be29d2ec8c209911301b5930e3e2017 | mozartfish/Summer_2019_Projects | /Linear Regression Algorithm/best_fit_line_intercept.py | 964 | 4.1875 | 4 | # this program explores writing a simple regression algorithm
# author: Pranav Rajan
# Date: June 10, 2019
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
# generate some random scattered data
xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.fl... |
b6b846c0dd8dd44ca23fc56689d67fa876354571 | ginalamp/Coding_Challenges | /hacker_rank/sorting/max_toys.py | 778 | 4.09375 | 4 | '''
Given a list of toy prices and a budget, this program maximises the amount of
toys that can be bought with the budget.
'''
def main(toy_prices, budget):
'''
@param toy_prices - an int array with toy prices
@param budget - the maximum amount that the buyer can spend
@return the ... |
c95369771981b2f1a1c73b49a0156ede63aa3675 | ginalamp/Coding_Challenges | /hacker_rank/arrays/min_swaps.py | 1,383 | 4.34375 | 4 | '''
Given an unsorted array with consecutive integers, this program
sorts the array and prints the minimum amount of swaps needed
to sort the array
'''
def main(arr):
'''
@param arr - an array of consecutive integers (unsorted)
@return the minimum amount of swaps needed to sort the giv... |
2f0bf74ae562367103b6d8d412186b4dc038e6b9 | SarveshGuptaPythonist/SortingVisualization-inpython | /main.py | 2,735 | 3.515625 | 4 | from tkinter import *
from tkinter import ttk
import random
from Algorithms import bubbleSort
root = Tk()
root.title("Sorting Visualization")
root.maxsize(900,700)
root.config(bg="black")
#variables
selected_alg=StringVar()
data = []
def drawData(data, colorArray):
canvas.delete("all")
... |
11e063293a79202d0fea831afc6d900eb4ddbef1 | patcdaniel/weather_board | /get_weather.py | 1,166 | 3.515625 | 4 | from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
def get_mlml_weather():
'''
Get latest wind speed, wind dir and air temp from MLML pubdata site
returns:
- windSpeed = Meters per second
- windDir = Wind direction in degrees from North
- airTemp = Air Tempe... |
31d7048456fecb9a1ebfe9df6a301bf9a559fccc | kingdavid476/video-5 | /stat.py | 1,127 | 3.703125 | 4 | #Abraham David Hartanto 71200632
#Pengolahan string
#Buatlah sebuah program untuk mengubah 3 input berupa satu kata di setiap inputnya dengan ketentuan
'''
Syarat :
Apabila input pertama > 5 huruf maka tampilkan semua input secara berurutan
Apabila input kedua diawali dengan huruf a maka tampilkan jumlah total d... |
409e2e8b7530f48be1e9c8a6f275430d157cd2c0 | poojasgrover/pythonwork | /day2.py | 917 | 3.875 | 4 | #!/usr/bin/
####################################
# Playing with Classes in Python #
# A dummy Class for practice #
####################################
####################################
# defining class for makeup #
####################################
class makeup:
itemtype = "eyemakeup"
eyeline... |
4913e592a53b683b924075f74709f76e13ab7c86 | kshitij-srivastav/Hacking-Scripts | /Python/youtube_video_downloader/main.py | 9,322 | 3.546875 | 4 | #
# # Importing necessary packages
# import tkinter as tk
# from tkinter import *
from pytube import YouTube
from tkinter import messagebox, filedialog
#
#
# # Defining CreateWidgets() function
# # to create necessary tkinter widgets
# def Widgets():
# link_label = Label(root,
# t... |
675120288658a6462ae7398d226c8f09d78f394c | kalina/exercism-python | /pythagorean-triplet/pythagorean_triplet.py | 1,351 | 3.53125 | 4 | #need to look at this as it should be refactored to be more efficient
from math import sqrt
from fractions import gcd
def primitive_triplets(n):
out = []
if n % 4 != 0:
raise ValueError("Must be divisible by 4")
for a in range(3,n+1):
for b in range(4,n*n+1):
if ((a-b) % 2) == 0... |
c3664455f1d6c3b4cb92f47347407bc08b97fc37 | chirag111222/Daily_Coding_Problems | /DailyCodingProblem/208_pivot_linked_list.py | 1,706 | 3.84375 | 4 |
'''
This problem was asked by LinkedIn.
Given a linked list of numbers and a pivot k,
partition the linked list so that all nodes
less than k come before nodes greater than or equal to k.
For example, given the linked list 5 -> 1 -> 8 -> 0 -> 3
and k = 3, the solution could be 1 -> 0 -> 5 -> 8 -> 3.
'''
class No... |
af4af156a2155fe94dc540f2db596fdfc35c2e6f | chirag111222/Daily_Coding_Problems | /Youtube/back2back/stacks_queues_arrays_linked_lists/reverse_linked_list.py | 474 | 3.765625 | 4 |
class Node:
def __init__(self, v):
self.v = v
self.n = None
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n1.n = n2
n2.n = n3
n3.n = n4
def print_ll(n):
while n is not None:
print(n.v)
n = n.n
return
print_ll(n1)
def reverse_ll(n):
prev_ = next_ = None
whi... |
8ba201adfcd377f70a096e7e442f1c57f06c2e7a | chirag111222/Daily_Coding_Problems | /Youtube/Tushar_Roy/bt_is_BST.py | 908 | 4 | 4 |
'''
Check if a Binary Tree is a Binary Search Tree
'''
class Node:
def __init__(self, v):
self.v = v
self.l = self.r = None
n1 = Node(10)
n2 = Node(-10)
n3 = Node(-20)
n4 = Node(0)
n5 = Node(19)
n6 = Node(17)
n1.l = n2
n2.l = n3
n2.r = n4
n1.r = n5
n5.l = n6
def inorder(root):
if root.l:
... |
14d9147819a3d4f3ebca1e7018b741cc77356df8 | chirag111222/Daily_Coding_Problems | /Youtube/CS_Dojo/linked_list_trees/lca_bt.py | 650 | 3.703125 | 4 |
'''
Find the lowest common ancestor in a BT
given the root and two values. No duplicates
'''
class Node:
def __init__(self, v):
self.v = v
self.l = self.r = None
n1 = Node(5)
n2 = Node(1)
n3 = Node(3)
n4 = Node(6)
n5 = Node(7)
n6 = Node(8)
n7 = Node(4)
n1.l = n2
n2.l = n3
n3.l = n4
n2.r = n6
n3.... |
7c8769095f5ba9cbd735e862a6dd368e389ced4c | chirag111222/Daily_Coding_Problems | /Cracking the Coding Interview/02_Linked_Lists/03_delete_middle_node.py | 508 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 12:54:49 2019
@author: pabloruizruiz
"""
from linked_list import LinkedList
def delete_middle_node(node):
message = "Node to delete can't be head or tail nodes from the list"
assert node.next is not None, message
node.data = node.n... |
de1bc5f89a9380c33a1e52d7eef5577db367878e | chirag111222/Daily_Coding_Problems | /Interview_Portilla/Search/binary_search.py | 1,053 | 4.09375 | 4 |
'''
Python => x in list --> How does it work?
Sequential Search
-----------------
'''
unorder = [4,51,32,1,41,54,13,23,5,2,12,40]
order = sorted(unorder)
def iter_bin_search(arr,t):
i1 = 0
i2 = len(arr)-1
found = False
while i1 <= i2 and not found:
im = (i1+i2)//2
print('I1: {}, I2:... |
b61297dda5618a5f68360f9637d2a844a4ec4e54 | chirag111222/Daily_Coding_Problems | /Cracking the Coding Interview/04_Trees_and_Graphs/trees_and_graphs.py | 2,240 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
from collections import defaultdict
class TreeNode:
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def insert(self, value):
if value <= self.value:
if s... |
34efaab69689b6c500c207850fce530deae882d9 | chirag111222/Daily_Coding_Problems | /Youtube/CS_Dojo/linked_list_trees/is_bt_bst.py | 884 | 4.09375 | 4 |
'''
Check if a Binary Tree is a Binary Search Tree
'''
class Node:
def __init__(self, v):
self.v = v
self.l = self.r = None
n1 = Node(3)
n2 = Node(1)
n3 = Node(0)
n4 = Node(2)
n5 = Node(5)
n6 = Node(4)
n7 = Node(6)
n1.l = n2
n2.l = n3
n2.r = n4
n1.r = n5
n5.l = n6
n5.r = n7
def inorder(root):
... |
bc4b57224a398bd694c26be191dcad88cba424df | chirag111222/Daily_Coding_Problems | /Youtube/back2back/trees_graphs/min_heap.py | 1,391 | 3.859375 | 4 | '''
Implement a Binary Min-Heap
'''
from collections import deque
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder(root):
if root.left:
inorder(root.left)
print(root.val)
if root.right:
... |
1b197b509801f9d0923458e245928fa9df8494aa | chirag111222/Daily_Coding_Problems | /DailyCodingProblem/211_regex.py | 509 | 4 | 4 |
'''
This problem was asked by Microsoft.
Given a string and a pattern, find the starting indices of all occurrences
of the pattern in the string. For example, given the string "abracadabra"
and the pattern "abr", you should return [0, 7].
'''
w = "abracadabra"
p = "abr"
def get_matches(w,p):
ids = list()
... |
ff4d35988ba52045cd9ac48c91a00f1308427fba | chirag111222/Daily_Coding_Problems | /Interview_Portilla/Interview Mocks/05_reverse_string_recursion.py | 145 | 4 | 4 |
string = 'abcdefg'
def reverse(s):
# Base case:
if len(s) <= 1:
return s
return s[-1]+reverse(s[:-1])
reverse(string)
|
340a802c8c77fdc2c4428926a8a2904fe8a388d0 | chirag111222/Daily_Coding_Problems | /Interview_Portilla/Search/sequential_seach.py | 513 | 4.15625 | 4 |
'''
Python => x in list --> How does it work?
Sequential Search
-----------------
'''
unorder = [4,51,32,1,41,54,13,23,5,2,12,40]
order = sorted(unorder)
def seq_search(arr,t):
found = False
for i in arr:
print(i)
if i == t:
found = True
return found
def ord_seq_search(arr... |
d9f9a0c1350d5d68c8e651a6c59b5f6cdd8bfbf1 | chirag111222/Daily_Coding_Problems | /DailyCodingProblem/201_max_path_sum.py | 1,816 | 4.125 | 4 |
'''
You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at a time to an adjacent value,
eventually ending w... |
f32d578291b06c29e741090bdae3424e2b0f21f1 | chirag111222/Daily_Coding_Problems | /Interview_Portilla/Recursion/fib_iter_rec_dp.py | 931 | 3.859375 | 4 |
'''
Cummulative sum of the first n Fibonacci numbers
'''
from timeit import timeit
# def iter_fib(n):
# if n <= 1:
# return 1
# arr = [1,1]
# for i in range(1,n-1):
# arr.append(arr[-2]+arr[-1])
# return arr[-1]
''' ITERATIVE '''
def iter_fib(n):
a,b = 0,1
for i in rang... |
b6b120859d03de824374a23ed5f6876f2d9b0bd0 | chirag111222/Daily_Coding_Problems | /DailyCodingProblem/214_length_longest_substring.py | 532 | 3.9375 | 4 |
'''
This problem was asked by Stripe.
Given an integer n, return the length of the longest
consecutive run of 1s in its binary representation.
For example, given 156, you should return 3.
'''
input = 156
bin(input)[2:]
def longest_1s_path(n):
n = bin(input)[2:]
max_length = cur_lenght = 0
for digit i... |
72cbfa9e3e72c688bf1f321b2e23d975f50fba79 | silvium76/coding_nomads_labs | /02_basic_datatypes/1_numbers/02_04_temp.py | 554 | 4.3125 | 4 | '''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
temperature_fahrenheit = int(input("Please enter th... |
d950c290d15fe9c59fcf008919e77523c9a60e9e | silvium76/coding_nomads_labs | /01_python_fundamentals/01_07_area_perimeter.py | 280 | 4.03125 | 4 | '''
Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4.
'''
# x is the area
# y is perimeter
width = 2.4
height = 6.4
x = width * height
print("Area = ", x)
y = width * 2 + height * 2
print("Perimeter = ", y) |
3b1fc4638f8458e0d6981bdde750fd1a754ce1cc | Avikalp7/PyAlgos | /heaps.py | 8,887 | 3.65625 | 4 | """
This module deals with many aspects of the heap data structure.
Author: Avikalp Srivastava
"""
from __future__ import print_function
from __future__ import division
import numpy as np
from math import floor
import copy
################################################
class MinHeap(object):
"""
Implements th... |
f45ef9def56080cedc8353226aa95d8bea72fddc | msfidelis/design-pytterns | /11-Visitor/operacoes.py | 1,878 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# DSL Domain Design Language
from abc import ABCMeta, abstractmethod
##
# Abstract Class de Expressão
# obriga a implementação do método Avalia()
##
class Expressao(object):
__metaclass__ = ABCMeta
@abstractmethod
def avalia(self):
pass
##
# Classe responsável pela subtração
##
class S... |
53c523317ce23220e925790448528de38976063b | viperk17/PythonExercises | /Guess the number.py | 483 | 3.71875 | 4 | from random import randint
import sys
ans = randint(1,10)
while True:
try:
print(ans)
guess = int(input("Guess a number in 1-10: "))
if 0 < guess < 11:
if guess == ans:
print("You won")
break
else:
print("Enter 1-10.")
exc... |
1433bc7b63997e5f3f72e62c707eef0c608bc44e | gowenrw/BSidesDFW_2020_HHV | /code/HHV2020_04/Adafruit_Trinket_Tactile_Switch_LED_Control/main.py | 865 | 3.515625 | 4 | import board
import digitalio
import time
# Assign pin D13 (On-Board Red LED)
rled = digitalio.DigitalInOut(board.D13)
# Assign pin D4 (External LED)
led4 = digitalio.DigitalInOut(board.D4)
# Assign pin D3 (External Switch Input)
sw1 = digitalio.DigitalInOut(board.D3)
# Set IO Direction
rled.direction = digitalio.Direc... |
9d1a77a62b54b6c658c9bd17e68da4de6407eb42 | corze900/Coding_for_fun | /python/class_gender_percentage.py | 521 | 3.9375 | 4 | def getInput():
return input()
def classPercent(x,n):
print(format(x/n,'.0%'))
def main():
print("Enter the number of males in class :")
maleN = int(getInput())
print("Enter the number of females in class :")
femalesN = int(getInput())
print("The % of males is: ")
cla... |
911d64a64bc82fc5ce27b783f30b29b7256c2de6 | duocang/python | /learning/deadlock.py | 1,334 | 3.765625 | 4 |
import threading
import time# 死锁
# 有锁就可以方便的处理线程同步问题,可是多线程的复杂度和难以调试的根源也来自于线程的锁。
mutex_a = threading.Lock()
mutex_b = threading.Lock()
class MyThread(threading.Thread):
def task_a(self):
if mutex_a.acquire(): # Acquire a lock, blocking or non-blocking.
print('thread %s ges mutex a' %self.name... |
f00024898d8ad21f1e737423a72db9b06f5c989b | duocang/python | /sortMethods/bubbleSort.py | 226 | 4.03125 | 4 | def bubble(list):
for i in range(len(list)):
for j in range( len(list)-1-i):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
#if name == 'main':
list1 = [2,3,4,32,1,34,5,10]
bubble(list1)
print(list1) |
dece541e8d4ac83fad1f6e7ddecb16c26ce6f8d8 | duocang/python | /learning/coroutine.py | 2,812 | 3.71875 | 4 |
import asyncio
import time
from datetime import datetime
# 协程是运行在单线程当中的并发
# 协程相比线程的一大优势就是省去了多线程之间的切换开销
def consumer():
r = ''
while True:
n = yield r
print("what is n here", n)
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'
def produc... |
fb8c32166e77f488cb59ccc358feec467e625f61 | dbhojoo/learnpy | /lesson11/ex11.py | 382 | 3.625 | 4 | print "How old are you?",
age = float(raw_input())
print "What units?",
au = raw_input()
print "How tall are you?",
height = float(raw_input())
print "What units?",
tu = raw_input()
print "How much do you weigh?",
weight = float(raw_input())
print "What units?",
wu = raw_input()
print "So, you're %f %r old, %f %r ta... |
2aa7c144d26d53ba0e8463dbbee1ba6ed6da9535 | Laquania/course-material | /exercices/230/solution.py | 484 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Éditeur de Spyder
Ceci est un script temporaire.
"""
def is_prime2(num):
import numpy as N
a = 0
if num == 1 | num == 0:
return False
else:
for i in range(2, int(N.sqrt(num))+1):
if num % i == 0:
a = a+1
if a == 0:
... |
41bca089478f8eb3392e56e925b4a75fdbe54362 | Laquania/course-material | /exercices/200/solution.py | 1,871 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 23 11:41:31 2014
@author: Amaury
"""
#def is_prime(num):
#
# if num/2==int(num/2):
# print("false")
# elif num/3==int(num/3):
# print("false")
# elif num/5==int(num/5):
# print("false")
# elif num/7==int(num/7):
# print("false"... |
ad7d9917ba30341041e6d325d0ffb7f3415f026d | Laquania/course-material | /exercices/220/solution.py | 522 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 24 12:39:27 2014
@author: Amaury
"""
def is_prime2(num):
import numpy as N
a = 0
if num == 1 | num == 0:
return False
else:
for i in range(2, int(N.sqrt(num))+1):
if num % i == 0:
a = a+1
if a == 0:
... |
921465e2a021bfa4d902af991c5bb6bb91c123eb | RomuloMileris/UCD_Professional_Certificate_in_Data_Analytics | /Week 8 - Introduction to Data Visualization with Seaborn/10-Changing the style of scatter plot points.py | 277 | 3.640625 | 4 | # Import Matplotlib and Seaborn
import matplotlib.pyplot as plt
import seaborn as sns
# Create a scatter plot of acceleration vs. mpg
sns.relplot(x="acceleration", y="mpg",
data=mpg, kind="scatter",
style="origin", hue="origin")
# Show plot
plt.show() |
9de3890c4f330a812f707be61b8bfb460f2d6352 | RomuloMileris/UCD_Professional_Certificate_in_Data_Analytics | /Week 8 - Introduction to Data Visualization with Seaborn/4-Making a count plot with a DataFrame.py | 300 | 3.71875 | 4 | # Import Matplotlib, Pandas, and Seaborn
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Create a DataFrame from csv file
df = pd.read_csv(csv_filepath)
# Create a count plot with "Spiders" on the x-axis
sns.countplot(x="Spiders", data=df)
# Display the plot
plt.show() |
39c8b24a4fb40c73a0db66371e977a1723fb66aa | RomuloMileris/UCD_Professional_Certificate_in_Data_Analytics | /Week 8 - Introduction to Data Visualization with Seaborn/14-Count plots.py | 444 | 3.703125 | 4 | # Create count plot of internet usage
sns.catplot(x="Internet usage", data=survey_data,
kind="count")
# Show plot
plt.show()
# Change the orientation of the plot
sns.catplot(y="Internet usage", data=survey_data,
kind="count")
# Show plot
plt.show()
# Create column subplots based on age cate... |
49b659d48fa7fd9448b6701a8777c37f8767b4dc | Aberwang/InterviewFAQ | /数据结构与算法/剑指offer/python/IsPopOrder.py | 413 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
while len(popV) > 0:
n = popV.pop(0)
if n not in pushV:
return False
index = pushV.index(n)
if index > 0 and popV[0] in pushV[:index-1]:
... |
02a25762b76a6e379cbdcae8b1c9ea4d0659ff24 | Aberwang/InterviewFAQ | /数据结构与算法/剑指offer/python/StrToInt.py | 660 | 3.578125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
ls = list(s)
if len(s) == 0:
return 0
if ls[0] == '+' and len(ls) > 1:
for i in ls[1:]:
if i < '0' or i > '9':
return 0
return int('... |
e39250bc29b0faed5e65ec2b1903d5f5e5a5eeeb | Aberwang/InterviewFAQ | /数据结构与算法/剑指offer/python/GetMedian.py | 4,003 | 3.921875 | 4 | # -*- coding:utf-8 -*-
class Solution:
"""
如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。
如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
排序实现:插入复杂度O(1), 得到中位数复杂度O(nlogn)
"""
def __init__(self):
self.ls = []
def Insert(self, num):
# write code here
self.ls.append(num)
def GetMe... |
ca9bbaf3fc531d87e45d1842044b077822eeea4d | Aberwang/InterviewFAQ | /数据结构与算法/剑指offer/python/deleteDuplication.py | 949 | 3.625 | 4 | # -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
"""
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
"""
# write c... |
429f214d36b8d315f04485a926298e5e7a71b442 | dakheniya/python_practice | /ex_15.py | 182 | 4.28125 | 4 | def reverse():
string = str(input("Enter your string: "))
split = string.split(" ")
split.reverse()
new_string = str(" ".join(split))
return new_string
reverse() |
81fa2d101ffe89b41cda561fb040936c43e3a2a7 | tryoasnafi/hackerrank | /problems/003_between_two_sets/solution.py | 586 | 3.71875 | 4 | from functools import reduce
from math import gcd
def getTotalX(a, b):
# Find the GCD array B
lcm_a = reduce(lambda x, y: x * y // gcd(x, y), a)
# Find the LCM array A
gcd_b = reduce(gcd, b)
# Count the number of multiples of LCM that evenly divides the GCD.
return sum([1 for num in range(lcm_... |
92df0293c269ff5d3206d31a7653919cadf34a90 | prachivishnoi27/Data-Structures-and-Algorithms-specialization-University-of-California-San-Diego | /course 1 - Algorithmic toolbox/week2_algorithmic_warmup/3_greatest_common_divisor/gcd.py | 469 | 3.546875 | 4 | # Uses python3
import sys
def gcd_naive(a, b):
m = max(a,b)
n = min(a,b)
if m%n ==0 :
return n
return gcd_naive(n,m%n)
# current_gcd = 1
# for d in range(2, min(a, b) + 1):
# if a % d == 0 and b % d == 0:
# if d > current_gcd:
# current_gcd ... |
069b75ee11d7273d92a9364977359c08ed5b93dc | prachivishnoi27/Data-Structures-and-Algorithms-specialization-University-of-California-San-Diego | /course 1 - Algorithmic toolbox/week5_dynamic_programming1/2_primitive_calculator/primitive_calculator.py | 1,929 | 3.53125 | 4 | # Uses python3
import sys
# def optimal_sequence(n):
# sequence = []
# while n >= 1:
# sequence.append(n)
# if n % 3 == 0:
# n = n // 3
# elif n % 2 == 0:
# n = n // 2
# else:
# n = n - 1
# return reversed(sequence)
def dp_solution(n):
... |
e1b588a089bfc843ac186549b1763db5e55b70bd | umunusb1/PythonMaterial | /python3/02_Basics/02_String_Operations/f_palindrome_check.py | 621 | 4.46875 | 4 | #!/usr/bin/python3
"""
Purpose: Demonstration of Palindrome check
palindrome strings
dad
mom
Algorithms:
-----------
Step 1: Take the string in run-time and store in a variable
Step 2: Compute the reverse of that string
Step 3: Check whether both the strings are equal or not
Step 4: If equal, pr... |
d469d187bb4013c4fa80f46f1c69f625a5274654 | umunusb1/PythonMaterial | /python3/06_Collections/04_Dictionaries/i_frequency_analyses.py | 3,108 | 4.03125 | 4 | #!/usr/bin/python
"""
Purpose: Test Frequency Analyses
"""
sentence = '''Python is a wonderful language.
we can solve any
computational problem with this language'''
# Character frequency analyses
# Method 1
frequency = {}
for each_char in sentence:
# print(each_char)
try:
frequency[each_char] = freq... |
37b61ba736f127ebd0ef05a07a4b92b7311fae76 | umunusb1/PythonMaterial | /python3/03_Language_Components/07_Conditional_Operations/b_number_guessing_game.py | 790 | 4.1875 | 4 | #!/usr/bin/python3
"""
Purpose: Number Guessing Game
"""
LUCKY_NUMBER = 69
given_number = int(input('Enter no. of between 0 & 100:'))
print(f'{LUCKY_NUMBER = }')
print(f'{given_number = }')
# print(f'{given_number == LUCKY_NUMBER =}')
# Method 1
# if given_number == LUCKY_NUMBER:
# print('You Guessed Correctly... |
400031d6d94eb77df6188d9ffb0ce00a31ba0ce9 | umunusb1/PythonMaterial | /python2/03_Language_Components/05_Conditional_Operations/leap_year_check.py | 1,282 | 4.40625 | 4 | # Python program to check if the input year is a leap year or not
# year = 2018
# To get year (integer input) from the user
year = int(raw_input('year='))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("... |
c2a860ead59a1428a716433d21b4c0c155145cec | umunusb1/PythonMaterial | /python3/04_Exceptions/06_exception_handling.py | 413 | 3.96875 | 4 | #!/usr/bin/python
"""
Purpose: Exception Handling
Exception Hierarchy
"""
try:
num1 = int(input('Enter an integer:'))
num2 = int(input('Enter an integer:'))
division = num1 / num2
except ValueError as ve:
# print(f'{ve =}')
print('Please enter integers only')
except ZeroDivisionError as ze:
... |
1d5792162ec1b60096f98ba0598e4221893d6682 | umunusb1/PythonMaterial | /python3/09_Iterators_generators_coroutines/05_asyncio_module/a_asynchronous_function.py | 545 | 3.5625 | 4 | # /usr/bin/python
"""
Purpose: asyncio
working from python 3.7+
In Python 3.7, two new keywords (async and await) were introduced
"""
import asyncio
def hello():
print('Hello')
print('world')
hello()
async def asynchronous_hello():
print('Hello')
print('World')
# asynchronous_hello()
# a_a... |
4bfc733c59848c52302a52b5366704fbedce4c94 | umunusb1/PythonMaterial | /python3/04_Exceptions/13_custom_exceptions.py | 564 | 4.15625 | 4 | #!/usr/bin/python3
"""
Purpose: Using Custom Exceptions
"""
# creating a custom exception
class InvalidAge(Exception):
pass
try:
age = int(input('Enter your age:'))
age = abs(age)
if age < 18:
# raise InvalidAge('You are not eligible for voting')
raise InvalidAge(f'You are short by {18... |
aa1335b87fa6dab6a3d4f3169d36a9eff9e80040 | umunusb1/PythonMaterial | /python3/11_File_Operations/03_image_files/03_image_with_text.py | 209 | 3.5625 | 4 | from PIL import Image, ImageDraw
img = Image.new('RGB', (100, 30),
color=(73, 109, 137))
d = ImageDraw.Draw(img)
d.text((10, 15), "Hello World", fill=(255, 255, 0))
img.save('pil_text.png')
|
e53448ad9ec7cd295a7570fc4e75187533c4c134 | umunusb1/PythonMaterial | /python3/10_Modules/03_argparse/a_arg_parse.py | 1,739 | 4.34375 | 4 | #!/usr/bin/python
"""
Purpose: importance and usage of argparse
"""
# # Method 1: hard- coding
# user_name = 'udhay'
# password = 'udhay@123'
# server_name = 'issadsad.mydomain.in'
# # Method 2: input() - run time
# user_name = input('Enter username:')
# password = input('Enter password:')
# server_name = input('Enter... |
f3665f6ae8aca1f6ad4017983ef50d681609809f | umunusb1/PythonMaterial | /python2/13_OOP/Practical/06_OOP.py | 779 | 4.21875 | 4 | #!/usr/bin/python
"""
Purpose: demo of OOP
"""
class Person:
def __init__(self): # constructor method
"""
This is constructor
"""
self.name = '' # instance variables
self.age = 0 # instance variables
def enter_age(self, age): # instance methods
self.age = a... |
7c875cebaca044773b81ed26d5018e6be2fc93f4 | umunusb1/PythonMaterial | /python2/15_Regular_Expressions/re6/f2.py | 210 | 3.875 | 4 | #!/usr/bin/python
import re
f = open("file1.txt")
reg = re.compile('.*@.*')
for line in f:
if reg.search(line):
print reg.search(line).group()
'''
f = open("file1.txt")
for line in f:
print line
'''
|
9515145d725d6dce708440c262d853f644c7af16 | umunusb1/PythonMaterial | /python2/04_Collections/01_Lists/05_copy_problem.py | 2,063 | 3.96875 | 4 | #!/usr/bin/python
"""
Purpose: COPY PROBLEM
assignment vs Shallow copy vs deep copy
Detailed Explanation: https://www.youtube.com/watch?v=yjYIyydmrc0
"""
par_list = [1, 11, 111, 1111]
print 'par_list ', par_list, type(par_list), id(par_list)
hard_copy_list = par_list
print 'hard_copy_list', hard_copy_list, ... |
48e4150ddd65fa1c4d39e4363ced82fcd3057c78 | umunusb1/PythonMaterial | /python3/02_Basics/02_String_Operations/q_bytearray_strings.py | 1,040 | 3.96875 | 4 | #!/usr/bin/python
"""
Purpose: demo of bytearray strings
bytearray objects are a mutable strings
"""
# Creating an empty instance:
print('bytearray() ', bytearray())
# Creating a zero-filled instance with a given length:
print('bytearray(10) ', bytearray(10))
# From an iterable of integers:
print(... |
2a202dd5ba552f4bda62adb4bfc92342d867d895 | umunusb1/PythonMaterial | /python2/04_Collections/01_Lists/02_lists.py | 1,791 | 4.59375 | 5 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
List can be classified as single-dimensional and multi-dimensional.
List is representing using [].
List is a mutable object, which means elements in list can be changed.
It can store asymmetric data types
"""
numbers = [88, 99, 666]
# homogenous
print 'type(numbers)', ty... |
3fa5fc83351612d9c75111001b3c252a941497d5 | umunusb1/PythonMaterial | /python2/08_Decorators/03_Decorators.py | 565 | 3.75 | 4 | from math import sqrt
print map(sqrt, (4, 16, 25))
print map(sqrt, [4])
# print map(sqrt, 4)TypeError: argument 2 to map() must support iteration
# Improving the above with decorators
def elementwise(fn):
def newfn(arg):
if hasattr(arg,'__getitem__'): # is a Sequence
return type(arg)(map(fn,... |
bb8783822f84e5a910551a3d0d175cf2ae72946d | umunusb1/PythonMaterial | /python2/10_Modules/04_argparse/argparsedemo.py | 775 | 3.953125 | 4 | import argparse
def main(m, n, p):
""" Short script to add three numbers """
return m + n + p
# print '__name__', __name__
# if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Script to add three numbers")
parser.add_argument('-a',
help='First value',
... |
8d4dd752f37cc90ff22c31fb32be7edc24d4a631 | umunusb1/PythonMaterial | /python3/17_Data_science_modules/04_nltk/nltk_module/d_nltk_ex.py | 544 | 3.890625 | 4 | #!/usr/bin/python
"""
Purpose: NLTK
Stemming vs Lemmatization
- While stemming can create words that do not actually
exist, Python lemmatization will only ever result in
words that do. lemmas are actual words.
"""
import nltk
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
ps = P... |
28a1a30159b43289dddfee81cfca150c98c6e1d7 | umunusb1/PythonMaterial | /python3/06_Collections/02_Tuples/02_tuple_attributes.py | 1,401 | 3.8125 | 4 | #!/usr/bin/python
"""
Purpose: Tuple attributes
"""
mytuple = (12, 5, 6, 8, (5,))
print(dir(mytuple))
print()
print("len(mytuple) =", len(mytuple))
print("mytuple.__len__() =", mytuple.__len__())
assert len(mytuple) == mytuple.__len__()
print()
print("str(mytuple) =", str(mytuple))
print("typ... |
a50e7f45fb0f1283d6fedb1d108ae05c90e08060 | umunusb1/PythonMaterial | /python2/09_Iterators_generators_coroutines/07_simple_coroutine.py | 707 | 3.703125 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
"""
• Coroutines are not related to iteration
- generators are data producers
- coroutines are data consumers
- Coroutines consume values using a (yield)
"""
def coro():
hello = yield "Hello"
yield hello # resulted with c.send("W... |
7e83632d361b1ef09142d86fb45ec5584f8a12c2 | umunusb1/PythonMaterial | /python2/02_Basics/01_Arithmetic_Operations/c_ArithmeticOperations.py | 1,883 | 4.15625 | 4 | #!/usr/bin/python
"""
Purpose: Demonstration of Arithmetic Operations
"""
# compound operators
# += -= *= /= %=
myNumber = 123
print 'myNumber = ', myNumber
myNumber = myNumber + 1
print 'myNumber = ', myNumber
# In cases, where the same variable is present both the sides, then compound operations are valid
myNum... |
f74b9eacbdbf872d13578b2802622482f5cf0f28 | umunusb1/PythonMaterial | /python2/15_Regular_Expressions/re7/f1.py | 274 | 4.1875 | 4 | #!/usr/bin/python
import re
string = raw_input("please enter the name of the string:")
reg = re.compile('^.....$',re.DOTALL)
if reg.match(string):
print "our string is 5 character long - %s" %(reg.match(string).group())
else:
print "our string is not 5 characate long"
|
fade13e4729b9c536a933116f7eab65f3031fcb4 | umunusb1/PythonMaterial | /python2/06_Debugging/newFile.py | 264 | 3.875 | 4 | #!/usr/bin/python
__author__ = 'udhay'
costOfMangos = float(raw_input("Enter the cost of Mangos, in Euros: "))
def grocerryShop(quantity):
costOfApples = 2
TotalCost = quantity*(costOfApples + costOfMangos)
return TotalCost
print grocerryShop(12)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.