blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e9e390b38789e105f9ae5f806f46768acfc6ab81 | Aasthaengg/IBMdataset | /Python_codes/p02261/s606263197.py | 1,297 | 3.921875 | 4 | # -*- coding: utf-8 -*-
def BubbleSort(C, N):
flag = 1
while flag == 1:
flag = 0
for i in range(N - 1, 0, -1):
if int(C[i][1]) < int(C[i - 1][1]):
C[i], C[i - 1] = C[i - 1], C[i]
flag = 1
return C
def SelectionSort(C, N):
flag = 0
for i in range(N):
if N == 1:
break
minj = i
for j in range(i, N):
if int(C[j][1]) < int(C[minj][1]):
minj = j
flag = 1
if flag == 1:
C[i], C[minj] = C[minj], C[i]
flag = 0
return C
def print_line(A):
for i in range(len(A)):
if i == len(A) - 1:
print('{0}{1}'.format(A[i][0], A[i][1]))
else:
print('{0}{1} '.format(A[i][0], A[i][1]), end='')
def check_stable(Bubble_A, Select_A):
for i in range(len(Select_A)):
if Bubble_A[i][0] != Select_A[i][0]:
print('Not stable')
break
elif i == len(Select_A) - 1:
print('Stable')
N = int(input())
A = list(input())
A = [A[i:i+2] for i in range(0, len(A), 3)]
Bubble_A = BubbleSort(A[:], N)
Select_A = SelectionSort(A[:], N)
print_line(Bubble_A)
print('Stable')
print_line(Select_A)
check_stable(Bubble_A, Select_A)
|
f0350bae9353a72c47a12654f0c5610ea3ba3dfb | Vasilic-Maxim/LeetCode-Problems | /problems/797. All Paths From Source to Target/1 - DFS [Recursion].py | 534 | 3.6875 | 4 | from typing import List
class Solution:
"""
Time: O(n)
Space: O(n)
"""
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
paths = []
self.dfs(graph, 0, [], paths)
return paths
def dfs(self, graph: List[List[int]], node: int, path: List[int], paths=List[List[int]]):
path.append(node)
if not graph[node]:
paths.append(path[:])
for child in graph[node]:
self.dfs(graph, child, path, paths)
path.pop()
|
6dd97005177d0499160bb03eab671c1a19d2c41d | Soumodip13/TCS-NQT-2020-Practice-Problems | /nCr.py | 269 | 3.921875 | 4 | def factorial(i):
if i == 0:
return 1
elif i == 1:
return 1
else:
return i*factorial(i-1)
# Calculates nCr=n!/((n-r)!*r!
n = int(input("Enter n"))
r = int(input("Enter r"))
ncr = factorial(n)/(factorial(n-r)*factorial(r))
print ncr |
60f2ca7b04a5cf156721b0221f05afb68cfc39ff | alessandrosilva10/the-modern-python3-bootcamp | /args.py | 389 | 3.84375 | 4 | def sum_all_nums(*args):
total = 0
for num in args:
total += num
return total
print(sum_all_nums(1, 2, 3))
def ensure_correct_info(*args):
if "Colt" in args and "Steele" in args:
return "Welcome back Colt!"
return "Not sure who you are"
print(ensure_correct_info(1, True, "Steele", "Colt"))
print(ensure_correct_info(1, True, "Steele", "Cold"))
|
10e43e77a3409d0a5c04af55ece1b708cb368347 | Roshanchabila/hacktoberfest2021 | /Python/Password Encrypter/Password_Encrypter.py | 944 | 4.1875 | 4 | #Encrypt Function
def encrypt(password):
password_li = list(password)
encrypted_password = ""
for i in password_li:
ascii_password_li = chr(ord(i) + 5)
encrypted_password = encrypted_password + ascii_password_li
print("Your encrypted password is: ")
print(encrypted_password)
#decrypt Function
def decrypt(password):
password_li = list(password)
decrypted_password = ""
for i in password_li:
ascii_password_li = chr(ord(i) - 5)
decrypted_password = decrypted_password + ascii_password_li
print("Your decrypted password is: ")
print(decrypted_password)
option_selected = input("You want to encrypt or decrypt: \n 1: Encrypt \n 2: Decrypt \n")
if int(option_selected )== 1 :
password = input("Enter you password: ")
encrypt(password)
else:
password = input("Enter you encrypted password which was encrypted by this program only: ")
decrypt(password)
|
c9a80cf20ed3eeb54e937303bd0ed71d76c45e77 | jakewilliami/scripts | /julia/Other/advent_of_code/2020/doov/01/main.py | 362 | 3.546875 | 4 |
def getnum():
f = open("input.txt", "r")
numbers = [int(x) for x in f.readlines()]
for i in numbers:
for j in numbers:
for k in numbers:
if i == j or i == k or j == k:
continue
if i + j + k == 2020:
return i * j * k
f.close()
print(getnum()) |
37a9d47502c9bc66b5742f825ed308b3b1628569 | JonathanShifman/riddles | /Monkey Riddle/MonkeyRiddle.py | 1,923 | 3.609375 | 4 | from random import randint
def make_guess(guess, monkey_position, output_lines):
output_string = 'Guessed ' + str(guess) + ' while monkey was in ' + str(monkey_position) + '. '
succeeded = guess == monkey_position
if succeeded:
output_string += 'HIT!'
else:
output_string += 'Missed.'
output_lines.append(output_string)
return succeeded
def move(monkey_position, number_of_cars, output_lines):
if monkey_position == 1:
new_monkey_position = 2
elif monkey_position == number_of_cars:
new_monkey_position = number_of_cars - 1
else:
dir = randint(0, 1)
if dir == 0:
new_monkey_position = monkey_position + 1
else:
new_monkey_position = monkey_position - 1
output_lines.append('Moved from ' + str(monkey_position) + ' to ' + str(new_monkey_position) + '.')
return new_monkey_position
def print_buffer(output_lines):
for i in range(2):
output_lines.append('')
number_of_cars = 10
number_of_simulations = 20
output_lines = []
for i in range(number_of_simulations):
output_lines.append('Running simulation number ' + str(i+1))
succeeded = False
monkey_position = randint(1, number_of_cars)
output_lines.append('Monkey initial position: ' + str(monkey_position))
for guess in range(2, 10):
succeeded = make_guess(guess, monkey_position, output_lines)
if succeeded:
break
monkey_position = move(monkey_position, number_of_cars, output_lines)
if not succeeded:
for guess in range(9, 1, -1):
succeeded = make_guess(guess, monkey_position, output_lines)
if succeeded:
break
monkey_position = move(monkey_position, number_of_cars, output_lines)
print_buffer(output_lines)
with open('output.txt', 'w') as f:
for line in output_lines:
f.write(line + '\n')
|
d51d37facb7042335209972da7b6ad0e523fc362 | paulfoley/MongoDB_University | /M101P/Chapter2-CRUD/pymongo/find_limit_skip_sort.py | 1,031 | 3.9375 | 4 | ## Example of using 1)Sort(.sort()) 2)Skip(.skip()) 3)Limit (.limit())in Pymongo
# Imports
import pymongo
# Connect to Mongo
connection = pymongo.MongoClient("mongodb://localhost")
# Connect to Database
db = connection.school
# Connect to Collection
scores = db.scores
def find():
# Program using 1)Sort 2)Skip 3)Limit
print ("find, reporting for duty")
# Query
query = {}
# Exception Handling
try:
# Create Cursor
# Out of order returns the same result
#cursor = scores.find(query).skip(4)
#cursor.limit(1)
#cursor.sort([('student_id', pymongo.ASCENDING), ('score', pymongo.DESCENDING)])
# In order returns the same result
cursor = scores.find(query)
cursor.sort([('student_id', pymongo.ASCENDING), ('score', pymongo.DESCENDING)]).skip(4).limit(1)
except Exception as e:
print("Unexpected error:", type(e), e)
# Outpu
for doc in cursor:
print (doc)
if __name__ == '__main__':
find()
|
0b2484cc15b142843a720fe549065ed9b0cf1de6 | Javiplus1310/DWY4001_19_s03_HolaMundo | /Persona.py | 457 | 3.65625 | 4 |
# Vamos a definir una clase. Primero una clase
class Persona:
# en python hay un solo "constructor", qe se llama __init__
# deben recibir un parametro self!!!
# si se parte con (underscore) _ se debe tratar como si fuera privada
def __init__(self, nombre, rut):
self.nombre = nombre
self.rut = rut
def imprimir(self):
texto = " ".join(("soy", self.nombre, "mi rut es", self.rut))
print(texto)
|
24b0fd6a0def5a5e7b7c3c0238a4b27b756ba034 | matejbolta/project-euler | /Problems/35.py | 1,317 | 3.609375 | 4 | '''
Circular Primes
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
'''
def je_prastevilo(n):
if n <= 2:
return n == 2
elif n % 2 == 0:
return False
else: #vsa liha ostanejo
d = 3
while d ** 2 <= n:
if n % d == 0:
return False
d += 2
return True
def zamakni(x):
'''da prvo števko na konec'''
niz = str(x)
zlepek = niz[1:] + niz[0]
return zlepek
def je_krozno_prastevilo(n):
'''true, če je, false, če ni'''
if not je_prastevilo(n):
return False
x = zamakni(n) #x je string zdej
while int(x) != n:
if not je_prastevilo(int(x)):
return False
else:
x = zamakni(x)
return True
def koliko_je_kroznih_prastevil_manjsih_od(n):
rezultat = 0
for x in range(n):
if je_krozno_prastevilo(x):
rezultat += 1
return rezultat
print(koliko_je_kroznih_prastevil_manjsih_od(10**6))
#100 13
#1000 25
#10 000 33
#100 000 43
#1 000 000 55 JA!
|
610850512a49f5b5d4e18eccd1e7943322aa8e49 | jarpszon/DSA | /OOP_Encapsulation.py | 860 | 3.59375 | 4 |
class SoftwareEngineer:
def __init__(self, name, age) -> None:
self.name = name
self.age = age
#PEP8 convention protected atr stars with '_' and prrivate with '__'
self._salary = None
self._num_bugs_solved = 0
def code(self):
self._num_bugs_solved += 1
#getters
def get_salary(self):
return self._salary
#setters
def set_salary(self, value):
self._salary = self._calculate_salary(value)
def _calculate_salary(self, base_salary):
if self._num_bugs_solved < 10:
return base_salary
if self._num_bugs_solved <100:
return base_salary * 2
return base_salary * 3
se1 = SoftwareEngineer('Jarek',25)
for i in range(70):
se1.code()
print(se1._num_bugs_solved)
se1.set_salary(5000)
print(se1.get_salary() )
|
01d745fd1e5ecf34fb0159c8f97ed010d47e6379 | samodeh97/pythonic-garage-band | /pythonic_garage_band/pythonic_garage_band.py | 1,852 | 3.703125 | 4 | from abc import ABC, abstractmethod, abstractstaticmethod, abstractclassmethod
class Band():
band_name=[]
member_name=[]
def __init__(self,name="unknown"):
self.name=name
Band.band_name.append(self)
def insert(self,name1):
self.name1=name1
Band.member_name.append(name1)
def play_solos(self):
result=""
for i in Band.member_name:
result+= f"{i.play_solo()}\n"
return result
@classmethod
def to_list(cls):
return cls.member_name
def __str__(self):
return "Band--->{self.name}"
def __repr__(self):
return "{self.name}"
class Musician():
def __init__(self,name):
self.name=name
@abstractmethod
def __str__(self):
return "Musician--->{self.name}"
@abstractmethod
def __repr__(self):
return "{self.name}"
def play_solo(self):
return f'{self.name}'
class Guitarist(Musician):
def __init__(self,name):
super().__init__(name)
def __str__(self):
return f"Guitarist--->{self.name}"
def __repr__(self):
return "{self.name}"
def get_instrument(self):
return "Guitarist"
class Bassist(Musician):
def __init__(self,name):
super().__init__(name)
def __str__(self):
return f"Bassist--->{self.name}"
def __repr__(self):
return f"{self.name}"
def get_instrument(self):
return "Bassist"
class Drummer(Musician):
def __init__(self,name):
super().__init__(name)
def __str__(self):
return f"Drummer--->{self.name}"
def __repr__(self):
return f"{self.name}"
def get_instrument(self):
return "Drummer"
if __name__=="__main__":
pass |
a2880d544dce83a7f4ed4dcf7b90bd5c6780b2be | vinicius-lds/Python-programming-exercises | /Question003.py | 211 | 3.53125 | 4 | from util.Console import get_int_input
dictionary = dict()
given_input = get_int_input(allow_zero=False, allow_negative=False)
for x in range(1, given_input + 1):
dictionary[x] = x * x
print(dictionary)
|
666d031883c8b04e079f23e5e1520d813fcf971e | KennethBlaney/sklearn_regression_sample | /sklearn_regression_sample/isotonic_regression.py | 813 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.isotonic import IsotonicRegression
from sklearn.utils import check_random_state
print("Generating Data.")
n = 100 # number of data points
x = np.arange(n) # x values
random_seed = check_random_state(0)
y = random_seed.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n)) # y values
# Fit IsotonicRegression models
print("Fitting model.")
ir = IsotonicRegression()
y_ = ir.fit_transform(x, y)
# Plot result
print("Displaying result.")
fig = plt.figure()
plt.plot(x, y, 'r.', markersize=12)
plt.plot(x, y_, 'b.-', markersize=12)
plt.legend(('Data', 'Isotonic Fit'), loc='upper left')
plt.title('Isotonic regression')
plt.show()
|
3dfcb3368a60024ff4a3ae96b61e343d7ac0b10c | chetan113/python | /moreprograms/stringreversal.py | 344 | 3.796875 | 4 | """s =input("enter a string:")
print(s[::-1])
"""
"""palendrom"""
"""
s= input("enter a string:")
i= len(s)-1
result = ''
while i>=0:
result =result+s[i]
i=i-1
print(result)
"""
""" join the string use reverse"""
s='---'.join(['a','b','c'])
print(s)
s1=input("enter a string:")
print(','.join(reversed(s1)))
|
2a5034fb8bd3e23c22e48d599d5196e2c2381a67 | Wojtbart/Python2020 | /rekurencja.py | 439 | 4.03125 | 4 | def factorialRec(n):
if n >= 0:
if n == 0 or n == 1:
return 1
else:
return n*factorialRec(n-1)
else:
raise Exception("Liczba musi być większa od zera")
def fibonacciRec(n):
if n >= 0:
if n == 0 or n == 1:
return n
else:
return fibonacciRec(n-2)+fibonacciRec(n-1)
else:
raise Exception("Liczba musi być większa od zera")
|
235ad34dd5f217708f74990759968f983bfda27a | 007HarshChaudhary/Google-Coding-Questions | /Frequency queries.py | 1,122 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 13 10:06:18 2020
@author: Harsh Chaudhary
"""
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the freqQuery function below.
def freqQuery(queries):
res = Counter()
res_2=Counter()
ans=[]
for q in queries:
if q[0]==1:
res_2[res[q[1]]] -= 1
res[q[1]] += 1
res_2[res[q[1]]] += 1
elif q[0]==2:
if res[q[1]]>0:
res_2[res[q[1]]] -= 1
res[q[1]] -= 1
res_2[res[q[1]]] += 1
else:
if res_2[q[1]]>0:
ans.append(1)
else:
ans.append(0)
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().strip())
queries = []
for _ in range(q):
queries.append(list(map(int, input().rstrip().split())))
ans = freqQuery(queries)
fptr.write('\n'.join(map(str, ans)))
fptr.write('\n')
fptr.close()
|
9eef6657e98d23dbc9d018ad1011135ec5d4fd82 | niayz10/Web-Programming | /week8/Logic-1/4.py | 392 | 3.765625 | 4 | def caught_speeding(speed, is_birthday):
if is_birthday:
if speed <= 65:
print("0")
elif speed >= 66 and speed <= 85:
print("1")
elif speed >= 86:
print("2")
else:
if speed <= 60:
print("0")
elif speed >= 61 and speed <= 80:
print("1")
elif speed >= 81:
print("2") |
635963591f34b61263c5c8cd925a5d02dd0ae931 | Pedro-1970/python | /convertkmmi.py | 631 | 4.21875 | 4 | #convertkmmi.py pedro-1970
'''
unit conerter: Miles and Kilomenters
'''
#convertkmmi.py pedro-1970
def print_menu():
print('1. kilometers to miles')
print('2. Miles to kilometers')
def km_miles():
km =flat(input('Enter distance in kilometrs:'))
miles + km / 1.609
print('distance in miles: {0}'format(miles))
def miles_km():
miles = float(input('enter distance in miles: '))
km + miles * 1.609
print('distance in kilometers: {0}'.format(km))
if _name_== '_main_':
print_men()
choice = input('which conversion would you like to do?: ')
if choice == '1':
km_miles()
if choice == '2':
miles_km()
|
5422878acf48744ee5e0acd30cffabb8b82c3c07 | LogicPenguins/BeginnerPython | /smallprojects/stopwatch_pretty.py | 767 | 3.796875 | 4 | #! python3
# stopwatch_pretty.py - A stopwatch with well formatted text. A brotherin of the origin stopwatch python program.
import time
import pyperclip
print('Press ENTER to begin. Afterward, press ENTER to "click" the stopwatch. Press CTRL-C to quit.')
input()
print('Started.')
original_time = time.time()
last_time = original_time
lap_num = 1
try:
while True:
input()
full_time = round(time.time() - original_time, 2)
lap_time = round(time.time() - last_time, 2)
output = f'Lap #{str(lap_num).rjust(2)}: {str(full_time).rjust(5)} ( {str(lap_time).rjust(5)})'
pyperclip.copy(output)
print(output, end='')
last_time = time.time()
lap_num += 1
except KeyboardInterrupt:
print('\nDone.') |
3adf8abe93e39e4e922b877223bbbff7685b48c5 | YutoTakaki0626/My-Python-REVIEW | /oop/inherit_name_mangling.py | 317 | 3.703125 | 4 | class Person:
def __init__(self, name):
self.name = name
self.mymethod()
def mymethod(self):
print('Person method is called')
#__mymethod = mymethod
class Baby(Person):
def mymethod(self):
print('Baby method is called')
taro_baby = Baby('Taro')
taro_baby.mymethod() |
ee323042eeb1d9a1afbc5cef80cbd4d7e8c579a0 | maan10/Explainable_AI | /Class_Activation_Maps/visualize_cam.py | 2,207 | 3.59375 | 4 | """
Created on Fri Aug 7 03:14:52 2020
@author: Vanditha Rao
This script allows the user to implement class activation maps. Image file can
be of any format.
This script requires that tensorflow and OpenCV be installed within the python
environment you are running this script in.
Here, tensorflow version 2.2, cv2 version 4.2.0 and python version 3.7.7 is
used. This file is imported as a module and contains visualize_cam functions
which implement class activation maps
"""
from tensorflow.keras import backend as K
import numpy as np
import cv2
def visualize_cam(model,
layer_name,
image,
colormap = cv2.COLORMAP_JET):
"""
Args:
image: str
The input image filepath. The model is trained with the augmented image.
Hence, here in this case, image is an augmented image and not an original
image
model:
tensorflow model
layer_name: str
The layer name of the last convolutional layer
colormap: str (default= cv2.COLORMAP_JET)
The Colormap instance or registered colormap name used to map scalar data
to colors. Colormaps is chosen from OpenCV
Returns:
heatmap: np.ndarray
heatmap with shape (H,W)
"""
class_weights = model.layers[-1].get_weights()[0] # weights from softmax layer
get_output = K.function([model.layers[0].input],
[model.get_layer(layer_name).output,
model.layers[-1].output])
[conv_outputs, predictions] = get_output(image)
conv_outputs = conv_outputs[0, :, :, :]
class_idx = np.argmax(predictions)
cam = np.zeros(dtype = np.float32, shape = conv_outputs.shape[0:2])
for i, w in enumerate(class_weights[:, class_idx]):
cam += w * conv_outputs[:, :, i]
cam /= np.max(cam)
cam = cv2.resize(cam, (600, 450)) # the height and the width of the original image.
heatmap = cv2.applyColorMap(np.uint8(255 * (255 - cam)), colormap)
heatmap[np.where(cam < 0.2)] = 0
return heatmap
|
dd1328cc2bff3b7ddbabb1ec7ec36d4cbfade36c | hongwenshen/Python_Study | /Python 100例/Python 练习实例46.py | 602 | 4.21875 | 4 | #!/usr/bin/env python
# coding=UTF-8
'''
@Description: About practicing python exercises
@Author: Shenhongwen
@LastEditors: Shenhongwen
@Date: 2019-03-11 21:37:40
@LastEditTime: 2019-03-11 21:40:45
'''
'''
题目:求输入数字的平方,如果平方运算后小于 50 则退出。
'''
TRUE = 1
FALSE = 0
def SQ(x):
return x * x
print('如果输入的数字小于50,程序将停止运行。')
again = 1
while again:
num = int(input('请输入一个数字:'))
print('运算结果为:{}'.format(SQ(num)))
if SQ(num) >= 50:
again = TRUE
else:
again = FALSE
|
1c8a2fd0ad9d29d92ee65bfbfd0a08943c424cab | chennipman/MCLS | /scripts/general_functions/hex2colormap.py | 1,640 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 28 21:48:45 2014
@author: coen
Input: 2 Hex
Output: colormap
"""
def hex2colormap(hex1, hex2):
from matplotlib.colors import hex2color
from matplotlib.colors import LinearSegmentedColormap
some_name = 'some_name'
[hex1r, hex1g, hex1b] = hex2color(hex1)
[hex2r, hex2g, hex2b] = hex2color(hex2)
cdict = {'red': ((0.0, hex1r, hex1r),
(1.0, hex2r, hex2r)),
'green': ((0.0, hex1g, hex1g),
(1.0, hex2g, hex2g)),
'blue': ((0.0, hex1b, hex1b),
(1.0, hex2b, hex2b))
}
colormapname2 = LinearSegmentedColormap(some_name, cdict)
return colormapname2
def hex3colormap(hex1, hex2, hex3):
from matplotlib.colors import hex2color
from matplotlib.colors import LinearSegmentedColormap
some_name = 'some_name'
[hex1r, hex1g, hex1b] = hex2color(hex1)
[hex2r, hex2g, hex2b] = hex2color(hex2)
[hex3r, hex3g, hex3b] = hex2color(hex3)
cdict = {'red': ((0.0, hex1r, hex1r),
(0.5, hex2r, hex2r),
(1.0, hex3r, hex3r)),
'green': ((0.0, hex1g, hex1g),
(0.5, hex2r, hex2r),
(1.0, hex3g, hex3g)),
'blue': ((0.0, hex1b, hex1b),
(0.5, hex2r, hex2r),
(1.0, hex3b, hex3b))
}
colormapname2 = LinearSegmentedColormap(some_name, cdict)
return colormapname2
|
25ce1d82eb3e272f7df4a3acb3456a1425888266 | carlop8/Intro-to-Programming-Fall-2018 | /resumescripts/tictactoe.py | 3,525 | 4.40625 | 4 | a# CMPT 120 Intro to Programming
# Chapter 11 lab: Lists and Error Handling
# Author: CarLIsaac Nicolas
# Created: 2018 11 2
board = [[0,0,0],[0,0,0],[0,0,0]] # TODO replace this with a list containing 3 elements, each one being a list of 3 zeroes
symbol = [" ", "x", "o"] # used to print out the board to the user
# This function prints out one row of the tic tac toe board
def printRow(row):
# initialize output to the left border - a vertical dash
print("|", end="") # end="" keeps the output for the next print on the same line
# for each element in the "row" list passed as a parameter to this function:
# Replace the question mark in the print statement below with correct symbol for this square(Hint: use the "symbol" list variable and row value--
# Example: symbol[0] will print a blank, symbol[1] prints "x", and symbol[2] prints "o"
for i in range(3):
print(" " + symbol[row[i]] + " " + "|", end="") # this will keep everything on the same line (no line return after printing)
print(end='\n')
print("+-----------+")# this will start a new line on next print.
# This function prints out the current state of the tic tac toe board to the user
def printBoard(board):
# print the top border
print("+-----------+")
# for each row in the board...
for i in range(3):
printRow(board[i]) # Call "printRow()" but pass the list element for the current row as a parameter instead of "(0,0,0"
# print the next border
# This function "marks" the board with the player's move by storing a "1" for an "x" or a "2" for an "o" in the correct row and col.
def markBoard(board, row, col, player):
if board[row][col] == 0:
board[row][col] = player
else:
print("Space taken")
# check to see whether the desired square is blank (Hint: index the proper row and col of "board" and see if the value is equal to "0")
# if True, store the "player" value in the list
# if False, then print out a message stating the space has already been taken
# This function prompts the user for a row and col. Explain that valid values are 0, 1, and 2 for rows/columns 1, 2, and 3
def getPlayerMove():
# prompt the user separately for the row and column numbers - remember to make the values integers!
row = int(input("pick a row"))
col = int(input("pick a col"))
return row, col # return the selected row and col values to "main()"
# This function checks to see if there are any remaining spaces left on the board.
def hasBlanks(board):
for i in range(3):
for j in range(3):
if board[i][j] == 0:
return True
return False
# for each row in the board...
# for each col in the row...
# If a space is available (represented by a "0" in the list element):
# return True
# If no square is blank, return False
# main function
def main():
player = 1 # Start player out as "x" (indicated by a value of 1)
while hasBlanks(board):
printBoard(board) # Print the current tic tac toe board out for the user to view
# Call getPlayerMove which prompts the user for a row a column
row, col = getPlayerMove()
# Call markBoard which will set the appropriate spot to an "x" or "o", depending on the value of "player" (1 for x, 2 for o)
markBoard(board, row, col, player)
player = player % 2 + 1 # switch player for next turn (1 becomes a 2 and a 2 becomes a 1)
main() |
6623f46c9de4da84735c77984dad57f2e0889baa | Poseidonst/Enigma | /Teije/LanguageDutchRecognition/Testing/TripletCounter.py | 1,403 | 3.765625 | 4 | def DependLength(inputsent, listname, countlist):
for i in range(0, len(inputsent) - 2):
p = inputsent[i:i + 3]
if p not in listname:
listname.append(p)
countlist.append(1)
else:
countlist[listname.index(p)] += 1
def Organise(listname, countlist, diction):
for i in range(0, len(listname)):
p = max(countlist)
index = countlist.index(p)
diction[listname[index]] = p
countlist.pop(index)
listname.pop(index)
def OnlySpace(inputsent):
inputlist = []
for i in inputsent:
if i == " ":
inputlist.append(i)
elif i.isalpha():
inputlist.append(i)
inputsent = "".join(inputlist)
return(inputsent)
def Triplet(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read().lower()
except:
inputsent = filename.lower()
inputsent = OnlySpace(inputsent)
inputlist = inputsent.split(" ")
listwords = []
listamount = []
dictionwords = {}
for i in inputlist:
if len(i) > 2:
DependLength(i, listwords, listamount)
Organise(listwords, listamount, dictionwords)
firsthundred = {k: dictionwords[k] for k in list(dictionwords)[:100]}
for i in firsthundred.items():
print(i)
if __name__ == "__main__":
Triplet("TextInput.txt")
|
8d5f4615da3b906cd649ae46e90a2a05278abc87 | igorlaur/computacao-grafica | /Aula07_02.py | 222 | 3.71875 | 4 | def funcao (x, lista=[]):
lista.append(x)
print(lista)
print("------funcao(1)")
funcao(1)
print("-------")
print("------funcao(5)")
funcao(5)
print("-------")
print("------funcao(3)")
funcao(3)
print("-------")
|
7c1a00c9a214574d6691f24b707912ee8cf61157 | dataxerik/starting_data | /text_count_example.py | 157 | 3.65625 | 4 | import sys, re
starts_with_hash = 0
with open('input.txt', 'r') as f:
for line in f:
if re.match("^#", line):
starts_with_hash += 1 |
a75be589dd171630cb9fcc533d965a8fd4376caa | kellysan/learn | /python/day08_函数/demo01函数的基本使用/demo09递归函数.py | 731 | 3.78125 | 4 | #! /usr/bin/env python
# @Author : sanyapeng
'''
递归函数:
函数调用自己
注意:
1. 递归要有出口
2. 逐渐向出口靠近
3.
例:求1-5的和
定义一个函数,用于求1-n的和 get_sun()
n = 5 get_sum(5) 求1-5的和
1-4的和 ,加5
n = 4 get_sum(4) 求1-4的和
get_sum(5) = get_sum(4) + 5
n = 3 get_sum(3)
get_sum(4) = get_sum(3) + 4
n = 2
get_sum(3) = get_sum(2) + 3
n = 1
get_sum2 = get_sum(1) + 2
'''
def getSum(n):
print('****')
if n == 1:
return 1
else:
return getSum(n-1) + n
print(getSum(5))
def getJc(n):
print('***')
if n == 1:
return 1
else:
return getJc(n-1) * n
print(getJc(5)) |
b9d475f758a390ae4e382ddf4f08f92ca1658b78 | monikmakwana/Python-Basics | /Prime.py | 505 | 4.25 | 4 | # Input a number a check whether it is Prime or not
num = int(input("Enter Number to check whether it is Prime or not : "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
input('\nPress Enter to Exit...')
"""
Output:
Enter a number to check whether it is prime or not : 7
7 is a prime number
"""
|
26b324dc0857047e0634a2a7e25d8bd21c7f1bf4 | chanduvenkyteju/pythonprogramming | /repeating or not.py | 143 | 3.75 | 4 | N=(raw_input())
a=[]
for i in N:
if(i not in a):
a.append(i)
a="".join(a)
if(N==a):
print("no")
else:
print("yes")
|
64b026bf9c4785a615f750831ca0eed4ba172bc4 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter05/ch5/gen.yield.for.py | 128 | 3.640625 | 4 | def print_squares(start, end):
for n in range(start, end):
yield n ** 2
for n in print_squares(2, 5):
print(n)
|
f107f118bc8b141d3359fd3d27de8b4c3256d9aa | palandesupriya/python | /regular expression/validemailandremovechar.py | 867 | 4.0625 | 4 | '''
1)WAP to validate E-mail ID using regular expressions
2)WAP to accept an alphanumeric string from user and remove all characters other than digits
using regular expressions
'''
import re
def verifyemail(szEmail):
#regExpr = re.search("[a-zA-Z0-9]+\@{1}[a-zA-Z]+\.{1}[a-zA-Z]+", szEmail)
regExpr = "([\w\.]+)@([\w\.]+)\.(\w+)"
if None == regExpr:
return False
if len(szEmail) == regExpr.end():
return True
return False
def rmCharFromString(szStr):
x = re.findall("[a-zA-Z]+", szStr)
i = 0
while i < len(x):
szStr = re.sub(x[i], "", szStr, 1)
i += 1
print("Removed all characters from string:{}".format(szStr))
def main():
szEmailID = input("Enter e-mail ID:")
bRet = verifyemail(szEmailID)
if True == bRet:
print("Correct Email-ID")
else:
print("Incorrect Email-ID")
rmCharFromString(szEmailID)
if __name__ == '__main__':
main()
|
194b567d1f3b358e3c703a12dedbeb20d2489bb7 | jemg2030/Retos-Python-CheckIO | /PYCON_TW/BuildingVisibility.py | 6,276 | 3.9375 | 4 | """
For our future Robotropolis we need to help the city planners calculate the way light
reaches our fair city so as to limit the Urban Canyon effect. To do this, you will need
to define the visibility of buildings from the southern edge of the base. You have been
given a map of the buildings in the complex as an aide for your planning.
The map is an orthogonal projection of each of the buildings onto a horizontal plane.
It's oriented on a rectangular coordinate system so that the positive x-axis points
east and the positive y-axis points north. No two buildings in the map overlap or touch.
Each of the buildings have perfectly rectangular sides which are aligned from north to
south and east to west. The map is a list of buildings with each building presented as
a list with coordinates describing the south-west corner, and north-east corner along
with the height - [Xsw, Ysw, Xne, Yne, height]. We need to determinate how many of the
buildings are visible from the area just south of the base (excluding the angle of
vision, just using projection.) See the illustration below.
Input: Building coordinates and heights as a list of lists. The coordinates are integers.
The heights are integers or floats.
Output: The quantity of visible buildings as an integer.
Example:
checkio([
[1, 1, 4, 5, 3.5],
[2, 6, 4, 8, 5],
[5, 1, 9, 3, 6],
[5, 5, 6, 6, 8],
[7, 4, 10, 6, 4],
[5, 7, 10, 8, 3]
]) == 5 #"First"
checkio([
[1, 1, 11, 2, 2],
[2, 3, 10, 4, 1],
[3, 5, 9, 6, 3],
[4, 7, 8, 8, 2]
]) == 2 #"Second"
assert checkio([
[1, 1, 3, 3, 6],
[5, 1, 7, 3, 6],
[9, 1, 11, 3, 6],
[1, 4, 3, 6, 6],
[5, 4, 7, 6, 6],
[9, 4, 11, 6, 6],
[1, 7, 11, 8, 3.25]
]) == 4 #"Third"
How it is used: This concept is useful for image recognition systems and graphical systems.
When rendering of 3D model you should determine the visibility of the surfaces. It can also
be applied in architecture and city planning, allowing you to plan out which sides of a
building will receive sunlight, or if a building will block natural light in another building.
Precondition:
0 < len(buildings) < 10
all(all(0 ≤ x < 12 for x in row[:4]) for row in buildings)
all(0 < row[4] ≤ 20 for row in buildings)
----------
----------
Para nuestra futura Robotropolis , tenemos que ayudar a los planificadores de la
ciudad a calcular como la luz alcanza nuestra bella ciudad, así como limitar el efecto
Urban Canyon . Para ello, tendrás que definir la visibilidad de los edificios desde el
extremo sur de la base. Se te ha asignado un mapa de los edificios del complejo, como
ayuda para tu planificación.
El mapa es una proyección ortogonal de cada uno de los edificios sobre un plano horizontal.
Está orientado en un sistema de coordenadas rectangulares de modo que el eje x positivo
se dirige hacia el este y el eje y positivo hacia el norte. No existen dos edificios en
el mapa que se sobre posicionen o se toquen. Cada uno de los edificios tiene lados perfectamente
rectangulares, que se encuentran alineados de norte a sur y de este a oeste. El mapa es una
lista de edificios con cada edificio presentado como una lista incluyendo las coordenadas de
la esquina suroeste, de la esquina noreste, así como la altura -[Xsw, Ysw, Xne, Yne, height].
Debemos determinar cuántos edificios son visibles desde la zona al sur de la base (excluyendo
el ángulo de visión, simplemente usando proyección.) Consulta la siguiente ilustración.
Datos de Entrada: Coordenadas y alturas de los edificios, como una lista de listas. Las
coordenadas son enteros ( int ). Las alturas son enteros ( int ) o decimales ( float ).
Salida: La cantidad de edificios visibles, como un entero ( int ).
Ejemplo:
checkio([
[1, 1, 4, 5, 3.5],
[2, 6, 4, 8, 5],
[5, 1, 9, 3, 6],
[5, 5, 6, 6, 8],
[7, 4, 10, 6, 4],
[5, 7, 10, 8, 3]
]) == 5 #"First"
checkio([
[1, 1, 11, 2, 2],
[2, 3, 10, 4, 1],
[3, 5, 9, 6, 3],
[4, 7, 8, 8, 2]
]) == 2 #"Second"
assert checkio([
[1, 1, 3, 3, 6],
[5, 1, 7, 3, 6],
[9, 1, 11, 3, 6],
[1, 4, 3, 6, 6],
[5, 4, 7, 6, 6],
[9, 4, 11, 6, 6],
[1, 7, 11, 8, 3.25]
]) == 4 #"Third"
¿Cómo se usa?: Este concepto es útil para sistemas de reconocimiento de imágenes y sistemas gráficos.
Cuando se representan modelos 3D, debes determinar la visibilidad de las superficies. También se
puede aplicar en la arquitectura y la planificación urbana, para determinar cuáles edificios van
a recibir la luz del sol (y en que lugares), o si un edificio bloqueará la luz natural para otro
edificio.
Condiciones:
0 < len(buildings) < 10
all(all(0 ≤ x < 12 for x in row[:4]) for row in buildings)
all(0 < row[4] ≤ 20 for row in buildings)
"""
def checkio(buildings):
# for example
d = {}
for n, b in enumerate(buildings):
for i in range(b[0], b[2]):
d[i] = d.get(i, []) + [[n, b[1], b[4]]]
s = set()
for L in d.values():
mh = 0
for ceil in sorted(L, key=lambda x: x[1]):
if ceil[2] > mh:
s.add(ceil[0])
mh = ceil[2]
return len(s)
if __name__ == "__main__":
assert (
checkio(
[
[1, 1, 4, 5, 3.5],
[2, 6, 4, 8, 5],
[5, 1, 9, 3, 6],
[5, 5, 6, 6, 8],
[7, 4, 10, 6, 4],
[5, 7, 10, 8, 3],
]
)
== 5
), "First"
assert (
checkio([[1, 1, 11, 2, 2], [2, 3, 10, 4, 1], [3, 5, 9, 6, 3], [4, 7, 8, 8, 2]])
== 2
), "Second"
assert (
checkio(
[
[1, 1, 3, 3, 6],
[5, 1, 7, 3, 6],
[9, 1, 11, 3, 6],
[1, 4, 3, 6, 6],
[5, 4, 7, 6, 6],
[9, 4, 11, 6, 6],
[1, 7, 11, 8, 3.25],
]
)
== 4
), "Third"
assert checkio([[0, 0, 1, 1, 10]]) == 1, "Alone"
assert checkio([[2, 2, 3, 3, 4], [2, 5, 3, 6, 4]]) == 1, "Shadow"
|
0efb239eb1bcae9d9bd15a4fe28392e0ec52e0be | BoatInTheRiver/codes_algorithm | /sort_algorithm/merge_sort.py | 1,479 | 4.09375 | 4 | #coding:utf-8
'''
算法思想:
采用分治法的思想,分即将问题分成小问题,然后递归求解,治是指将分阶段的各个答案合并在一起。
归并排序的形式是一棵二叉树,需要遍历的次数就是二叉树的深度。最好最坏平均时间复杂度都为O(nlogn),空间复杂度为O(n)。
归并排序是稳定算法。
归并排序、快速排序、堆排序比较:
若从空间复杂度来考虑,优先考虑堆排序,其次是快排,最后是归并。
若从稳定性来考虑,优先考虑归并排序,因为堆排序和快排都是不稳定的。
若从平均情况下的排序速度考虑,优先考虑快速排序。
'''
import random
def merge_sort(nums):
n = len(nums)
if n <= 1:
return nums
mid = n // 2
left_nums = merge_sort(nums[:mid])
right_nums = merge_sort(nums[mid:])
left_point, right_point = 0, 0
res = []
while left_point < len(left_nums) and right_point < len(right_nums):
if left_nums[left_point] <= right_nums[right_point]:
res.append(left_nums[left_point])
left_point += 1
else:
res.append(right_nums[right_point])
right_point += 1
res += left_nums[left_point:]
res += right_nums[right_point:]
return res
if __name__ == '__main__':
nums = [random.randint(1,20) for i in range(10)]
print(nums)
res = merge_sort(nums)
print('排序后的数组为:{}'.format(res)) |
5e96982fcd0de6a82e2285888ac8e70788743a30 | zyro-mixed-bag/algorithms-python | /CloseHashing.py | 2,442 | 3.703125 | 4 | def insert(T, key, size):
for i in range(size):
j = hashLinearProbe(key, i, size)
if T[j] is None or T[j] is -1:
T[j] = key
return T
else:
i += 1
print("Table full -- Rehashing")
T = rehashTable(T, size)
insert(T, key, size)
return T
def search(T, key, size):
i = 0
while i < size or T[i] is None:
j = hashLinearProbe(key, i , size)
if T[j] == key:
return j
else:
i += 1
return None
def delete(T, key, size):
j = search(T, key, size)
if j is not None:
T[j] = -1
def hashFunDivisionMethod(key, size):
return key % size
"""mid-square method
{
// 9452 * 9452 = 89 3403 04 : address is 3403
x = 9452
//select the middle four digits .. //APPEND ZEROES TO MAKE 8-digits
print((x * x//100)%10000)
//select the middle six digits
address = (x * x // 100) % 1000000;
}
"""
"""Folding
There are two folding methods that are used, fold shift and fold boundary. In fold shift,
the key value is divided into parts whose size matches the size of the required address.
Then the left and right parts are shifted and added with the middle part.
In fold boundary, the left and right numbers are folded on a fixed boundary between
them and the center number.
a. Fold Shift
Key: 123456789
123
456
789
---
1368 ( 1 is discarded)
b. Fold Boundary
Key: 123456789
321 (digit reversed)
456
987 (digit reversed)
---
1764 ( 1 is discarded)
"""
def hashLinearProbe(key, i, size):
return ((hashFunDivisionMethod(key, size) + i) % size)
def hashQuadProbe(key, i, size, c1, c2):
return ((hashFunDivisionMethod(key, size) + c1 * i + c2 * i * i) % size)
def hashDoubleHashing(key, i, size):
return((hashFunDivisionMethod(key, size) + i * hashFunDivisionMethod(key, size)) % size)
def rehashTable(T, size):
newSize = size * 2
temp = [None for i in range(newSize)]
for element in T:
insert(temp, element, newSize)
T = temp
return T
def main():
size = 10
T = [None for i in range(size)]
insert(T, 5, size)
print(T)
insert(T,3,size)
print(T)
insert(T,15,size)
print(T)
insert(T,1,size)
print(T)
insert(T,1,size)
print(T)
insert(T,10,size)
print(T)
insert(T,11,size)
print(T)
insert(T,6,size)
print(T)
insert(T,9,size)
print(T)
insert(T,9,size)
print(T)
T = insert(T,14,size)
print(T)
if __name__=='__main__':main()
|
a90f4ec2611b72a04501d162b3a2a34fe61540e9 | ZhiangHu/new-Triangle | /Triangle.py | 1,869 | 3.890625 | 4 | class Triangle(object):# pylint: disable=missing-docstring
def __init__(self):# pylint: disable=missing-docstring
super().__init__()
def triangle(self, A, B, c) :# pylint: disable=missing-docstring
if ((a + b) > c) and ((a + c) > b) and ((b + c) > a):
if (a == b) and (a == c):# pylint: disable=missing-docstring
print('equilateral triangle')
return 3
elif ((a == b) or (a == c) or (b == c)):# pylint: disable=missing-docstring
print('isosceles triangle')
return 2
elif (a * a + b * b == c * c) or (a * a + c * c == b * b) or (c * c + b * b == a * a):
print('right triangle')
if ((a == b) or (a == c) or (b == c)):# pylint: disable=missing-docstring
print('isosceles right triangle')
return 2
else:# pylint: disable=missing-docstring
return 1
else:# pylint: disable=missing-docstring
print('general triangle')
return 1
else:# pylint: disable=missing-docstring
print('not a triangle')
if __name__ == '__main__':# pylint: disable=missing-docstring
while True:# pylint: disable=missing-docstring
a = int(input('please enter the value of a:'))
b = int(input('please enter the value of b:'))
c = int(input('please enter the value of c:'))
if (0 < a <= 200) and (0 < b <= 200) and (0 < c <= 200):# pylint: disable=missing-docstring
print('the three sides of the input are correct')
triangle = Triangle()
print('the number of equal sides is:', triangle.triangle(a, b, c))
break
else:# pylint: disable=missing-docstring
print('wrong input')
|
449f14f1d51a6e4c0216e4fed69e1283845bcbf5 | Weikoi/offer_by_python | /58_对称二叉树.py | 490 | 4.03125 | 4 | class Solution:
def isSymmetrical(self, root):
# write code here
if not root:
return True
else:
return self.check(root.left, root.right)
def check(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return self.check(left.left, right.right) and self.check(left.right, right.left)
|
b42b14aee98869eee4877c7b32a3e7ba6655da60 | cxu60-zz/LeetCodeInPython | /merge_two_sorted_lists.py | 939 | 3.625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
merge_two_sorted_lists.py
Created by Shengwei on 2014-07-21.
"""
# https://oj.leetcode.com/problems/merge-two-sorted-lists/
# tags: easy, linked-list, merge, sorted
"""
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
cursor = dummy_head = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cursor.next = l1
l1 = l1.next
else:
cursor.next = l2
l2 = l2.next
cursor = cursor.next
cursor.next = l1 or l2
return dummy_head.next
|
34626bf2759e47229128c5065153024979a66d97 | mpinta/evovrp | /evovrp/main.py | 2,342 | 3.515625 | 4 | import file
import method
import directory
import evaluation
from random import randint
from NiaPy.util import Task, OptimizationType
from NiaPy.algorithms.basic.ga import GeneticAlgorithm
def print_result(best_instance):
"""Prints a result.
Prints overall best instance information to output.
Args:
best_instance: A Fitness object, indicating overall best instance.
Returns:
Method does not return anything.
"""
print('Best instance: ')
print('Generation: ' + str(best_instance.generation))
print('Instance: ' + str(best_instance.instance))
print('Fitness: ' + str(round(best_instance.value, 2)))
print('Phenotype: ' + str(best_instance.phenotype))
def main(file_name, algorithm, iterations, population_size, phenotype_coding):
"""Main function.
Function is used for connecting the main parts of a project. Firstly, it
calls deletion of before created image directories. Then it calls file
reading method and so gets parsed objects from it. It creates new task
with given information and runs it using selected evolutionary algorithm.
Lastly, it calls printing information of overall best instance to output.
Args:
file_name: A string, indicating name of a file, which will be read.
algorithm: A NiaPy algorithm, indicating evolutionary algorithm
that will be used.
iterations: An integer, indicating number of repetitions.
population_size: An integer, indicating number of instances that will
be created inside one generation.
phenotype_coding: An enum type, indicating which genotype-to-phenotype
coding will be used in evaluation.
Returns:
Method does not return anything.
"""
directory.Directory().delete_directories()
objects = file.File.read('../datasets/' + file_name)
task = Task(D=len(objects[1]), nFES=iterations, benchmark=evaluation.Evaluation(
objects, iterations, population_size, phenotype_coding), optType=OptimizationType.MINIMIZATION)
alg = algorithm(seed=randint(1000, 10000), task=task, NP=population_size)
result, fitness = alg.run()
print_result(evaluation.Evaluation.find_overall_best_instance(fitness))
if __name__ == '__main__':
main('C-mdvrptw/pr00', GeneticAlgorithm, 25, 5, method.Method.FIRST)
|
730358508122d11fdb313b866ddba01e0d094605 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/383.py | 178 | 3.515625 | 4 | def word_count(phrase):
wordlist = phrase.split()
counts = [wordlist.count(word) for word in wordlist]
wordcounts = dict(zip(wordlist, counts))
return wordcounts
|
c8570115e8467baecabe0cfaf5497fd46cf70fa7 | DavidMena-Q/learning_python | /first_steps-py/for.py | 584 | 3.875 | 4 | # count = 1
# print(count)
# while count < 10:
# count += 1
# print(count)
# a = list(range(100))
# print(a)
# for count in range(1, 101):
# print(count)
# for i in range(10):
# print(11 * i)
menu = print(' "Las tablas de multiplicar"')
def run():
multiplicador = float(input('De cuál número quieres ver su tabla de multiplicación? : '))
rango = int(input('Cuál quieres que sea el rango de la multiplicación? '))
for count in range(rango + 1):
print(round(count * multiplicador, 4))
if __name__ == ('__main__'):
run()
|
72a196d64d88b4ad9bdead714cf8ba5171cb7b48 | Rohitthapliyal/Python | /Conditional sta/14.py | 108 | 3.796875 | 4 | n=int(input("enter any number:\n"))
mul=1
while n>0:
x=n%10
n=n//10
mul=mul*x
print(mul)
|
5afa4627475b98056daecac8c087eb1e53ec7257 | abhr1994/Python-Challenges | /Python3_Programs/first-non-repeating-character-in-a-stream.py | 1,543 | 3.953125 | 4 | '''
https://practice.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream/0
Given an input stream of n characters consisting only of small case alphabets the task is to find the first non repeating character each time a character is inserted to the stream.
Example
Flow in stream : a, a, b, c
a goes to stream : 1st non repeating element a (a)
a goes to stream : no non repeating element -1 (5, 15)
b goes to stream : 1st non repeating element is b (a, a, b)
c goes to stream : 1st non repeating element is b (a, a, b, c)
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the stream. Then in the next line are x characters which are inserted to the stream.
Output:
For each test case in a new line print the first non repeating elements separated by spaces present in the stream at every instinct when a character is added to the stream, if no such element is present print -1.
Constraints:
1<=T<=200
1<=N<=500
Example:
Input:
2
4
a a b c
3
a a c
Output:
a -1 b b
a -1 c
'''
def non_rep(arr):
l=[]
for i in arr:
if i not in l:
if arr.count(i)==1:
return i
else:
l.append(i)
return '-1'
for _ in range(int(input())):
n = int(input())
out = []
inp = input().split()
for i in range(1,n+1):
out.append(non_rep(inp[0:i]))
print(" ".join(out))
|
8a55c4721f5b8133c6fe6b63a6f7f135d558ce64 | Pectin-eng/Lesson-2-Python | /lesson_2_task_4.py | 214 | 3.546875 | 4 |
print('Задача 4.')
c = str(input('Введите предложение'))
n = 0
for letter in c.split():
n += 1
if len(letter) > 10:
print(n, letter[:10])
else:
print(n, letter) |
bdbd337e30be44492e593f3a56da548a568bf519 | meadsteve/monte_predictor | /monte_predictor/roulette.py | 3,804 | 3.984375 | 4 | import collections
import math
import random
from dataclasses import dataclass
from typing import List
from matplotlib import pyplot as plt
@dataclass
class Future:
history: List[int]
final_balance: int
def _put_it_on_red(bet: int) -> int:
# 48.60% is the odds on winning if it all goes on red
if random.random() <= 0.4860:
return bet * 2
return 0
def generate_a_future(cash: int, gambles_to_run: int) -> Future:
# Keep a record of our fortunes:
money_history = [cash]
# Whilst we've still got time and money lets spin
while cash > 0 and len(money_history) <= gambles_to_run:
# We've decided our strategy is to always bet half our remaining
# cash on red
bet = math.ceil(cash / 2)
cash = cash - bet
winnings = _put_it_on_red(bet)
# Add our winnings back to our pile of money
cash = cash + winnings
money_history.append(cash)
# Gambling complete. Return the history
return Future(history=money_history, final_balance=cash)
@dataclass
class Prediction:
generated_futures: List[Future]
_final_balances: collections.Counter
def __init__(self, generated_futures: List[Future]):
self.generated_futures = generated_futures
# Find out how many "sprints" each simulation took
final_balances = [future.final_balance for future in generated_futures]
# Now count how common each sprint number was
self._final_balances = collections.Counter(final_balances)
@property
def mode_final_balance(self) -> int:
return self._final_balances.most_common()[0][0]
@property
def frequency_of_final_balances(self):
return self._final_balances.items()
def probability_of_having_money(self, target_money: int) -> float:
successes = [
freq for (balance, freq) in self.frequency_of_final_balances
if balance >= target_money
]
return sum(successes) / len(self.generated_futures)
def make_a_prediction(
starting_cash: int,
gambles_to_run: int,
simulation_count: int = 100_000
) -> Prediction:
# Run the number of simulations specified by the
# model and return this as a prediction
generated_futures = [
generate_a_future(starting_cash, gambles_to_run)
for _ in range(1, simulation_count)
]
return Prediction(generated_futures=generated_futures)
def graph_example_histories(prediction_to_plot: Prediction):
# Grab a bunch of the predictions and plot them
sample_to_graph = random.sample(prediction_to_plot.generated_futures, 10)
plt.xkcd()
for data in sample_to_graph:
plt.plot(data.history)
# No point in showing backwards in time or less than no money
plt.ylim(bottom=0)
plt.xlim(left=0)
# Label stuff
plt.title("Am I rich?")
plt.xlabel("Number of spins")
plt.ylabel("Euros")
plt.show()
def graph_frequencies(prediction_to_plot: Prediction):
x, y = zip(*prediction_to_plot.frequency_of_final_balances)
plt.xkcd()
plt.bar(x, y, color='g')
plt.tight_layout()
plt.title("How rich am I at the end?")
plt.xlabel("Euros I have")
plt.ylim(bottom=0, top=8000)
plt.xlim(left=0, right=150)
plt.show()
prediction = make_a_prediction(starting_cash=100, gambles_to_run=30)
print(f"The probability of having at least a single euro: {math.floor(100 * prediction.probability_of_having_money(1))}%")
print(f"The probability of having made at least a dollar: {math.floor(100 * prediction.probability_of_having_money(101))}%")
print(f"The probability of having at least doubled your money: {math.floor(100 * prediction.probability_of_having_money(200))}%")
graph_example_histories(prediction)
graph_frequencies(prediction)
|
ed4dabb1defd8e3e6d91776f4f618ef27f6e8606 | khatuu/gwccompilation | /dict.py | 312 | 3.9375 | 4 | def translate_shorthand(dict) :
answer = input("(define a shorthand)")
if answer in slangs.keys() :
for key, value in dict.items() :
print(value)
slangs() = {
"ttyl" : "talk to you later",
"omg" : "oh my gawd",
"wtf" : "what the fark",
"l8r" : "later"
}
translate_shorthand(slangs)
|
3df2e04839249650388023651ae94707a78131b8 | kshitijbhure/Python-Codes | /regularExpression.py | 938 | 4.125 | 4 |
# Regular expression sample
import re # import re for regular expression
f = open('regexFile.txt')
# prints all the lines that have Lenore or Nevermore - SEARCH keyword
for line in f:
if re.search('(Len|Neverm)ore', line):
print(line, end='')
print('\n\n End of first part \n')
# Search and replace - SUB keyword
p = open('regexFile.txt')
for line in p:
print (re.sub('(Len|Neverm)ore', '###', line),end='')
print('\n\n End of second part \n')
#Reusing the regular expression
q = open('regexFile.txt')
pattern = re.compile('(Len|Neverm)ore', re.IGNORECASE) # store the pattern in a variable and use it later, IGNORECASE used to ignore the case sensitive characters
# 'search' and 'substitute' both used in single code. this will display only the lines which has the pattern
for line in q:
if re.search(pattern, line):
print(pattern.sub('###',line),end='')
|
69f9cdc3448abd62e68b354f9ebcee601fbd2074 | ktapsyman/Nccucs_work | /Algorithm/HW1/Gen.py | 70 | 3.828125 | 4 | Str = ""
for num in range(1, 2001):
Str += (str(num)+" ")
print(Str)
|
5abe8633f7f2201ad3c0efb7b636935768b7bf93 | sbrodehl/hashcode2021 | /Online Qualifications/solver/street.py | 449 | 3.65625 | 4 | from dataclasses import dataclass, field
from collections import deque
@dataclass
class Street:
"""Class representing a street with intersections and travel time."""
id: int
begin_intersection: int
end_intersection: int
name: str
travel_time: int
waiting: deque["Car"] = field(default_factory=deque, init=False)
driving: dict = field(default_factory=dict, init=False)
visits: int = 0
starting_cars: int = 0
|
13dd52e57ff6f71acd51fe4e5c95aae96c7949cb | Rivareus24/ZNDRN_PL_Luca_python | /main.py | 3,734 | 4.375 | 4 | # 1. Introduction to Coding and to Python
# - Computational Thinking
# - Information binary representation
# - Introduction to the Python programming language
# - Jupyter notebooks
# region 2. Python Data Types
# - Variables, values and types
# - Integer, Float, String, Boolean data types and their operators
x = 9
x = 9.6 # NO double SI float
x = 'ciao'
x = True
print(type(x))
x = 9 == 7
x = 'ciaoo' == 'ciao'
# NUMBERS
# 9 operatore 9
# my_func(9, 9)
somma = 9 + 9
differenza = 4 - 9
# power **
# resto divisione %
# /
# ERROR --> False - 'ciao'
# STRING
print('ciao' + ' Lorenzo')
print('ciao', 'Lorenzo')
'ciao'.replace('c', 'd')
# BOOLEAN
# or ||
# and &&
x = True or False
x = True and False
# endregion
# region 3. Simple programs
# - From pseudo-code to code
# if ci sono 4 mele:
# allora stampo una mela
#
# ciclo tutti gli elementi:
# per ogni
# endregion
# region 4. Functions and Conditional Statements
# - Function definition
def get_result(x, y):
return x + y
get_result(8, 9)
# - Variable's scope
BASE_URL = 'www.google.com'
def get_result(x, y):
print(BASE_URL)
URL = ''
return x + y
# URL
get_result(8, 9)
# - Conditional Statements
if 6 > 8:
print('la matematica non esiste')
# endregion
# region 5. Iterative Computation
# - Formalization of iterative solutions
# - The while loop
condition = True
while condition:
# body
pass
# - The for loop
items = [1, 'ciao', [1, 2, 4], {}]
for item in items:
# body
pass
# endregion
# region 6. Iterative Computation II
# - Nested loops
x, y, z = 1, 2, 3
rows = cols = []
for row in rows:
for col in cols:
pass
# endregion
# region 7. Python Lists
# - Creating and manipulating lists
x = [1, 2, 3]
elements = (1, 2, 3)
# - Iterating through lists
for element in elements:
print(element)
# endregion
# region 8. Introduction to matplotlib
# - Plotting functions with matplotlib
# import matplotlib
# matplotlib.plot()
# - Customizing appearance
# - Using matplotlib to validate data analysis tasks
# endregion
# region 9. Python Lists II
# - Time-series analysis through list processing
# endregion
# region 10. Python Lists III
# - List comprehensions
x = [x + h
for x in [1, 2]
for h in [2, 3]
if x == 9]
# - List sorting
sorted([2, 4, 1])
# - Mutable and Immutable types
# list vs tuple
# - Anonymous functions
def my_func(y):
return y > 1
x = filter(lambda y: y > 1, [1, 2, 3])
x = filter(my_func, [1, 2, 3])
# endregion
# region 11. Python Strings
# - String slicing, concatenation and traversal
# - String manipulation methods
# 12. Python Strings II
# - Text processing, string manipulation and sub-string search
x = [1, 2, 3][1]
x = 'ciao lo'[1:5]
x = 'ciao lo'[-1]
x = 'ciao lo'[5:]
x = 'ciao lo'[:5]
# endregion
# region 13. Python Dictionaries
# - Dictionaries and mapping, keys and values
# - Dictionary creation and access
x = {
'name': 'Lorenzo',
'ral': 15000,
'label3': False,
'label4': [],
'label5': {
},
}
x = x['label1'] # se label1 non esiste spara eccezione
x = x.get('label1', default='Non ho trovato niente') # se label1 non esiste torna None
x['label1'] = 'ciao'
# endregion
# region 14. Python Dictionaries II
# - Iterating through dictionaries
# for x in [1, 2, 3]:
# for label, value in [['l', 'v'], ['l', 'v']]:
for label, value in {}.items():
print(label, value)
# - Efficiency of presence checking
if 'affitto' in {}:
print()
# endregion
# 15. Problem Solving
# - Binary search
|
28c3e66b16bd9ef2cce7700b186ace99dd9e3243 | Aishwarya-Pupala/xplore_pract | /reg_exp.py | 163 | 3.671875 | 4 |
import re
email="ashpupala12@gmail.com"
x=re.findall("@+.{1}com",email)
if x:
print("valid email id")
else:
print("invalid email id")
|
dc8f26036d9ba7f0ec048307a295e502161e8f74 | leocjj/0123 | /Python/python_dsa-master/recursion/factorial.py | 284 | 4.28125 | 4 | #!/usr/bin/python3
"""
Compute the factorial
"""
def factorial(n):
# Compute the factorial
if n <= 1:
return 1
else:
return n * factorial(n - 1)
if __name__ == '__main__':
for i in range(21):
print('The factorial of', i, 'is', factorial(i))
|
562eae2eadb4b754feeeb76ddae38aa7416ce187 | shadesdhiman/InterviewBit-Solutions | /Tree Data Structure/Path To Given Node.py | 861 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 26 12:27:27 2021
@author: wwwsh
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @param B : integer
# @return a list of integers
def solve(self, A, B):
ans= []
def fun(root, B):
if root == None:
return False
if root.val == B:
ans.insert(0,root.val)
return True
if fun(root.left, B):
ans.insert(0, root.val)
return True
if fun(root.right, B):
ans.insert(0, root.val)
return True
fun(A, B)
return ans |
2618dbeab558a74ea8f0dc5aae0aa8575814292f | catwang42/DataScience-at-scale | /1.Data_Manipulation/python-mapreduce/asymmetric_friendships.py | 906 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import MapReduce
import json
import sys
def mapper(record):
key = record[0]
value = record[1]
#we need to consider (a,b) and (b,a) as a same key
mr.emit_intermediate(hash(key)+hash(value),record)
def reducer(key, list_of_values):
if len(list_of_values)==1:
#if the list contains only one pair, i.e the same pair as the key (see mapper),
#it means if our key is (a,b) only (a,b) exists in the data and not (b,a)
#if (b,a) existd, then our key calculation would have yield the same result for (a,b) and (b,a) and so
#the list would have more than 1 entry if there was another combination.
print key
mr.emit((list_of_values[0][0],list_of_values[0][1]))
mr.emit((list_of_values[0][1],list_of_values[0][0]))
#def main():
mr = MapReduce.MapReduce()
#inputdata = open(sys.argv[1])
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
5218b59b828063d084683bcd7795379a365c923b | dlz215/hello_sqlite_python | /sqlite/hello_db_read_cursor_row_factory.py | 539 | 3.84375 | 4 | import sqlite3
conn = sqlite3.connect('first_db.sqlite') # Creates or opens database file
conn.row_factory = sqlite3.Row # Upgrade row_factory
# Create a table
conn.execute('create table if not exists phones (brand text, version integer)')
# Add some data
conn.execute('insert into phones values ("Android", 5)')
conn.execute('insert into phones values ("iPhone", 6)')
conn.commit() # Finalize updates
for row in conn.execute('select * from phones'):
print(row['brand'])
print(row['version'])
conn.close() # And close
|
6cdf0c0ebd495fe89fa2847332928d68a719e53c | armbuster/aoc2020 | /solutions/day11.py | 2,969 | 3.609375 | 4 |
import numpy as np
def search_diagonal(i,j, arr):
diagonal = np.diagonal(arr, j-i)
return any(diagonal[j]==2)
if __name__ == "__main__":
nums = open("inputs/day11.txt", "r").readlines()
nums =[l.strip().replace('.','0').replace("L",'1') for l in nums]
nums = np.array([[int(i) for i in l] for l in nums])
# add border of unnoccupied seats on each edge
nums = np.concatenate((np.array([1] * nums.shape[1]).reshape(1,-1), nums), axis=0)
nums = np.concatenate((nums, np.array([1] * nums.shape[1]).reshape(1,-1)), axis=0)
nums = np.concatenate((nums, np.array([1] * nums.shape[0]).reshape(-1,1)), axis=1)
nums = np.concatenate((np.array([1] * nums.shape[0]).reshape(-1,1), nums), axis=1)
nums2 = nums.copy()
bkup = nums.copy()
done=False
while not done:
done=True
for i in range(1, nums.shape[0]-1):
for j in range(1, nums.shape[1]-1):
empty = 0
full = 0
if nums[i,j] in [1,2]:
for k in range(-1,2):
for v in range(-1,2):
if not (k==0 and v==0):
#print((k,v))
empty+=int(nums[i+k,j+v] != 2)
full+=int(nums[i+k,j+v] == 2)
assert empty+full==8
if empty==8 and nums[i,j]==1:
done=False
nums2[i,j] = 2
elif full >=4 and nums[i,j]==2:
done=False
nums2[i,j] = 1
else:
nums2[i,j] = nums[i,j]
nums=nums2.copy()
print(f"Ans 1: {np.sum(nums==2)}")
directions = [(1,0), (-1,0), (0,1), (0,-1),\
(1,1), (-1,1), (1,-1), (-1,-1),]
nums = bkup.copy()
nums2 = bkup.copy()
r,c = nums.shape
done=False
while not done:
done=True
for i in range(1, nums.shape[0]-1):
for j in range(1, nums.shape[1]-1):
empty = 0
full = 0
if nums[i,j] in [1,2]:
for u,v in directions:
i_star, j_star =i,j
i_star += u
j_star += v
while nums[i_star,j_star] == 0:
i_star+=u
j_star+=v
full += nums[i_star,j_star]==2
empty += nums[i_star,j_star]==1
if empty==8 and nums[i,j]==1:
done=False
nums2[i,j] = 2
elif full >=5 and nums[i,j]==2:
done=False
nums2[i,j] = 1
else:
nums2[i,j] = nums[i,j]
nums=nums2.copy()
print(f"Ans 2: {np.sum(nums==2)}")
|
9c03a194b1599e5a641928b02d268b9b26fd5071 | guilhermealbino33/TECNICO-SENAI | /carroGuilhermeAlbino.py | 548 | 3.875 | 4 | carro = input ("Digite o nome do carro: ")
print ("Nome do carro: "+ carro)
combustivel = input ("Digite o combustível do carro: ")
print (carro, "é movido a "+ combustivel)
media = float (input("Km/l que o carro faz: "))
print ("Media do carro: ", media, "km/l.")
cidade = input ("Nome da cidade de destino: ")
distancia = float (input ("Digite a distância da cidade de destino: "))
print ("Cidade de destino: "+ cidade, "e fica a ", distancia, " km de distancia.")
print ("O carro consumirá" , distancia / media, "litros de ", combustivel)
|
24eac8d8d928512f028131651314cc87d22d4ff3 | Vladyslav92/Python_HW | /lesson_2/6_task.py | 345 | 3.609375 | 4 | # Дана строка "English = 78 Science = 83 Math = 68 History = 65".
# Вычислить сумму всех чисел в строке.
import re
starting_string = 'English = 78 Science = 83 Math = 68 History = 65'
summ = sum(map(int, re.findall('(\d+)', starting_string)))
print('Сумма всех чисел строки -', summ)
|
4753086394f31b3a3e7774a9c060b67f44499bde | mingz2013/study.python | /python02_spider_linux/01_urllib.py | 513 | 3.59375 | 4 | # -*- coding: UTF-8 -*-
import urllib
' 获取web页面内容并返回'
'''
def getWebPageContent(url):
f = urllib.urlopen(url)
data = f.read()
f.close()
return data
'''
#url = 'http://www.baidu.com'
#content = getWebPageContent(url)
'''
content = urllib.urlopen(url).read()
print content
'''
#print urllib.urlopen(url).read()
print urllib.urlopen("http://www.baidu.com").read()
'''
两行代码搞定,
第一行 引入urllib模块,
第二行 打开网址 并读取内容 然后打印
'''
|
56c0b6025423033344c96f21d2f087c379c623f7 | chenxy3791/leetcode | /basic-algo/basic-algo/countPrimes.py | 2,281 | 3.90625 | 4 | """
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
"""
import time
import math
class Solution:
def countPrimes1(self, n: int) -> int:
# Judged as Time-Out.
lst = [k for k in range(n)]
for k in range(2,int(n/2)+1):
m = 2
while (m*k) < n:
#print('k = {0}, m = {1}'.format(k,m))
lst[m*k] = None
m += 1
cntPrimes = 0
for k in range(2,n):
if lst[k] != None:
cntPrimes += 1
return cntPrimes
def countPrimes2(self, n: int) -> int:
# Somehow improved, but fail again.
lst = [k for k in range(n)]
for k in range(2,int(n/2)+1):
m = 2*k
while m < n:
#print('k = {0}, m = {1}'.format(k,m))
lst[m] = None
m += k
cntPrimes = 0
for k in range(2,n):
if lst[k] != None:
cntPrimes += 1
return cntPrimes
def countPrimes3(self, n: int) -> int:
# Greatly improved, Passed.
lst = [k for k in range(n)]
for k in range(2,int(n/2)+1):
if lst[k] == None:
continue
m = 2*k
while m < n:
#print('k = {0}, m = {1}'.format(k,m))
lst[m] = None
m += k
cntPrimes = 0
for k in range(2,n):
if lst[k] != None:
cntPrimes += 1
return cntPrimes
if __name__ == '__main__':
sln = Solution()
# Testcase1
print('Testcase1...')
tStart = time.time()
n = 1500000
print(sln.countPrimes1(n))
tElapsed = time.time() - tStart
print('tElapsed = ', tElapsed, ' (sec)')
tStart = time.time()
n = 1500000
print(sln.countPrimes2(n))
tElapsed = time.time() - tStart
print('tElapsed = ', tElapsed, ' (sec)')
tStart = time.time()
n = 1500000
print(sln.countPrimes3(n))
tElapsed = time.time() - tStart
print('tElapsed = ', tElapsed, ' (sec)') |
3bfa75d3a4e460658da0f53c6eb1d78ff0aa129f | lahusiak/objectOrientedPython | /game.py | 2,887 | 3.578125 | 4 | import sys
from character import Character
from monster import Goblin
from monster import Goose
from monster import Troll
from monster import Witch
class Game:
def set_up(self):
self.player = Character()
self.monsters = [
Goblin(),
Goose(),
Troll(),
Witch()
]
self.monster = self.get_next_monster()
def get_next_monster(self):
try:
return self.monsters.pop(0)
except IndexError:
return None
def got_hit(self):
self.player.hit_points -= 1
def monster_turn(self):
# check to see if monster attacks
if self.monster.attack():
print("{} is attacking!".format(self.monster))
if raw_input("Would you like to dodge? Y/n > ").lower() == 'y':
if self.player.dodge():
print("You dodged the attack!")
else:
print("{} hit you anyway".format(self.monster))
self.got_hit()
else:
print("{} hit you for 1 point".format(self.monster))
self.got_hit()
def player_turn(self):
player_action = raw_input("What would you like to do? [A]ttack, [R]est, [Q]uit > ").lower()
if player_action == 'a':
print("You've attacked {}!".format(self.monster))
if self.player.attack():
if self.monster.dodge():
print("{} dodged your attack".format(self.monster))
else:
print("You attacked {} with your {}".format(self.monster, self.player.weapon))
if self.player.leveled_up():
self.monster.hit_points -=2
else:
self.monster.hit_points -=1
else:
print("You missed!")
elif player_action == 'r':
print("You've decided to take a rest")
self.player.rest()
elif player_action =='q':
print("Thanks for playing")
sys.exit()
else:
self.player_turn()
def clean_up(self):
if self.monster.hit_points <= 0:
self.player.experience += self.monster.experience
print("You killed {}".format(self.monster))
self.monster = self.get_next_monster()
def __init__(self):
self.set_up()
while self.player and (self.monster or self.monsters):
print('\n'+'='*20)
print(self.player)
self.monster_turn()
print('\n' + '=' * 20)
self.player_turn()
self.clean_up()
print('\n' + '=' * 20)
if self.player.hit_points:
print("You win!")
elif self.monsters or self.monster:
print("You lose!")
sys.exit()
Game()
|
bfcbb47daba7c69f05b38ca007f1434d01c7c0ce | yshuifejng/python_test | /test.py | 602 | 3.8125 | 4 | # -*- coding: utf8 -*-
u'''
Created on 2017年8月22日 上午11:45:59
@author: shaofeng.yang
'''
class test(object):
def __init__(self, name, sex):
self._name = name
self._sex = sex
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if isinstance(name, dict):
raise Exception('name is dict')
else:
self._name = name
def get_msg(self):
return self._name
if __name__ == '__main__':
t = test('hello', 'famax')
t.name = 'abc'
print(t.name)
print(t.get_msg()) |
c36365d8cd581685d6f5d41f3bfc78e921984802 | MrYelameli/data-structure-algorithms | /Arrays/left_rotate.py | 225 | 4 | 4 | '''Counter clockwise movement'''
def counter_clockwise(arr):
temp=arr[0]
i=1
while i < len(arr):
arr[i-1]=arr[i]
i+=1
arr[len(arr)-1]=temp
return arr
print(counter_clockwise([1,2,3,4,5])) |
9dfedeee5ca7d0aa512e71a50af2cbc38087e06e | AnshTrehan/old-python-codes | /electricity bill.py | 521 | 3.859375 | 4 | n=int(input("Please enter your bill money "))
b=0
if (n<=50):
b=n*0.50
print(b)
elif (n>50 and n<=150):
n=n-50
b=(50*0.50)+(n*0.75)
print("Total bill payment is",b)
elif (n>150 and n<=250):
n=n-150
b=(50*0.50)+(100*0.75)+(n*1.20)
print("Total bill payment is",b)
elif (n>250):
n=n-250
b=(50*0.50)+(100*0.75)+(100*1.20)+(n*1.50)
print("Total bill payment is",b)
tax= (b/100)*20
total_bill= b+tax
print("TOTAL TAX BY THE ELECTRICITY DEPARTMENT OF INDIA",total_bill)
exit()
|
443cd48d19b9e1b0996831f419a771acdb3fed69 | 047H-04EH/python | /simple_class.py | 129 | 3.921875 | 4 | class Myclass:
"""example class"""
a=5
def func(self):
return 'hello'
x=Myclass()
print(x.func())
print(x.a)
|
815980faf8e0317c3a29f7c7b6d4acd743206652 | mateen91/python-bootcamp | /P2_Syntax.py | 121 | 3.546875 | 4 | # INDENTATION SYNTAX
# if 4 > 2:
# print("Four is greater than two!")
if 4 > 2:
print("Four is greater than two!")
|
9fbe9191ee7acfaf8333a543f9230641acbcdfcb | QhLiuSWJ/python_practtice | /practice100/P11.py | 347 | 3.5625 | 4 | # -*- coding: UTF-8 -*-
"""
@author:QHL
@file:P11.py
@time:2020/03/01
"""
def rabbit(num):
f1 = 1
# 第一个月为1
f2 = 1
# 第二个月为1
if num == 1 or num == 2:
return 1
else:
for i in range(num - 1):
f1, f2 = f2, f1 + f2
return f1
if __name__ == '__main__':
print(rabbit(36)) |
d3c77a2a68d6e262041912ca5758efb48e45ce0a | yawzyag/python | /sum.py | 222 | 3.703125 | 4 | import numpy as np
# delacaracion de las 2 array
A = ([1, 6, 5], [3, 4, 8], [2, 12, 3])
B = ([3, 4, 6], [5, 6, 7], [6, 56, 7])
# uso de numpy para sumar las 2 array
C = np.add(A, B)
print("Suma de los dos array : ", C)
|
3ae875f704f85769ddcaacf5c27efd8e8ebdb9eb | CharlesHehe/leetcode | /Linked List/Add Two Numbers.py | 1,710 | 3.875 | 4 | # You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#
# Example:
#
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
# Definition for singly-linked list.
# unfinished
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def add_list_item(self, item):
if not isinstance(item, ListNode):
item = ListNode(item)
self.next = item
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# iterate the list and get the value
a = []
while isinstance(l1, ListNode):
a.append(l1.val)
l1 = l1.next
a.reverse()
b = []
while isinstance(l2, ListNode):
b.append(l2.val)
l2 = l2.next
b.reverse()
sum_list = [a + b for a, b in zip(a, b)]
sum_list.reverse()
for i in range(len(sum_list) - 1):
ListNode(sum_list[i], ListNode(sum_list[i + 1]))
if __name__ == "__main__":
s = Solution()
a = [2, 4, 3]
b = [5, 6, 4]
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
# ListNode(a)
# for i in a:
# l1.add_list_item(ListNode(i, None))
# for j in b:
# l2.add_list_item(ListNode(j, None))
s.addTwoNumbers(l1, l2)
|
1c0a02de5545e8afd2044ab921d40b6b9bd46ca7 | cwjayroe/coding-challenges | /answers/problem1/answer.py | 554 | 3.53125 | 4 | def main():
test_array = [5,8,12]
test_k = 18
check_if_matches(test_array, test_k)
def check_if_matches(number_array, k):
number_array_index = 0
number_array_length = len(number_array)
for loop_number in number_array:
for range_number in range(number_array_index, number_array_length):
number_addition = loop_number + number_array[range_number]
if number_addition == k:
return True
number_array_index += 1
return False
if __name__ == "__main__":
main() |
36e4282b3f03b365394e0b0239ca943b1f9baca4 | ohentony/Aprendendo-python | /Condições em python/ex012.py | 743 | 3.75 | 4 | '''Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida:
- Média abaixo de 5.0: REPROVADO
- Média entre 5.0 e 6.9: RECUPERAÇÃO
- Média 7.0 ou superior: APROVADO'''
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
med = (n1 + n2)/2
if 5.0 <= med <= 6.9:
print('Tirando {} e {}, a média do aluno é {:.1f}\nO aluno está em \033[31mRECUPERAÇÃO\033[m'.format(n1,n2,med))
elif med < 5.0:
print('Tirando {} e {}, a média do aluno é {:.1f}\nO aluno está \033[31mREPROVADO\033[m'.format(n1,n2,med))
else:
print('Tirando {} e {}, a média do aluno é {:.1f}\nO aluno está \033[32mAPROVADO\033[m'.format(n1,n2,med))
|
8046fd272ff919a38736ca8a77df772338cb4089 | ipeksargin/data-structures-algorithms | /queues/queue.py | 516 | 3.875 | 4 | #first in first out principle
class queue():
def __init__(self):
self.items = []
def isEmpty(self):
if len(self.items)==0:
print("This queue is empty.")
else:
print("not empty")
def enqueue(self,item):
self.items.insert(0,item)
print(self.items)
def dequeue(self):
self.items.pop()
print(self.items)
myq = queue()
myq.enqueue("one")
myq.enqueue(2)
myq.enqueue(6)
myq.enqueue("ten")
myq.dequeue()
#myq.isEmpty()
|
114951996b50d5941774203e31ad1d76d5008650 | PP1-hub/PP2 | /TSIS 3/3760.py | 120 | 3.59375 | 4 | x = int(input())
map={}
for i in range(x):
a,b=input().split()
map[a]=b
map[b]=a
z = input()
print(map[z]) |
47159e345385bfee28dde42332804c1d85b1079d | vongrossi/HPD-CodeOps | /python/exercicio.py | 619 | 3.921875 | 4 | print('Qual eh o seu nome')
nome = input()
print('Ola ' + nome + ' Qual a sua idade' )
idade = input()
print(str(idade) + ' legal qual o seu sexo ')
sexo = input()
print('sexo: ' + sexo + ' Qual a sua cidade')
cidade = input()
print('Em qual estado fica ' + cidade )
estado = input()
print('Legal então ' + cidade + ' fica em ' + estado + ' agora informe o seu estado civil' )
estado_civil = input()
print('confirmando os dados informados : ' + nome + ' voce tem ' + str(idade) + ' eh do sexo ' + sexo + ' sua cidade eh: ' + cidade + ' que fica no estado de ' + estado + ' e seu estado civil eh ' + estado_civil)
|
040dd6551bf45eb4c558635d0017ab974604bd04 | MagdalenaSvilenova/Python-Advanced | /multidimensional_lists/primary_diagonal.py | 304 | 3.6875 | 4 | size = int(input())
matrix = [[0] * size for row in range(0, size)]
for x in range(0, size):
line = list(map(int, input().split()))
for y in range(0, size):
matrix[x][y] = line[y]
sum_diagonal = sum(matrix[size - i - 1][size - i - 1] for i in range(size))
print(sum_diagonal)
|
fc188df8f4daa25d3253a1c54fbcc1553361e922 | Spyroslon/CM1103-Problem-Solving-with-Python | /Week8/week8ex8.py | 240 | 4.1875 | 4 | import re
def matchEmail(email):
result = re.match("[a-z]+@[a-z]+.[a-z]{3}",email)
if result != None:
print ("Matched")
else:
print("Not Matched")
matchEmail(str(input("Enter an email address: ")))
|
29a760da7e28e86bf5b68eab14e8bcc0075f6d4a | deepakmanktala/AutomateBoringStuff | /mainuserpwd.py | 282 | 3.640625 | 4 | print('Enter Name')
name = raw_input()
if name == 'Mary':
print('Hello Mary')
print('Enter Password')
password = raw_input()
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
else:
print('Wrong Username.')
|
5e666b4902bdb4ba69ab8479546276b407eb375f | mvpoland/django-utilities | /src/utilities/__init__.py | 2,169 | 3.78125 | 4 | VERSION = (0, 1,)
# Dynamically calculate the version based on VERSION tuple
if len(VERSION) > 2 and VERSION[2] is not None:
str_version = "%s.%s_%s" % VERSION[:3]
else:
str_version = "%s.%s" % VERSION[:2]
__version__ = str_version
import datetime
def is_years_ago(verify_date, years, start_date=None):
if start_date is None:
if isinstance(verify_date, datetime.datetime):
start_date = datetime.datetime.now()
else:
start_date = datetime.date.today()
try:
start_date = start_date.replace(year=start_date.year - years)
except ValueError:
if start_date.month == 2 and start_date.day == 29:
start_date = start_date.replace(month=2, day=28,
year=start_date.year - years)
return (verify_date - start_date).days > 0
def sorted_dict(adict, reverse=False):
keys = adict.keys()
keys.sort(reverse=reverse)
return map(adict.get, keys)
def whole_number(number):
"""
If the value has no decimal value then we convert to int. This looks nicer
"""
if number % 1 == 0:
return int(number)
return number
class EnrichedIterable(object):
"""
Enricher for an iterable object. The enrich method will be called as late
as possible. (On retrieval of a single item.)
"""
def __init__(self, iterable, enrich_func):
self.iterable = iterable
self.enrich_func = enrich_func
class Iterator(object):
def __init__(self, iterator, enrich_func):
self.iterator = iterator
self.enrich_func = enrich_func
def next(self):
item = self.iterator.next()
self.enrich_func(item)
return item
def __getitem__(self, k):
if isinstance(k, slice):
return EnrichedIterable(self.iterable[k], self.enrich_func)
else:
item = self.iterable[k]
self.enrich_func(item)
return item
def __iter__(self):
return EnrichedIterable.Iterator(self.iterable.__iter__(), self.enrich_func)
def __len__(self):
return len(self.iterable)
|
d9ee8476009c9e5cfa9dbe539c2174d317370928 | abbeeda/ggbo | /jj6.py | 568 | 3.5625 | 4 | <<<<<<< HEAD
a=input("请输入年份:")
b=a[-1:]
c=int(a[:-1])
while b == "年":
break
else:
print("输入错误")
if c%4==0:
if c%100==0:
print("该年不是闰年")
else:
print("该年是闰年")
else:
print("该年不是闰年")
=======
a=input("请输入年份:")
b=a[-1:]
c=int(a[:-1])
while b == "年":
break
else:
print("输入错误")
if c%4==0:
if c%100==0:
print("该年不是闰年")
else:
print("该年是闰年")
else:
print("该年不是闰年")
>>>>>>> c4107b7d195ae20fa506d622edecf008161c987b
|
142db6f2d8b035ba41d0d5cdb3492d3c3fc7d85e | felipesch92/PythonExercicios | /ex010.py | 135 | 3.65625 | 4 | v = float(input('Informe quanto você possui na carteira: '))
d = v/5.31
print('Com R$ {} você pode comprar US$ {:.2f}'.format(v, d))
|
27a76db3f2c04c1ad4fe1c008d20e445904b40f8 | jason-tung/transform | /matrix.py | 2,507 | 4.09375 | 4 | """
A matrix will be an N sized list of 4 element lists.
Each individual list will represent an [x, y, z, 1] point.
For multiplication purposes, consider the lists like so:
x0 x1 xn
y0 y1 yn
z0 z1 ... zn
1 1 1
"""
import math
def make_translate(x, y, z):
idmat = new_matrix()
ident(idmat)
hey = [x, y, z, 1]
for x in range(len(idmat)):
idmat[3][x] = hey[x]
return idmat
def make_scale(x, y, z):
idmat = new_matrix()
ident(idmat)
hey = [x, y, z, 1]
for x in range(len(idmat)):
idmat[x][x] = hey[x]
return idmat
def make_rotX(theta):
idmat = new_matrix()
ident(idmat)
for x in range(2):
idmat[x + 1][x + 1] = math.cos(math.radians(theta))
idmat[1][2] = math.sin(math.radians(theta))
idmat[2][1] = -math.sin(math.radians(theta))
return idmat
def make_rotY(theta):
idmat = new_matrix()
ident(idmat)
for x in range(0, 3, 2):
idmat[x][x] = math.cos(math.radians(theta))
idmat[0][2] = -math.sin(math.radians(theta))
idmat[2][0] = math.sin(math.radians(theta))
return idmat
def make_rotZ(theta):
idmat = new_matrix()
ident(idmat)
for x in range(2):
idmat[x][x] = math.cos(math.radians(theta))
idmat[0][1] = math.sin(math.radians(theta))
idmat[1][0] = -math.sin(math.radians(theta))
return idmat
# print the matrix such that it looks like
# the template in the top comment
def print_matrix(matrix):
s = ''
for r in range(len(matrix[0])):
for c in range(len(matrix)):
s += str(matrix[c][r]) + ' '
s += '\n'
print (s)
# turn the paramter matrix into an identity matrix
# you may assume matrix is square
def ident(matrix):
for r in range(len(matrix[0])):
for c in range(len(matrix)):
if r == c:
matrix[c][r] = 1
else:
matrix[c][r] = 0
# multiply m1 by m2, modifying m2 to be the product
# m1 * m2 -> m2
def matrix_mult(m1, m2):
point = 0
for row in m2:
# get a copy of the next point
tmp = row[:]
for r in range(4):
m2[point][r] = (m1[0][r] * tmp[0] +
m1[1][r] * tmp[1] +
m1[2][r] * tmp[2] +
m1[3][r] * tmp[3])
point += 1
def new_matrix(rows=4, cols=4):
m = []
for c in range(cols):
m.append([])
for r in range(rows):
m[c].append(0)
return m
|
654185914957fb3065ea4d6eba03c6607b2692bf | yarnoiser/PyDungeon | /dice.py | 752 | 3.734375 | 4 | # Implementation of randbelow from python 3.6's secrets module
# Copyright © 2001-2017 Python Software Foundation; All Rights Reserved
from random import SystemRandom
_sysrand = SystemRandom()
def randbelow(exclusive_upper_bound):
"""Return a random int in the range [0, n)."""
if exclusive_upper_bound <= 0:
raise ValueError("Upper bound must be positive.")
return _sysrand._randbelow(exclusive_upper_bound)
# End of python software foundation code
# ====================================================================
class Die():
def __init__(self, sides):
self.sides = sides
def roll(self):
return randbelow(self.sides) + 1
D4 = Die(4)
D6 = Die(6)
D8 = Die(8)
D10 = Die(10)
D12 = Die(12)
D20 = Die(20)
D100 = Die(100)
|
54cfc9cebf13812a5772c12e37bc403ec778567f | ffadullgu/programaciondecomputadores | /codigo/python3/13_referencias.py | 333 | 3.578125 | 4 | class Persona:
def __init__(self):
self.nombre = ""
self.codigo = 0
p1 = Persona()
p1.nombre = "Juan"
p1.codigo = 100
p2 = p1
p2.nombre = "Ana"
print(p1.nombre, "tiene el código", p1.codigo)
print(p2.nombre, "tiene el código", p2.codigo)
print(p1)
print(p2)
print(p1 is p2)
print(type(p1))
print(type(p2))
|
7deab9a4f91eb444b409307cfb5bbb5b8c8742f1 | RobertNguyen125/PY4E | /ex_08_list/ex_08_05.py | 311 | 3.703125 | 4 | fhand = open('mbox_short.txt')
count = 0
for line in fhand:
line = line.rstrip()
if line.startswith('From '):
count = count + 1
words = line.split()
print(words[1]) #pay attention to indentation here
print('There were ', count, ' lines in the file with From as the first words')
|
0c7bdbd27949e3fe13abf448812d25a45d043580 | da-foxbite/KSU121 | /Python/lab8 [2, 5, 7, 12, 17]/t7.py | 2,392 | 3.640625 | 4 | # 141, Суптеля Владислав
# 【Дата】:「09.04.20」
# 7. Скласти опис класу для визначення одновимірних масивів рядків фіксованої довжини. Передбачити контроль виходу за межі
# масиву, можливість звернення до окремих рядків масиву за індексами, виконання операцій поелементного зчеплення двох масивів
# з утворенням нового масиву, злиття двох масивів з виключенням повторюваних елементів, а також висновок на екран елемента масиву
# по заданому індексу і всього масиву.
from typing import List
class FixArray:
length: int
capacity: int
elements: List[str]
def __init__(self, elements: List[str], capacity: int = None):
self.length = len(elements)
self.elements = []
if capacity is None:
capacity = self.length
self.capacity = capacity
for elem in elements:
self.elements.append(elem)
def __getitem__(self, key):
assert (key < self.length)
return self.elements[key]
def append(self, value):
assert (self.length < self.capacity)
self.elements.append(value)
self.length += 1
def concat(self, arr):
united = FixArray([], self.capacity + arr.capacity)
for elem in self.elements:
united.append(elem)
for elem in arr.elements:
united.append(elem)
return united
def fuse(self, arr):
fused = FixArray([], self.capacity + arr.capacity)
considered = {}
for elem in self.elements:
if elem not in considered:
fused.append(elem)
considered[elem] = True
for elem in arr.elements:
if elem not in considered:
fused.append(elem)
considered[elem] = True
return fused
def __str__(self):
description = ''
for elem in self.elements:
description += elem + ' ► '
return description
arr1 = FixArray(['-1', 'new var', 'var'], 3)
arr2 = FixArray(['var', '0', '0'], 2)
unity = arr1.fuse(arr2)
print(unity)
|
8f70ac7492e068b807a8bf04a6c8be8499e1b9d6 | dopiwoo/basic-algorithm | /pattern1-sliding-window/7. Longest Substring with Same Letters after Replacement (hard).py | 2,941 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 16:07:27 2020
@author: dopiwoo
Given a string with lowercase letters only, if you are allowed to replace no more than 'k' letters with any letter, find
the length of the longest substring having the same letters after replacement.
Example 1:
Input: 'aabccbb', k=2
Output: 5
Explanation: Replace the two 'c' with 'b' to have a longest repeating substring 'bbbbb'.
Example 2:
Input: 'abbcb', k=1
Output: 4
Explanation: Replace the 'c' with 'b' to have a longest repeating substring 'bbbb'.
"""
def length_of_longest_substring(str1: str, k: int) -> int:
"""
This problem follows the Sliding Window pattern, and we can use a similar dynamic sliding window strategy as
discussed in No-repeat Substring. We can use a HashMap to count the frequency of each letter.
We’ll iterate through the string to add one letter at a time in the window.
We’ll also keep track of the count of the maximum repeating letter in any window (let’s call it
maxRepeatLetterCount).
So, at any time, we know that we can have a window which has one letter repeating maxRepeatLetterCount times; this
means we should try to replace the remaining letters.
If we have more than ‘k’ remaining letters, we should shrink the window as we are not allowed to replace more than
‘k’ letters.
While shrinking the window, we don’t need to update maxRepeatLetterCount (which makes it global count; hence, it is
the maximum count for ANY window). Why don’t we need to update this count when we shrink the window? The answer: In
any window, since we have to replace all the remaining letters to get the longest substring having the same letter,
we can’t get a better answer from any other window even though all occurrences of the letter with frequency
maxRepeatLetterCount is not in the current window.
Time Complexity: O(N)
Space Complexity: O(1)
Parameters
----------
str1 : str
input string
k : int
maximum number of replacement
Returns
-------
max_length : int
the length of the longest substring having the same letters after replacement
"""
max_repeat = 0
max_length = 0
seen = {}
window_start = 0
for window_end in range(len(str1)):
right_char = str1[window_end]
if right_char not in seen:
seen[right_char] = 1
else:
seen[right_char] += 1
max_freq_count = max(max_repeat, seen[right_char])
if window_end - window_start + 1 - max_freq_count > k:
seen[str1[window_start]] -= 1
window_start += 1
max_length = max(max_length, window_end - window_start + 1)
return max_length
if __name__ == '__main__':
print(length_of_longest_substring('aabccbb', 2))
print(length_of_longest_substring('abbcb', 1))
print(length_of_longest_substring('abccde', 1))
|
74481bfd1e2772f8ca5663fbbef250e8c81036d8 | harmanbirdi/python | /1app/phone.py | 3,959 | 3.984375 | 4 | #!/usr/bin/env python
#
# Description : Let's say I have some files and sub-directories in a directory tree.
# Given the path to this directory, I want you to write a script or even a single command-line/shell
# statement (if you can) that will examine each file found within the directory tree and print out any
# lines that contain possible phone numbers. Let's assume a phone number is 10 digits in length.
# o xxx.xxx.xxxx is a valid phone number
# o (xxx) xxx-xxxx is also a valid phone number
# o xxxxxxxxxx is also a valid phone number
#
# Bonus:
# o if the script can also print out the full path and filename of the file before printing
# the matching lines with phone numbers
# o if the script can reformat the phone number into a standard, normalized form
# o if the script can also detect possible phone numbers with country codes
# e.g. +20 010 012 5486
# Implementation: Uses the Tree class with the optional function processing capability for each file.
# The print_phones function is passes to the Tree class, which prints the tree and runs
# print_phones function for text (ASCII) files, but displays errors for binary files.
# More Info : Asked by Nour for 1app phone screen interview
# __author__ : Harman Birdi
# Date : Sep 16, 2016
# TODO : Detect phone numbers with its country code
#
import sys
import re
import commands
from colors import Colors
from tree import Tree
from optparse import OptionParser
def find_phones(fle):
"""
This method finds all the phones that match on a line (only one per line)
:param fle:
Full path to the input file
:return:
List of phone numbers
"""
digits = []
fh = open(fle)
lines = fh.readlines()
# Remove all non-digits from the line - quick hack instead of doing various pattern recognition
# for phone numbers. Proper regex would be better way to go. It returns only first 10 numbers
# matched on each line.
for line in lines:
digits.append(re.sub('\D', '', line))
fh.close()
return [phone for phone in digits if len(phone) == 10]
def normalize(phones):
"""
This method normalizes and returns phone list to (xxx) xxx-xxxx format
:param phones:
List of phone numbers that needs to be normalized.
:return:
List of normalized phone numbers.
"""
fones = []
for phone in phones:
fones.append('(%s) %s-%s' % (phone[0:3], phone[3:6], phone[6:]))
return fones
def print_phones(**kwargs):
"""
Function passed to tree which is called for a file by the Tree.process_tree() method
:param kwargs:
:return:
"""
full_path = kwargs['full_path']
separator = kwargs['separator']
depth = kwargs['depth']
mime = commands.getoutput('file %s' % full_path)
try:
if 'empty' in mime:
pass
elif 'text' in mime:
phones = normalize(find_phones(full_path))
for phone in phones:
print separator * (Tree.depth + 1), phone
else:
print separator * (depth + 1),
print Colors.FAIL + 'ERROR: File is of binary type' + Colors.ENDC
except ValueError:
pass
# Main starts here
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-d", "--dir", dest="dirname", help="Directory name for tree", metavar="DIR")
(options, args) = parser.parse_args()
if options.dirname is None:
err = Colors.FAIL + ' Dirname argument cannot be empty.\n'
err += ' Use -h flag for additional help.\n' + Colors.ENDC
sys.stderr.write(err)
exit(1)
dirname = options.dirname
tree = Tree()
tree.process_tree(dirname, func=print_phones)
|
9064828458366276c74df5b4bba9f332c98ad268 | paxzeno/CrackingTheCodingInterview | /interview_questions/stacks_n_queues/three_in_one.py | 2,079 | 3.640625 | 4 | class A:
def __init__(self, value):
self._value = value
def get_value(self):
return self._value
@staticmethod
def get_type():
return 'A'
class B(A):
def __init__(self, value):
A.__init__(self, value)
@staticmethod
def get_type():
return 'B'
class C(A):
def __init__(self, value):
A.__init__(self, value)
@staticmethod
def get_type():
return 'C'
class ThreeStack:
def __init__(self, size):
self._list = [None] * size
self._PA1 = 0
self._PA2 = 0
self._PB1 = size / 3
self._PB2 = size / 3
self._PC1 = (size / 3) * 2
self._PC2 = (size / 3) * 2
def push(self, item):
# prevent collisions
if item.get_type() == 'A':
self._list[self._PA2] = item
self._PA2 += 1
# if self._PA2 == self._PB1:
if item.get_type() == 'B':
self._list[self._PB2] = item
self._PB2 += 1
if item.get_type() == 'C':
self._list[self._PC2] = item
self._PC2 += 1
def pop_a(self):
a = self._list[self._PA2 - 1]
self._list[self._PA2 - 1] = None
self._PA2 -= 1
return a
def pop_b(self):
self._PB2 -= 1
return self.pop(self._PB2)
def pop(self, pointer):
item = self._list[pointer]
self._list[pointer] = None
return item
if __name__ == '__main__':
a1 = A(1)
b1 = B(2)
c1 = C(3)
a2 = A(2)
b2 = B(4)
c2 = C(6)
a3 = A(4)
b3 = B(8)
c3 = C(12)
a4 = A(8)
b4 = B(16)
c4 = C(24)
stack = ThreeStack(10)
stack.push(a1)
stack.push(b1)
stack.push(c1)
stack.push(a2)
stack.push(b2)
stack.push(c2)
stack.push(a3)
stack.push(b3)
stack.push(c3)
# stack.add(a4)
# stack.add(b4)
# stack.add(c4)
print('A' + str(stack.pop_a().get_value()))
print('B' + str(stack.pop_b().get_value()))
print('B' + str(stack.pop_b().get_value()))
print('coisas')
|
cfd185d73e6db08f968f2a89f0005239d8d5d504 | JollenWang/study | /python/python_prj/try_exception.py | 245 | 3.5625 | 4 | #!/usr/bin/python
# try to occure an excepiton
import sys
try:
s = raw_input('Enter somthing-->')
except EOFError:
print('error of EOF!')
sys.exit()
except:
print('some other exception occurs!')
print('Done:')
|
7debcd65480361741ae1f00023b620f3b0d5a718 | hanhan392003/nguyenhanhan-c4t8-hw6 | /for_list.py | 239 | 3.703125 | 4 | items = ["pho", "com", "chao"]
# print(items)
# print(*items)
# print(items[0])
# l = len(items)
# for i in range(l):
# print(items[i])
# for item in items:
# print(item)
for i, item in enumerate(items):
print(i+1,".", item) |
efca2a9d53aa4bde1e5a7a5afda416eb93b67303 | Mirsait/100_days_of_python | /day_013/main.py | 1,577 | 3.640625 | 4 | import random
from art import logo, vs, crown
from game_data import data
def clear_and_logo():
print('\033c')
print(logo)
def print_info(letter, obj):
print(f" {letter}. {obj['name']}")
print(f"{obj['description']} from {obj['country']}")
def print_lose_end(score, obj1, obj2):
print(f"{obj1['name']} has {obj1['follower_count']}M followers.")
print(f"{obj2['name']} has {obj2['follower_count']}M followers.")
print(f"\nYour score: {score}.\n")
def print_win_end(score):
print(crown)
print(f"\nYour score: {score}.\n")
def game():
random.shuffle(data)
data_count = len(data)
current = 0
is_continue = True
score = 0
is_win = False
while is_continue:
# for terminal clearing
clear_and_logo()
fact1 = data[current]
print_info("A", fact1)
print(vs)
fact2 = data[current + 1]
print_info("B", fact2)
is_higher = fact1["follower_count"] >= fact2["follower_count"]
is_hl = input(
f"\nWho has more followers? [A or B] ").lower() == 'a'
if is_higher == is_hl:
score += 1
current += 1
else:
is_continue = False
is_win = False
if current == data_count-1:
is_continue = False
is_win = True
clear_and_logo()
if is_win:
print_win_end(score)
else:
print_lose_end(score, fact1, fact2)
is_new_game = input("Do you wanna play again?[y/N] ").lower() == 'y'
if is_new_game:
game()
game()
|
f3417ed1fda8dcfd7e91cc21074c99b046e1d279 | eskeype/GamePlayer | /src/Match.py | 1,136 | 3.90625 | 4 |
class Match:
def __init__(self, game, player1, player2):
self.game = game
player1.match_initializer(1, game)
player2.match_initializer(2, game)
self.players = {1:player1, 2:player2}
def play(self, verbose = True, finalize = True):
current_player = 1
if verbose:
print( "{}\n".format(self.game.board_to_string()))
while not (self.game.draw() or self.game.winner() != 0):
self.players[current_player].play_move()
if verbose:
print( "{}\n".format(self.game.board_to_string()))
current_player = 3 - current_player
if finalize:
# Finalization methods are called here
# These can be used to train learning game players
# or do other bookkeeping at the end of a game
# Finalization can be skipped, so that if a Match
# is being played for validation, the training method
# does not need to be called
self.players[1].finalize()
self.players[2].finalize()
winner = self.game.winner()
if winner != 0:
if verbose:
print("Player {} won!\n".format(winner))
return winner
elif verbose:
#draw game
print("Draw Game!\n")
return 0
|
e092056b43d7b65453ec855d4f97b422ccd32d6f | StarFc/Listappv3.py | /Listappv3.py | 6,634 | 4.1875 | 4 | import random
myList = []
unique_list = []
def mainProgram():
#build our while loop
while True:
print("Hello, there! Let's work with lists!")
print("Please choose front the following options. Type the number of the choice")
choice = input("""1. Add to a list,
2. Return a value in a list,
3. Add a bunch of numbers!
4. Random search
5. Linear Search
6. sort List
7. Print lists
8. Quit """)
if choice == "1":
addToList()
elif choice == "2":
indexValues()
elif choice == "3":
addABunch()
elif choice == "4":
randomSearch()
elif choice == "5":
linearSearch()
elif choice == "6":
sortList(myList)
elif choice == "7":
printLists()
elif choice == "8":
searchItem = input("What are you looking for? ")
recursiveBinarySearch(unique_list, 0, len(unique_list)-1, int(searchItem))
else:
break
void printSomething();
int main(){
printSomething();
return 0;
}
void printSomething(){
print("I'm a function"):
return;
}
def addToList():
print("Adding to a list! Great choice!")
newItem = input("Type an integer here! ")
myList.append(int(newItem))
#we need to think about errors!
''
def addABunch():
print("we're gonna add a bunch of number to your list!")
numToAdd = input("How many new integers would you like to add? ")
numRange = input("And how high would you like these numbers to go ")
for x in range(0, int(numToAdd)):
myList.append(random.randint(0, int(numRange)))
print("Your list is complete!")
def sortList(myList):
#"myList" is the ARGUMENT this function takes.
for x in myList:
if x not in unique_list:
unique_list.append(x)
unique_list.sort()
showMe = input("Wanna see your new, sorted list? Y/N")
if showMe.lower() =="y":
print(unique_list)
"""
Function explanation: we created a variable called 'indexPos', and stored
the result of an input function inside it.
We then force the value stored in indexPos into an integer (using the int() function)
and used the variable to call a value at a specific index position.
"""
def randomSearch():
print("oH, iM sO rAnDom!!!")
myList[random.randint(0, len(myList) -1)]
"""
The first line where it says "randomseach" it means adding a random vector, and vector has to do with the two random segments.
the second line shows that so the computer can understand the statment you are trying to give.
The 3rd line is to create a variable.
"""
def linearSearch():
print("We're going to go through this list one item at a time!")
searchValue = input("What are you looking for?" )
for x in range(len(myList)):
if myList[x] == int(searchValue):
print("Your item is at index position ()".format(x))
"""
Linearsearch is suppose to check the elements of this program.
Second line is the give a statment.
third line returns it back, so when if you were to run it it returns to where you code it to stop
For "x in range" I remember it having to do something like with an integer, to a loop.
5th line is ti create a variable.
The last line I think is to print what you want the computer to know.
"""
def recursiveBinarySearch(unique_list, low, high, x):
if high >= low:
mid = (high + low) // 2
if unique_list[mid] == x:
print("Your number is at index psoition{}".format(mid))
return mid
elif unique_list[mid] > x:
return recursiveBinarySearch(unique_list, low, mid, mid-1, x)
else:
return recursiveBinarySearch(unique_list, mid +1, high, x)
else:
print("Your number isn't here!")
"""
BinarySeach is an algorthm, and with recursive it means looping around over and over.
The second line I think its so the computer can understand it, but I dont know what it does, same with the third line.
The fourth line It does everything step by step.
The 5th line, where it says "print"your making a statement, to show the computer.
return is the reurn the program.
elif is also makes a statement i think.
return is to return to where you want it to return when you run the program.
For else, I assume it will be the same as elif, like it being a statment.
"""
def literativeBinarySearch(unique_list, x):
low = 0
high = len(unique _list)-1
mid = 0
while low <= high:
mid = (high + low) //2
if unique_list[mid] < x:
low = mid + 1
elif unique_list[mid] > x:
high = mid - 1
else:
return mid
return -1
"""
The first line is like to obtain something.
for low, high, mid, I think they have something to do with the numbers, like for example 1 to 100, or something like that.
for unique list, is for so the computer can understand what we are trying to do.
where elif is, its to make a statment, but with the unique list, it can mean a different thing, or it can try to make a statment with that.
return, is to return to where you started.
"""
def indexValues():
print("At what index position do you want to search?")
indexPos = input("Type an index position here: ")
print(myList[int(indexPost)])
"""
The IndexValue is a squence, for the program.
The second line is the statment your trying to make.
I think indexPos is sort like a key value.
the last line prints a lsit for the index thing.
"""
def printLists():
if len(unique_list) ==0:
print(myList)
else:
whichOne = input("Which list do you want to see? Sorted or un-sorted? ")
if whichOne.lower() == "sorted":
print(unique_list)
"""
Def printLists is like changing the code.
The seoncd line, I think its like creating it so it wont mess with something.
Third line prints lsit for the index thing.
else is making a statment I think.
The fifth line I think its either making a statment for the code or updating something.
The sixth line is the sort the code, like when you run it.
The last line is so the computer can understand what you are trying to do.
"""
if __name__ == "__main__":
mainProgram()
"""
That first part of the first line has something to do with modules, but I dont remeber what it was. "Main" is so you can run the file straight into it.
|
60b588ecb0f26d0c09fada2230d7c59923376e6b | p83218882/270201032 | /lab5/example2.py | 256 | 3.859375 | 4 | #lab5 ex2
n = int(input('How many numbers? : '))
a = []
while n > 0 :
n = n - 1
l = int(input('enter an integer: '))
if l % 2 == 0 :
a.append(0)
else:
l == 1
a.append(1)
print(f"{(a.count(0)) / (len(a)) * 100} % ")
|
d22f0806ec754c0aedca4cd5e09ded9b61dca7e7 | Ewa-Gruba/Building_AI | /Scripts/C1E1_Optimalization.py | 710 | 3.8125 | 4 |
import math
import random
import numpy as np
import io
from io import StringIO
portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
def permutation(start, end=[]):
if len(start) == 0:
if end[0] == 0:
print(' '.join([portnames[i] for i in end]))
else:
for i in range(len(start)):
permutation(start[:i] + start[i+1:], end + start[i:i+1])
def permutations(route, ports):
routes = route + ports
permutation(routes)
# write the recursive function here
# remember to print out the route as the recursion ends
# this will start the recursion with 0 as the first stop
permutations([0], list(range(1, len(portnames))))
|
1ed33e86ed325c8f561a21a616db96e2a3d009cc | gabriel-correia0408/Sala_Green_GabrielCorreia | /Aula1_maykon/classe_endereco.py | 1,803 | 4.28125 | 4 | #criando classe endereco,com 3 atributos e 7 métodos
class Endereco:
#criando método construtor "__init__"e passando os métodos que devem receber os
#dados
def __init__(self, cidade:str, rua:str, numero:str) -> None:
#criando as variaveis com valore padroes,para independente do dado que entrar
# a variavél seja,criada,mesmo que não passe pelas verificações abaixo
#lembrando que pelas anderlines, as variaveis estão privadas.
self.__cidade = ''
self.__rua = ''
self.__numero = 0
# se p tipo "type" da varivél "nome" for igual a "str"
#a varivél da classe "self.__cidade", vai receber o valor da variavél
# do "cidade" do método construtor "__init__"
if type(cidade) == str:
self.__cidade = cidade
#mesma lógica do código acima única diferença que muda o a varivél
# aora avariável é a "rua"
if type(rua) == str:
self.__rua = rua
# mesma lógica de verificação dos códigos acima.
if type(numero) == int and numero > 0:
self.__numero = numero
def get_cidade(self):
return self.cidade
def get_rua(self):
return self.rua
def get_numero(self):
return self.numero
def set_cidade(self, cidade):
self.cidade = cidade
def set_rua(self,rua):
self.rua = rua
def set_numero(self,numero):
self.__numero = numero
def verifica_cidade(self,cidade) -> bool:
if type(cidade) == str:
self.__cidade = cidade
def verefica_rua(self,rua) -> str:
if type(rua) == str:
self.__rua = rua
def verefica_numero(self,numero) -> int:
if type(numero) == int:
self.__numero = numero
|
2a529ec2882dce8541d0264af1667b189f119b89 | gaoyanganggyg/sort | /effective_python/T5.py | 1,477 | 4.5 | 4 | #!-*-coding:utf-8-*-
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2
def my_decorator(func):
# 这里传递参数的能力是借鉴了 closures.
# 如果对closures感到困惑可以看看下面这个:
# http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2
# 不要忘了装饰器参数和函数参数!
def wrapped(function_arg1, function_arg2):
print ("I am the wrapper around the decorated function.\n"
"I can access all the variables\n"
"\t- from the decorator: {0} {1}\n"
"\t- from the function call: {2} {3}\n"
"Then I can pass them to the decorated function"
.format(decorator_arg1, decorator_arg2,
function_arg1, function_arg2))
return func(function_arg1, function_arg2)
return wrapped
return my_decorator
@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
print ("I am the decorated function and only knows about my arguments: {0}"
" {1}".format(function_arg1, function_arg2))
decorated_function_with_arguments("Rajesh", "Howard") |
55dc6d0202d0c0a2c48d9bc66bd0d22cccdc1f3e | Ri-Hong/CCC-Solutions | /CCC '11/CCC '11 S1 - English or French?.py | 760 | 4.03125 | 4 | '''
Author: Ri Hong
Date AC'd: Feb 22, 2020
Problem: https://dmoj.ca/problem/ccc11s1
'''
#Explanation
'''
Count the number of s, S, t, and Ts in the given lines. Then if the number of ss is greater than or equal to the number of ts,
then the language is French. Otherwise, the language is English
'''
#Code
N = int(input())
sCounter = 0 #Stores the # of 's' and 'S'
tCounter = 0 #Stores the # of 't' and 'T'
#Get each sentence
for i in range(N):
sentence = input()
#Count the number of ss and ts in the sentence
for j in sentence:
if j == "s" or j =="S":
sCounter += 1
elif j == "t" or j =="T":
tCounter += 1
#Compare the numbers and determine the language
if sCounter >= tCounter:
print ("French")
else:
print ("English") |
79c1c1c8da2ad4a95a3a94bba06156ecb09e80c7 | Zeemon056/12th-practicals | /q13.py | 474 | 4 | 4 | choice = input("PLease enter the string choice here: ")
characters = [",", "?","!","."]
if choice[len(choice)-1] in characters:
words = choice.split(" ")
a = words[len(words)-1]
final = ""
for i in range(len(a)):
if a[i] not in characters:
final += a[i]
words.pop()
words.append(final)
words.sort()
for i in range(len(words)):
print(words[i], end = " ")
else:
print("Enter the correct end of line character")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.