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 sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play. Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros. ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12). Input: ----- The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. Output: ------ For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output. Example Sample input: 3 24 1 4358 754 305 794 Sample output: 34 1998 1 ''' def reverseNum(numIn): numOut = 0; while (numIn <> 0): numOut = numOut * 10 numOut = numOut + numIn%10 numIn = numIn/10 return numOut inCount = raw_input() print inCount for i in range(int(inCount)): inValues = raw_input().split(" ") print reverseNum(reverseNum(int(inValues[0])) + reverseNum(int(inValues[1])))
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 = lazy_sum(1, 3, 5) print(f) print(f()) # 在这个例子中,我们在函数lazy_sum中又定义了函数sum, # 并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时, # 相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力。 def count(): funcs = [] for i in range(1, 4): def func(): return i * i funcs.append(func) return funcs f1, f2, f3 = count() # 这里是自动解析 print(f1()) # 9 print(f2()) # 9 print(f3()) # 9 # ! 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。 # 如果要引用循环变量可以: def count1(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs f1, f2, f3 = count1() # 这里是自动解析 print(f1()) # 1 print(f2()) # 4 print(f3()) # 9
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(), dic.keys()) list(zip(dic.values(), dic.keys()).__iter__()) list(zip(dic.values(), dic.keys())) zip(dic.values(), dic.keys()).__iter__() from collections import Iterable, Iterator zip_res = zip(dic.values(), dic.keys()) isinstance(zip_res, Iterable) isinstance(zip_res, Iterator) zip_res.__next__() sorted(zip(dic.values(), dic.keys())) sorted(dic.items(), key=lambda x: x[1], reverse=True)
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(next(G)) # StopIteration G = (x * x for x in range(1, 11)) # 类似于一个状态机 for g in G: print(g) # 通过定义函数的方式创建generator def fib(m): n, a, b = 0, 0, 1 while n < m: yield b a, b = b, a + b n = n + 1 return 'done' print(fib(6)) print(list(fib(6))) g = fib(6) while True: try: x = next(g) # 注意:每次fib(6)执行得到一个新的generator print('g:', x) except StopIteration as e: # 通过catch stopIteration异常来获得函数执行结束的return值 print('Generator return value:', e.value) break
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 find_month_cells(start: datetime, end: datetime) -> list: """ |This function takes two arguments start of period and and of period |It is used to find number of separate month in the provided timespan |It make 28 days (week) steps to find 'year cell' |'week cells' then ae used in another function to find start and end |dates of the months """ result = [start] cur = start while True: cur = cur + timedelta(days=27) if cur > end: break if cur.month != result[-1].month: result.append(cur) if result[-1].month != end.month: result.append(end) return result if _start > _end: raise ValueError(f"end date {_end} should be later then start date: {_start}") if (_start.month == _end.month) and (_start.year == _end.year): return [(_start, _end, _start.strftime("%Y.%m"),)] m_cells = find_month_cells(_start, _end) result = [] for cell in m_cells: _, m_end = calendar.monthrange(cell.year, cell.month) m_start = datetime(cell.year, cell.month, 1) m_end = datetime(cell.year, cell.month, m_end) if m_start <= _start: m_start = _start if m_end >= _end: m_end = _end result.append((m_start, m_end + timedelta(seconds=86399), m_start.strftime("%Y.%m"),)) return result def find_full_days_in_period(_start: datetime, _end: datetime) -> list: """ | This function takes two arguments, start of the period and end of the period | The function returns list of dates between start date and end date """ if _start > _end: raise ValueError(f"end date {_end} should be later then start date: {_start}") result = [(_start, _start + timedelta(seconds=86399), _start.strftime("%Y.%m.%d"),)] if _start == _end: return result cur = _start while True: cur += timedelta(days=1) if cur == _end: break result.append((cur, cur + timedelta(seconds=86399), cur.strftime("%Y.%m.%d"),)) result.append((_end, _end + timedelta(seconds=86399), _end.strftime("%Y.%m.%d"))) return result def find_full_weeks_in_period(_start: datetime, _end: datetime) -> list: """ | This function takes two arguments start of period and end of period | It returns list of tuples (start_week, end_week, string = 'year/week number') """ def _find_weeks_cells(start: datetime, end: datetime) -> list: """ |This function takes two arguments start of period and and of period |It is used to find number of separate weeks in the provided timespan |It make 7 days (week) steps to find 'week cell' |'week cells' then are used in another function to find start and end | dates of the weeks """ _dates = [start] cur = start while True: cur = cur + timedelta(days=7) if cur >= end: break _dates.append(cur) if _dates[-1].isocalendar()[1] != end.isocalendar()[1]: _dates.append(end) return _dates if _end < _start: raise ValueError(f"end date {_end} should be later then start date: {_start}") if _start.isocalendar()[1] == _end.isocalendar()[1]: # the error is here return [(_start, _end + timedelta(seconds=86399), str(_start.year) + "/" + str(_start.isocalendar()[1]),)] cells = _find_weeks_cells(_start, _end) result = [] for cell in cells: w_start = cell - timedelta(days=cell.weekday()) w_end = w_start + timedelta(days=6) if w_start <= _start: w_start = _start if w_end >= _end: w_end = _end result.append( (w_start, w_end + timedelta(seconds=86399), str(w_start.year) + "/" + str(w_start.isocalendar()[1]),)) return result if __name__ == "__main__": result = find_full_weeks_in_period(datetime(1892, 6, 1), datetime(1893, 6, 7)) print("Total weeks: {}".format(len(result))) print(" {:^30} | {:^30} | {:^50}".format("start", "end", "")) for i in result: print(" {:^30} | {:^30} | {:50}".format(i[0].strftime("%d/%m/%Y %H:%M:%S"), i[1].strftime("%d/%m/%Y %H:%M:%S"), i[2])) print(type(result))
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) cuboid_digonal=math.sqrt(digonal) return cuboid_digonal if __name__ == '__main__': height_of_locker,length_of_locker,width_of_locker,length_of_magic_stick= map(int,input().split()) result = fittingAnalysis(height_of_locker ,length_of_locker,width_of_locker,length_of_magic_stick) print(result)
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 __future__ import print_function # Import OpenCV library import cv2 as cv # Function to detect and display the detections of Faces and Eyes in a current loaded frame def detectAndDisplay(frame): # Convert the current loaded frame of the video capture to a gray scale to be use, if necessary print("Loading the current loaded frame of the video capture...") frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Detect Faces on the current loaded frame of the video capture in a gray scale print("Converting the current loaded frame of the video capture to a gray scale, to detect the Faces on it...") faces = face_cascade.detectMultiScale(frame_gray, 1.3, 5) for (x, y, w, h) in faces: center = ((x + (w // 2)), (y + (h // 2))) frame = cv.ellipse(frame, center, ((w // 2), (h // 2)), 0, 0, 360, (0, 0, 255), 4) face_roi = frame_gray[y:(y + h), x:(x + w)] # Detect Eyes on the current loaded frame of the video capture in a gray scale print("Converting the current loaded frame of the video capture to a gray scale, to detect the Eyes on it...") eyes = eyes_cascade.detectMultiScale(face_roi) for (x2, y2, w2, h2) in eyes: eye_center = (x + x2 + w2//2, y + y2 + h2//2) radius = int(round((w2 + h2) * 0.25)) frame = cv.circle(frame, eye_center, radius, (0, 255, 0), 4) # Generate the current final loaded frame of the video capture with all the detected Faces and Eyes print("Generating the final loaded frame of the video capture with all the detected Faces and Eyes...") cv.imshow('Faces and Eyes Detection - Tutorial #2', frame) # Fetch the Cascade Classifiers for Faces and Eyes print("Loading Haar Cascade Classifiers...") face_cascade = cv.CascadeClassifier('classifiers/haar-cascade/haarcascade_frontalface_alt.xml') eyes_cascade = cv.CascadeClassifier('classifiers/haar-cascade/haarcascade_eye_tree_eyeglasses.xml') # Print a message in the case of an error occurred, during the loading of the Cascade Classifiers for the Faces if not face_cascade.load('classifiers/haar-cascade/haarcascade_frontalface_alt.xml'): print('Error in loading of the Cascade Classifiers for the Faces...') exit(0) # Print a message in the case of an error occurred, during the loading of the Cascade Classifiers for the Eyes if not eyes_cascade.load('classifiers/haar-cascade/haarcascade_eye_tree_eyeglasses.xml'): print('Error in loading of the Cascade Classifiers for the Eyes...') exit(0) camera_device = 0 # Read/Load the Video Stream/Capture cap = cv.VideoCapture(camera_device) # Print a message in the case of an error occurred, during the reading/loading of the Video Stream/Capture if not cap.isOpened: print('Error in reading/loading of the Video Stream/Capture...') exit(0) while True: ret, frame = cap.read() frame = cv.resize(frame, (1080, 720), interpolation=cv.INTER_AREA) if frame is None: print('No Frame from the Video Stream/Capture!!!') break detectAndDisplay(frame) # Wait until some key is pressed to close the window with the video capture with all the detected Faces and Eyes... print("Press some key to close the window with the video capture with all the detected Faces and Eyes...") if cv.waitKey(10) == 27: break
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:len(bin(i))] ibins = ""+"1"*(32-len(bins)) for c in bins: if c == '0': ibins += '1' else: ibins += '0' inv = int(ibins,2) inv += 1 return inv num = 0x70000000 #largest whole number print num print invert(num) #prints two's complement in 32-bit splendor, for MARS print (0xffffffff)/2
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.index = df['Date'] del df['Date'] #(4.) Remove all the values of NO2(GT) greater than 100 from march 2005 till june 2005 #df = df[(df['Date'] >='2005-03') & (df['Date'] <= '2005-06') & (df['NO2(GT)'] > 100)] df = df['2005-03':'2005-06'] df = df[(df['NO2(GT)'] > 100)] print(df)
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!') elif periodoalismento > 18: print('Você já passou {} anos do prazo.'.format(periodoalismento - 18))
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 # função len(frase), len = comprimento. # frase.count('o,0,13') o comando vai contar quantas letras 'o' existem na frase, entre caracter 0 e 13. # frase.find ('deo') #Transformação # frase.replace ('Python, Android) # frase.upper() / frase.lower() # frase.strip() remove os espaço inuteis, no inicio e no final da str, frase.rstrip elimina pela direita # frase.lstrip() remove os espaços pela esquerda # frase.title() captaliza a primeira letra de cada palavra # frase.split() utiliza os espaço para separar # '-'.join(frase) para juntas, utilizando o separado das ' ' frase = str(input('Frase: ')) print(len(frase), frase[:15:3], '\n', frase[:10] )
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 horizontal_index = horizontal_position % len(lines[0]) if lines[vertical_position][horizontal_index] == '#': tree_count += 1 horizontal_position += horizontal_movement vertical_position += vertical_movement return tree_count movement_amounts = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] print(math.prod( count_trees(i[0], i[1]) for i in movement_amounts ))
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(frequency) if instruction[0] == '+': frequency += int(instruction[1:]) else: frequency -= int(instruction[1:]) print(result)
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.items(): print(i + "derslerini aldı: "+ j) ''' for i in dersler.items(): print(type(i)) print(i[0] ,i[1]) isim=input("isim giriniz") print(" {} in aldığı dersler:".format(isim)) for i in (dersler[isim]): print(i) print(dersler["mete"])
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() datetime.date(2019,7,30) ''' -------------------------------------------------HW----------------------------------------- you will ask birthday calculate number of days until his birthday-- or check is it passed or will be come on that day. -------------------------------------------------HW2----------------------------------------- how many week in month? first monday can be in week one or week 2 (calendar şekli pazartesiden başlar--basic_datetime.py codunda son basılan august bak.) identify first monday of month(12)- calculate day of presentation day(every monday of the month-) -------------------------------------------------HW3----------------------------------------- worksheet2 for import * import math from math import pi farkları -benzerlikleri? -------------------------------------------------HW4-----------------------------------------+ get cvs from webpage-oxford cvs learn how to read from webpage tmax- average for every 10 years(1910-1919:1920-1929...) sun hours for 10 years where dos it start(you have to determine where does it start) ''' ''' MODULES: reliability: should check invalid inputs aas an example... ''' ''' if __name== '__main__': main() ''' import urllib.request #wh=urllib.request('...') # kodda sorun olabilir incele #wh.read() url='http://www.ku.edu.tr/' sayfa=urllib.request.urlopen(url).read() wf=open('mete.html','w') sayfa_utf=sayfa.decode('utf-8') type(sayfa_utf) wf.write(sayfa_utf) wf.close() # bu kod hata verir çünkü bytes write yapılamaz string olmalıdır. with urllib.request.urlopen('http://python.org/') as response: htmlPage=response.read() type(htmlPage) url2='https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/oxforddata.txt' urllib.request.urlretrieve(url,filename='Oxford_wdata.txt') ''' Numpy array kullanmak ile list kullanmak farkı nedir? bunu bak sen dersten çıktıktan sonra işlendi.. x=[range(10)] print(x) [range(0, 10)] print(x[0]) range(0, 10) print(type(x[0])) <class 'range'> list(range(10)) Out[27]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] '''
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 index if index == len(katar): index = 0 return devam if dict[dizi[index]] == katar[index] or dict[dizi[index]] == "": # print("yazi :",dict[dizi[index]],katar[index] , index) index += 1 devam = ara(dict, katar) else: devam = False return devam def bilgiDoldur(): dict = {} print("warning :girmek istemediginiz bilgileri bos birakin") ad = input("ogrenci adi ...:") soyad = input("ogrenci soyadi ....:") yas = input("ogrenci yasi....:") okul = input("ogrenci okulu ....:") bolum = input("ogrenci bolumu....:") if ad == "" and soyad == "" and yas == "" and okul == "" and bolum == "": print("\nErr :Lutfen en az 1 deger giriniz") else: if (ad != ""): dict["ad"] = ad else: dict["ad"] = "" if (soyad != ""): dict["soyad"] = soyad else: dict["soyad"] = "" if (yas != ""): dict["yas"] = yas else: dict["yas"] = "" if (okul != ""): dict["okul"] = okul else: dict["okul"] = "" if (bolum != ""): dict["bolum"] = bolum else: dict["bolum"] = "" return dict def goruntule(katar): if sonuc == True: print("Success.....:") print("ad :", katar[0]) print("soyad :", katar[1]) print("yas :", katar[2]) print("okul :", katar[3]) print("bolum :", katar[4]) devam = True # devami en sonda true yaptik def dosyaAc(fileName, mode): try: dosya = open(fileName, mode) except: print("boyle bir dosya bulunmamaktatir...") return False return dosya while True: print("-----------Yurt Otomasyonou ------------\n") print("1-Ogrenci Ekle") print("2-Ogrenci Sil") print("3-Ogrenci Listele") print("4-exit") var = int(input("secim....:")) if var == 1: dosya = open("ogrenciler.txt", "a+") # sonuna ekle yoksa olustur oku/yaz ad = input("ad :") soyad = input("soyad :") yas = input("yas :") okul = input("okul :") bolum = input("bolum :") dosya.write(ad + "\t" + soyad + "\t" + yas + "\t" + okul + "\t" + bolum + "\n") dosya.close() print("ogrenci kayit edildi...") elif var == 2: dosya = dosyaAc("ogrenciler.txt", "r") if dosya == False: continue dosya2 = dosyaAc("ogrenciler2.txt", "a+") if dosya == False: continue dict = bilgiDoldur() if len(dict) == 0: continue while True: katar = dosya.readline() if katar == "": break # satiri dizi haline getiriyoruz katar = katar.split('\t') # # aramaya basliyoruz sonuc = ara(dict, katar) devam = True if sonuc == False: dosya2.write(katar[0] + "\t" + katar[1] + "\t" + katar[2] + "\t" + katar[3] + "\t" + katar[4]) else: continue dosya.close() dosya2.close() os.remove("ogrenciler.txt") os.rename("ogrenciler2.txt", "ogrenciler.txt") elif var == 3: dosya = dosyaAc("ogrenciler.txt", "r") if dosya == False: continue boolean = input("ogrenci bilgisini girecek misiniz e/h ? :") # print("debug ....:",boolean) if boolean == "e" or boolean == "E": dict = bilgiDoldur() if len(dict) == 0: continue while True: katar = dosya.readline() if katar == "": break # satiri dizi haline getiriyoruz katar = katar.split('\t') # # aramaya basliyoruz sonuc = ara(dict, katar) if sonuc == False: continue else: goruntule(katar) if sonuc == False: print("\nNo result...\n") else: print("--------------------------\n") ogrenciler = dosya.read() print(ogrenciler) print("---------Dosya Sonu ---------") elif var == 4: break else: print("yanlis deger girildi...\n") input() # bos bekle os.system("cls") # clear screen
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 + 42)=2562 b)(10/1.61)=6.211180124223602 c)6.87 minutes 52.48 seconds B) 1- a-SyntaxError: can't assign to literal(24=n) b-(x=y=3) there is no error x and y set as 3 c-(x=5;) x set as 5 d-(xy) Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'xy' is not defined 2- a)math.pi*(r**3) =392.6990816987241 b) c)7.15.42 ''' print(5++7) list=[1,2,3,4,5] myset={1,2,3,4} tüp=(1,2,3,4) for i in "mete":
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.csv') data_set.head() data_set.info() data_set.describe() data_set.columns x = data_set[['Year']] y = data_set[['Colombo','Gampaha','Kalutara','Kandy','Matale','Nuwara - Eliya','Galle','Matara','Hambantota','Jaffna','Mannar','Vavuniya','Mullaitivu','Kilinochchi','Batticaloa','Ampara','Trincomalee','Kurunagala','Puttalam','Chilaw','Anuradhapura','Polannaruwa','Badulla','Monaragala','Ratnapura','Kegalle']] lm = LinearRegression() lm.fit(x ,y) predictions = lm.predict(prediction_years) with open('population_by_district_in_census_years_predictions.csv', mode='w', newline='') as employee_file: output_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) output_writer.writerow(['Colombo','Gampaha','Kalutara','Kandy','Matale','Nuwara - Eliya','Galle','Matara','Hambantota','Jaffna','Mannar','Vavuniya','Mullaitivu','Kilinochchi','Batticaloa','Ampara','Trincomalee','Kurunagala','Puttalam','Chilaw','Anuradhapura','Polannaruwa','Badulla','Monaragala','Ratnapura','Kegalle']) for row in predictions: output_writer.writerow([row[0], row[1],row[2], row[3],row[4], row[5],row[6], row[7],row[8], row[9],row[10], row[11],row[12], row[13],row[14], row[15],row[17], row[17],row[18],row[19], row[20],row[21], row[22],row[23], row[24]])
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) circle(15, 90) fd(173) circle(1, 90) end_fill() penup() fd(100) right(60) back(105) a = pos() pendown() color(60, 67, 0) fillcolor(85, 97, 9) begin_fill() fd(120) goto(a) penup() back(15) left(90) fd(20) right(90) pendown() fd(150) right(120) fd(24) right(60) fd(120) right(60) fd(24) end_fill() begin_fill() left(110) fd(65) left(100) fd(24) left(80) fd(50) end_fill() # 画盘子 def plate(a, b, angle, steps, rotateAngle): minAngle = (2 * math.pi / 360) * angle / steps rotateAngle = rotateAngle / 360 * 2 * math.pi penup() # 起笔 setpos(b * math.sin(rotateAngle), -b * math.cos(rotateAngle)) pendown() # 落笔 for i in range(steps): nextPoint = [a * math.sin((i + 1) * minAngle), -b * math.cos((i + 1) * minAngle)] nextPoint = [nextPoint[0] * math.cos(rotateAngle) - nextPoint[1] * math.sin(rotateAngle), nextPoint[0] * math.sin(rotateAngle) + nextPoint[1] * math.cos(rotateAngle)] setpos(nextPoint) # 移动 def move(x, y): penup() # 起笔 setpos(x, y) # 画笔位置 pendown() # 落笔 # 文字 def word(): write("祝大家端午安康", move=False, align="center", font=("Comic Sans", 18, "bold")) if __name__ == '__main__': colormode(255) # 颜色模式 hideturtle() # 隐藏画笔 fillcolor(153, 229, 153) begin_fill() plate(300, 200, 360, 300, 0) end_fill() move(40, -50) rice_dumpling() move(20, 100) rice_dumpling() move(-50, -70) rice_dumpling() move(10, 150) word() done()
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", "end_date", "driver_license_validity", "gender" ] df = pd.read_excel(file_path, usecols="A:H", header=None,names=COL_NAMES) df.drop([0],axis=0, inplace=True) df=df[df['code'].notna()] df.drop_duplicates(['code'],keep='last', inplace=True) df[ [ 'birth_date', 'naturalization_date', 'contract_date','end_date', 'driver_license_validity' ] ]=df[ [ 'birth_date', 'naturalization_date', 'contract_date','end_date', 'driver_license_validity' ] ].apply( pd.to_datetime, format='%Y-%m-%d', errors='coerce' ) df[ [ 'birth_date', 'naturalization_date', 'contract_date', 'end_date', 'driver_license_validity' ] ]=df[ [ 'birth_date', 'naturalization_date', 'contract_date', 'end_date', 'driver_license_validity' ] ].astype(str) df.replace({'NaT':None},regex=True, inplace=True) return df
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.float64) ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64) # .scatter(xs, ys) # plt.show() def best_fit_slope(_and_interceptxs, ys): m = (((mean(xs) * mean(ys)) - mean(xs * ys)) / ((mean(xs) * mean(xs)) - mean(xs * xs))) b= mean(ys) - m * mean(xs) return m, b m, b = best_fit_slope(xs, ys) regression_line = [(m * x) + b for x in xs] # predict some future data points predict_x = 7 predict_y = (m * predict_x) + b print(predict_y) predict_x = 7 predict_y = (m*predict_x)+b plt.scatter(xs,ys,color='#003F72',label='data') plt.plot(xs, regression_line, label='regression line') plt.legend(loc=4) plt.show() # print(m, b)
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 maximum amount of toys that can be bought given the budget ''' toy_prices = sorted(toy_prices) num_toys = 0 for i in range(len(toy_prices)): valid_purchase = budget - toy_prices[i] if valid_purchase >= 0: budget -= toy_prices[i] num_toys += 1 print(num_toys) return num_toys if __name__ == '__main__': toy_prices = [1,12,5,111,200,1000,10] budget = 50 main(toy_prices, budget)
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 given array ''' # temp is an array where the values are the indexes # If one accesses temp[val], one would get the index (i) as output # The index in this case would be the expected value - 1 temp = {val: i for i, val in enumerate(arr)} min_swaps = 0 for i in range(len(arr)): value = arr[i] # array contains consecutive integers starting from 1 expected_value = i + 1 # get the index of the value wanted expected_i = temp[expected_value] # swap values if not in the correct order if value != expected_value: # in the main array: swap current with the value wanted at the current index arr[i] = expected_value arr[expected_i] = value # in the enum array: swap current with the value wanted at the current index temp[value] = expected_i temp[expected_value] = i min_swaps += 1 print(min_swaps) return min_swaps if __name__ == '__main__': arr = [1,3,5,2,4,6,7] main(arr)
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") c_height = 380 c_width = 680 x_width = c_width/(len(data)+1) offset = 20 spacing = 10 normalizedData = [i/max(data) for i in data] for i, height in enumerate(normalizedData): x0 = i*x_width + offset + spacing y0 = c_height - height * 340 x1 = (i+1) * x_width + offset y1 = c_height canvas.create_rectangle(x0,y0,x1,y1,fill=colorArray[i]) canvas.create_text(x0+2,y0, anchor=SW, fill = "red", text=str(data[i])) root.update_idletasks() def StartAlgo(): speed= speedScale.get() global data bubbleSort(data, drawData,speed) def Generate(): global data minVal = int(minEntry.get()) maxVal = int(maxEntry.get()) size = int(sizeEntry.get()) print("Generated..." + selected_alg.get() + " "+str(maxVal) + " " +str(minVal)+ " " +str(size)) data = [random.randint(minVal,maxVal) for i in range(size)] drawData(data, ["red"]*size) #frame UI_frame = Frame(root, width=700, height=260, bg="grey") UI_frame.grid(row=0, column=0, padx=10, pady=5) canvas = Canvas(root, width=700, height=380) canvas.grid(row=1, column=0, padx=10, pady=5) # UI Label(UI_frame, text="Algorithm: ", bg="grey").grid(row=0, column= 0, padx=5, pady=5) algMenu = ttk.Combobox(UI_frame, textvariable=selected_alg, values=['Bubble Sort', 'Quick Sort']) algMenu.grid(row=0, column=1,padx=5, pady=5) algMenu.current(0) # speed speedScale = Scale(UI_frame,from_=0.01, to=2.0,length=200,digits=2,resolution=0.1, orient=HORIZONTAL, label="Speed [s]") speedScale.grid(row=0, column=2, padx = 5,pady=5) Button(UI_frame, text="Start", command=StartAlgo, bg="red").grid(row=0,column=3,padx=5, pady=5) # size sizeEntry = Scale(UI_frame,from_=3, to=50,resolution=1, orient=HORIZONTAL, label="Data Size") sizeEntry.grid(row=1, column= 0, padx=5, pady=5) # min value minEntry = Scale(UI_frame,from_=0, to=25,resolution=1, orient=HORIZONTAL, label="Min Size") minEntry.grid(row=1, column= 1, padx=5, pady=5) # max value maxEntry = Scale(UI_frame,from_=25, to=100,resolution=1, orient=HORIZONTAL, label="Max SIze") maxEntry.grid(row=1, column= 2, padx=5, pady=5) Button(UI_frame, text="Generate", command=Generate, bg="white").grid(row=1 ,column=3,padx=5, pady=5) root.mainloop()
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 Temperture in degrees F ''' url = "http://pubdata.mlml.calstate.edu/weather/recent.html" content = urlopen(url).read() soup = BeautifulSoup(content, 'html.parser') out = [tr.find('td').text for tr in soup.findAll('tr')] data = out[1] data = data.split('\n') data = [l for l in data if l != ''] data = [l.strip('> ') for l in data] for i,l in enumerate(data): if l.lower().find('wind speed') != -1: windSpeed = float((re.search('Wind Speed:(\d+\.\d+) m/s.+',l).group(1))) elif l.lower().find('wind direction') != -1: windDir = int((re.search('Wind Direction:(\d+).+',l).group(1))) elif l.lower().find('air temperature') != -1: airTemp = float((re.search('Air Temperature:(\d+\.\d+).+',l).group(1))) return windSpeed,windDir,airTemp
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 dari ketiga input tersebut Apabila input ketiga memiliki suku kata "ku" maka tampilkan "error" Apabila ada 2 atau lebih ketentuan terpenuhi maka minta sebuah input lagi dari user dan tampilkan input tersebut dengan huruf kapital secara terbalik kecuali huruf pertama ''' x = 0 satu = str(input("Masukkan kata pertama :")) dua = str(input("Masukkan kata kedua :")) tiga = str(input("Masukkan kata ketiga :")) y = "ku" in tiga spertama = len(satu) if spertama > 5 : print(satu,dua,tiga) x = x + 1 if dua[0] == "a" : print(len(satu) + len(dua) + len(tiga)) x = x + 1 if y == True : print("error") x = x + 1 if x > 0 : empat = str(input("Masukkan kata keempat :")) empat_1 = len(empat) - 1 empat_kapital = empat[(empat_1):0:-1].upper() print(empat_kapital)
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" eyelinercolour = "black" def __init__(self,userselecteditemtype): self.itemtype = userselecteditemtype def geteyelinercolour(self,colour): self.eyelinercolour = colour def showitemtype(self): print "Item selected is ", self.itemtype ####################################### # defining the main entrant function # ####################################### def my_main(): makeupinstance = makeup("blushon") makeupinstance.showitemtype() ######################################## # calling main() to begin the execution# ######################################## my_main()
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, # text="YouTube link :", # bg="#E8D579") # link_label.grid(row=1, # column=0, # pady=5, # padx=5) # # root.linkText = Entry(root, # width=55, # textvariable=video_Link) # root.linkText.grid(row=1, # column=1, # pady=5, # padx=5, # columnspan = 2) # # destination_label = Label(root, # text="Destination :", # bg="#E8D579") # destination_label.grid(row=2, # column=0, # pady=5, # padx=5) # # root.destinationText = Entry(root, # width=40, # textvariable=download_Path) # root.destinationText.grid(row=2, # column=1, # pady=5, # padx=5) # # browse_B = Button(root, # text="Browse", # command=Browse, # width=10, # bg="#05E8E0") # browse_B.grid(row=2, # column=2, # pady=1, # padx=1) # # Download_B = Button(root, # text="Download", # command=Download, # width=20, # bg="#05E8E0") # Download_B.grid(row=3, # column=1, # pady=3, # padx=3) # # # Defining Browse() to select a # # destination folder to save the video # # def Browse(): # # Presenting user with a pop-up for # # directory selection. initialdir # # argument is optional Retrieving the # # user-input destination directory and # # storing it in downloadDirectory # download_Directory = filedialog.askdirectory(initialdir="YOUR DIRECTORY PATH") # # # Displaying the directory in the directory # # textbox # download_Path.set(download_Directory) # # # Defining Download() to download the video # def Download(): # # # getting user-input Youtube Link # Youtube_link = video_Link.get() # # # select the optimal location for # # saving file's # download_Folder = download_Path.get() # # # Creating object of YouTube() # getVideo = YouTube(Youtube_link) # # # Getting all the available streams of the # # youtube video and selecting the first # # from the # videoStream = getVideo.streams.first() # # # Downloading the video to destination # # directory # videoStream.download(download_Folder) # # # Displaying the message # messagebox.showinfo("SUCCESSFULLY", # "DOWNLOADED AND SAVED IN\n" # + download_Folder) # # # Creating object of tk class # root = tk.Tk() # # # Setting the title, background color # # and size of the tkinter window and # # disabling the resizing property # root.geometry("600x120") # root.resizable(False, False) # root.title("YouTube_Video_Downloader") # root.config(background="#000000") # # # Creating the tkinter Variables # video_Link = StringVar() # download_Path = StringVar() # # # Calling the Widgets() function # Widgets() # # # Defining infinite loop to run # # application # root.mainloop() # # link = 'https://www.youtube.com/watch?v=Je2OItlb4pY' ######################input("Enter the link: ") # yt = YouTube(link) #print(yt.title,yt.rating,yt.author,yt.description,yt.keywords,yt.length,yt.metadata,yt.publish_date,yt.views) #print(type(yt.streams.filter(only_audio=True))) #x = input("Enter 1 for audio ,two for video") #print(yt.streams.get_by_resolution('1080p')) #if x ==1: #print(yt.streams.filter(only_audio=True)) #else: # def combine_audio(vidname, audname, outname, fps=30): # import moviepy.editor as mpe # my_clip = mpe.VideoFileClip(vidname) # audio_background = mpe.AudioFileClip(audname) # final_clip = my_clip.set_audio(audio_background) # final_clip.write_videofile(outname,fps=fps) # loc = 'C:/Users/maind/Desktop/Flutter+deep' # video = yt.streams.filter(only_video=True,progressive=False,res="720p").first() # audio = yt.streams.filter(only_audio=True,progressive=False).first() # # print("downloading") # #video.download(loc,filename=yt.title+" video") # #audio.download(loc,filename=yt.title+" audio") # import ffmpeg # print(yt.title) # video_stream = ffmpeg.input("1.mp4") # audio_stream = ffmpeg.input("2.mp4") # final=ffmpeg.output(audio_stream, video_stream,'3.mp4') # final.run() #combine_audio('C:/Users/maind/Desktop/Flutter+deep/Lil Uzi Vert - Sanguine Paradise [Official Music Video] video.mp4','C:/Users/maind/Desktop/Flutter+deep/Lil Uzi Vert - Sanguine Paradise [Official Music Video] audio.mp4','C:/Users/maind/Desktop/Flutter+deep/Finalbruh.mp4') #C:\Users\maind\Desktop\Flutter+deep\Lil Uzi Vert - Sanguine Paradise [Official Music Video] video.mp4 import ffmpeg #pytube.StreamQuery.filter() from tkinter import * from tkinter import ttk from tkinter import filedialog from pytube import YouTube #pip install pytube3 Folder_Name = "" #file location def openLocation(): global Folder_Name Folder_Name = filedialog.askdirectory() if(len(Folder_Name) > 1): locationError.config(text=Folder_Name,fg="green") else: locationError.config(text="Please Choose Folder!!",fg="red") #URL def CheckURL(): url = ytdEntry.get() yt = YouTube(url) x = yt.title if(len(x) > 1): ytdError.config(text=x,fg="green") else: ytdError.config(text="Invalid URL",fg="red") #donwload video def DownloadVideo(): choice = ytdchoices.get() url = ytdEntry.get() if(len(url)>1): ytdError.config(text="") yt = YouTube(url) if(choice == choices[0]): try: select = yt.streams.filter(progressive=True).get_highest_resolution() except: ytdError.config(text="Please choose another configuration",fg="red") elif(choice == choices[1]): try: select = yt.streams.filter(progressive=True,file_extension='mp4').last() except: ytdError.config(text="Please choose another configuration",fg="red") elif(choice == choices[2]): try: select = yt.streams.filter(only_audio=True).first() except: ytdError.config(text="Please choose another configuration",fg="red") elif(choice ==choices[3]): try: select = yt.streams.filter(only_video=True,progressive=False).get_highest_resolution() except: ytdError.config(text="Please choose another configuration",fg="red") else: ytdError.config(text="Please choose another configuration",fg="red") #download function select.download(Folder_Name) ytdError.config(text="Download Completed!!") root = Tk() root.title("YT Vid Downloader") #root.config(background="#000001") root.geometry("450x450") #set window root.columnconfigure(0,weight=1)#set all content in center. #Ytd Link Label ytdLabel = Label(root,text="Enter the URL of the Video",font=("Comic Sans MS",20,"bold"),bg="#E8D579") ytdLabel.grid() #Entry Box ytdEntryVar = StringVar() ytdEntry = Entry(root,width=50,textvariable=ytdEntryVar) ytdEntry.grid() #Error Msg CheckEntry = Button(root,width=10,bg="#05E8E0",fg="white",text="Check",command=CheckURL) CheckEntry.grid() ytdError = Label(root,text="Invalid URL",fg="red",font=("Fixedsys",15,"bold")) ytdError.grid() #Asking save file label saveLabel = Label(root,text="Save the Video File",font=("MS Serif",20,"bold"),bg="#E8D579") saveLabel.grid() #btn of save file saveEntry = Button(root,width=10,bg="#05E8E0",fg="white",text="Choose Path",command=openLocation) saveEntry.grid() #Error Msg location locationError = Label(root,text="Invalid Path",fg="red",font=("Symbol",15,"bold")) locationError.grid() #Download Quality ytdQuality = Label(root,text="Select Quality",font=("System",20,"bold"),bg="#E8D579") ytdQuality.grid() #combobox choices = ["High res","Low res","Only Audio","Only Video"] ytdchoices = ttk.Combobox(root,values=choices) ytdchoices.grid() #donwload btn downloadbtn = Button(root,text="Download",width=10,bg="#05E8E0",fg="white",command=DownloadVideo) downloadbtn.grid() #developer Label developerlabel = Label(root,text="Hacking Scripts",font=("Verdana",20,"bold")) developerlabel.grid() root.mainloop()
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 or a > b: continue cf = sqrt(a*a+b*b) c = int(cf) #if a == n: # print a,b,c if c == cf and (a==n or b == n or c == n) and gcd(a,b) == 1 : out.append((a,b,c)) return set(out) def primitive_triplet(n): out = [] if n % 4 != 0: raise ValueError("Must be divisible by 4") def triplets_in_range(start, limit ): out = [] for i in range(start, limit+1): #print i xx = i * i y = i + 1 z = y + 1 #print i, y, z while (z <= limit): zz = xx + y * y #print i, y, z, zz while(z * z < zz): z = z + 1 #print z, zz if (z*z == zz and z <= limit): out.append((i,y,z)) #print i,y,z y = y + 1 return set(out) def is_triplet(b): return (b[0] * b[0] + b[1] * b[1] == b[2] * b[2] or b[0] * b[0] + b[2] * b[2] == b[1] * b[1] or b[1] * b[1] + b[2] * b[2] == b[0] * b[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 Node: def __init__(self,value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def insert(self, data): if not self.head: self.head = self.tail = Node(data) else: temp = Node(data) temp.next = self.head self.head = temp def append(self, data): if not self.head: self.head = self.tail = Node(data) else: temp = Node(data) self.tail.next = temp self.tail = self.tail.next def printLL(head): vals = list() while head is not None: vals.append(head.value) head = head.next return '->'.join(map(str,vals)) ''' we can solve this in a simple way: as we traverse the input list: - we insert elements whose value is less than k into our new linked list - and append everything else ''' pivot = 3 values = [5,1,8,0,3] original = LinkedList() for v in values: original.append(v) print('ORIGINAL') printLL(original.head) def partition(head, pivot): new = LinkedList() while head: if head.value < pivot: new.insert(head.value) else: new.append(head.value) head = head.next return new new = partition(original.head, pivot) print('NEW') printLL(new.head)
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 while n is not None: next_ = n.n n.n = prev_ prev_ = n n = next_ return prev_ l = reverse_ll(n1) print_ll(reverse_ll(l))
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: inorder(root.l) print(root.v) if root.r: inorder(root.r) inorder(n1) import math inf = math.inf def check_helper(node:Node, low:int, upp:int) -> bool: # Base case if node is None: return True if not (node.v >= low and node.v <= upp): return False return check_helper(node.l, low, node.v) and \ check_helper(node.r, node.v, upp) def check(node:Node): if node is None: return False return check_helper(node.l, low=-inf, upp=node.v) and \ check_helper(node.r, low=node.v, upp=inf) check(n1)
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.r = n5 n1.r = n7 def lca(n:Node, v1:int, v2:int) -> Node: # Base Case 1 if n is None: return n # Base Case 2 if n.v == v1 or n.v == v2: return n # Recurse l,r = lca(n.l,v1,v2), lca(n.r,v1,v2) # Decide if l is None: return r if r is None: return l return n lca(n1,6,8).v
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.next.data node.next = node.next.next ll = LinkedList() ll.add_multiple([7,4,3]) middle_node = ll.add(5) ll.add_multiple([7,4,3]) print(ll) delete_middle_node(middle_node) print(ll)
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: {}'.format(arr[i1],arr[i2])) print('iM: {}'.format(arr[im])) if arr[im] == t: found = True else: if arr[im] <= t: i1 = im+1 else: i2 = im-1 return found iter_bin_search(order,32) def rec_bin_search(arr,t): # Base Case if len(arr) == 0: return False i = len(arr)//2 print('Array: ', arr) print('Position: ', i) print('Value: ', arr[i]) if arr[i] == t: print('Found at ', i) return True if arr[i] >= t: print('Moving left') rec_bin_search(arr[:i],t) else: print('Moving right') rec_bin_search(arr[i+1:],t) res = rec_bin_search(order,32)
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 self.left is None: self.left = TreeNode(value) else: self.left.insert(value) else: if self.right is None: self.right = TreeNode(value) else: self.right.insert(value) def print_int_order(self): if self.left is not None: self.left.print_int_order() print(self.value) if self.right is not None: self.right.print_int_order() def __str__(self): return '('+str(self.left)+':L ' + "V:" + str(self.value) + " R:" + str(self.right)+')' class Graph_AdjList: ''' Use adjancent-list to store connections (default dict) ''' def __init__(self, nodes:int): self.N = nodes # Number of total nodes self.nodes = defaultdict(list) # Each key stores a list def addEdge(self, n1, n2): self.nodes[n1].append(n2) class Node: def __init__(self, name): self.name = name self.visited = False self.adjacents = list() def add_Adjacent(self, node): self.adjacents.append(node) def clead_Adjacents(self): self.adjacents = list() class Graph: ''' Use adjancent-list to store connections (default dict) ''' def __init__(self, nodes:int): self.N = nodes # Number of total nodes self.nodes = list() def addNode(self, node): if len(self.nodes) < self.N: self.nodes.append(node) else: print('Graph is full') def addEdge(self, n1:Node, n2:Node): n1.add_Adjacent(n2) def clean_Graph(self): for node in self.nodes: node.ajacents = list()
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): if root.l: inorder(root.l) print(root.v) if root.r: inorder(root.r) inorder(n1) import math inf = math.inf def is_BST_helper(n:Node, lw:int, up:int) -> bool: # Base case if n is None: return True if n.v < lw or n.v > up: print('Im {} and my bound are {}'.format(n.v, [lw,up])) return False return is_BST_helper(n.l,lw,n.v) and is_BST_helper(n.r,n.v,up) def is_BST(n:Node): return is_BST_helper(n,-inf,inf) is_BST(n1) n1 = Node(0) n2 = Node(1) n3 = Node(2) n1.l = n2 n1.r = n3 is_BST(n1)
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: inorder(root.right) def level_order(root): stack = list() queue = deque([root]) while queue: node = queue.popleft() for n in [n_ for n_ in [node.left, node.right] if n_]: queue.append(n) stack.append(node) return [s.val for s in stack] class MinHeap: def __init__(self, root:Node): self.root = root def get_last(self, n): if not n.left or not n.right: return n if n.left: return self.get_last(n.left) if n.right: return self.get_last(n.right) def restore(self, node1, node2): if def insert(self, node): parent = self.get_last(self.root) if not parent.left: parent.left = node else: parent.right = node n1 = Node(10) n2 = Node(4) n3 = Node(15) n4 = Node(20) n5 = Node(0) n6 = Node(30) n7 = Node(2) n8 = Node(4) n9 = Node(-1) n10 = Node(-3) heap = MinHeap(n1) heap.insert(n2) heap.insert(n3) heap.insert(n4) # heap.push() inorder(n1) level_order(n1)
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() for L in range(0, len(w)-len(p)): if w[L:L+len(p)] == p: ids.append(L) return ids get_matches(w,p) ''' More efficient solutions using Rolling Hash Functions ! '''
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,t): for i in arr: print(i) if i == t: return True if i > t: return False return False seq_search(unorder,3) ord_seq_search(order,3)
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 with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries. Write a program that returns the weight of the maximum weight path.''' # Could we gain something from moving it to a tree? class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right input = [[1], [2, 3], [1, 5, 1]] ''' Approach: Iterative calculate the max-cumulative sum at each node. We are going to visit every node 1 time. O(N) ''' import copy cumulative_sum = copy.deepcopy(input) for j in range(1,len(input)): for i, entry in enumerate(input[j]): print('\n\n{}'.format((j,i))) print('cumulative_sum[{}][{}] += max(cumulative_sum[{}][max(0,{})], cumulative_sum[{}][min({},{})]'.format( j,i,j-1,i-1,j-1,i,j-1)) print('N = {} + max({},{})'.format( cumulative_sum[j][i], cumulative_sum[j-1][max(0,i-1)], cumulative_sum[j-1][min(i,j-1)] )) cumulative_sum[j][i] += max( cumulative_sum[j-1][max(0,i-1)], cumulative_sum[j-1][min(i,j-1)] ) print(cumulative_sum) def max_path(input): depth = len(input) for j in range(1,depth): for i, entry in enumerate(input[j]): input[j][i] += max( input[j-1][max(0,i-1)], input[j-1][min(i,j-1)] ) return max(input[j]) max_path(input)
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 range(n): a,b = b,a+b return a # timeit(iter_fib(5)) # timeit(iter_fib(10)) # timeit(iter_fib(15)) ''' RECURSION ''' def rec_fib(n): if n <= 1: return n return rec_fib(n-1) + rec_fib(n-2) # timeit(rec_fib(5)) # timeit(rec_fib(10)) # timeit(rec_fib(15)) ''' DP ''' def dp_fib(n,memo=None): if memo is None: memo = [None] * (n+1) if n<=1: return n if memo[n] is not None: print('Recomputation avoided!') return memo[n] memo[n] = dp_fib(n-1,memo) + dp_fib(n-2,memo) print(memo) return memo[n] dp_fib(5) dp_fib(10)
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 in n: if digit == '1': cur_lenght += 1 max_length = max(max_length, cur_lenght) else: cur_lenght = 0 return max_length longest_1s_path(input)
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 the temperature in Fahrenheit: ")) print(temperature_fahrenheit) temperature_celsius = (temperature_fahrenheit - 32) * (5 / 9) print(str(temperature_fahrenheit) + " degrees fahrenhei = " + str(temperature_celsius) + " degrees celsius ")
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 the classic data structure min-heap. Provides functions for heapifying an unsorted list, heap-sorting the list, insert and delete (pop) from heap in O(lg n). """ def __init__(self, items): """ Create a new MinHeap instance using a list of unsorted items Time Complexity: O(n) """ self.heap = copy.deepcopy(items) # Do not want to alter items self.min_heapify_list(self.heap) return def insert(self, elem): """ Insert element elem into the heap. Time Complexity: O(lg(n)) """ self.heap.append(elem) heap_size = len(h) + 1 self.percolate_up(heap_size-1) return def pop(self): """ Remove the smallest element, and return it as well Time Complexity: O(lg(n)) """ temp = self.heap[0] self.heap[0] = self.heap[-1] self.heap[-1] = temp popped_element = self.heap.pop() MinHeap.min_heapify(self.heap, 0, len(self.heap)) return popped_element def delete_by_pos(self, pos): """ Delete the element at position pos and return the element. Time Complexity: O(lg(n)) """ n = len(self.heap) parent_pos = int((pos-1)/2) deleted_element = self.heap[pos] self.heap[pos] = self.heap[n-1] self.heap.pop() if self.heap[pos] < self.heap[parent_pos]: self.percolate_up(pos) else: MinHeap.min_heapify(self.heap, pos, n-1) return deleted_element def percolate_up(self, pos): """ An element at position pos is not at its correct place, keep percolating it up till it reaches a place congruous with the min-heap data structure. Time Complexity: O(lg(n)) """ if pos > 0: parent_pos = int((pos-1)/2) if self.heap[parent_pos] > self.heap[pos]: temp = self.heap[parent_pos] self.heap[parent_pos] = self.heap[pos] self.heap[pos] = temp self.percolate_up(parent_pos) return def get_sorted_elements_descending(self): sorted_elements = copy.deepcopy(self.heap) for last_pos in range(len(self.heap)-1, 0, -1): temp = sorted_elements[0] sorted_elements[0] = sorted_elements[last_pos] sorted_elements[last_pos] = temp MinHeap.min_heapify(sorted_elements, 0, last_pos) return sorted_elements @staticmethod def min_heapify(l, current_pos, heap_length): """ Perform the well known heapify operation. Time Complexity: O(lg(n)), where n is heap_length """ min_pos = current_pos left_child_pos = (current_pos << 1) + 1 right_child_pos = left_child_pos + 1 if left_child_pos < heap_length and l[left_child_pos] < l[min_pos]: min_pos = left_child_pos if right_child_pos < heap_length and l[right_child_pos] < l[min_pos]: min_pos = right_child_pos if min_pos != current_pos: temp = l[current_pos] l[current_pos] = l[min_pos] l[min_pos] = temp MinHeap.min_heapify(l, min_pos, heap_length) return @staticmethod def min_heapify_list(l): """ Convert a list into a min-heap Time Complexity: O(n) """ n = len(l) for current_pos in range(int(floor(n/2)) - 1, -1, -1): MinHeap.min_heapify(l, current_pos, len(l)) return @staticmethod def heap_sort(l, asc=True): """ Given a list l, sort it using the heap-sort method Time Complexity: O(nlg(n)) Return: sorted list l """ # Don't want to sort the reference itself, so we rebind the reference to mimick pass by value on the object l = copy.deepcopy(l) n = len(l) MinHeap.min_heapify_list(l) for current_pos in range(n-1, 0, -1): temp = l[current_pos] l[current_pos] = l[0] l[0] = temp MinHeap.min_heapify(l, 0, current_pos) if asc: return l[::-1] else: return l @staticmethod def check_list_min_heap(l): """ Given list l, determine if it qualifies as a binary min-heap Return True/False Time Complexity: O(n) """ answer = True for current_pos in range(int(floor(len(l)/2))): left_child = l[2*current_pos + 1] right_child = l[2*current_pos + 2] if 2*current_pos + 2 < len(l) else None if l[current_pos] > left_child or (right_child is not None and l[current_pos] > right_child): answer = False break return answer ################################################ # Extension of https://stackoverflow.com/a/407922 class PriorityQueueSet(object): """ Combined priority queue and set data structure. Acts like a priority queue, except that its items are guaranteed to be unique. Provides O(1) membership test, O(log N) insertion and O(log N) removal of the smallest item. Important: the items of this data structure must be both comparable and hashable (i.e. must implement __cmp__ and __hash__). This is true of Python's built-in objects, but you should implement those methods if you want to use the data structure for custom objects. """ def __init__(self, items=None): """ Create a new PriorityQueueSet. Arguments: items (list): An initial item list - it can be unsorted and non-unique. The data structure will be created in O(N). """ self.set = set(items) if items is not None else set() self.heap = list(self.set) min_heapify_list(self.heap) return def has_item(self, item): """Check if ``item`` exists in the queue.""" return item in self.set def pop_smallest(self): """Remove and return the smallest item from the queue.""" smallest = heapq.heappop(self.heap) del self.set[smallest] return smallest def add(self, item): """Add ``item`` to the queue if doesn't already exist.""" if item not in self.set: self.set[item] = True heapq.heappush(self.heap, item) def max_heapify(l, current_pos, heap_length): """ Perform the well known heapify operation and return the list/heap Time Complexity: O(lg(n)), where n is heap_length """ max_pos = current_pos left_child_pos = (current_pos << 1) + 1 right_child_pos = left_child_pos + 1 if left_child_pos < heap_length and l[left_child_pos] > l[max_pos]: max_pos = left_child_pos if right_child_pos < heap_length and l[right_child_pos] > l[max_pos]: max_pos = right_child_pos if max_pos != current_pos: temp = l[current_pos] l[current_pos] = l[max_pos] l[max_pos] = temp max_heapify(l, max_pos, heap_length) return def max_heapify_list(l): """ Convert a list into a max-heap Time Complexity: O(n) """ n = len(l) for current_pos in range(int(floor(n/2)) - 1, -1, -1): max_heapify(l, current_pos, len(l)) return def heap_sort_ascending(l): """ Given a list l, sort it using the heap-sort method Time Complexity: O(nlg(n)) Return: sorted list l """ # Don't want to sort the reference itself, so we rebind the reference to mimick pass by value on the object l = copy.deepcopy(l) n = len(l) max_heapify_list(l) for current_pos in range(n-1, 0, -1): temp = l[current_pos] l[current_pos] = l[0] l[0] = temp max_heapify(l, 0, current_pos) return l ################################################ # 1. Check if given list is a binary max-heap def check_list_max_heap(l): """ Given list l, determine if it qualifies as a binary max-heap Return True/False Time Complexity: O(n) """ answer = True for current_pos in range(int(floor(len(l)/2))): left_child = l[2*current_pos + 1] right_child = l[2*current_pos + 2] if 2*current_pos + 2 < len(l) else None if l[current_pos] < left_child or (right_child is not None and l[current_pos] < right_child): answer = False break return answer # 2. Find the kth smallest element of an unsorted list l # P.S.: There exist methods with expected and worst-case linear time as well for this. def find_kth_smallest_element(l, k): """ Return the kth smallest element of the list l. Here k is 1-indexed. Time Complexity: O(n + klg(n)) """ l = copy.deepcopy(l) n = len(l) MinHeap.min_heapify_list(l) for i in range(0, k): last_idx = n-i-1 temp = l[0] l[0] = l[last_idx] l[last_idx] = temp MinHeap.min_heapify(l, 0, n-i-1) return l[n-k] def main(): l1 = [90, 15, 10, 7, 12, 2, 7, 3] l2 = [90, 15, 10, 7, 12, 2, 17] l3 = [-2, -1] print(check_list_max_heap(l1)) print(check_list_max_heap(l2)) print(check_list_max_heap(l3)) print(heap_sort_ascending(l1)) print(heap_sort_ascending(l2)) print(heap_sort_ascending(l3)) print(find_kth_smallest_element(l1, 3)) ######################################### h1 = MinHeap(l1) print(MinHeap.check_list_min_heap(h1.heap)) print(MinHeap.heap_sort(l1)) print(h1.pop()) print(h1.delete_by_pos(2)) print(MinHeap.check_list_min_heap(h1.heap)) print(h1.get_sorted_elements_descending()) if __name__ == "__main__": main()
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 Subtracao(Expressao): def __init__(self, expressao_esquerda, expressao_direita): self.__expressao_esquerda = expressao_esquerda self.__expressao_direita = expressao_direita def avalia(self): return self.__expressao_esquerda.avalia() - self.__expressao_direita.avalia() def aceita(self, visitor): visitor.visita_subtracao(self) @property def expressao_esquerda(self): return self.__expressao_esquerda @property def expressao_direita(self): return self.__expressao_direita ## # Classe responsável pela soma ## class Soma(Expressao): def __init__(self, expressao_esquerda, expressao_direita): self.__expressao_esquerda = expressao_esquerda self.__expressao_direita = expressao_direita def avalia(self): return self.__expressao_esquerda.avalia() + self.__expressao_direita.avalia() def aceita(self, visitor): visitor.visita_soma(self) @property def expressao_esquerda(self): return self.__expressao_esquerda @property def expressao_direita(self): return self.__expressao_direita ## # Objeto de representação de um número ## class Numero(Expressao): def __init__(self, numero): self.__numero = numero def avalia(self): return self.__numero def aceita(self, visitor): visitor.visita_numero(self) if __name__ == "__main__": from impressao import Impressao expressao_esquerda = Soma(Numero(40), Numero(120)) expressao_direita = Subtracao(Numero(50), Numero(20)) expressao_conta = Soma(expressao_esquerda, expressao_direita) impressao = Impressao() expressao_conta.aceita(impressao)
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.") except ValueError: print("Please enter a number... ") <<<<<<< HEAD continue ======= continue >>>>>>> 9903a5aad660c35811fdef1f4b2789b2ac6e1f43
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.Direction.OUTPUT led4.direction = digitalio.Direction.OUTPUT sw1.direction = digitalio.Direction.INPUT # Main Loop while True: # Read Button Value Button = sw1.value # Serial Output Button Value print("Button Value:", Button) # Turn rled ON/OFF based on conditional Button Value if (Button == True): # Set LED state to ON rled.value = True else: # Set LED state to OFF rled.value = False # Set led4 to Button Value led4.value = Button # Pause for 0.2 second time.sleep(0.2)
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: ") classPercent(maleN,maleN+femalesN) print("The % of females is: ") classPercent(femalesN,maleN+femalesN) main() #Taken from starting out with Python book. Page 525. Date is 2020-04-02
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) time.sleep(1) if mutex_b.acquire(): print('thread %s gets mutex b' % self.name) mutex_b.release() mutex_a.release() def task_b(self): if mutex_b.acquire(): print('thread %s ges mutex a' % self.name) time.sleep(1) if mutex_a.acquire(): print('thread %s gets mutex b' % self.name) mutex_a.release() mutex_b.release() def run(self): self.task_a() self.task_b() def main(): print ("Start main threading") threads = [MyThread() for i in range(2)] for t in threads: t.start() for t in threads: t.join() print ("End Main threading") # 线程需要执行两个任务,两个任务都需要获取锁,然而两个任务先得到锁后, # 就需要等另外锁释放。 if __name__ == '__main__': main()
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 produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c) # consumer函数式一个generator, 把一个consumer传入produce后: # 1. 首先调用c.send(None)启动生成器 # 2. 然后,一旦产生了东西,通过c.send(n)切换到consumer执行 # 3. consumer通过yield拿到消息,处理,又通过yield把结果传回 # 4. produce拿到consumer处理的结果,继续生产吓一跳消息 # 5. produce决定不生产了,通过c.close()关闭consumer,整个过程结束。 # 整个流程无锁,由一个线程执行,produce和consumer协作完成任务,所以称为“协程”,而非线程的抢占式多任务。 # 使用同步 sleep 方法的代码 async def custom_sleep(): print('SLEEP', datetime.now()) time.sleep(1) async def factorial(name, number): f = 1 for i in range(2, number+1): print('Task {}: Compute factorial({})'.format(name, i)) await custom_sleep() f *= i print('Task {}: factorial({}) is {}\n'.format(name, number, f)) start = time.time() loop = asyncio.get_event_loop() tasks = [ asyncio.ensure_future(factorial("A", 3)), asyncio.ensure_future(factorial("B", 4)), ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print("Total time: {}".format(end - start)) # 使用异步 Sleep 的代码: import asyncio import time from datetime import datetime async def custom_sleep(): print('SLEEP {}\n'.format(datetime.now())) # 当使用异步模式的时候(每次调用 await asyncio.sleep(1) ),进程控制权会返回到主程序的消息循环里, # 并开始运行队列的其他任务(任务A或者任务B)。 await asyncio.sleep(1) async def factorial(name, number): f = 1 for i in range(2, number+1): print('Task {}: Compute factorial({})'.format(name, i)) await custom_sleep() f *= i print('Task {}: factorial({}) is {}\n'.format(name, number, f)) start = time.time() loop = asyncio.get_event_loop() tasks = [ asyncio.ensure_future(factorial("A", 3)), asyncio.ensure_future(factorial("B", 4)), ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print("Total time: {}".format(end - start))
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 tall and %f %r heavy." % ( age, au, height, tu, weight, wu)
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: return num else: return 'r' b = [] for i in range(100000000, 100000200): if is_prime2(i) != 'r': b = b + [is_prime2(i)] print(b[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") # elif num/11==int(num/11): # print("false") # elif num/13==int(num/13): # print("false") # elif num/17==int(num/17): # print("false") # elif num/19==int(num/19): # print("false") # elif num/23==int(num/23): # print("false") # elif num/29==int(num/29): # print("false") # elif num/31==int(num/31): # print("false") # elif num/37==int(num/37): # print("false") # elif num/41==int(num/41): # print("false") # elif num/43==int(num/43): # print("false") # elif num/47==int(num/47): # print("false") # elif num/53==int(num/53): # print("false") # elif num/59==int(num/59): # print("false") # elif num/61==int(num/61): # print("false") # elif num/67==int(num/67): # print("false") # elif num/71==int(num/71): # print("false") # elif num/73==int(num/73): # print("false") # elif num/79==int(num/79): # print("false") # elif num/83==int(num/83): # print("false") # elif num/89==int(num/89): # print("false") # elif num/97==int(num/97): # print("false") # else: # print("true") # # #import sys #is_prime(int(sys.argv[1])) 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: return True else: return 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: return num else: return 'r' b = [] for i in range(10000, 10050): if is_prime2(i) != 'r': b = b + [is_prime2(i)] print(b[0], ', ', b[1], ', ', b[2], ', ', b[3])
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 category sns.catplot(y="Internet usage", data=survey_data, kind="count", col="Age Category") # Show plot plt.show()
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]: return False else: pushV.pop(index) return True
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(''.join(ls[1:])) elif ls[0] == '-' and len(ls) > 1: for i in ls[1:]: if i < '0' or i > '9': return 0 return -int(''.join(ls[1:])) else: for i in ls: if i < '0' or i > '9': return 0 return int(''.join(ls))
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 GetMedian(self, flag=True): # write code here self.ls.sort() n = len(self.ls) if n % 2 == 0: return (self.ls[n/2] + self.ls[n/2 -1]) / 2.0 else: return self.ls[n/2] # -*- coding:utf-8 -*- class SolutionHeap: """ 维护最大堆、最小堆,保证最大堆中的数小于最小堆中的所有数 插入复杂度O(logn), 得到中位数复杂度O(1) """ def __init__(self): self.max_heap = [] self.min_heap = [] def max_heapify(self): n = len(self.max_heap) k = n - 1 while k > 0 and self.max_heap[(k-1)/2] < self.max_heap[k]: self.max_heap[(k-1)/2], self.max_heap[k] = self.max_heap[k], self.max_heap[(k-1)/2] k = (k-1) / 2 def min_heapify(self): n = len(self.min_heap) k = n - 1 while k > 0 and self.min_heap[(k-1)/2] > self.min_heap[k]: self.min_heap[(k-1)/2], self.min_heap[k] = self.min_heap[k], self.min_heap[(k-1)/2] k = (k-1) / 2 def del_max(self): self.max_heap[0], self.max_heap[-1] = self.max_heap[-1], self.max_heap[0] val = self.max_heap.pop() k = 0 while 2*k + 1 < len(self.max_heap): j = 2*k + 1 if j + 1 < len(self.max_heap) and self.max_heap[j] < self.max_heap[j+1]: j += 1 if self.max_heap[k] < self.max_heap[j]: self.max_heap[k], self.max_heap[j] = self.max_heap[j], self.max_heap[k] k = j else: break return val def del_min(self): self.min_heap[0], self.min_heap[-1] = self.min_heap[-1], self.min_heap[0] val = self.min_heap.pop() k = 0 while 2*k + 1 < len(self.max_heap): j = 2*k + 1 if j + 1 < len(self.max_heap) and self.max_heap[j] > self.max_heap[j+1]: j += 1 if self.max_heap[k] > self.max_heap[j]: self.max_heap[k], self.max_heap[j] = self.max_heap[j], self.max_heap[k] k = j else: break return val def Insert(self, num): # write code here if len(self.min_heap) == 0: self.min_heap.append(num) self.min_heapify() return if (len(self.max_heap) + len(self.min_heap)) % 2 == 0: # 偶数插入最小堆 if num < self.max_heap[0]: a = self.del_max() self.max_heap.append(num) self.max_heapify() self.min_heap.append(a) self.min_heapify() else: self.min_heap.append(num) self.min_heapify() else: # 奇数插入最大堆 if num > self.min_heap[0]: a = self.del_min() self.min_heap.append(num) self.min_heapify() self.max_heap.append(a) self.max_heapify() else: self.max_heap.append(num) self.max_heapify() def GetMedian(self, flag=True): # write code here if (len(self.max_heap) + len(self.min_heap)) % 2 == 0: return (self.max_heap[0] + self.min_heap[0]) / 2.0 else: return self.min_heap[0] if __name__ == '__main__': solution = Solution() for i in range(5): solution.Insert(i) print(solution.GetMedian())
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 code here if pHead == None: return None if not pHead.next: return pHead temp = pHead.next if pHead.val == temp.val: # 头指针重复,找到第一个不重复的节点,递归 while temp and temp.val == pHead.val: temp = temp.next return self.deleteDuplication(temp) else: # 头指针不重复,直接递归下一个节点 pHead.next = self.deleteDuplication(pHead.next) return pHead
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_a, gcd_b + 1, lcm_a) if gcd_b % num == 0]) if __name__ == '__main__': input() # We don't need the first input arr = list(map(int, input().strip().split())) brr = list(map(int, input().strip().split())) total = getTotalX(arr, brr) print(total)
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 = d # return current_gcd if __name__ == "__main__": input = sys.stdin.read() a, b = map(int, input.split()) print(gcd_naive(a, b))
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): operations_count = [0] * (n + 1) operations_count[1] = 1 for i in range(2, n + 1): count_index = [i - 1] #the worst case where i have to add 1 all the time, so index of prev number if i % 2 == 0: count_index.append(i // 2) # steps to i//2 times +1, so index of i//2 if i % 3 == 0: count_index.append(i // 3) # steps to i//3 + 1, so index of i//3 operations_count[i] = min([operations_count[x] for x in count_index]) +1 # previous values are already counted. #so see which one is min and add 1 to it current_value = n intermed_numbers = [current_value] while current_value != 1: #until the value we are looking at is 1 option_list = [current_value - 1] #possibilty of coming from prev number if current_value % 2 == 0: #possibility of arriving from current_value//2 option_list.append(current_value // 2) if current_value % 3 == 0: #possibility of arriving from current_value//3 option_list.append(current_value // 3) current_value = min([(c, operations_count[c]) for c in option_list],key=lambda x: x[1])[0] #choose the one with min #operations as everything reaches to n with 1 step. intermed_numbers.append(current_value) return reversed(intermed_numbers) input = sys.stdin.read() n = int(input) sequence = list(dp_solution(n)) print(len(sequence) - 1) for x in sequence: print(x, end=' ')
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, print that it is palindrome string """ test_string = input('Enter any string:') print(test_string) # reverse string reverse_string = test_string[::-1] print(reverse_string) if test_string == reverse_string: print( test_string, 'is palindrome') else: print( test_string, 'is NOT a palindrome')
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] = frequency[each_char] + 1 except KeyError as ex: # print('No such key', ex) frequency[each_char] = 1 print(frequency) # Method 2 frequency = {} for each_char in sentence: frequency.setdefault(each_char, 0) # creates key with value 0, if key is not present frequency[each_char] = frequency[each_char] + 1 print(frequency) # Method 3 frequency = {} for each_char in sentence: if frequency.get(each_char): # key is present # frequency[each_char] = frequency[each_char] + 1 frequency[each_char] += 1 else: # key not present frequency[each_char] = 0 print(frequency) # Method 4 frequency = {} for each_char in sentence: # frequency[each_char] = frequency.get(each_char) + 1 # 'NoneType' and 'int' frequency[each_char] = frequency.get(each_char, 0) + 1 print(frequency) # ----------------------------- print() print(f"{sorted('abacus') =}") print(f"{sorted('322321') =}") print(f"{sorted([23,43,-2, 1]) =}") print(f"{sorted([23,43,-2, 1], reverse=True) =}") print() frequency1 = {'a': 3, 'b': 2, 'c': 2, 'd': 1} print(f'{frequency1 =}') print(f'{sorted(frequency1) =}') print(f'{sorted(frequency1.keys()) =}') print(f'{sorted(frequency1.values())=}') print() print(f'{sorted(frequency1.items()) =}') # default - sort by 0th value in pair print(f'{sorted(frequency1.items(), reverse=True) =}') print() print(f'{sorted(frequency1.items()) =}') print(f'{sorted(frequency1.items(), key=lambda x:x[0]) =}') # sort by key print(f'{sorted(frequency1.items(), key=lambda x:x[0], reverse=True) =}') # sort by key print(f'{sorted(frequency1.items(), key=lambda x:x[1]) =}') # sort by value print(f'{sorted(frequency1.items(), key=lambda x:x[1], reverse=True) =}') # sort by value frequency1_result = dict(sorted(frequency1.items(), key=lambda x:x[1], reverse=True)) print(frequency1_result) print(frequency1_result.keys()) print('Top 3 chars in frequecny are', list(frequency1_result.keys())[:3]) # Assignment # In character frequency analyses, try to get top 5 occurring characters sorted(frequency.items, key=lambda x:x[1])[-5:] ''' Assignment ========== choose a large sentence greater than 150 words and perform the following 1) character frequency analyses a) case sensitive { 'P': 1, 'y': 2, 't : 5 .... } b) case insensitive { 'p': 2, 'y': 2, 't : 5 ..... } HINT: str.lower() 2) word frequency analyses a) case sensitive b) case insensitive HINT: str.split() 3) cleansed_words frequency analyses HINT: string module -> string.punctuation a) case sensitive b) case insensitive '''
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!') # Method 2 # if given_number == LUCKY_NUMBER: # print('You Guessed Correctly!') # else: # print('Please Try Again!!') # Method 3 if given_number == LUCKY_NUMBER: print('You Guessed Correctly!') elif given_number > LUCKY_NUMBER: # 78 > 69 print('Please Try Again with reducing your guess number') elif given_number < LUCKY_NUMBER: # 34 < 69 print('Please Try Again with increasing your guess number') # NOTE: else block is optional in python
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("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) ################################################## if ((year % 4) == 0) and ((year % 100) == 0) and ((year % 400) == 0): print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) ################################################## if (not year % 4) and (not year % 100) and (not year % 400): # 0 0 0 print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) """ >>> >>> "{0} is a leap year".format('1998') '1998 is a leap year' >>> "{0} is a leap year".format(1998) '1998 is a leap year' >>> "{0} is a leap year".format(True) 'True is a leap year' >>> "{0} is a leap {2}year{1}".format(True, 'vishnu', 1652) 'True is a leap 1652yearvishnu' >>> """
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: # print(f'{ve =}') print('Denominator cant be zero') else: print(f'{division = }')
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_asyncio_ex.py:21: RuntimeWarning: coroutine 'asynchronous_hello' was never awaited print() loop = asyncio.get_event_loop() loop.run_until_complete(asynchronous_hello()) loop.close() print() asyncio.run(asynchronous_hello())
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 - age} years for voting') except InvalidAge as ex: print(str(ex)) except ValueError: print('Please enter valid age number') except Exception as ex: print('Unhandled Exception -', repr(ex)) else: print('Eligible for voting!!!')
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 server name:') # # Method 3: sys.argv # import sys # print('sys.argv = ', sys.argv) # assert sys.argv[0] == __file__ # # help # if len(sys.argv) != 4: # print('Help:') # print(f'{__file__} username password server_fqdn') # sys.exit(1) # # user_name = sys.argv[1] # # password = sys.argv[2] # # server_name = sys.argv[3] # # unpacking # user_name, password, server_name = sys.argv[1:] # Method 4: argparse import argparse parser = argparse.ArgumentParser( description="Details to login to server", epilog='-----Please follow help doc ----') # description: for the text that is shown before the help text # epilog: for the text shown after the help text parser.add_argument('-u', '--username', help='login user name', type=str, required=True) parser.add_argument('-p', '--password', help='login password', type=str, required=True) parser.add_argument('-s', '--servername', help='server name', type=str, default='www.google.com', required=False) args = parser.parse_args() user_name = args.username password = args.password server_name = args.servername print(f''' The server login details are: USER NAME : {user_name} PASSWORD : {password} SERVER NAME : {server_name} ''')
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 = age def display_age(self): # instance methods print('Person age is %d' % self.age) def enter_name(self, name): # instance methods self.name = name def display_name(self): # instance methods print('Person name is ' + self.name) p = Person() print(dir(p)) p.display_age() p.enter_age(23) p.display_age() p.display_name() p.enter_name('Ramesh') p.display_name() print callable(p.age) print callable(p.display_age)
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, type(hard_copy_list), id(par_list) print 'par_list[2]', par_list[2] par_list[2] = 'THREE 3' print 'par_list[2]', par_list[2] print 'par_list ', par_list, type(par_list) # leakage problem print 'hard_copy_list', hard_copy_list, type(hard_copy_list) print import copy soft_copy_list = copy.copy(par_list) print 'soft_copy_list ', soft_copy_list, type(soft_copy_list), id(soft_copy_list) print 'hard_copy_list[3]', hard_copy_list[3] hard_copy_list[3] = "FOUR" print print 'par_list ', par_list, type(par_list), id(par_list) print 'hard_copy_list ', hard_copy_list, type(hard_copy_list), id(hard_copy_list) print 'soft_copy_list ', soft_copy_list, type(soft_copy_list), id(soft_copy_list) print 'soft_copy_list[0]', soft_copy_list[0] soft_copy_list[0] = 'ZERO' print print 'par_list ', par_list, type(par_list), id(par_list) print 'hard_copy_list ', hard_copy_list, type(hard_copy_list), id(hard_copy_list) print 'soft_copy_list ', soft_copy_list, type(soft_copy_list), id(soft_copy_list) print '='* 80 new_list = [90, 89, [78, 89, [4, 441, 6]]] new_softcopy_list = copy.copy(new_list) new_deepcopy_list = copy.deepcopy(new_list) print 'new_list ', new_list, type(new_list), id(new_list) print 'new_softcopy_list ', new_softcopy_list, type(new_softcopy_list), id(new_softcopy_list) print 'new_deepcopy_list ', new_deepcopy_list, type(new_deepcopy_list), id(new_deepcopy_list) print 'new_list[2][2][1]', new_list[2][2][1] new_list[2][2][1] = 'FFO' print print 'new_list ', new_list, type(new_list), id(new_list) print 'new_softcopy_list ', new_softcopy_list, type(new_softcopy_list), id(new_softcopy_list) print 'new_deepcopy_list ', new_deepcopy_list, type(new_deepcopy_list), id(new_deepcopy_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('bytearray(range(10)) ', bytearray(range(10))) # Copying existing binary data via the buffer protocol: print("bytearray(b'Hi!')", bytearray(b'Hi!')) ########################################## # hex to bytearray print(" bytearray.fromhex('2Ef0 F1f2 ')", bytearray.fromhex('2Ef0 F1f2 ')) # bytearray to hex print("bytearray(b'\xf0\xf1\xf2').hex()", bytearray(b'\xf0\xf1\xf2').hex()) ############################################ # b = bytearray('python') # TypeError: string argument without an encoding b = bytearray('python', 'utf-8') b = bytearray(b'python') print(b, type(b)) # b[0] will be an integer, print(b[0], type(b[0])) # while b[0:1] will be a bytearray object of length 1 print(b[0:1], type(b[0:1]))
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)', type(numbers) print 'dir(numbers)=', dir(numbers) print "len(numbers)=", len(numbers) print "numbers.__len__()=", numbers.__len__() print len(numbers) == numbers.__len__() # True print "str(numbers) =", str(numbers) print "type(str(numbers)) =", type(str(numbers)) print "numbers.__str__() =", numbers.__str__() print "type(numbers.__str__())=", type(numbers.__str__()) # print "help(numbers)=", help(numbers) print "numbers.__doc__=", numbers.__doc__ print "numbers * 3 =", numbers * 3 # original object not modified print 'numbers =', numbers print "numbers.__imul__(3) =", numbers.__imul__(3) # original object IS modified print 'numbers =', numbers print "id(numbers)=", id(numbers) # object overwriting numbers = [88, 99, 666] print "id(numbers)=", id(numbers) # list concatenation print 'numbers\t\t\t\t=', numbers alphabets = ['b', 'c'] print "numbers + alphabets\t\t=", numbers + alphabets print 'numbers\t\t\t\t=', numbers print "numbers.__add__(alphabets)\t=", numbers.__add__(alphabets) print 'numbers\t\t\t\t=', numbers # list concatenation will create new obect; # orginal objects are not changed print "numbers.__iadd__(alphabets)\t=", numbers.__iadd__(alphabets) print 'numbers\t\t\t\t=', numbers # first object IS changed print "numbers.__contains__(12) =", numbers.__contains__(12) print "12 in numbers =", 12 in numbers print numbers.__sizeof__() # # print help(numbers.__sizeof__())
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, arg)) else: return fn(arg) return newfn @elementwise def compute(x): return x**3 - 1 print compute(5) # prints: 124 print compute([1,2,3]) # prints: [0, 7, 26] print compute((1,2,3)) # prints: (0, 7, 26)
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', type=float, default=0) parser.add_argument('-b', help='Second value', type=float, required=True) parser.add_argument('-c', help='Third value', type=int) args = parser.parse_args() print 'type(args.a)', type(args.a) print 'type(args.b)', type(args.b) print 'type(args.c)', type(args.c) print(main(args.a, args.b, args.c))
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 = PorterStemmer() lz = WordNetLemmatizer() words = ['child', 'children', 'childhood', 'childs', 'indetify'] for word in words: print(f"{word:12}: {ps.stem(word)}") print(f"{word:12}: {lz.lemmatize(word)}\n")
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("type(str(mytuple)) =", type(str(mytuple))) print("mytuple.__str__() =", mytuple.__str__()) print("type(mytuple.__str__())=", type(mytuple.__str__())) assert str(mytuple) == mytuple.__str__() # Tuple repetition operation - original object not modified print() print("mytuple * 3 =", mytuple * 3) print('mytuple =', mytuple) print("mytuple.__mul__(3) =", mytuple.__mul__(3)) print('mytuple =', mytuple) print('\n Tuple Attributes excluding dunder methods') for each_attribute in dir(mytuple): if not each_attribute.startswith('__'): print(each_attribute) print('mytuple =', mytuple) print('mytuple.count(5) =', mytuple.count(5)) mytuple = (12, 5, 6, 8, (5)) # 0 1 2 3 4 print('mytuple =', mytuple) print('mytuple.count(5) =', mytuple.count(5)) print() print('mytuple.index(8) =', mytuple.index(8)) print('mytuple.index(5) =', mytuple.index(5)) try: print('mytuple.index(55) =', mytuple.index(55)) except ValueError as ex: print(ex)
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("World") c = coro() print('c', c) # All coroutines must be "primed" by first calling .next() (or send(None)) print(next(c)) print(c.send("World")) try: c.throw(RuntimeError,"I am throwing exception") except RuntimeError as ex: print(ex) # closing(shutdown) a coroutine c.close() # garbage collection too calls .close() # close() can be catched by GeneratorExit Exception
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 myNumber += 1 # myNumber = myNumber + 1 print 'myNumber = ', myNumber newNumber = 56 myNumber += newNumber + 1 # myNumber = myNumber + newNumber + 1 print 'myNumber = ', myNumber myNumber -= 58 # myNumber = myNumber - 58 print 'myNumber = ', myNumber myNumber *= 100 # myNumber = myNumber * 100 print 'myNumber = ', myNumber myNumber /= 10 # myNumber = myNumber / 10 print 'myNumber = ', myNumber myNumber %= 10 # myNumber = myNumber % 10 print 'myNumber = ', myNumber # python dosnt support unary operations ; ++i, i++, --i, i-- # it should used as i += 1, i -=1 print '-----------------------------------------------' print 'bitwise Operations' # >> << myNewNumber = 4 print 'myNewNumber =', myNewNumber myNewNumber <<= 1 # myNewNumber = myNewNumber << 1 print 'myNewNumber = ', myNewNumber # 8 4 2 1 # 4 0 1 0 0 = 0 * 8 + 1 * 4 + 0 * 2 + 0 * 1 = 4 # << 1 0 0 0 # 13 1 1 0 1 # 7 0 1 1 1 # 15 1 1 1 1 result = 14 >> 2 print "14 >> 2 = ", result # 8 4 2 1 # 14 1 1 1 0 # >>2 0 0 1 1 result = 3 << 2 print "3 << 2 = ", result # 8 4 2 1 # 3 0 0 1 1 # <<2 1 1 0 0 => 12 calculated_result = 10 << 4 print '10 << 4', calculated_result # 128 64 32 16 8 4 2 1 # 10 1 0 1 0 # 1 0 1 0 1st shift # 1 0 1 0 2nd shift # 1 0 1 0 3rd shift # 1 0 1 0 4th shift
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)