blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
1fcd42c435dbb422aaa1b5e70dcd5eaf2cad6853 | pdspatrick/IT310-Code | /labs/minheightBST.py | 806 | 3.953125 | 4 | class TreeNode:
'''Node for a simple binary tree structure'''
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def min_height_BST(alist):
'''Returns a minimum-height BST built from the elements in alist (which are in sorted order)'''
... |
7e19abc5efaf17e647805596b81bf9be3f3c1ea3 | Thamaraiselvimurugan/python | /upplwr.py | 312 | 3.96875 | 4 | def upplow(a):
up=0
lw=0
for i in range(len(a)):
if a[i].isupper():
up=up+1
if a[i].islower():
lw=lw+1
print("No. of uppercase is ="+str(up))
print("No. of lowercase is="+str(lw))
a=raw_input("Enter a string")
upplow(a) |
0cc2311e0b09f3055b6e85921c3c53f8a1a474f5 | JakeVidal/ECE-441-project | /number_format.py | 401 | 3.8125 | 4 | input_value = float(input("enter a decimal value: "))
output_value = "00"
adjustment = "0000000000000001"
post_decimal = input_value
for i in range(0, 14):
temp = post_decimal
post_decimal = temp*2 - int(temp*2)
temp = temp*2
output_value = output_value + str(int(temp))
output_value = int(output_val... |
7c6a6f84e2240e40c9593283083457ff27d78e7f | MiWerner/rAIcer | /Clients/Python-rAIcer-Client/MatrixOps.py | 6,900 | 3.53125 | 4 | import numpy as np
import math
def multidim_intersect(arr1, arr2):
"""
Finds and returns all points that are present in both arrays
:param arr1: the first array
:param arr2: the second array
:return: an array of all points that are present in both arrays
"""
# Remove third dimension from t... |
f53dec941f3422e8731285a1f3a375ea45121c41 | ifeedtherain/Python_Stepik | /02-07_stringm.py | 244 | 3.515625 | 4 | s = str(input())
t = str(input())
cnt = 0
def cnt_occur(s, t, cnt):
i = -1
while True:
i = s.find(t, i+1)
if i == -1:
return cnt
cnt += 1
if t in s:
print(cnt_occur(s,t, cnt))
else:
print(cnt) |
b367f9a09739b87aef87a011a5e9454b87c3b6fe | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 4/Tuplas.py | 338 | 4.09375 | 4 | tupla = (100, "Hola", [1, 2, 3], -50)
for dato in tupla:
print(dato)
# Funciones de tuplas
print("La cantidad de datos que tiene esta posicion (Solo si son listas) en la tupla es :",len(tupla[1]))
print("El índice del valor 100 es :", tupla.index(100))
print("El índice del valor 'Hola' es :", tupla.index("Hola")... |
eb65ff92ef8086781e3657ca6f543dc2edadc228 | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 4/Listas.py | 737 | 4.21875 | 4 | numeros = [1, 2, 3, 4, 5]
datos = [5, "cadena", 5.5, "texto"]
print("Numeros", numeros)
print("Datos", datos)
# Mostramos datos de la lista por índice
print("Mostramos datos de la lista por índice :", datos[-1])
# Mostramos datos por Slicing
print("Mostramos datos por Slicing :", datos[0:2])
# Suma de Listas
listas... |
5d86707b669cf0fcf7c822473de137649d5a228e | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 8/MetodosEspeciales.py | 669 | 3.84375 | 4 | class Pelicula:
# Contructor de la clase
def __init__(self, titulo, duracion, lanzamiento):
self.titulo = titulo
self.duracion = duracion
self.lanzamiento = lanzamiento
print("Se creó la película", self.titulo)
# Destructor de la lcase
def __del__(self):
print(... |
745b9f249e9c21f26fc2a4c9f04f4aa604c2293e | valerocar/geometry-blender | /gblend/geometry.py | 10,000 | 4.1875 | 4 | """
Geometry classes
"""
from gblend.variables import x, y, z, rxy
from sympy.algebras.quaternion import Quaternion
from sympy import symbols, cos, sin, sqrt, N, lambdify, exp
def sigmoid(s, k):
"""
The sigmoid function.
:param s: independent variable
:param k: smoothing parameter
:return:
""... |
e129e980c58a0c812c96d4d862404361765cbaa6 | rafiqulislam21/python_codes | /serieWithValue.py | 660 | 4.1875 | 4 | n = int(input("Enter the last number : "))
sumVal = 0
#avoid builtin names, here sum is a built in name in python
for x in range(1, n+1, 1):
# here for x in range(1 = start value, n = end value, 1 = increasing value)
if x != n:
print(str(x)+" + ", end =" ") #this line will show 1+2+3+............
#... |
33d35100498e40f3e2e2b175bb08908764795180 | Ascarik/Checkio | /Scientific_Expedition/14.py | 1,256 | 3.71875 | 4 | import re
def checkio(line: str) -> int:
# your code here
gl = ('A', 'E', 'I', 'O', 'U', 'Y')
sl = ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z')
line = line.upper()
line = re.sub("[.,!?]", " ", line)
words = line.split(sep=" ")
count ... |
5fe9f18569a4428aaa121c5090e53b65b820900b | Ascarik/Checkio | /home/21.py | 733 | 3.859375 | 4 | from collections.abc import Iterable
def duplicate_zeros(donuts: list[int]) -> Iterable[int]:
# your code here
l = list()
for v in donuts:
if v == 0:
l += [0, 0]
else:
l.append(v)
return l
print("Example:")
print(list(duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0]))... |
6b0e7d8b19429a89e3efb5e3fd1ed23a01cb08a4 | Ascarik/Checkio | /Scientific_Expedition/2.py | 871 | 3.671875 | 4 | def yaml(a):
# your code here
result = {}
list_values = a.split("\n")
for value in list_values:
if not value:
continue
key, value = value.split(":")
key, value = key.strip(), value.strip()
if value.isnumeric():
value = int(value)
result[key... |
222fde26ceeabe38f9af3ff6da73fa3328a0ce44 | idrishkhan/IDRISHKHAN | /idrish 10.py | 71 | 3.546875 | 4 | x=int(input())
count=0
while(x>1):
x=x/10
count=count+1
print(count)
|
f390a3bee6b5ef187a5c8ab9c60091cb289862bb | MatusMaruna/Transformers | /4DV507.rd222dv.A4/ofp_example_programs/while.py | 182 | 3.625 | 4 | def sumUpTo(n):
i=1
ofp_sum=0
while i<n+1:
ofp_sum=ofp_sum+i
i=i+1
return ofp_sum
#
# Program entry point - main
#
n=10
res=sumUpTo(n)
print(res)
|
378377ffb254db27a2e823bd282124a63dfba06c | mmore500/conduit | /tests/netuit/arrange/scripts/make_ring.py | 772 | 3.671875 | 4 | #!/usr/bin/python3
"""
Generate ring graphs.
This script makes use of NetworkX to generate
ring graphs (nodes are connected in a ring).
This tool creates adjacency list files (.adj)
whose filename represent the characteristics
of the graph created.
"""
from keyname import keyname as kn
import networkx as nx
dims = ... |
407ae0b9bd3004e0655b747f9f5ffda563ae8cae | anooptrivedi/workshops-python-level2 | /list2.py | 338 | 4.21875 | 4 | # Slicing in List - more examples
example = [0,1,2,3,4,5,6,7,8,9]
print(example[:])
print(example[0:10:2])
print(example[1:10:2])
print(example[10:0:-1]) #counting from right to left
print(example[10:0:-2]) #counting from right to left
print(example[::-3]) #counting from right to left
print(example[:5:-1]) #counting ... |
ca7c8607e41db501f958a746028fb28040133d54 | anooptrivedi/workshops-python-level2 | /guessgame.py | 460 | 4.125 | 4 | # Number guessing game
import random
secret = random.randint(1,10)
guess = 0
attempts = 0
while secret != guess:
guess = int(input("Guess a number between 1 and 10: "))
attempts = attempts + 1;
if (guess == secret):
print("You found the secret number", secret, "in", attempts, "attempts")
... |
c5dae743955e135a879799766903fe1e9a6d4b1f | abhinavk99/rubik-solver | /src/solver.py | 8,055 | 3.546875 | 4 | from tkinter import Tk, Label, Button, Canvas, StringVar, Entry
from cube import Cube
class RubikSolverGUI:
def __init__(self, master):
"""Creates the GUI"""
self.master = master
master.title('Rubik Solver')
self.label = Label(master, text='Rubik Solver')
self.label.pack()
... |
00fb14c2e66e3c49102c223d3ec95266ab15cd2d | drvinceknight/agent-based-learn | /ablearn/population/agents.py | 593 | 3.875 | 4 | class Agent:
"""
A generic class for agents that will be used by the library
"""
""" INITIALIZATION """
def __init__(self, strategies=False, label=False): # The properties each agent will have.
self.strategies = strategies # Strategy the agent will use.
self.utility = 0 # Utility th... |
ab8cacb11a83b66b3754303ddbd8b8532130f590 | igoreduardo/teste_python_junior | /teste_1240.py | 217 | 3.515625 | 4 | ncasos = int(input())
while ncasos > 0:
a,b = list(input().split())
if (len(a) >= len(b)):
if a[-len(b):] == b:
print("encaixa")
else:
print("não encaixa")
else:
print('')
ncasos -=1
|
1325e94c27e1a70f6ccaa8d12ab54900a351504e | harshajk/advent-of-code-2020 | /day01.py | 1,103 | 3.53125 | 4 | import unittest
import itertools
def day1p1(filename):
f = open(filename, "r")
entries = [int(ent) for ent in set(f.read().split("\n"))]
for ent in entries:
reqrd = 2020 - ent
if reqrd in entries:
f.close()
return reqrd * ent
return -1
def d... |
4d4336b3a33831a4a0f48faa84051ba3233aba0e | ppnbb/Python | /list.py | 119 | 3.5 | 4 | s = [1, 'four', 9, 16, 25]
print(s)
print(s[0])
print(len(s))
s[1] = 4
print(s)
del s[2]
print(s)
s.append(36)
print(s) |
f7c99be0a3edde23c91d40edbe184d7f7f6a89ca | INFOPAUL/DeepLearning_Proj2 | /activations/Tanh.py | 838 | 3.59375 | 4 | from Module import Module
class Tanh(Module):
"""Applies the element-wise function:
Tanh(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)} {\exp(x) + \exp(-x)}
Shape
-----
- Input: `(N, *)` where `*` means, any number of additional dimensions
- Output: `(N, *)`, same shape as the input
... |
4047cddfa36d495357e8cbe9d890406446c888ae | INFOPAUL/DeepLearning_Proj2 | /weight_initialization/xavier_uniform.py | 662 | 4 | 4 | import math
def xavier_uniform(tensor):
"""Fills the input tensor with values according to the method
described in `Understanding the difficulty of training deep feedforward
neural networks` - Glorot, X. & Bengio, Y. (2010), using a uniform
distribution. The resulting tensor will have values sampled f... |
21947c14f2c2f197853704ac0fad4f42022be6d4 | x4nth055/pythoncode-tutorials | /machine-learning/image-transformation/reflection.py | 934 | 3.5625 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
# read the input image
img = cv2.imread("city.jpg")
# convert from BGR to RGB so we can plot using matplotlib
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# disable x & y axis
plt.axis('off')
# show the image
plt.imshow(img)
plt.show()
# get the image shape
... |
a1b6068223e0aaaab6976e0c06c48171254c3fbc | x4nth055/pythoncode-tutorials | /python-standard-library/using-threads/multiple_threads_using_threading.py | 1,561 | 3.609375 | 4 | import requests
from threading import Thread
from queue import Queue
# thread-safe queue initialization
q = Queue()
# number of threads to spawn
n_threads = 5
# read 1024 bytes every time
buffer_size = 1024
def download():
global q
while True:
# get the url from the queue
url = q.get()
... |
650fae3372e044e73b1bed85128889758ae1f885 | x4nth055/pythoncode-tutorials | /machine-learning/shape-detection/circle_detector.py | 1,117 | 3.59375 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import sys
# load the image
img = cv2.imread(sys.argv[1])
# convert BGR to RGB to be suitable for showing using matplotlib library
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# make a copy of the original image
cimg = img.copy()
# convert image to grayscale
... |
4cb9aea7093ea178b506ef4b522e6c8fd7bf7444 | x4nth055/pythoncode-tutorials | /python-standard-library/logging/logger_handlers.py | 630 | 3.609375 | 4 | import logging
# return a logger with the specified name & creating it if necessary
logger = logging.getLogger(__name__)
# create a logger handler, in this case: file handler
file_handler = logging.FileHandler("file.log")
# set the level of logging to INFO
file_handler.setLevel(logging.INFO)
# create a logger format... |
b579ca7d200ccf359ddaddbfc63bcb2523f0b3ab | x4nth055/pythoncode-tutorials | /machine-learning/image-transformation/translation.py | 768 | 3.65625 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
# read the input image
img = cv2.imread("city.jpg")
# convert from BGR to RGB so we can plot using matplotlib
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# disable x & y axis
plt.axis('off')
# show the image
plt.imshow(img)
plt.show()
# get the image shape
... |
a36caeefcb4d3981e146ec5be64caae06d2d8e39 | x4nth055/pythoncode-tutorials | /general/simple-math-game/simple_math_game.py | 1,015 | 3.953125 | 4 | # Imports
import pyinputplus as pyip
from random import choice
# Variables
questionTypes = ['+', '-', '*', '/', '**']
numbersRange = [num for num in range(1, 20)]
points = 0
# Hints
print('Round down to one Number after the Comma.')
print('When asked to press enter to continue, type stop to stop.\n')
# Game Loop
whi... |
556a1ee02b0e41c666f2ded73fe84d46d177ccd0 | x4nth055/pythoncode-tutorials | /ethical-hacking/ftp-cracker/simple_ftp_cracker.py | 1,153 | 3.5625 | 4 | import ftplib
from colorama import Fore, init # for fancy colors, nothing else
# init the console for colors (for Windows)
init()
# hostname or IP address of the FTP server
host = "192.168.1.113"
# username of the FTP server, root as default for linux
user = "test"
# port of FTP, aka 21
port = 21
def is_correct(passw... |
4eaba11433ea548d2f95f8e5515c1b2c5bfaf3ce | x4nth055/pythoncode-tutorials | /gui-programming/chess-game/data/classes/Piece.py | 1,897 | 3.6875 | 4 | import pygame
class Piece:
def __init__(self, pos, color, board):
self.pos = pos
self.x = pos[0]
self.y = pos[1]
self.color = color
self.has_moved = False
def move(self, board, square, force=False):
for i in board.squares:
i.highlight = False
if square in self.get_valid_moves(board) or force:
... |
5c420b7d6d0efc40dcff469f8a130259aff0ac75 | x4nth055/pythoncode-tutorials | /python-standard-library/print-variable-name-and-value/print_variable_name_and_value.py | 153 | 4.0625 | 4 | # Normal way to print variable name and value
name = "Abdou"
age = 24
print(f"name: {name}, age: {age}")
# using the "=" sign
print(f"{name=}, {age=}")
|
6b6dd3b2a888029cf3f1e9dd43f9710421778b8d | x4nth055/pythoncode-tutorials | /gui-programming/currency-converter-gui/currency_converter.py | 4,166 | 3.59375 | 4 | # importing everything from tkinter
from tkinter import *
# importing ttk widgets from tkinter
from tkinter import ttk
import requests
# tkinter message box for displaying errors
from tkinter.messagebox import showerror
API_KEY = 'put your API key here'
# the Standard request url
url = f'https://v6.exchangerate-api.... |
96ec108cb0ac2c756220ac07685f16e393ef7706 | x4nth055/pythoncode-tutorials | /general/url-shortener/cuttly_shortener.py | 589 | 3.5625 | 4 | import requests
import sys
# replace your API key
api_key = "64d1303e4ba02f1ebba4699bc871413f0510a"
# the URL you want to shorten
url = sys.argv[1]
# preferred name in the URL
api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}"
# or
# api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}&... |
2dbadce9d4d45885537755e69599f7774af7142a | x4nth055/pythoncode-tutorials | /gui-programming/platformer-game/world.py | 4,383 | 3.5625 | 4 | import pygame
from settings import tile_size, WIDTH
from tile import Tile
from trap import Trap
from goal import Goal
from player import Player
from game import Game
class World:
def __init__(self, world_data, screen):
self.screen = screen
self.world_data = world_data
self._setup_world(world_data)
self.world_... |
78ce0accceb722296ce623a1887aba4c258145a4 | x4nth055/pythoncode-tutorials | /general/mouse-controller/control_mouse.py | 1,004 | 3.75 | 4 | import mouse
# left click
mouse.click('left')
# right click
mouse.click('right')
# middle click
mouse.click('middle')
# get the position of mouse
print(mouse.get_position())
# In [12]: mouse.get_position()
# Out[12]: (714, 488)
# presses but doesn't release
mouse.hold('left')
# mouse.press('left')
# drag from (0,... |
c2f3c2f4f9e5f4d6fcba4789bdcfcb0982167d1b | x4nth055/pythoncode-tutorials | /general/video-to-audio-converter/video2audio_moviepy.py | 457 | 3.5 | 4 | import os
import sys
from moviepy.editor import VideoFileClip
def convert_video_to_audio_moviepy(video_file, output_ext="mp3"):
"""Converts video to audio using MoviePy library
that uses `ffmpeg` under the hood"""
filename, ext = os.path.splitext(video_file)
clip = VideoFileClip(video_file)
clip.a... |
502aeeb7cc94fca111d0597f863a2d09528a525a | aravind9643/Python_Programs | /Aravind/Practice_2_14112018.py | 428 | 3.703125 | 4 | #String Handling methods
s1 = "aravind"
s2 = "Aravind"
s3 = "ARAVIND"
s4 = " "
s5 = "A5"
s6 = " Aravind "
print "Upper : ",s1.upper()
print "Lower : ",s2.lower()
print "Capitalize",s1.capitalize()
print "Is Upper : ",s3.isupper()
print "Is Lower : ",s1.islower()
print "Is Space : ",s4.isspace()
print "Is Alpha : ... |
25b8baaafb486e6018eb9290bbddfa67740cb882 | aravind9643/Python_Programs | /Aravind/Practice_3_14112018.py | 77 | 3.875 | 4 | #String Operations (Slicing)
str = "Aravind"
print str[1:5]
print str[-6:-2] |
2b96b7dd86cc485189f87f81fae1f875f3c76d19 | swaraj1999/python | /chap 3 if_and_loop/for_loop_string.py | 293 | 3.640625 | 4 | # for i in range(len(name)):
# print(name(i)) #old process
name="swaraj"
for i in name:
print(i) #python
#1256= 1+2+5+6
num=input("enter name ::")
total=0
for i in num:
total+=int(i)
print(total) #python spl |
4ecfc694f1652d1f3ecc2b3cc6addff325126ab8 | swaraj1999/python | /chap 3 if_and_loop/exercise6.py | 313 | 4.0625 | 4 | #ask user for name and age,if name starts with (a or A) and age is above 10 can watch mpovie otherwise sorry
name,age=input("enter \t name \n \t age ((separated by space)::").split()
age=int(age)
if (age>=10) and (name[0]=='a' or name[0]=='A'):
print("you can watch movie")
else:
print("sorry") |
1d68a3df1eabd82b222b90a1ce2ef85556cff033 | swaraj1999/python | /chap 2 string/more_inputs_in_one_line.py | 514 | 3.9375 | 4 | #input more than one input in one line
name,age= input("enter your name and age(separated by space)").split() #.split splits the string in specific separator and returns a list
print(name)
print (age)
#during giving name and age,a space will be provided into name and age,other wise it will be error,swaraj19 will n... |
be1df6b6d7690e3e55bf9a7c50b7d496707c22fa | swaraj1999/python | /chap 7 dictionary/more.py | 304 | 3.9375 | 4 | # more about get method
user={'name':'swaraj','age':19}
print(user.get('names','not found')) # it will print not found instead of none cz names is not key,other wise print value
#more than two same keys
user={'name':'swaraj','age':19,'age':12} # it will overwrite 12
print(user)
|
06d831bdfe88c48846a0230006e81c439890eeb2 | swaraj1999/python | /chap 2 string/variable_more.py | 253 | 3.75 | 4 | # taking one or more variables in one line
name, age=" swaraj","19" #dont take 19, take 19 as string "19",otherwise it will give error
print("hello " + name + " your age is " + age) # hello swaraj your age is 19
XX=YY=ZZ=1
print(XX+YY+ZZ)
#ANS 3
|
8f8e8651d25ac8333692a5aa18bc26589f3fefe4 | swaraj1999/python | /chap 8 set/set_intro.py | 1,092 | 4.1875 | 4 | # set data type
# unordered collection of unique items
s={1,2,3,2,'swaraj'}
print(s) # we cant do indexing here like:: s[1]>>wrong here,UNORDERED
L={1,2,4,4,8,7,0,9,8,8,0,9,7}
s2=set(L) # removes duplicate,unique items only
print(s2)
s3=list(set(L))
print(s3) ... |
4b4ced98150d913d22ec9ce39a21f21dcdd8faa8 | swaraj1999/python | /chap 7 dictionary/in_itterations.py | 889 | 4.03125 | 4 | # in keyword and iterations in dictionary
user_info = {
'name':'swaraj',
'age':19,
'fav movies':['ggg','hhh'],
'fav tunes':['qqq','www'],
}
# check if key in dictionary
if 'name' in user_info: # check any key word
print('present')
else:
print('not present')
# check i... |
15c3309d2d94b809fccc1c1aaaa0cd66cdfd3954 | swaraj1999/python | /chap 4 function/exercise11.py | 317 | 4.375 | 4 | # pallindrome function like madam,
def is_pallindrome(name):
return name == name[::-1]
#if name == reverse of name
# then true,otherwise false
# print(is_pallindrome(input("enter name"))) #not working for all words
print(is_pallindrome("horse")) #working for all words |
aa200cf39c63f65b74bf0490391a048be026dc6f | swaraj1999/python | /chap 5 list/function.py | 226 | 3.796875 | 4 | #min and max function
numbers=[6,60,2]
def greatest_diff(l):
return max(l)-min(l)
print(greatest_diff(numbers)) #print diff of two no
print(min(numbers)) # min
print(max(numbers)) #max |
5334cf3288c199a6f4d943541d318a14e6ad1d56 | fsandhu/qrCode-gen | /main.py | 1,042 | 3.609375 | 4 | __author__ = "Fateh Sandhu"
__email__ = "fatehkaran@huskers.unl.edu"
"""
Takes in a weblink or text and converts it into qrCode using a GUI
Built using Tkinter library.
"""
import sys
import tkinter as tk
import qrcode as qr
from PIL import Image
from tkinter import messagebox
qrCode = qr.make("welcome")
qrCode.sa... |
36a7847a50d3af04b66455750f93a9a731db9c4b | raullopezgonzalez/Artificial-Intelligence | /Lab5/src/pca_utils.py | 1,899 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def toy_example_pca():
rng = np.random.RandomState(1)
X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T
# do the plotting
plt.scatter(X[:, 0], X[:, 1])
plt.xlabel('$x_1$', fontsize... |
6443de5f4faef205aa7cb2b213f262b625cea272 | chelosilvero78/small-projects | /exercises-python/AutomateTheBoringStuff/ch9-3-1b.py | 1,791 | 3.734375 | 4 | ###Automate tbs.
'''
Filling in the Gaps
Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files t... |
d0beb6ea25578dadd9859a79955980e6f42f0436 | chelosilvero78/small-projects | /small-projects-python/ClearDone-3.py | 1,652 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created 4/19/17, 11:34 AM
@author: davecohen
Title: Clear Done
Input: text file that has lines that begin with 'x ' (these are done files)
Output: text file that moves those lines to the end of the file with date stamp at top.
USAGE:
Run file with terminal - copy y... |
f586137284403932a921fe86453e8894c40fcc17 | chelosilvero78/small-projects | /exercises-python/MIT-6-0001/tests-hangman2.py | 2,906 | 3.546875 | 4 | '''
testing helper functions before committing to main file
'''
from hangman_no_hints import *
wordlist = load_words()
def reduceList(myList, num):
return [word for word in wordlist if len(word) == num]
# print('>>> reduceList tests')
# print(reduceList(wordlist, 2))
# print(reduceList(wordlist, 3))
# print(red... |
424325f5f0d12aaf1de6c1ed351cf647e63de4d7 | chelosilvero78/small-projects | /small-projects-python/Game-Hangman-3.py | 2,228 | 3.625 | 4 | #pythontemplate
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 3/1/17, 12:31 PM
@author: davecohen
Title: Hangman
===TODO
able to restart the game?
word list
graphics
"""
############
###GAME SETUP
############
import re
import getpass
#Word is prompted by non-game player. This may only work in bash t... |
924837c49470fc6971c1593e5f09712409368779 | chelosilvero78/small-projects | /notes-python/PythonForEverybody/10-tuples.py | 3,055 | 3.953125 | 4 | #python3
print('Ch10.1 -\nTuples are immutable')
t_no = 'a', 'b', 'c', 'd', 'e'
t_paren = ('a', 'b', 'c', 'd', 'e')
print(t_no == t_paren)
print(t_no is t_paren)
t1 = ('a',)
print(type(t1))
s1 = ('a')
print(type(s1),'<-always include the final comma in a tuple of len 1!')
t_emp = tuple()
print(t_emp)
t_lup = tuple('lup... |
6d08454da7f8c3b15ec404505a6b77b9192e570e | breschdleng/Pracs | /fair_unfair_coin.py | 1,307 | 4.28125 | 4 | import random
"""
Given an unfair coin, where probability of HEADS coming up is P and TAILS is (1-P), implement a fair coin from the given unfair coin
Approach: assume an unfair coin that gives HEADS with prob 0.3 and TAILS with 0.7. The objective is to convert this
to a fair set of probabilities of 0.5 each
Solution... |
c841e0852e4f1874f392065d0a21b32dfe9262e4 | AndrewZhang1996/DFSandBFS | /node.py | 347 | 3.546875 | 4 | class node():
def __init__(self, name, hasPrevious, hasNext):
self.name = name
self.previous = None
self.next = None
self.hasPrevious = hasPrevious
self.hasNext = hasNext
def set_previous(self, _previous):
if self.hasPrevious==1:
self.previous = _previous
def set_next(self, _next):
if self.hasNex... |
5b6fc5dbfa1e7d85d4c80642ecb2822c23d5a6be | ShainaJordan/thinkful_lessons | /fibo.py | 282 | 4.15625 | 4 | #Define the function for the Fibonacci algorithm
def F(n):
if n < 2:
return n
else:
print "the function is iterating through the %d function" %(n)
return (F(n-2) + F(n-1))
n = 8
print "The %d number in the Fibonacci sequence is: %d" %(n, F(n)) |
556ba64f9a8ac34fae4876547d44e2d990582742 | DL-py/python-notebook | /001基础部分/015函数.py | 1,548 | 4.34375 | 4 | """
函数:
"""
"""
函数定义:
def 函数名(参数):
代码
"""
"""
函数的说明文档:
1.定义函数说明文档的语法:
def 函数名(参数):
""" """内部写函数信息
代码
2.查看函数的说明文档方法:
help(函数名)
"""
# 函数说明文档的高级使用:
def sum_num3(a, b):
"""
求和函数sum_num3
:param a:参数1
:param b:函数2
:return:返回值
"""
return a + b
"""
返回值:可以返回多个值(默认是元组),也可以返回列表、字典、集合等
"""... |
85d74879093a2041af2b2457d8f144a0df9e4bb5 | DL-py/python-notebook | /001基础部分/006元组.py | 230 | 3.78125 | 4 | """
元组:
1.元组与列表的区别:
元组中的数据不能修改(元组中的列表中的数据可以修改);列表中的数据可以修改
"""
# 创建元组:
tuple1 = (1, 2, 3, 4)
tuple2 = (1,) # 逗号不能省
|
2f6b959205e4761ab4147d1369f214ba7b81fad3 | changyubiao/myalgorithm-demo | /leetcode/leetcode215.py | 2,274 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
著作权归领扣网络所有。商业转载请联系官方授... |
9ce8a31ed3cedb1f9f097f1df67eb1b26eff07e7 | changyubiao/myalgorithm-demo | /classthree/5.py | 3,694 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/1/1 13:21
@File : 5.py
@Author : frank.chang@shoufuyou.com
转圈打印矩阵
【 题目5 】 给定一个整型矩阵matrix, 请按照转圈的方式打印它。
例如: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
array=[
[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 ... |
dac2fa508d94199d6b188da9c78742a2b6de26c6 | changyubiao/myalgorithm-demo | /classfour/1.py | 6,251 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/2/10 22:16
@File : 1.py
@Author : frank.chang@shoufuyou.com
二叉树相关练习
实现 二叉树的先序、中序、后序遍历,包括递归方式和非递归方式
"""
from util.stack import Stack
class Node:
"""
二叉树 结点
"""
def __init__(self, data):
self.value = data
self... |
eb07b756e4de5cda92741b93630997f9cbff01e5 | changyubiao/myalgorithm-demo | /classthree/1.py | 3,591 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2018/12/16 14:48
@File : 1.py
@Author : frank.chang@shoufuyou.com
用数组结构 实现大小固定的队列和栈
1.实现 栈结构
2.实现 队列结构
"""
class ArrayToStack:
def __init__(self, init_size):
if init_size < 0:
raise ValueError("The init size is less th... |
2e5e728e42819ca386083f2dbd9ce51055d73fc6 | Clearyoi/adventofcode | /2020/6/part2.py | 438 | 3.703125 | 4 | def overallTotal( groups ):
return sum ( [ groupTotal( group ) for group in groups ] )
def groupTotal( group ):
people = group.split( '\n' )
answers = people[0]
for person in people:
for answer in answers:
if answer not in person:
answers = answers.replace( answer, '' )
return len( answers )
groups = [ ... |
135aec9f9fa998bda9a1782d1091dba08fa5b7e6 | Clearyoi/adventofcode | /2020/7/part1.py | 833 | 3.53125 | 4 | def parseBags( bagsRaw ):
bags = []
for bag in bagsRaw:
bags.append( ( bag[0].split()[0] + bag[0].split()[1], [ x.split()[1] + x.split()[2] for x in bag[1] ] ) )
return bags
def findOuterBagsInner( bags, seeking ):
newSeeking = seeking.copy()
for bag in bags:
for seek in seeking:
if seek in bag[1]:
ne... |
8d852b9ba3fb4403dc783cc6c703c451ee0197f7 | Pranav-Tumminkatti/Python-Turtle-Graphics | /Turtle Graphics Tutorial.py | 979 | 4.40625 | 4 | #Turtle Graphics in Pygame
#Reference: https://docs.python.org/2/library/turtle.html
#Reference: https://michael0x2a.com/blog/turtle-examples
#Very Important Reference: https://realpython.com/beginners-guide-python-turtle/
import turtle
tim = turtle.Turtle() #set item type
tim.color('red') #set colour
tim.pensize(5... |
ec2c17082037d296706d9659c6a56709b4027d48 | namitanair0201/leetcode | /rotateMatrix.py | 759 | 3.875 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place... |
78f4b8b8aa2eb93a5daf00dfb0e3077df20a217e | sAnjali12/BsicasPythonProgrammas | /python/if1.py | 123 | 4.03125 | 4 | number = input("enter your no.")
num = int(number)
if num<10:
print "small hai"
elif num>10 or num<20:
print "yeeeeeeee"
|
d58cd85ebb232f5540e8cde005f1352d9fb8e2e4 | sAnjali12/BsicasPythonProgrammas | /python/reportAvarage.py | 386 | 3.5625 | 4 | marks = [
[78, 76, 94, 86, 88],
[91, 71, 98, 65, 76],
[95, 45, 78, 52, 49]]
index = 0
total_sum=0
while index<len(marks):
j = 0
sum=0
count = 0
while j<len(marks[index]):
sum = sum+marks[index][j]
count = count+1
average = sum/count
j = j+1
print sum
print average
total_su... |
b68c9db55ce6af793f0fc36505e12e741c497c31 | sAnjali12/BsicasPythonProgrammas | /python/userInput_PrimeNum.py | 339 | 4.1875 | 4 | start_num = int(input("enter your start number"))
end_num = int(input("enter your end number"))
while (start_num<=end_num):
count = 0
i = 2
while (i<=start_num/2):
if (start_num):
print "number is not prime"
count = count+1
break
i = i+1
if (count==0 and start_num!=1):
print "prime number"
start_... |
0c2c3eaca985cb68fc6a58e24ffaea257dbb89ad | sAnjali12/BsicasPythonProgrammas | /python/sum.py | 421 | 3.75 | 4 | elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43]
index = 0
sum1 = 0
sum2 = 0
count1 = 0
count2 = 0
while index<len(elements):
if elements[index]%2==0:
count1 = count1+1
sum1 = sum1+elements[index]
else:
count2 = count2+1
sum2 = sum2+elements[index]
index = index+1
even_average = sum1/count1
odd_... |
932faa7f15b06df9c922ff7b84c74853d869a93a | isaacgs95/Kata1 | /kata2/programa_2_4.py | 270 | 4 | 4 | '''
Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla la
cuenta atrás desde ese número hasta cero separados por comas.
'''
numero = int(input("Introduce un número: "))
for i in range(numero, -1, -1):
print(i, end=", ")
|
3750e8f1fc7137dddda348c755655db99026922b | xilaluna/web1.1-homework-1-req-res-flask | /app.py | 1,335 | 4.21875 | 4 |
# TODO: Follow the assignment instructions to complete the required routes!
# (And make sure to delete this TODO message when you're done!)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
"""Shows a greeting to the user."""
return f'Are you there, world? It\'s me, Ducky!'
@app.r... |
9d0241b8b9a5d399ca4334a5cd95caefd6284651 | ecoBela/flask_app_game_wk3_wkend_hw | /app/tests/test_game.py | 1,709 | 3.875 | 4 | import unittest
from app.models.game import Game
from app.models.games import *
from app.models.player import Player
class TestGame(unittest.TestCase):
def setUp(self):
self.player1 = Player("Socrates", "Rock")
self.player2 = Player("Plato", "Paper")
self.player3 = Player("Aristotle", "Scis... |
71e703749e9420528dd2dc48e8d89d4f5d7da8ce | Davidrbl/python-6 | /Room.py | 1,129 | 3.53125 | 4 | class Room:
def __init__(self, _name, _exits=[], _items=[], _people=[]):
self.exits = _exits
self.items = _items
self.people = _people
self.name = _name
def add_exit(self, room):
self.exits.append(room)
def describe(self, game):
game.printHeader()
#... |
d0beb6a3f23b2a9337b60dd68d6083c1c60873ed | DanielFlores23/Tareas | /multiplicacion2.py | 536 | 3.84375 | 4 | for indice in range (32,36):
print("Tabla de ", inndice
for elemento in range(1,11):
resultado = indice * elemento
print("{2} x {0} = {1}".format(elemento,resultado,indice))
print()
print()
print("Otros Valores")
print()
tablas= [21, 34, 54, 65, 76]
for indice in tablas:
... |
715634e01c2a166e581c9fa0554218ef11072444 | terryjungtj/OpenCV_Practice | /04-shapesAndTexts.py | 1,212 | 3.671875 | 4 | # Shapes and Texts
import cv2
import numpy as np
print("Package Imported")
img = np.zeros((512, 512, 3), np.uint8) # matrix of 0 (black)
# img[:] = 255, 0, 0 # change all the pixels in the matrix to blue
cv2.line(img, (0,0), (300,300), (0,255,0), 3) ... |
21fbb16cd1da3148922030c29f5f6f0563d12463 | Ahmedatef-09/machine_learning | /python_files/ML_English/logistic_regreesion/logistic_regression.py | 1,681 | 3.578125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
sns.set()
from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import f_regression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selecti... |
266cb9b64f570b1262f7bfd62d9d81892ced05fe | Ahmedatef-09/machine_learning | /python_files/ML_Arabic/pandas_groupby.py | 618 | 3.546875 | 4 | import numpy as np
import pandas as pd
dic = {'a':[1,2,3],
'b':[4,5,6],
'c':[7,8,9],
'key':'a b c'.split()}
dic2 = {'a':[10,20,30],
'b':[40,50,60],
'c':[70,80,90],
'key':'a b c'.split()}
df = pd.DataFrame(dic,index=[0,1,2])
df2 = pd.DataFrame(dic2,in... |
6e825fd8dbd70ac20d3502995a7a1efa4da77ab9 | shivangsoni/NLP | /HW/ShivangSoni_HW1/CustomLanguageModel | 2,439 | 3.546875 | 4 | import math
from collections import Counter
from collections import defaultdict
class CustomLanguageModel:
def __init__(self, corpus):
"""Initialize your data structures in the constructor."""
self.unigram_count = Counter()
self.bigram_count = Counter()
self.trigram_count = Counter()
self.vocabu... |
26a5cbe6f6590d875069427d1b72cf5f7d6a86c1 | nikolajjsj/IntoToCSPython | /week2/tower_of_hanoi.py | 418 | 3.8125 | 4 | def printMove(from_stack, to_stack):
print('Move from ' + str(from_stack) + ' to ' + str(to_stack))
def towers_of_hanoi(n, from_stack, to_stack, spare_stack):
if n == 1:
printMove(from_stack, to_stack)
else:
towers_of_hanoi(n-1, from_stack, spare_stack, to_stack)
towers_of_hanoi(n, ... |
dfabde0a7eddb09e12accbde3198111ff9f0cfa0 | 770847573/Python_learn | /Hello/正则/3.边界匹配.py | 2,098 | 3.890625 | 4 | """
--------------锚字符(边界字符)-------------
^ 行首匹配,和在[]里的^不是一个意思 [^xxxxx]
$ 行尾匹配
\A 匹配字符串开始,它和^的区别是,\A只匹配整个字符串的开头,即使在re.M模式下也不会匹配它行的行首
\Z 匹配字符串结束,它和$的区别是,\Z只匹配整个字符串的结束,即使在re.M模式下也不会匹配它行的行尾
\b 匹配一个单词的边界,也就是值单词和空格间的位置
\B 匹配非单词边界
"""
import re
# search():使用指定的正则在指定的字符串中从左往右依次进行搜索,只要找到一个符合条件的子字符串,则立... |
d4509f58c0d0721b86336e567946646df9431717 | 770847573/Python_learn | /Hello/错误和异常/抛出异常raise.py | 391 | 4.15625 | 4 | # 产生异常的形式
# 形式一:根据具体问题产生异常【异常对象】
try:
list1 = [12, 3, 43, 34]
print(list1[23])
except IndexError as e:
print(e)
#形式2:直接通过异常类创建异常对象,
# raise异常类(异常描述)表示在程序中跑出一个异常对象
try:
raise IndexError("下标越界~~~")
except IndexError as e:
print(e) |
fdc709509a4898c4be7205c77a5f0a7c3a3f029e | 770847573/Python_learn | /Hello/正则/1.数量词匹配.py | 1,759 | 3.875 | 4 | """
-------------------匹配多个字符------------------------
说明:下方的x、y、z均为假设的普通字符,n、m(非负整数),不是正则表达式的元字符
(xyz) 匹配小括号内的xyz(作为一个整体去匹配)
x? 匹配0个或者1个x
x* 匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符(换行符除外))
x+ 匹配至少一个x
x{n} 匹配确定的n个x(n是一个非负整数)
x{n,} 匹配至少n个x
x{n,m} 匹配至少n个最多m个x。注意:n <= m
x|y |表示或,匹配的是x或y
"""
"""
(... |
df37cd6d0c236e8f92f0892484ea4d63bfcd1d93 | 770847573/Python_learn | /Hello/Day13Code/4.装饰器使用一.py | 2,245 | 4 | 4 | # 1.闭包
def func1():
n = 45
def func2():
print(n)
return func2
# 方式一
f = func1()
f()
# 方式二
func1()()
# 2.
"""
假设我们要增强某个函数的功能,但又不希望修改原函数的定义,
这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)
"""
# 装饰器的本质:实际上是一个闭包
# 闭包的书写形式
# 方式一
def outter1(a):
def inner1(b):
print(a,b)
return inner1
f1 = outter... |
7b756c270d420e1256cfe977fb7576833a54b4d5 | 770847573/Python_learn | /Hello/简单排序算法/1.作业讲解.py | 900 | 3.796875 | 4 | # 需求:利用列表推导式将已知列表中的整数提取出来
list1 = [True, 17, "hello", "bye", 98, 34, 21]
# 注意:isdigit()是字符串的功能,其他类型的变量无法使用
# 方式一:str()
list2 = [ele for ele in list1 if str(ele).isdigit()]
print(list2)
# 方式二:type() # [17, 98, 34, 21]
list2 = [ele for ele in list1 if type(ele) == int]
print(list2)
# 方式三:isinstance(变量,类型)判断一个变量是否是指定的数据类... |
69ecb5fe76a1dee7a56808755922d0a942c069cb | 770847573/Python_learn | /shopcar1/storage.py | 2,479 | 3.65625 | 4 | """
仓库类:【信息保存在本地磁盘:程序刚启动时把列表先存储到文件中,之后使用再读取出来】
商品列表
商品名称 价格 剩余量
Mac电脑 20000 100
PthonBook 30 200
草莓键盘 80 60
iPhone 7000 70
"""
import os,pickle
from shopcar1.goods import Goods # 注意:导入类和导入函数以及变量的方式相同
# 假设存储仓库中商品列表的文件名为goodslist.txt
path = r"goodslist.txt"
... |
7bbf2b2e59d035278ed1512201e70391af6c2e8a | 770847573/Python_learn | /day19/4.多态的应用.py | 1,664 | 4.4375 | 4 | # 1.多态的概念
# a.
class Animal(object):
pass
class Cat(Animal):
pass
# 在继承的前提下,一个子类对象的类型可以是当前类,也可以是父类,也可以是祖先类
c = Cat()
# isinstance(对象,类型)判断对象是否是指定的类型
print(isinstance(c,object)) # True
print(isinstance(c,Animal)) # True
print(isinstance(c,Cat)) # True
a = Animal()
print(isinstance(a,Cat)) # False
# b.
... |
37cb9c59405d6f6c92945782ff7c68b5adff0388 | 770847573/Python_learn | /Hello/Day15/day15作业.py | 504 | 3.609375 | 4 | #获取当前时间,判断是否是元旦,如果不是,计算和元旦差了多少天
import datetime
def get_time():
time_now = datetime.datetime.now()
time_now_day = time_now.strftime('%Y/%m/%d')
if time_now_day == '2021/01/01':
print('今天是是元旦')
else:
yuandan_date =datetime.datetime(2021,1,1,0,0,0)
days1= time_now - yuandan_date
... |
bccdae6959d7354f0a68014f753b98a6e7075dc0 | 770847573/Python_learn | /Hello/抽象类的使用.py | 400 | 4.125 | 4 | import abc
class MyClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def mymethod(self):
pass
class My1(MyClass):
def mymethod(self):
print('Do something!!!')
my = My1()#如果一个类继承自抽象类,而未实现抽象方法,仍然是一个抽象类
my.mymethod()
#my1 = MyClass() TypeError: Can't instantiate abstract class MyClass with abs... |
a5fc666c80858fc0a3f313bfe562b0e25115e840 | 770847573/Python_learn | /Hello/Day13Code/5.装饰器使用二.py | 1,517 | 3.875 | 4 | # 1.需求:书写一个装饰器,对年龄进行校验
def get_age(age):
print("年龄:%d" % (age))
def check_age(func):
def inner(n):
# 新的功能:校验传进来的年龄是否是负数,如果是负数,则改为相反数
if n < 0:
n = -n
# 调用原函数
func(n)
return inner
f = check_age(get_age)
f(-6)
# 使用场景:如果原函数有参数,而且在装饰器中需要对原函数中的参数做出操作,则在装饰器的内部函数中设置参数... |
7a61d100ca4bd6b29b7642691b09b1de68709424 | 770847573/Python_learn | /Hello/正则/7.正则练习一.py | 551 | 3.609375 | 4 | # 1.要求从控制台输入用户名和密码,如果用户名和密码都输入合法,则注册成功
"""
要求:
用户名:只能由数字或字母组成,长度为6~12位
密码:只能由数字组成,长度必须为6位
"""
import re
username = input("请输入用户名:")
pwd = input("请输入密码:")
# 匹配上,返回一个对象,匹配不上,返回None
r1 = re.match(r"^[0-9a-zA-Z]{6,12}$",username)
r2 = re.match(r"^\d{6}$",pwd)
if r1 and r2:
print("注册成功")
else:
print("注册失败... |
b10c4327168a5edd2d50a588ac0731f3b67bc4c9 | KurinchiMalar/DataStructures | /DynamicProgramming/MaximumSumContiguousSubsequence.py | 3,855 | 3.78125 | 4 | '''
Given a sequence of n numbers A(1)....A(n) give an algorithm for finding a contiguous subsequence A(i)....A(j) for
which the sum of elements in the subsequence is maximum.
Example : {-2, 11,-4, 13, -5, 2} --> 20 (11 + -4 + 13)
{1, -3, 4, -2, -1, 6} --> 7 (4 + -2,+ -1 + 6)
'''
# Time C... |
9e97f5a89008686e2f7317b30441b7f2eeffe933 | KurinchiMalar/DataStructures | /Sorting/CountingSort.py | 1,053 | 3.671875 | 4 | # Time Complexity : O(n+k)
# Space Complexity : O(n+k)
def counting_sort(Ar,k):
B = [0 for el in Ar]
C = [0 for el in range(0,k+1)]
print "Ar :"+str(Ar)
print "B :"+str(B)
print "C :"+str(C)
for j in range(0,len(Ar)): #Build the counting array...how many times current index has occured in origi... |
9a97498c8f5dfe49b5a0118718c8e6b81dbd97f2 | KurinchiMalar/DataStructures | /Strings/RemoveAdjacentDuplicatesRecursively.py | 1,016 | 3.890625 | 4 | '''
Recursively remove all adjacent duplicates. Given a string of characters, recursively remove adjacent duplicate characters
from string. The output string should not have any adjacent duplicates.
'''
# Time Complexity : O(n)
# Space Complexity : O(1) ... inplace, no stack.
def remove_adj_duplicates(mystr... |
6b1dc96656928464dc9fd37109885b88c9560134 | KurinchiMalar/DataStructures | /Searching/FirstRepeatingElement.py | 2,180 | 3.578125 | 4 | #https://ideone.com/daLlg9
#Time Complexity = O(n) (Building hash_ar and finding max of negatives)
#Space Complexity = O(k) ---- k is the range of numbers in the input array. Here 0 to 5. Hence k = 5
'''
Solution:
1) Store the position of occurence in input array in hash_ar
2) On second occurence negate
3) If alread... |
d15a8a84b1a7e7ac54f74d47180757109a17782a | KurinchiMalar/DataStructures | /Medians/FindLargestInArray.py | 505 | 4.28125 | 4 | __author__ = 'kurnagar'
import sys
# Time Complexity : O(n)
# Worst Case Comparisons : n-1
# Space Complexity : O(1)
def find_largest_element_in_array(Ar):
max = -sys.maxint - 1 # pythonic way of assigning most minimum value
#print type(max)
#max = -sys.maxint - 2
#print type(max)
for i in rang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.