blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
815b8d503fb53750f2de4a146b769115fe305659 | marianomayo/Curso-de-Python-Inicial | /datos tipo tupla/listaYtuplaAnidada.py | 682 | 3.5625 | 4 | def cargar_paispoblacion():
paises=[]
for x in range(5):
nom=input("Ingresar el nombredel pais: ")
cant = int(input("Ingrese la cantidad de habitantes"))
paises.append((nom, cant))
return paises
def imprimirPaises(paises):
print("Paises y su poblacion")
for x in range(len(paises)):
print(paises[x][0], paises[x][1])
def pais_masPoblacion(paises):
pos=0
for x in range(1, len(paises)):
if paises[x][1] > paises[pos][1]:
pos=x
print("Pais con mayor cantidad de poblacion es: ", paises[pos][0])
#bloque principal
paises = cargar_paispoblacion()
imprimirPaises(paises)
pais_masPoblacion(paises)
|
fdc723deee646053d433ce77bb8174ebed70a76d | Kafka-21/Econ_lab | /Week 4/Python Basics/PY_05.py | 1,403 | 4.03125 | 4 | # learning sklearn
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
#load the diabetes dataset
diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
# loading data in array
print(diabetes_y)
# use only one feature
diabetes_X = diabetes_X[:,np.newaxis,2]
# split the date into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
# Split the targets into training/testing sets
diabetes_y_train = diabetes_y[:-20]
diabetes_y_test = diabetes_y[-20:]
# Create linear regresssion object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)
# Make prediction using the testing set
diabetes_y_pred = regr.predict(diabetes_X_test)
# The coefficients
print('coefficients: \n', regr.coef_)
# The mean squared error
print('Mean squared error: %.2f' %mean_squared_error(diabetes_y_test, diabetes_y_pred))
# The coefficient of determination: 1 is perfect prediction
print('coefficient of determination: %.2f' %r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
# plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
# plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
# plt.xticks(())
# plt.yticks(())
# plt.show()
|
60156998e6005ad30cd41ed137423b1015a48e70 | ShakhrizodSaidov/python_solutions01 | /spyderpro14.py | 460 | 3.859375 | 4 | my_father={"name":"Erkin",
"surname":"Sharipov",
"born":1977,
"lives":"Bukhara"}
print(f"My father's name is {my_father['name']}\
and his surname is {my_father['surname']},\
he was born in {my_father['born']},\
he lives in {my_father['lives']} ")
# talaba_0 = {'ism':'murod olimov','yosh':20,'t_yil':2000}
# print(f"{talaba_0['ism'].title()},\
# {talaba_0['t_yil']}-yilda tu'gilgan,\
# {talaba_0['yosh']} yoshda") |
0ce8eb014ba3bde265d74c89426cadfbdc5f7681 | chithien0909/Competitive-Programming | /Leetcode/Leetcode - Range Sum Query 2D - Mutable.py | 1,707 | 3.9375 | 4 | """
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
Note:
The matrix is only modifiable by the update function.
You may assume the number of calls to update and sumRegion function is distributed evenly.
You may assume that row1 ≤ row2 and col1 ≤ col2.
"""
import collections
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
self.changes = collections.defaultdict(int)
self.sum = [[0] * len(matrix[0]) for _ in range(len(matrix))]
for i, row in enumerate(matrix):
for j, num in enumerate(row):
if i * j == 0:
if i == j: self.sum[i][j] = matrix[i][j]
elif i == 0: self.sum[i][j] += self.sum[i][j - 1]
else: self.sum[i][j] += self.sum[i - 1][j]
else:
self.sum[i][j] = self.sum[i - 1][j] + self.sum[i][j - 1] - self.sum[i - 1][j - 1]
def update(self, row: int, col: int, val: int) -> None:
self.changes[(row, col)] += val
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2) |
ce558dd7444d0bf453e7d055db8d869bf912fd27 | gasamoma/cracking-code | /Strings/1.3.py | 2,226 | 4.5 | 4 | # URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.)
# so Id ask if i have to make the swap from space to url space in place? YES
# double space has to be compressed? No, it should be two %20
#Ok so first I was thinking of each space I encounter move the rest of the string to the back so im going to do a quick implementations of that, but that wont be efficient
#IDK what means the true length of the str i would suppose that is excluding the extra space at the end so an example would be like
# 'asd asd ', 7 so two extra spaces for the extra %20 i need to add
def urilify(str1, str_len): # O(n^2)
max_len = len(str1)
if max_len == str_len:
return str1
for ith in range(max_len):
if ith == str_len:
return str1[:max_len]
if str1[ith]== " ":
str1=str1[:ith]+"%20"+str1[ith+1:] #if all the string is made of spaces**
ith+=2
Return str1[:max_len+1]
##if all the string is spaces then assuming the string is N i have to move n chars N times
#means that n^2
# im ignoring that they are givin me the extra space at the end because of some reason
def urilify_2(str1,str_len):#O(n)
str1 = invert(str1)#this is O(n)
ith = 0
jth = len(str1) - str_len
while jth < len(str1):#this is O(n)
if str1[jth]==" ":
str1[ith]="0"
str1[ith+1]="2"
str1[ith+2]="%"
ith+=2
else:
str1[ith]=str1[jth]
jth+=1
ith+=1
return ''.join(invert(str1))#this is O(2n)
def invert(str1):#inverting a list is O(n)
str_len = len(str1)
str1 = list(str1)#this is O(n)
for ith in range(int(str_len/2)):#this is O(n/2)
tempo=str1[ith]#space O(n)
str1[ith]= str1[str_len-ith-1]
str1[str_len-ith-1]=tempo
return str1
print(urilify_2("asdasd", 6))
print(urilify_2("asd asd ", 8))
print(urilify_2("asd a sd ", 9))
#so I could improve this solution and as soon as I start inverting the string start checking if its a space and swap with %20 and as soon as i finish i just revert it back
|
d311b597c2c3d6290392a1f24be4212ba02e97ae | Karthiga1/CICD_Jenkins | /run.py | 911 | 3.5 | 4 | import requests
import json
import datetime
from datetime import date
def myFunction():
now = datetime.datetime.now()
date_today = date.today()
#print(date_today)
parameters = {
"api_key": "758f54db8c52c2b500c928282fe83af1b1aa2be8",
"country": "IN",
"year" : now.year
}
#response = requests.get("https://calendarific.com/api/v2/holidays?&api_key=758f54db8c52c2b500c928282fe83af1b1aa2be8&country=IN&year=2020")
response = requests.get("https://calendarific.com/api/v2/holidays", params=parameters)
holiday_list = response.json()['response']
y = json.dumps(holiday_list)
x = json.loads(y)
holidays = []
for d in x['holidays']:
time = d['date']['iso']
holidays.append(time)
for e in holidays:
if date_today == e:
return False
else:
return True
if __name__ == "__main__":
print(myFunction()) |
9e3b56e731f28f99c628e8a633b11aaf54ea365a | chayabenyehuda/LearnPython | /She Codes/Le9_romania.py | 923 | 4.03125 | 4 | # ex1 program a func that accepts a string representing Roman numeral and returns a number
def romanToInt( s: str):
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
# add all of the values together ignoring special cases like IX or IV
for n in s:
total += d[n]
# subtract
# if we find any of the letters that can have a predecessor that modifies the value
# subtract twice the value of the predecessor (twice bc we already added it once in the add cycle)
for n in range(1, len(s)):
if s[n] == 'V' or s[n] == 'X':
if s[n - 1] == 'I':
total -= d['I'] * 2
elif s[n] == 'L' or s[n] == 'C':
if s[n - 1] == 'X':
total -= d['X'] * 2
elif s[n] == 'D' or s[n] == 'M':
if s[n - 1] == 'C':
total -= d['C'] * 2
return total
print(romanToInt('II'))
|
42ad748206b557425c75319b6d673194bc962393 | yograjshisode/PythonRepository | /LeapYear.py | 750 | 4.0625 | 4 | '''Leap year finder
Description
Leap years occur according to the following formula: a leap year is divisible by four, but not by one hundred, unless
it is divisible by four hundred. For example, 1992, 1996, and 2000 are leap years, but 1993 and 1900 are not. The next
leap year that falls on a century will be 2400.
Input
Your program should take a year as input.
Output
Your program should print whether the year is or is not a leap year.'''
year=int(raw_input("What year : "))
if (year%4==0) :
if(year%100==0) :
if(year%400==0) :
print "%d is leap year" % year
else :
print "%d is not leap year" % year
else :
print "%d is leap year" % year
else :
print "%d is not leap year" % year
|
5200d8cedccac138f7da39723a2c7266b591234c | acharles7/problem-solving | /Vmware/sort_array_by_parity.py | 389 | 4.09375 | 4 | """
Given an array A of non-negative integers, return an array consisting
of all the even elements of A, followed by all the odd elements of A.
"""
def sortArrayByParity(A):
ptr, i = 0, 0
while i < len(A):
if A[i] % 2 == 0:
A[ptr], A[i] = A[i], A[ptr]
ptr += 1
i += 1
return A
A = [1,6,8,3,0,2,3,4,5,6,7,9]
print(sortArrayByParity(A))
|
40d6b203a69ff547a84a3c30ccaa0112d042b3c6 | daichi0315/VehicleClassifier | /vehicle_cnn_aug.py | 1,945 | 3.625 | 4 | from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D
from keras.layers import Activation,Dropout,Flatten,Dense
from keras.utils import np_utils
import numpy as np
from keras import optimizers
import keras
classes = ['car','forklift','truck']
num_classes = len(classes)
image_size = 50
#メインの関数を定義する
def main():
X_train,X_test,y_train,y_test = np.load('./vehicle_aug.npy',allow_pickle = True)
X_train = X_train.astype('float') /256
X_test = X_test.astype('float') /256
y_train = np_utils.to_categorical(y_train,num_classes)
y_test = np_utils.to_categorical(y_test,num_classes)
model = model_train(X_train,y_train)
model_eval(model,X_test,y_test)
def model_train(X,y):
model = Sequential()
model.add(Conv2D(32,(3,3),padding='same',input_shape=X.shape[1:]))
model.add(Activation('relu'))
model.add(Conv2D(32,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3),padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(3))
model.add(Activation('softmax'))
#opt = keras.optimizers.rmsprop(lr=0.0001,decay=1e-6)
opt = keras.optimizers.adam()
model.compile(loss ='categorical_crossentropy',
optimizer=opt,metrics=['accuracy'])
model.fit(X,y,batch_size=32,epochs=100)
#モデルの保存
model.save('./vehicle_cnn_aug.h5')
return model
def model_eval(model,X,y):
scores = model.evaluate(X,y,verbose=1)
print('Test Loss: {}'.format(scores[0]))
print('Test Accuracy: {}'.format(scores[1]))
if __name__ == '__main__':
main() |
2bae2e11e8184e14a951d800c08675603d5f4d5e | Immaannn2222/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/2-cofactor.py | 2,973 | 4.375 | 4 | #!/usr/bin/env python3
"""advanced linear algebra"""
def determinant(matrix):
"""calculates the determinant of a matrix"""
if not isinstance(matrix, list) or matrix == []:
raise TypeError('matrix must be a list of lists')
if any(not isinstance(i, list) for i in matrix):
raise TypeError('matrix must be a list of lists')
if matrix == [[]]:
return 1
if any(len(i) != len(matrix) for i in matrix):
raise ValueError('matrix must be a square matrix')
n = len(matrix)
if n == 1:
return matrix[0][0]
# calculate the determinant of 2x2 matrix
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for i in range(n):
det += (-1) ** i * matrix[0][i] * determinant(reduce_mat(matrix, i))
return det
def reduce_mat(matrix, x):
"""returns reduced matrix starting after the first linz"""
# reducing the matrix/ elimminating column
return [col[:x] + col[x + 1:] for col in (matrix[1:])]
# def reduce_mat_double(matrix, x, y):
# """returns reduced matrix"""
# # reducing the matrix/ elimminating column
# return [col[:x] + col[x + 1:] for col in (matrix[:y] + matrix[y + 1:])]
def minor(matrix):
"""calculates the minor matrix of a matrix"""
if not isinstance(matrix, list) or matrix == []:
raise TypeError('matrix must be a list of lists')
if any(not isinstance(i, list) for i in matrix):
raise TypeError('matrix must be a list of lists')
if any(len(i) != len(matrix) for i in matrix):
raise ValueError('matrix must be a non-empty square matrix')
if len(matrix[0]) == 0:
raise ValueError('matrix must be a non-empty square matrix')
n = len(matrix)
if n == 1:
return [[1]]
if n == 2:
return [elem[::-1] for elem in matrix][::-1]
else:
final_list = []
for i in range(n):
listt = []
for j in range(n):
new_mat = [col[:j] + col[j + 1:] for
col in (matrix[:i] + matrix[i + 1:])]
listt.append(determinant(new_mat))
final_list.append((listt))
return final_list
def cofactor(matrix):
"""calculates the cofactor matrix of a matrix"""
if not isinstance(matrix, list) or matrix == []:
raise TypeError('matrix must be a list of lists')
if any(not isinstance(i, list) for i in matrix):
raise TypeError('matrix must be a list of lists')
if any(len(i) != len(matrix) for i in matrix):
raise ValueError('matrix must be a non-empty square matrix')
if len(matrix[0]) == 0:
raise ValueError('matrix must be a non-empty square matrix')
n = len(matrix)
if n == 1:
return [[1]]
minor_mat = minor(matrix)
for i in range(len(minor_mat)):
for j in range(len(minor_mat)):
minor_mat[i][j] = minor_mat[i][j] * ((-1) ** (i + j))
return minor_mat
|
e2a8b49bb308aa4ef5ca33645ae23e6684cd61c3 | Leeoku/leetcode | /Completed/Puzzle/204_count_primes.py | 2,007 | 3.78125 | 4 | #Count the number of prime numbers less than a non-negative number, n.
#test case, n = 10
class Solution:
def countPrimes(self, n: int) -> int:
#Sieve of Eratosthenes
#Make array for all integers, assume they are prime
#Time = O(nlogn) (inner loop runs fewer runs),
#Space = O(n) , traverse through n numbers
if n < 2:
return 0
primes = [True] * n
#Set case scenario for 0,1 as not prime exception
primes[0]= primes[1] = False
for i in range(2,n):
if primes[i]:
#Find numbers that aren't prime up to the square (next multiple)
for j in range(i*i, n, i):
primes[j] = False
# j = i*i
# while j < n :
# primes[j] = False
# j+=i
print(primes)
return primes.count(True)
#BRUTE FORCE
#Time O(n^2), Space O(n)
#Loop thru all the numbers and check to see if they are divisible by each number
# count = 0
# def isPrime(x):
# for i in range(2,x):
# if x % i == 0:
# return False
# return True
# for j in range(2,n):
# if isPrime(j) == True:
# count +=1
# return count
# primes = []
# count = 0
# if n < 2:
# return None
# for i in range(2,n):
# for j in range(2,i):
# if j == 2:z
# count +=1
# #if divisible, that means it's not a prime number
# if i % j == 0:
# break
# count += 1
# primes.append(i)
# return count, primes
n = 10
s = Solution()
total = s.countPrimes(n)
print(f"Total number of primes is {total}")
# print(s.isPrime(n))
# print(total)
# print(total.count(True)) |
9a772db91b42c8f99c756083c09a49dea8c6947d | shouxie/qa_note | /python/python11_算法与数据结构/1-nodelist.py | 3,202 | 3.765625 | 4 | # -*- coding:utf-8 -*-
#@Time : 2020/5/14 下午7:27
#@Author: 手写
#@File : 1-nodelist.py
'''
数据结构-单链表:
【data, 下一个的指针】 --- data, 下一个的指针】...
'''
# 节点类 【data, 下一个的指针】
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
# 单链表
class SingleList:
def __init__(self, node=None):
# _head 首地址
self._head = node
# 判断为空
def isEmpty(self):
return self._head == None
def append(self, item):
node = Node(item)
if self.isEmpty():
self._head = node
else:
current = self._head
while current.next != None:
current = current.next
current.next = node
def len(self):
count = 0
current = self._head
while current != None:
count += 1
current = current.next
return count
def print_all(self):
cur = self._head
while cur != None:
print(cur)
cur = cur.next
def pop(self, index):
if index < 0 or index > self.len():
raise IndexError('Index Error')
elif index == 0:
self._head = self._head.next
else:
cur = self._head
while index - 1:
cur = cur.next
index -= 1
# 当前指针的前一个指针直接指向当前指针的下一个指针,此时cur为前一个
cur.next = cur.next.next
def inert(self, index, item):
if index < 0 or index > self.len():
raise IndexError('index error: range is not valid')
elif isinstance(item, Node):
raise TypeError('type is not valid')
else:
if index == 0:
node = Node(item)
node.next = self._head
self._head = node
else:
node = Node(item)
cur = self._head
while index - 1:
cur = cur.next
index -= 1
# 当前指针的前一个指针直接指向insert指针,insert指针指向当前指针的下一个指针,此时cur为前一个
# 【data next】 --insert--【 data next】 -- 【 data next】
node.next = cur.next
cur.next = node
def update(self, index, newItem):
pass
def remove(self, item):
pass
if __name__ == '__main__':
slist = SingleList()
print(slist.isEmpty()) # True
slist.append(1)
print(slist.len()) # 1
# slist.print_all() # TypeError: __str__ returned non-string (type int) def __str__(self): return str(self.data)
slist.append(2)
slist.append(3)
slist.print_all() # 1 2 3
slist1 = SingleList()
for i in range(10):
slist1.append(i)
slist1.print_all()
slist1.pop(5)
slist1.print_all()
print('--'*10)
slist2 = SingleList()
for i in range(10):
slist2.append(i)
slist2.inert(2, 'hello python')
slist2.print_all() |
252a2962b8819822684e045f3489405e6195ac4d | GBoshnakov/SoftUni-OOP | /Iterators and Generators/dictionary_iterator.py | 468 | 3.890625 | 4 | class dictionary_iter:
def __init__(self, d):
self.d = d
self.elements = [(key, val) for key, val in self.d.items()]
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index == len(self.d):
raise StopIteration()
current = self.index
self.index += 1
return self.elements[current]
result = dictionary_iter({1: "1", 2: "2"})
for x in result:
print(x)
|
0ca59aec9ef6924e05ce6152057ab8ae7332a4bc | daniel-reich/turbo-robot | /C6pHyc4iN6BNzmhsM_19.py | 2,315 | 4.125 | 4 | """
In this challenge, you have to establish which kind of Poker combination is
present in a deck of five cards. Every card is a string containing the card
value (with the upper-case initial for face-cards) and the lower-case initial
for suits, as in the examples below:
"Ah" ➞ Ace of hearts
"Ks" ➞ King of spades
"3d" ➞ Three of diamonds
"Qc" ➞ Queen of clubs
There are 10 different combinations. Here's the list, in decreasing order of
importance:
Name| Description
---|---
**Royal Flush**| A, K, Q, J, 10, all with the same suit.
**Straight Flush**| Five cards in sequence, all with the same suit.
**Four of a Kind**| Four cards of the same rank.
**Full House**| Three of a Kind with a Pair.
**Flush**| Any five cards of the same suit, not in sequence.
**Straight**| Five cards in a sequence, but not of the same suit.
**Three of a Kind**| Three cards of the same rank.
**Two Pair**| Two different Pair.
**Pair**| Two cards of the same rank.
**High Card**| No other valid combination.
Given a list `hand` containing five strings being the cards, implement a
function that returns a string with the name of the highest combination
obtained, accordingly to the table above.
### Examples
poker_hand_ranking(["10h", "Jh", "Qh", "Ah", "Kh"]) ➞ "Royal Flush"
poker_hand_ranking(["3h", "5h", "Qs", "9h", "Ad"]) ➞ "High Card"
poker_hand_ranking(["10s", "10c", "8d", "10d", "10h"]) ➞ "Four of a Kind"
### Notes
N/A
"""
def poker_hand_ranking(hand):
d = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}
values = sorted(int(d.get(i[:-1], i[:-1])) for i in hand)
suits = len(set(i[-1] for i in hand))
if suits == 1 and values == list(range(10, 15)):
return 'Royal Flush'
if suits == 1 and values == list(range(min(values),max(values)+1)):
return 'Straight Flush'
if any(values.count(i) == 4 for i in values):
return 'Four of a Kind'
if len(set(values)) == 2:
return 'Full House'
if suits == 1:
return 'Flush'
if values == list(range(min(values),max(values)+1)):
return 'Straight'
if any(values.count(i) == 3 for i in values):
return 'Three of a Kind'
if len(set(values)) == 3:
return 'Two Pair'
if len(set(values)) == 4:
return 'Pair'
return 'High Card';
|
6b2c04774959ba8611d5262a318aef19ff74b20d | mrifqy-abdallah/python-exercises | /easy/023_meetup/meetup.py | 1,310 | 3.75 | 4 | from datetime import date
from calendar import monthcalendar, setfirstweekday
class MeetupDayException(Exception):
""" Return exception when encountered """
def __init__(message):
super().__init__("No such date exists")
def meetup(year:int, month:int, week:str, day_of_week:str):
setfirstweekday(6) # Set Sunday as the first day of the week
weeks = {
"1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "5th": 5, "teenth": 3, "last": 5
}
days = {
"sunday": 0, "monday": 1, "tuesday": 2, "wednesday": 3, "thursday": 4, "friday": 5, "saturday": 6
}
month_calendar = monthcalendar(year, month) # Return a list of the month's calendar
day = days[day_of_week.lower()]
the_week = weeks[week]
the_date = 0
count = 0
for each_week in month_calendar:
if each_week[day] != 0:
the_date = each_week[day]
count += 1
if count == the_week:
break
# This one case needs to be re-counted
if week == "teenth" and the_date >= 20:
the_date -= 7
try:
if count != the_week and week != "last": # 'last' category is excluded from the exception
raise MeetupDayException()
except Exception:
raise
return date(year, month, the_date)
|
923048f2634fff05fd6665977fedb6404843af79 | DeveloperArthur/Data-Science-Python | /grafico-linha2.py | 175 | 3.6875 | 4 | import matplotlib.pyplot as plt
x = [1,2,5]
y = [2,3,7]
plt.title("Meu primeiro grafico com Python")
plt.xlabel("Eixo X")
plt.ylabel("Eixo Y")
plt.plot(x, y)
plt.show()
|
c799ec86d03b308ee4b8b5852bda24f6ad16e06d | ocoboj/Master-Python | /08-funciones/main.py | 3,024 | 4.4375 | 4 | """
FUNCIONES:
Una función es un conjunto de instrucciones agrupadas bajo
un nombre concreto que pueden reutilizarse invocando a
la función tantas veces como sea necesario.
def nombreDeMiFuncion(parametros):
# BLOQUE / CONJUNTO DE INSTRUCCIONES
nombreDeMiFuncion(mi_parametro)
nombreDeMiFuncion(mi_parametro) -> se puede llamar las veces que queramos
"""
# Ejemplo 1
print("####### EJEMPLO 1 #######")
# Definir funcion
def muestraNombres():
print("Víctor")
print("Paco")
print("Juan")
print("Aitor")
print("Nestor")
print("\n")
# Invocar función
muestraNombres()
# Ejemplo 2: parametros
print("####### EJEMPLO 2 #######")
""" def mostrarTuNombre(nombre, edad):
print(f"Tu nombre es: {nombre}")
if edad >= 18:
print("Eres mayor de edad")
nombre = input("Introduce tu nombre: ")
edad = int(input("Introduce tu edad: "))
mostrarTuNombre(nombre, edad) """
print("\n")
# Ejemplo 3
print("####### EJEMPLO 3 #######")
print("\n")
def tabla(numero):
print(f"Tabla de mutiplicar del número: {numero}")
for contador in range(11):
operacion = numero*contador
print(f"{numero} x {contador} = {operacion}")
print("\n")
tabla(3)
tabla(7)
tabla(12)
# Ejemplo 3.1
print("------------------------------------------------")
for numero_tabla in range (1, 11):
tabla(numero_tabla)
# Ejemplo 4: Parametros Opcionales
print("####### EJEMPLO 4 #######")
def getEmpleado(nombre, dni = None):
print("EMPLEADO")
print(f"Nombre: {nombre}")
if dni != None:
print(f"DNI: {dni}")
getEmpleado("Olga Conesa", 646464664)
# Ejemplo 5: Return o devolver datos
print("\n####### EJEMPLO 5 #######")
def saludame(nombre):
saludo = f"Hola, saludos {nombre}"
return saludo
print(saludame("Olga"))
# Ejemplo 6
print("\n####### EJEMPLO 6 #######")
def calculadora(numero1, numero2, basicas = False):
suma = numero1 + numero2
resta = numero1 - numero2
multiplicacion = numero1 * numero2
division = numero1 / numero2
cadena = ""
if basicas != False:
cadena += "Suma: " + str(suma)
cadena += "\n"
cadena += "Resta: " + str(resta)
cadena += "\n"
else:
cadena += "Multiplicacion: " + str(multiplicacion)
cadena += "\n"
cadena += "División: " + str(division)
return cadena
print(calculadora(56, 5, True))
# Ejemplo 7
print("\n####### EJEMPLO 7 #######")
def getNombre(nombre):
texto = f"El nombre es: {nombre}"
return texto
def getApellidos(apellidos):
texto = f"Los apellidos son: {apellidos}"
return texto
def devuelveTodo(nombre, apellidos):
texto = getNombre(nombre) + "\n" + getApellidos(apellidos)
return texto
print(devuelveTodo("Olga", "Conesa Boj"))
# Ejemplo 8: Funciones Lambda: funciones anónimas (definidas en una linea)
print("\n####### EJEMPLO 8 #######")
dime_el_year = lambda year: f"El año es {year}"
print(dime_el_year(2034)) |
86436f130e0f93ad3ced4f94180ad3a9bd7c618a | kaif-rgb/Project-2021-tictactoe | /Project-2021-tictactoe/tictactoe.py | 6,127 | 3.515625 | 4 | from tkinter import *
from tkinter import messagebox
from functools import partial
import random
from copy import deepcopy
global board
board = [[' ' for x in range(3)] for y in range(3)]
sign = 0
def winner(b,l):
return ((b[0][0]==l and b[0][1]==l and b[0][2]==l) or
(b[1][0]==l and b[1][1]==l and b[1][2]==l) or
(b[2][0]==l and b[2][1]==l and b[2][2]==l) or
(b[0][0]==l and b[1][0]==l and b[2][0]==l) or
(b[0][1]==l and b[1][1]==l and b[2][1]==l) or
(b[0][2]==l and b[1][2]==l and b[2][2]==l) or
(b[0][0]==l and b[1][1]==l and b[2][2]==l) or
(b[0][2]==l and b[1][1]==l and b[2][0]==l))
def isfull():
flag = True
for i in board:
if i.count(' ') > 0:
flag = False
return flag
def pc():
possiblemove = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == ' ':
possiblemove.append([i,j])
if len(possiblemove) == 0:
return
else:
for let in ['O', 'X']:
for i in possiblemove:
boardcopy = deepcopy(board)
boardcopy[i[0]][i[1]] = let
if winner(boardcopy, let):
return i
corner = []
for i in possiblemove:
if i in [[0, 0], [0, 2], [2, 0], [2, 2]]:
corner.append(i)
if len(corner) > 0:
move = random.randint(0, len(corner)-1)
return corner[move]
edge = []
for i in possiblemove:
if i in [[0, 1], [1, 0], [1, 2], [2, 1]]:
edge.append(i)
if len(edge) > 0:
move = random.randint(0, len(edge)-1)
return edge[move]
def get_text_pc(i,j,gb,l1,l2):
global sign
if board[i][j] == " ":
if sign % 2==0:
l1.config(state=DISABLED)
l2.config(state=ACTIVE)
board[i][j] = 'X'
else:
l1.config(state=ACTIVE)
l2.config(state=DISABLED)
board[i][j] = 'O'
sign +=1
button[i][j].config(text = board[i][j])
x = True
if winner(board,'X'):
x = False
gb.destroy()
messagebox.showinfo('Winner','Player X won the match.')
elif winner(board,'O'):
x = False
gb.destroy()
messagebox.showinfo('Winner','Player O won the match.')
elif isfull():
x = False
gb.destroy()
messagebox.showinfo('Tie','No one won the match')
if x:
if sign %2 != 0:
move = pc()
button[move[0]][move[1]].config(state=DISABLED)
get_text_pc(move[0],move[1],gb,l1,l2)
def get_text_pl(i,j,gb,l1,l2):
global sign
if board[i][j] == " ":
if sign % 2==0:
l1.config(state=DISABLED)
l2.config(state=ACTIVE)
board[i][j] = 'X'
else:
l1.config(state=ACTIVE)
l2.config(state=DISABLED)
board[i][j] = 'O'
sign +=1
button[i][j].config(text = board[i][j])
if winner(board,'X'):
gb.destroy()
messagebox.showinfo('Winner','Player X won the match.')
elif winner(board,'O'):
gb.destroy()
messagebox.showinfo('Winner','Player O won the match.')
elif isfull():
gb.destroy()
messagebox.showinfo('Tie','No one won the match')
def gameboard_pc(game_board,l1,l2):
global button
button = []
for i in range(3):
m = i + 3
button.append(i)
button[i] = []
for j in range(3):
n = j
button[i].append(j)
get_t = partial(get_text_pc,i,j,game_board,l1,l2)
button[i][j] = Button(game_board,height=4, width=8,bd=2,command=get_t)
button[i][j].grid(row=m,column=n)
game_board.mainloop()
def gameboard_pl(game_board,l1,l2):
global button
button = []
for i in range(3):
m = i + 3
button.append(i)
button[i] = []
for j in range(3):
n = j
button[i].append(j)
get_t_pl = partial(get_text_pl,i,j,game_board,l1,l2)
button[i][j] = Button(game_board,height=4, width=8,bd=2,command=get_t_pl)
button[i][j].grid(row=m,column=n)
game_board.mainloop()
def withplayer(game_board):
game_board.destroy()
game_board = Tk()
game_board.title('tiktactoe')
l1 = Button(text = 'Player: X',state=ACTIVE,width=10)
l2 = Button(text = 'Player: O',state=DISABLED,width=10)
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)
gameboard_pl(game_board,l1,l2)
def withpc(game_board):
game_board.destroy()
game_board = Tk()
game_board.title('tiktaktoe')
l1 = Button(text = 'Player: X',state=ACTIVE,width=10)
l2 = Button(text = 'Player: O',state=DISABLED,width=10)
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)
gameboard_pc(game_board,l1,l2)
def play():
menu = Tk()
menu.config(background= 'light green')
menu.geometry('250x250')
menu.title('tictactoe')
wpc= partial(withpc,menu)
wpl = partial(withplayer,menu)
button1 = Button(menu,text='Tictactoe',activebackground='yellow',activeforeground='red',bg='red',fg='yellow',width=50,bd=5)
button2 = Button(menu,text='Singleplayer',activebackground='yellow',activeforeground='red',bg='red',command=wpc,fg='yellow',width=50,bd=5)
button3 = Button(menu,text='Multiplayer',activebackground='yellow',activeforeground='red',bg='red',command=wpl,fg='yellow',width=50,bd=5)
button4 = Button(menu,text='Exit',command=menu.quit,activebackground='yellow',activeforeground='red',bg='red',fg='yellow',width=50,bd=5)
button1.pack()
button2.pack()
button3.pack()
button4.pack()
menu.mainloop()
play() |
577bfe770cf7a22d24d8b01c9da965349d491fc4 | 6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion | /CH04/EX4.34.py | 644 | 4.3125 | 4 | # 4.34 (Hex to heximal) Write a program that prompts the user to enter a hex character
# and displays its corresponding heximal integer.
hex = input("Enter a hex character: ")
if '0' <= hex <= '9':
print("The decimal value is", hex)
elif hex.upper() == 'A':
print("The decimal value is 10")
elif hex.upper() == 'B':
print("The decimal value is 11")
elif hex.upper() == 'C':
print("The decimal value is 12")
elif hex.upper() == 'D':
print("The decimal value is 13")
elif hex.upper() == 'E':
print("The decimal value is 14")
elif hex.upper() == 'D':
print("The decimal value is 15")
else:
print("Invalid input")
|
ac9c7f9898371b9020da8846c062018d5965418d | Nikolay-Pomytkin/cs2 | /python/maddieJin.py | 221 | 3.890625 | 4 | def randomlyDislike(name):
if name == "maddie jin":
return "you dislike katherine yoon"
else:
return "you dont randomly dislike people"
i = input("What is your name?")
print(randomlyDislike(i)) |
3189641113d14513630039b4702e37a02da5fba6 | w1pereira/aurorae | /aurorae/providers/spreadsheet/utils.py | 1,341 | 3.796875 | 4 | from openpyxl import load_workbook
def worksheet_dict_reader(worksheet):
"""
A generator for the rows in a given worksheet. It maps columns on
the first row of the spreadsheet to each of the following lines
returning a dict like {
"header_column_name_1": "value_column_1",
"header_column_name_1": "value_column_2"
}
:param worksheet: a worksheet object
:type worksheet: `openpyxl.worksheet.ReadOnlyWorksheet`
"""
rows = worksheet.iter_rows(values_only=True)
# pylint: disable=stop-iteration-return
header = list(filter(None, next(rows)))
for row in rows:
if not any(row):
return
yield dict(zip(header, row))
def get_spreadsheet_data(filename) -> dict:
"""
Uses `openpyxl.load_workbook` to process the specified file.
Returns a dict of the spreadsheet data grouped by worksheet.
"""
workbook = load_workbook(filename=filename, read_only=True, data_only=True)
dados_empresa = worksheet_dict_reader(workbook["Empresa"])
dados_funcionarios = worksheet_dict_reader(workbook["Funcionários"])
dados_pagamentos = worksheet_dict_reader(workbook["Pagamentos"])
return {
"Empresa": list(dados_empresa)[0],
"Funcionários": list(dados_funcionarios),
"Pagamentos": list(dados_pagamentos),
}
|
f502527a887cc6ab5411799822d38e45bd0b3741 | Phantomn/Python | /study/base64.py | 1,131 | 3.578125 | 4 | def encrypt(plain):
bn = ""
for text in plain:
bn += ("0" * (8-len((bin(ord(text)).split("b")[1]))) + bin(ord(text)).split("b")[1])
out = []
bn += "0"*(6-len(bn)%6)
out += [bn[i:i+6] for i in range(0, len(bn), 6)] # string -> ascii -> 8bit
dict = []
for n in range( ord("A"), ord("Z")+1 ):
dict.append(chr(n))
for n in range( ord("a"), ord("z")+1 ):
dict.append(chr(n))
for n in range( 0, 10 ):
dict.append(str(n))
dict.append(["+", "/"])
encoded = ""
for binary in out:
encoded += (dict[int(binary, 2)])
encoded += "=" * ((4 - len(encoded)%4)%4)
return encoded
'''def decrypt(plain):
# Y W F h Y Q ==
#01011001 01010111 01000110 01101000 01011001 01010001 00000000
bn = ""
for text in plain:
bn += (bin(ord(text)).split("b")[1]) + bin(ord(text)).split("b")[1])
out += [bn[i:i+8] for i in range(0, len(bn), 8)]
return out
'''
data = raw_input("Encrypt Code in Base 64 : ")
print "Plain Text : %s"%(data)
print "Encrypted Base 64 Text : %s"%(encrypt(data))
#print "Decrypted Plain Text : %s"%(decrypt(encrypt(data))) |
6d8dab473efb9f0c0aa32f5d43fa0e36d3e9c4e2 | emanuelgomes-university/alpP1IFPBGBA | /12 - Questões para implementação/Q3.py | 816 | 3.78125 | 4 | def imc(peso, altura):
return peso / altura**2
def situacao_imc(imc):
if(imc < 16):
return "Magreza grave"
elif(imc >= 16 and imc< 17):
return "Magreza moderada"
elif(imc >= 17 and imc< 18.5):
return "Magreza leve"
elif(imc >= 18.5 and imc< 25):
return "Saudável"
elif(imc >= 25 and imc< 30):
return "Sobrepeso"
elif(imc >= 30 and imc< 35):
return "Obesidade Grau I"
elif(imc >= 35 and imc< 40):
return "Obesidade Grau II"
elif(imc >= 40):
return "Obesidade Grau III"
peso = float(input("Digite seu peso aqui: "))
altura = float(input("Digite sua altura aqui: "))
imc = imc(peso, altura)
situacao = situacao_imc(imc)
print("Seu IMC é: %.1f , A classificação do seu IMC se enquadra em: %s" %(imc, situacao))
|
8dbfb1d251cb898f4d1fa2f521f10b1152ae3aff | vkmicro/Person_coding_exercises | /extraTasks/Lecturing.py | 1,802 | 3.796875 | 4 | '''
Author: Vasiliy Ulin
This is a file with test code and explanatory comments which I use to teach my friends basics of programming
'''
import random
"""
block
comment
"""
'''
interchangable
neat eh
'''
'''
var1 = 5
var2 = 2
res = 5/2
print( " res : " + str(res) + "\n hi")
i = 0
for i in range(10):
print(i)
i= i+1
# print("statement")
var1 = 2
var2 = 12
Res = var1 + var2
Res2 = var1 - var2
Res3 = var2 / var1
print('Res is: ' + str(Res) + '\nRes2 is: ' + str(Res2) + '\nRes3 is: ' + str(Res3))
#if Res > Res2:
# print(Res3)
# create for loop which iterates 10 times and increments i every iteration, print i
i = 0
for i in range(10):
print(i)
i = i + 1
# casting int to string##
#temp1 = 1 ##5
#temp1Str = str(temp1) # = "15" stri###ng
# (accessing loop)
# v1
# for loops
# for item in list:
# pr
# animals = ['lion', 'tiger', 'elephant', 'mouse']
# v1 loop would print:
# lion
# tiger
# elephant
# mouse
# e.g. if item == "lion"
# you can't print any other animal...
########################## int(i (indexing loop)tem)
# v2
# i = 0
# for i in range(len(list)):
# print(list
# prints the same but through indexing[# indexing allows you to access other indexies based on current index
# e.g
# if list[i] == "lion"
# print (list[i-1])i])
# i +=1
#k = random.randint
'''
def main():
hwrk1()
def hwrk1():
# given a string, turn string into an array of single characters
# on same string, count up amount of occurences of letter "a"
resArr = []
#resArr2 = []
countA = 0
tempStr = "this is a temporary string aaaaaaaaaaa hah ho he ha"
for char in tempStr:
resArr.append(char)
if char == "a":
countA += 1
# print(char)
print(resArr)
print(countA)
if __name__ == "__main__":
main() |
61f1571cacb89ca270bc9d595474add78b040827 | EthanWhang/crimtechcomp | /assignments/000/Ethanwhang/000-code/assignment.py | 1,052 | 3.71875 | 4 | def say_hello():
print("Hello, world!")
# Color: Blue
def echo_me(msg):
print(msg)
def string_or_not(d):
exec(d)
def append_msg(msg):
print("Your message should have been: {}!".format(msg))
class QuickMaths():
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
return x / y
def increment_by_one(lst):
new_list = list()
for x in lst:
new_list.append(x + 1)
return new_list
def update_name(person, new_name):
person = {}
person["name"] = new_name
return person
# TODO: implement - these are still required, but are combinations of learned skills + some
def challenge1(lst):
for x in range(len(lst)):
lst[x] = lst[x][::-1]
lst.reverse()
return lst
# TODO: implement
def challenge2(n):
factors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
factors.append((i, n / i))
return factors
|
14502ab85732cc557876d0f93a5b2ec1929fa014 | PerlaLunaD/csv-py | /quiz.py | 1,374 | 4.21875 | 4 | name= 'Goreti'
print(f'welcome to {name} choose your own adventure, as you follow the story. Enjoy the play, lets do it.')
print('you will find a room with two doors. The frist door is red and the second door is white')
door_choice = input('What door do you want to choose? \nRed door or White? :')
if door_choice == 'red':
print('great, you walk through the red door and now you are in your own future.')
choice_one = input('what do you want to do? \nEnter 1 to accept or 2 to decline: ')
if choice_one == '1':
print(f'{name} continue to the next level, good lucky')
else:
print(f'{name} the game is over. Too bad')
choice_two = input('What box do you want to open? \nBox orange or Box yellow: ')
if choice_two == 'Box orange':
print(' Take the key. Do you know what will open?')
print('Find out in the last level')
choice_three = input('Are you ready for you gift? Choose one door: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10: ?')
if choice_three == '3':
print(f'Congratulates {name}, you are in front to next washing machine')
elif choice_three == '6':
print(f'Congratulates {name}, you are in front to your stove')
elif choice_three =='1':
print('You have won $100 dll')
else:
print('You are where it all began!!')
print('Better luck next time!')
# INPUT te permite escribir a tu eleccion, asignada a diferentes variables, puedes eleguir.
|
1517b6c8035231b6a79f65c8a3e1cb2aac270a73 | vasundhara7/DataStructuresAndAlgorithms | /GreedyAlgorithm/DistributeCandy.py | 976 | 3.578125 | 4 | # There are N children standing in a line. Each child is assigned a rating value.
# You are giving candies to these children subjected to the following requirements:
# 1. Each child must have at least one candy.
# 2. Children with a higher rating get more candies than their neighbors.
# What is the minimum candies you must give?
# Input Format:
# The first and the only argument contains N integers in an array A.
# Output Format:
# Return an integer, representing the minimum candies to be given.
class Solution:
# @param A : list of integers
# @return an integer
def candy(self, A):
left=[1]*len(A)
right=[1]*len(A)
for i in range(1,len(A)):
if A[i]>A[i-1]:
left[i]=left[i-1]+1
for i in range(len(A)-2,-1,-1):
if A[i]>A[i+1]:
right[i]=right[i+1]+1
s=0
for i in range(len(left)):
s+=max(left[i],right[i])
return s |
6a1406ad362042d8ca869a083ee064a25fc19478 | AlejandroPu/budapow | /testspath/matrix_verification.py | 1,328 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 1 20:10:17 2021
@author: retac
"""
def verifications( matrix ):
verification = True
est_col = matrix.keys()[0]=='Estaciones'
tip_col = matrix.keys()[-1]=='Tipo'
square = ( len(matrix.keys())-2 )==len(matrix)
stations = list(matrix.transpose().iloc[0])==list(matrix.keys()[1:-1])
if square==True:
simetry = True
for array in range(len(matrix)):
line = list(matrix.transpose().iloc[array+1])\
==list(matrix.iloc[array])[1:-1]
simetry = simetry and line
else:
simetry = False
values = {
"est_col": [ est_col, "Falta la columna Estaciones" ],
"tip_col": [ tip_col, "Falta la columna Tipo" ],
"square": [ square, "La matriz no es cuadrada" ],
"stations": [stations, "Asimetría en estaciones de la matriz" ],
"simetry": [simetry, "Asimetría en datos de la matriz" ]
}
for value in values.keys():
verification = ( verification and values[value][0] )
if values[value][0]==False:
print("Verificación "+value+" es incorrecta.")
print("Existe un error en la matriz de entrada.")
print(values[value][1])
break
return verification
|
54e9762ec75abf30a844f9791d82ce97bde48821 | SereneBe/chatbot.github.io | /hangman.py | 1,344 | 4.28125 | 4 | word = input("falafel")
# Converts the word to lowercase
word = word.lower()
# Checks if only letters are present (isalpha means it has no numbers)
if(word.isalpha() == False):
print("That's not a word!")
# Some useful variables
guesses = []
maxfails = 7
# make a list of blank spaces
spaces = []
for letter in word:
spaces.append("_")
len(word)
# check if one letter, make it lowercase
while maxfails > 0:
if "_" not in spaces:
print("You win!")
break
guess = input("Guess a letter")
# tell how many fails left
guess = guess.lower()
# check if letter has been guessed already
if guess in guesses:
print("You already guessed that")
if not (guess.isalpha() and len(guess) == 1):
print("That's not a letter!")
else:
if guess in guesses:
print("You already guessed that. Try Again")
else:
guesses.append(guess)
if guess in word:
for letter in range(len(word)):
if guess == word[letter]:
spaces[letter] = guess
print("Correct!")
else:
maxfails -= 1
print("Wrong!")
print("You have "+str(maxfails) + "chances left")
print(spaces)
# if the letter is in word, add it to the blank spaces
# if not in the word, record it as a "failure"
# add letter to list of guesses
# if spaces are full, win
# if max fails are reached, lose
# check every letter in word to see if = guessed letter
|
b4404072c1b0d281ad45b614ab5d2ea80df56546 | dustinsnoap/code-challenges | /python/valid_palindrome.py | 573 | 4.40625 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Example 1:
# Input: "A man, a plan, a canal: Panama"
# Output: true
# Example 2:
# Input: "race a car"
# Output: false
import re
def isPalindrome(s):
s = re.sub(r'[^a-z0-9]', '', s.lower())
return s == s[::-1]
ex1 = "A man, a plan, a canal: Panama" #true
ex2 = "arace a car" #false
print(isPalindrome(ex1))
print(isPalindrome(ex2)) |
5c3babf386e2870a1b93f097a08965e60174a4a7 | jonathanmockostrand/Homework4 | /HW4_Jonathan_Mocko-Strand.py | 2,042 | 3.859375 | 4 | ###########################################################
## ##
## Jonathan Mocko-Strand ##
## Dept. of Geology & Geophysics, TAMU. 2013-10-22 ##
## Python for Geoscientists ##
## Homework Assignment 4 ##
## ##
###########################################################
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import urllib
def url_cm_import(filename):
'''
This function will import a specific color map directly from:
http://geography.uoregon.edu/datagraphics/
The available color map options can be found on the website.
The imput file is the .txt color map filename
The output is a 100x100 cell plot of randomly generated numbers
with the chosen color bar.
'''
url = 'http://geography.uoregon.edu/datagraphics/color/'+filename
cm_data = urllib.urlopen(url)
r=[]; g=[]; b=[];
for line in cm_data.readlines()[2:]:
colors = line.split()
r.append(float(colors[0]))
g.append(float(colors[1]))
b.append(float(colors[2]))
cm_length = len(r)
red_component = [((float(n)/(cm_length-1)), r[n-1], r[n]) for n in range(cm_length)]
green_component = [((float(n)/(cm_length-1)), g[n-1], g[n]) for n in range(cm_length)]
blue_component = [((float(n)/(cm_length-1)), b[n-1], b[n]) for n in range(cm_length)]
cdict = {'red' : red_component,
'green': green_component,
'blue' : blue_component}
return matplotlib.colors.LinearSegmentedColormap('url_cm_import',cdict,256)
if __name__ == '__main__':
url_cm_import = url_cm_import('GrMg_16.txt')
plt.title('GrMg_16 Color Map of Randomly Generated Numbers\n' )
plt.pcolor(np.random.rand(100,100),cmap=url_cm_import)
plt.colorbar()
plt.show()
plt.savefig("My_colormap.pdf") |
bacd3b925693361942403d100e0c5b6c0c6377af | Oihana1/python | /funtzioak.py | 378 | 3.5625 | 4 | def Kenketa(num1,num2):
if(num1>numb2):
ken=numb1-numb2
else:
ken=numb2-numb1
return ken
def Biderketa(num1,num2):
bider=num1*num2
return bider
def Zatiketa(num1,num2):
if(num1>numb2):
zati=numb1/numb2
else:https://github.com/Oihana1/python
zati=numb2/numb1
return zati
def Ezabatu():
|
d3b62136f4d413240d32a3ed0f44a1e52edaadd2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/29464e89fa7740148084914804c36fa8.py | 477 | 3.890625 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
ANSWER_YELLING = 'Whoa, chill out!'
ANSWER_EMPTY = 'Fine. Be that way!'
ANSWER_QUESTION = 'Sure.'
ANSWER_ANYTHING_ELSE = 'Whatever.'
def hey(what):
what = what.rstrip() # so questions can be properly detected
if what.isupper():
return ANSWER_YELLING
elif not what:
return ANSWER_EMPTY
elif what.endswith('?'):
return ANSWER_QUESTION
else:
return ANSWER_ANYTHING_ELSE
|
f6cf32bbcd7ba63990fb409f0e77d4cab45f9bf6 | TanaseMihaela/Data_wrangling | /sql_queries.py | 6,684 | 3.703125 | 4 |
import sqlite3
import csv
from pprint import pprint
sqlite_file = 'bucharest.db' # name of the sqlite database file
# Connect to the database
conn = sqlite3.connect(sqlite_file)
# Get a cursor object
cur = conn.cursor()
#number of nodes and ways
QUERY = "select COUNT(*) from nodes "
cur.execute(QUERY)
result = cur.fetchone()
print "Number of nodes:", result[0]
QUERY = "select COUNT(*) from ways "
cur.execute(QUERY)
result = cur.fetchone()
print "Number of ways:", result[0]
#number of unique users
QUERY = "select count(distinct uid) from (select uid from nodes union all select uid from ways)"
cur.execute(QUERY)
result = cur.fetchone()
print "Number of unique users:", result[0]
#top 3 contributing users
QUERY = "SELECT user, count(*) as USERS_COUNT \
FROM (select user, uid from nodes UNION ALL select user, uid FROM ways) \
GROUP BY user \
ORDER BY USERS_COUNT DESC \
LIMIT 3"
cur.execute(QUERY)
result = cur.fetchall()
print "----top 3 contributing users----"
c=1
for i in result:
print c,"User name: %s, Posts counts: %s" % (i[0], i[1])
c+=1
#number of users contributing once
QUERY = "SELECT count(*) FROM \
(SELECT user, count(*) as USERS_COUNT \
FROM (select user, uid from nodes UNION ALL select user, uid FROM ways) \
GROUP BY user \
HAVING USERS_COUNT=1)"
cur.execute(QUERY)
result = cur.fetchone()
print "----Users contributing once----"
print "Number of users contributing once:", result[0]
#number of mobile shops
QUERY = "SELECT value, count(*)\
FROM nodes_tags WHERE value in ('Telekom','Orange','Vodafone') \
GROUP BY value"
cur.execute(QUERY)
result = cur.fetchall()
print "----Mobile shops----"
for i in result:
print "Shop name: %s, counts: %s" % (i[0], i[1])
#operator with most shops
QUERY = "SELECT value, max(No_shops) FROM \
(SELECT value, count(*) as No_shops\
FROM nodes_tags WHERE value IN ('Telekom','Orange','Vodafone') \
GROUP BY value)"
cur.execute(QUERY)
result = cur.fetchall()
print "----Mobile operator with most shops----"
for i in result:
print "Shop name: %s, max counts: %s" % (i[0], i[1])
#Shops position on map
QUERY = "SELECT value, lon, lat FROM (\
(SELECT id, value \
FROM nodes_tags WHERE value IN ('Telekom','Orange','Vodafone')) t_shops \
LEFT JOIN \
(SELECT DISTINCT id, lon, lat\
FROM nodes) t_pos \
ON t_shops.id=t_pos.id)"
cur.execute(QUERY)
result = cur.fetchall()
print "----Mobile shops position on map----"
for i in result:
print "Shop name: %s, Lat: %s, Lon: %s" %(i[0], i[1], i[2])
#Min and Max date by shop when the shop was updated on the map
QUERY = "SELECT value, MIN(SUBSTR(timestamp,1,10)), MAX(SUBSTR(timestamp,1,10))FROM (\
(SELECT id, value \
FROM nodes_tags WHERE value IN ('Telekom','Orange','Vodafone')) t_shops \
LEFT JOIN \
(SELECT distinct id, timestamp\
FROM nodes) t_date \
ON t_shops.id=t_date.id) fin_table \
GROUP BY fin_table.value "
cur.execute(QUERY)
result = cur.fetchall()
import sqlite3
import csv
from pprint import pprint
sqlite_file = 'bucharest.db' # name of the sqlite database file
# Connect to the database
conn = sqlite3.connect(sqlite_file)
# Get a cursor object
cur = conn.cursor()
#number of nodes and ways
QUERY = "select COUNT(*) from nodes "
cur.execute(QUERY)
result = cur.fetchone()
print "Number of nodes:", result[0]
QUERY = "select COUNT(*) from ways "
cur.execute(QUERY)
result = cur.fetchone()
print "Number of ways:", result[0]
#number of unique users
QUERY = "select count(distinct uid) from (select uid from nodes union all select uid from ways)"
cur.execute(QUERY)
result = cur.fetchone()
print "Number of unique users:", result[0]
#top 3 contributing users
QUERY = "SELECT user, count(*) as USERS_COUNT \
FROM (select user, uid from nodes UNION ALL select user, uid FROM ways) \
GROUP BY user \
ORDER BY USERS_COUNT DESC \
LIMIT 3"
cur.execute(QUERY)
result = cur.fetchall()
print "----top 3 contributing users----"
c=1
for i in result:
print c,"User name: %s, Posts counts: %s" % (i[0], i[1])
c+=1
#number of users contributing once
QUERY = "SELECT count(*) FROM \
(SELECT user, count(*) as USERS_COUNT \
FROM (select user, uid from nodes UNION ALL select user, uid FROM ways) \
GROUP BY user \
HAVING USERS_COUNT=1)"
cur.execute(QUERY)
result = cur.fetchone()
print "----Users contributing once----"
print "Number of users contributing once:", result[0]
#number of mobile shops
QUERY = "SELECT value, count(*)\
FROM nodes_tags WHERE value in ('Telekom','Orange','Vodafone') \
GROUP BY value"
cur.execute(QUERY)
result = cur.fetchall()
print "----Mobile shops----"
for i in result:
print "Shop name: %s, counts: %s" % (i[0], i[1])
#operator with most shops
QUERY = "SELECT value, max(No_shops) FROM \
(SELECT value, count(*) as No_shops\
FROM nodes_tags WHERE value IN ('Telekom','Orange','Vodafone') \
GROUP BY value)"
cur.execute(QUERY)
result = cur.fetchall()
print "----Mobile operator with most shops----"
for i in result:
print "Shop name: %s, max counts: %s" % (i[0], i[1])
#Shops position on map
QUERY = "SELECT value, lon, lat FROM (\
(SELECT id, value \
FROM nodes_tags WHERE value IN ('Telekom','Orange','Vodafone')) t_shops \
LEFT JOIN \
(SELECT DISTINCT id, lon, lat\
FROM nodes) t_pos \
ON t_shops.id=t_pos.id)"
cur.execute(QUERY)
result = cur.fetchall()
print "----Mobile shops position on map----"
for i in result:
print "Shop name: %s, Lat: %s, Lon: %s" %(i[0], i[1], i[2])
#Min and Max date by shop when the shop was included in openstreetmap
QUERY = "SELECT value, MIN(SUBSTR(timestamp,1,10)), MAX(SUBSTR(timestamp,1,10))FROM (\
(SELECT id, value \
FROM nodes_tags WHERE value IN ('Telekom','Orange','Vodafone')) t_shops \
LEFT JOIN \
(SELECT distinct id, timestamp\
FROM nodes) t_date \
ON t_shops.id=t_date.id) \
GROUP BY value "
cur.execute(QUERY)
result = cur.fetchall()
print "----First and last time each shop was updated----"
for i in result:
print "Shop name: %s, Min date: %s, Max date: %s" %(i[0], i[1], i[2])
|
1dfeabafaf85e2d57f22d2fb715668f47ed4f302 | OmenNXGen/Coding_with_Python-Lists | /content/1-lists/length.py | 271 | 4.25 | 4 |
aString = '12345'
# use the len() function to get the length of a string
print('the string has a length of:')
print(len(aString))
aList = [1,2,3,4,5]
# you can also use the len() function to get the length of a list
print('the list has a length of:')
print(len(aList))
|
ae333d1b58ebc14b108b5f5fb9dfcd7545f0f731 | Dyksonn/Exercicios-Uri | /1133.py | 145 | 3.953125 | 4 | a = int(input())
b = int(input())
if(a > b):
a, b = b, a
for num in range(a + 1, b):
if(num % 5 == 2) or (num % 5 == 3):
print(num) |
10544f4c60b88773dd53ae4e8f51be8feb718ac5 | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/serialization/449_serialize_and_deserialize_BST.py | 2,157 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
if not root:
return ""
result = []
stack=[root]
while stack:
node = stack.pop()
result.append(str(node.val))
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return "#".join(result)
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree.
"""
if not data:
return None
elements = collections.deque([int(i) for i in data.split("#")])
def helper(low, high):
if not elements or elements[0] < low or elements[0] > high:
return None
newnode = TreeNode(int(elements.popleft()))
newnode.left = helper(low, newnode.val)
newnode.right = helper(newnode.val, high)
return newnode
return helper(float("-inf"), float("inf"))
def deserialize2(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree.
"""
if not data:
return None
elements = data.split("#")
def helper(left, right):
if left > right:
return None
newnode = TreeNode(int(elements[left]))
if left == right:
return newnode
rightchild = left + 1
while rightchild <= right:
if int(elements[rightchild]) < int(newnode.val):
rightchild += 1
else:
break
newnode.left = helper(left+1, rightchild-1)
newnode.right = helper(rightchild, right)
return newnode
return helper(0, len(elements)-1)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
|
489d79577464ed4eccbf7b9c6d652f1fc7d2a4b4 | ervitis/challenges | /leetcode/range_addition_2/main.py | 742 | 3.578125 | 4 | """
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
"""
from typing import List
def max_count(m: int, n: int, ops: List[List[int]]) -> int:
for op in ops:
m = min(m, op[0])
n = min(n, op[1])
return m * n
if __name__ == '__main__':
print(max_count(3, 3, [[2, 2], [3, 3]]))
print(max_count(3, 3, [[2, 2], [3, 3], [3, 3], [3, 3], [2, 2], [3, 3], [3, 3], [3, 3], [2, 2], [3, 3], [3, 3], [3, 3]]))
print(max_count(3, 3, []))
print(max_count(3000, 3000, []))
|
3d752760c3a10939b299dbed5467d8e94f617a6c | kaizer1v/py-exercises | /alternating_chars.py | 498 | 4.21875 | 4 | def alternating_chars(s):
'''
Given a string like AABABBAB, you need to return how many chars need to be
deleted so that no subsequent letters are the same
Basically, AABABABBA should become ABABABA (return total chars to be
deleted)
'''
toDel = 0
for x in range(1, len(s)):
if s[x] == s[x - 1]:
toDel = toDel + 1
# total = total - 1
for index, char in enumerate(s):
if s[index] == s[index - 1]
alternating_chars('AABABABBA')
|
636874fab0a3811cb0ff9357ece4001133c8e462 | ozcayci/01_python | /gun12/starcraft_games.py | 1,615 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
starcraft_games.py
"""
def get_raw_data():
data = """
Game GameRankings Metacritic
StarCraft (PC) 93%[109] (PC) 88[111]
Insurrection 48%[113] —
Retribution —[114] —
StarCraft: Brood War 95%[115] —
StarCraft II: Wings of Liberty 92%[116] 93[117]
StarCraft II: Heart of the Swarm 86%[118] 86[119]
StarCraft II: Legacy of the Void 88%[120] 88[121]
"""
return data
def split_to_lines(raw_data):
return raw_data.strip().splitlines()
def extract_point(text):
"""
>>> extract_point("(PC) 93%[109] -> 109")
109
>>> extract_point("(PC) 88[111] -> 111")
111
>>> extract_point("'—'")
None
:return:
"""
# TODO: extract_point()
pass
def parse_data(lines):
header_line = lines.pop(0)
parsed_elements = []
for line in lines:
parts = line.split("\t")
parts = [x.strip() for x in parts]
print(parts)
# ['StarCraft II: Legacy of the Void', '88%[120]', '88[121]']
# TODO: parts'in ilgili elemanlarini extract_point()'den gecirelim.
# TODO: bu elemanlari kullanarak bir dict olusturalim.
# TODO: bu dict'i bir list'e ekleyelim.
print(parsed_elements)
# TODO: list'i dondurelim.
def main():
raw_data = get_raw_data()
lines = split_to_lines(raw_data)
parsed_lines = parse_data(lines)
# [
# {"game":"StarCraft", "GameRankings":109, "Metacritic":111}
# ...
# ]
print()
if __name__ == "__main__":
main()
|
cccfeeb16d38db6e1c3e2172f40d65dcdafb311a | Gera2019/gu_python_algorythm | /lesson_7/task_2.py | 1,593 | 4 | 4 | '''
2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами
на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
'''
import random
def merge_sort(arr, start, end):
''' Сортировка вещественного массива методом слияния '''
if end - start > 1:
mid = (start + end) // 2
merge_sort(arr, start, mid)
merge_sort(arr, mid, end)
# слияние сортированных подсписков
left = arr[start:mid]
right = arr[mid:end]
s = start
i = 0
j = 0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
arr[s] = left[i]
i += 1
else:
arr[s] = right[j]
j += 1
s += 1
if start + i < mid:
while s < end:
arr[s] = left[i]
i += 1
s += 1
else:
while s < end:
arr[s] = right[j]
j += 1
s += 1
def main():
size = 15
user_array = [round(random.uniform(0, 50), 2) for _ in range(size)]
print('Исходный массив', user_array)
merge_sort(user_array, 0, size)
print('Сортированный массив:', user_array)
if __name__ == '__main__':
main() |
e36423051224c9fc2e2ce9d61e3393486209cdcc | campbelldgunn/cracking-the-coding-interview | /ctci-06-03-dominoes.py | 557 | 3.75 | 4 | #!/usr/bin/env python3
"""
Given an 8x8 checker board with two opposite corners cut out, and 31 domioes
which can each cover two spots, can you cover the entire board?
Completion time: 15 minutes.
Notes
- Tried on 4x4 first, convinced you cannot manually.
- Tried 2x2, obviously not.
- Could not prove it past intuition.
- First hint - count number of white/black spots.
- Turns out that opposite corners MUST be the same color.
- So, 8x8 board means 6 black spots, 8 white spots open.
- Each dominoe MUST cover one white and one black - can't work.
"""
|
0d0e9cb23aacde7b3baa17710c338204439b6b96 | yongfuhu/python.learning | /quadratic.py | 566 | 3.8125 | 4 | a = int(input('请输入ax**2+bx+c=0中的a的值:'))
b = int(input('请输入ax**2+bx+c=0中的b的值:'))
c = int(input('请输入ax**2+bx+c=0中的c的值:'))
import math
def quadratic(a, b, c):
for x in (a, b, c):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
n = b**2 - 4*a*c
if a == 0:
x = - b/c
return x
if n >= 0:
x1 = (math.sqrt(b**2 - 4*a*c) - b) / (2*a)
x2 = -(math.sqrt(b**2 - 4*a*c) + b) / (2*a)
return x1, x2
else:
print ('无解')
print ('结果为:'+str(quadratic(a, b, c))) |
6daee309a4eacddec5b28982d7a0d1b9f76b6fa1 | nielsenjared/algorithms | /20-recursive-factorial/app.py | 148 | 4.03125 | 4 | def factorial(n):
if (n == 0) or (n == 1):
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) |
5fa92e40799bd358912c8b4cd8910f5effb7b366 | jjmuesesq/ALGORITMOS_2018-1 | /LABORATORIOS/LAB2/punto 2/mergeSort.py | 929 | 4 | 4 | def merge(A, start, mid, end):
p=start
q= mid+1
Arr=[0]*(end-start+1)
k=0
#print(range(start, end))
for i in range(start, end+1):
if(p > mid):
Arr[k]=A[q]
k+=1
q+=1
#print("if1")
elif(q > end):
Arr[k]=A[p]
k+=1
p+=1
#print("if2")
elif(A[p] < A[q]):
Arr[k] = A[p]
k+=1
p+=1
#print("if3")
else:
Arr[k]=A[q]
k+=1
q+=1
#print("else")
#print(Arr)
for j in range(0, k):
A[start] = Arr[j]
start+=1
return A
def merge_Sort(A, start, end):
#print(A)
if(start < end):
mid= int((start+end)/2)
merge_Sort(A, start, mid)
merge_Sort(A, mid+1, end)
merge(A, start, mid, end)
M=[9, 7, 8, 3, 2, 1]
merge_Sort(M, 0, 5)
print(M)
|
7f0f58aec1f467a2072d582dcd70e5ee28a769d9 | Slothfulwave612/The-CSV-Reader | /csvFunctionFile.py | 64,993 | 3.515625 | 4 | # this is csv's most function file
# the most important file, as it will contain all the option function's code
# we will link this file to our main file and execute the required operation
import csv # importing csv module
import os # importing os module
import time # importing time module
import sys # importing sys module
import logging # importing logging module
import datetime # importing datetime module
import csvExceptionFile as ce # importing csvFunctionFile as ce
import csvReuse as cr # importing csvReuse as cr
import csvReuseInputOutput as ci # importing csvReuseInputOutput as ci
class csvExecution:
# class named csvExcution for executing all the operation
def createCSV(self):
# this function will create a new csv file
try:
os.makedirs('csvDocument')
# making the directory where all csv files
except Exception:
pass
os.chdir('csvDocument')
# changing the directory to csvDocument, as all files will be saved there
logging.basicConfig(filename='csvReaderLogFile.log', level=logging.INFO, format='%(asctime)s : %(message)s')
# using basicConfig function to keep a track what is happening in the program
file_name = ci.enterName(num=0) # calling enterName function with parameter num=0
cr.lineTime(sec=0.5) # calling lineTime function
ci.openSys() # calling openSys function
cr.lineTime(sec=0.5) # calling lineTime function
with open(file_name, 'w') as my_file:
# opening the specified file name in write mode
logging.info(f'{file_name} has been opened for writing the content') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
totColumn = ci.totalColumn() # calling totalColumn function and assigning totColumn the value of x
cr.lineTime(sec=0.5) # calling lineTime function
colList = []
# list that will store column names
for i in range(totColumn):
# inputting the column names in specified csv file
col_name = input(f'Enter The Column Name {i+1} :- ').strip()
colList.append(col_name)
# appending the column name to colList
logging.info(f'Column Name {i+1} :- {col_name}') # using logging.info
if(i+1 == totColumn):
my_file.write(col_name)
else:
my_file.write(col_name + ',')
# writing down the column name in the csv file
my_file.write('\n') # writing a new line in the file
cr.lineTime(sec=0.5) # calling lineTime function
numLines = ci.totalLines() # calling totalLines function and assiging numLines the value of x
cr.lineTime(sec=0.5) # calling lineTime function
for i in range(1, numLines + 1):
for j in range(1, totColumn + 1):
while True:
# try-except clause
try:
col_info = input(f'Enter {colList[j-1]} For Line {i} :- ').strip()
logging.info(f'{colList[j-1]} For Line {i} :- {col_info}') # using logging.info
for i in col_info:
if(i == ','):
col_info = col_info.replace(',', '-')
# inputting the information in respective column
break # breaking when input is valid
except ValueError:
# if value error is caught
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Invalid Input') # using logging.info
print('Invalid Input')
cr.lineTime(sec=0.5) # calling lineTime function
if(j != totColumn):
my_file.write(col_info + ',')
else:
my_file.write(col_info)
# appending the information in the csv file
cr.lineTime(sec=0.5) # calling lineTime function
my_file.write('\n')
logging.info('Saving Your File') # using logging.info
cr.saveFile(name=file_name) # calling saveFile function
os.chdir('..') # comming back from the directory csvDocument
logging.info(os.getcwd()) # using logging.info
def displayCSV(self, num):
# this function will display all the column names and thier information in a tabular format
# if num = 0 then display all the information in a tabular format
# if num = 1 then display specific information in a tabular format
# try-exception clause
try:
os.chdir('csvDocument')
# changing the directory to csvDocument
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # stopping the time for 0.5 seconds
print('csvDocument Does Not Exist')
logging.info('csvDocument Does Not Exist') # using logging.info
else:
# if no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
if(num == 0):
# for displaying all the information
logging.info('Displaying all the information in a tabular format')
cr.displayTable(Listcol=colList, Listinfo=infoList) # calling displayTable function
# to print the whole data in a tabular format
elif(num == 1):
# to display specific information
print(f'{file_name} has following {len(colList)} columns :-')
cr.lineTime(sec=0.5) # calling lineTime function
cr.columnNames(l=colList) # calling columnNames function
numCol = cr.exceptionX(xnum=0, l=colList) # calling exceptionX function
indexl = []
colSpecific = []
# colSpecific is an empty list
cr.lineTime(sec=0.5) # calling lineTime function
cr.columnNames(l=colList) # calling columnNames function
for i in range(numCol):
a = cr.exceptionX(xnum=1, l=colList) # calling exceptionX funtion
colSpecific.append(colList[a-1])
# appending the column names to colSpecific list
indexl.append(a-1)
# appending index in another list indexl
logging.info(f'{colSpecific} are the column names')
infoSpecific = [] # infoSpecific is an empty list
temp = 0
for i in range(len(infoList) // len(colList)):
for j in indexl:
infoSpecific.append(infoList[temp + j])
temp += len(colList)
# appending specific information in infoSpecific list
logging.info('Displaying specific information in a tabular format') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
# for displaying all the information
cr.displayTable(Listcol=colSpecific, Listinfo=infoSpecific) # calling displayTable function
# to print the whole data in a tabular format
except Exception as e:
cr.lineTime(sec=0.5) # calling lineTime function
print('Error In Opening The File')
print(e)
logging.info('Error In Opening The File') # using logging.info
os.chdir('..') # comming back from csvDocument
logging.info(f'{os.getcwd()} is our current directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime funtion
cr.enter_Exception() # calling enter_Exception funciton
def dispSavedFiles(self):
# this function will display all the files that are saved inside csvDocument directory
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory to csvDocument
logging.info(f'{os.getcwd()} is our current directory') # using logging.info
except Exception:
# if any exception is found
cr.lineTime(sec=0.5) # calling lineTime function
print('csvDocument Not Found')
logging.info('csvDocument Not Found') # using logging.info
else:
# if no exception is found
cr.dispFileName() # calling dispFileName
os.chdir('..') # comming back from csvDocument
logging.info(f'{os.getcwd()} is our current directory')
cr.enter_Exception() # calling enter_Exception
def removeSpecificFiles(self):
# this function will remove the files
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
# try-except clause
try:
fileList = cr.dispFileName() # calling dispFileName function
if(len(fileList) == 0):
raise(ce.nosuchfileException)
cr.lineTime(sec=0.5) # calling lineTime function
indexFile = ci.indexFileNumber(num=1, l=fileList) # calling indexFileNumber function and assiging the value of x in indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected') # using logging.info
os.remove(file_name) # removing the file specified
logging.info(f'{file_name} Removed')
print(f'{file_name} Is Removed Successfully')
except ce.nosuchfileException:
cr.lineTime(sec=0.5) # calling lineTime function
os.chdir('..') # coming back from the directory
logging.info(f'{os.getcwd()} is our current directory') # using logging.info
cr.enter_Exception() # calling enter_Exception function
def removeAllFiles(self):
# this function will remove all the files present in the csvDocument
# try-except clause
try:
os.chdir('csvDocument') # changing the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
cr.lineTime(sec=0.5) # calling lineTime function
print('File Not Found')
logging.info('File Not Found')
else:
try:
deleteFile = cr.delAllFile()
if(len(deleteFile) == 0):
raise(ce.nosuchfileException)
for files in deleteFile:
os.remove(files)
# removing files
except ce.nosuchfileException:
cr.lineTime(sec=0.5) # calling lineTime function
print('No File Is Saved')
else:
cr.lineTime(sec=0.5) # calling lineTime function
print('All Files Have Been Successfully Removed')
logging.info('All Files Have Been Successfully Removed') # using logging.info
os.chdir('..') # coming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.enter_Exception() # calling enter_Exception function
def renameFiles(self):
# this function will rename files
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('So Such File Present')
else:
# is no error is caught
try:
fileList = cr.dispFileName() # calling dispFileName function
if(len(fileList) == 0):
raise(ce.nosuchfileException)
cr.lineTime(sec=0.5) # calling lineTime function
indexFile = ci.indexFileNumber(num=2, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected') # using logging.info
newName = ci.enterName(num=1) # calling enterName function
cr.lineTime(sec=0.5) # calling lineTime function
os.rename(file_name, newName) # renaming the file
print(f'{file_name} has been renamed to {newName}')
logging.info(f'{file_name} has been renamed to {newName}') # using logging.info
except ce.nosuchfileException:
cr.lineTime(sec=0.5)
os.chdir('..') # coming back from the directory
logging.info(f'{os.getcwd()} is our current directory') # using logging.info
cr.enter_Exception() # using enter_Exception function
def copyContent(self, call):
# this function is for copying the content from one file to another file
# if call = 0 then copy all the content to another file
# if call = 1 then copy only specific content to another file
# try-exception clause
try:
os.chdir('csvDocument')
# changing the directory to csvDocument
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # stopping the time for 0.5 seconds
print('csvDocument Does Not Exist')
logging.info('csvDocument Does Not Exist') # using logging.info
else:
# if no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
logging.info(f'Opening {file_name}') # using loggging.info
csv_reader = csv.DictReader(my_file) # using DictReader to read the content of the csv file
file_name2 = ci.enterName(num=0) # calling enterName function with parameter num=0
logging.info(f'{file_name2} is our new file') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
with open(file_name2, 'w') as new_file:
if(call == 0):
# for writing down all the information
logging.info('Writing Down All Information') # using logging.info
fieldnames = cr.appendFileCol(file_name) # calling appendFileCol function
logging.info(f'{fieldnames} are the specific columns') # calling logging.info
csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames) # using DictWriter for writing down the information
csv_writer.writeheader() # using writeheader() to write the column names
for lines in csv_reader:
csv_writer.writerow(lines) # writing down the lines
elif(call == 1):
# for writing down specific information
logging.info('Writing down specific information')
colList = cr.appendFileCol(file_name) # using appendFileCol function
logging.info(f'{colList} are the columns') # using logging.info
# to display specific information
print(f'{file_name} has following {len(colList)} columns :-')
cr.lineTime(sec=0.5) # calling lineTime function
cr.columnNames(l=colList) # calling columnNames function
numCol = cr.exceptionX(xnum=0, l=colList) # calling exceptionX function
colSpecific = [] # colSpecific is an empty list
delCol = [] # delCol is an empty list
cr.lineTime(sec=0.5) # calling lineTime function
cr.columnNames(l=colList) # calling columnNames function
for i in range(numCol):
a = cr.exceptionX(xnum=1, l=colList) # calling exceptionX funtion
colSpecific.append(colList[a-1])
# appending the column names to colSpecific list
for i in colList:
if i not in colSpecific:
delCol.append(i)
# appending columns that are to be deleted from the file
logging.info(f'{colSpecific} are the column names') # using logging.info
csv_writer = csv.DictWriter(new_file, fieldnames=colSpecific) # using DictWriter method
csv_writer.writeheader() # using writeheader method
for lines in csv_reader:
for item in delCol:
del lines[item]
csv_writer.writerow(lines)
cr.lineTime(sec=0.5) # calling lineTime function
print('Copying Successfully Done')
except Exception as e:
# if exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print(e)
print('Error')
logging.info('Error')
os.chdir('..') # coming back from the directory
logging.info(f'{os.getcwd()} is our current working directory')
cr.enter_Exception() # calling enter_Exception function
def addAtFront(self):
# this function will add a line at the top of the file
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
infoUpdate = [] # infoUpdate is an empty list
with open('new_file.csv', 'w') as new_file:
# opening new file to store the updated information
for i in colList:
while True:
# try-except clause
try:
x = input(f'Enter Description in {i} :- ').strip() # enter the information
for i in x:
if(i == ','):
x = x.replace(',', '-')
break # breaking when valid input is entered
except ValueError:
# if value error is caught
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
infoUpdate.append(x)
# appending information at font of the list
for i in infoList:
infoUpdate.append(i)
# appending all other information in the list
ci.csvWriteFile(fileName=new_file, col=colList, info=infoUpdate) # calling csvWriteFile function
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('Information Added Successfully')
logging.info('Information Added Successfully') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
os.remove(file_name) # removing file_name
os.rename('new_file.csv', file_name) # renaming the file
except Exception as e:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print(e)
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def addInBtw(self):
# this function will add information in between the line
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
infoUpdate = [] # infoUpdate is an empty list
with open('new_file.csv', 'w') as new_file:
# opening new file to store the updated information
while True:
# try-except clause
try:
c = 0
whichElement = input(f'Enter {colList[0]} after which you want to add another line :- ')
# entering the information
logging.info(f'{whichElement} is the element after which element will be added')
for i in range(0, len(infoList), len(colList)):
if(whichElement != infoList[i]):
c += 1
if(c == len(infoList) // len(colList)):
raise(ce.nosuchcolumnException)
break # breaking the clause when the input in valid
except ValueError:
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input')
except ce.nosuchcolumnException:
cr.lineTime(sec=0.5)
print(f'{whichElement} not present')
logging.info(f'{whichElement} not present')
cr.lineTime(sec=0.5) # calling lineTime function
try:
position = infoList.index(whichElement)
except Exception:
cr.lineTime(sec=0.5) # calling lineTime function
print(f'No such {colList[0]} present')
else:
for i in range(len(infoList)):
# appending information in list infoUpdate
if(i == position + len(colList)):
for j in range(len(colList)):
while True:
# try-except clause
try:
x = input(f'Enter Discription In {colList[j]} :- ').strip() # enter information
for i in x:
if(i == ','):
x = x.replace(',', '-')
logging.info(f'{x} is entered as {colList[j]}') # using logging.info
break # breaking the clause when input is valid
except ValueError:
# if value error is caught
cr.lineTime(sec=0.5) # using lineTime function
print('Invalid Input')
logging.info('Invalid Input')
infoUpdate.append(x)
logging.info(f'{x} is entered as {colList[j]}') # using logging.info
infoUpdate.append(infoList[i])
else:
infoUpdate.append(infoList[i])
# appending the information
ci.csvWriteFile(fileName=new_file, col=colList, info=infoUpdate) # calling csvWriteFile function
cr.lineTime(sec=0.5) # calling lineTime function
print('Information Added Successfully')
logging.info('Information Added Successfully') # using logging.info
os.remove(file_name) # removing file_name
os.rename('new_file.csv', file_name) # renaming the file
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def addAtRare(self):
# this function will add information at the end of the file
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
with open('new_file.csv', 'w') as new_file:
# opening new file to store the updated information
for i in range(len(colList)):
while True:
# try-except clause
try:
x = input(f'Enter Discription In {colList[i]} :- ').strip() # entering the information
for i in x:
if(i == ','):
x = x.replace(',', '-')
logging.info(f'{x} is entered as {colList[i]}') # using logging.info
break # breaking the clause when the input is valid
except ValueError:
cr.lineTime(sec=0.5) # using lineTime function
print('Invalid Input')
logging.info('Invalid Input') # using logging.info
infoList.append(x)
# appending the information
ci.csvWriteFile(fileName=new_file, col=colList, info=infoList) # calling csvWriteFile function
cr.lineTime(sec=0.5) # calling lineTime function
print('Information Added Successfully')
logging.info('Information Added Successfully') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
os.remove(file_name) # removing file_name
os.rename('new_file.csv', file_name) # renaming the file
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def updateLine(self):
# this function will update the whole line
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
UpdatedinfoList = [] # UpdatedinfoList is an empty list
with open('new_file.csv', 'w') as new_file:
# opening new file to store the updated information
while True:
# try-except clause
try:
c = 0
x = input(f'Enter {colList[0]} after which you want to add another line :- ')
# entering the information
logging.info(f'{x} is the element after which element will be added')
for i in range(0, len(infoList), len(colList)):
if(x != infoList[i]):
c += 1
if(c == len(infoList) // len(colList)):
raise(ce.nosuchcolumnException)
break # breaking the clause when the input in valid
except ValueError:
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input')
except ce.nosuchcolumnException:
cr.lineTime(sec=0.5)
print(f'{x} not present')
logging.info(f'{x} not present')
cr.lineTime(sec=0.5) # calling lineTime function
try:
position = infoList.index(x) # assiging the index of x to variable position
except Exception:
# if any exception is caught
print(f'{x} is not present')
ci.csvWriteFile(fileName=new_file, col=colList, info=infoList) # calling csvWriteFile function
else:
k = 0
length = len(colList)
for i in range(len(infoList)):
if(i == position and length != 0):
cr.lineTime(sec=0.5) # calling lineTime Function
while True:
try:
x = input(f'Enter Discription in {colList[k]} :- ').strip() # entering the required information
for i in x:
if(i == ','):
x = x.replace(',', '-')
logging.info(f'{x} is entered as {colList[k]}') # using logging.info
break # breaking the clause when the input is valid
except Exception:
# when any exception is encountered
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input') # using logging.info
UpdatedinfoList.append(x)
k += 1
position += 1
length -= 1
else:
UpdatedinfoList.append(infoList[i])
# appending the updated information in the list UpdatedinfoList
ci.csvWriteFile(fileName=new_file, col=colList, info=UpdatedinfoList) # calling csvWriteFile function
cr.lineTime(sec=0.5) # calling lineTime funtion
print('Information Updated Successfully')
logging.info('Information Updated Successfully') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
os.remove(file_name) # removing file_name
os.rename('new_file.csv', file_name) # renaming the file
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def UpdateSpecific(self):
# this function will update specific content of any specified line
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
UpdatedinfoList = [] # UpdatedinfoList is an empty list
find = 0 # assiging the value 0 to varaible find
with open('new_file.csv', 'w') as new_file:
# opening new file to store the updated information
while True:
# try-except clause
try:
c = 0
updateFinder = input(f'Enter {colList[0]} after which you want to add another line :- ')
# entering the information
logging.info(f'{updateFinder} is the element after which element will be added')
for i in range(0, len(infoList), len(colList)):
if(updateFinder != infoList[i]):
c += 1
if(c == len(infoList) // len(colList)):
raise(ce.nosuchcolumnException)
break # breaking the clause when the input in valid
except ValueError:
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input')
except ce.nosuchcolumnException:
cr.lineTime(sec=0.5)
print(f'{updateFinder} not present')
logging.info(f'{updateFinder} not present')
cr.lineTime(sec=0.5) # calling lineTime function
print(f'All the columns present in the file {file_name} are as follows :-')
cr.lineTime(sec=0.5) # calling lineTime function
cr.columnNames(l=colList) # calling columnNames function
numCol = cr.exceptionX(xnum=3, l=colList) # calling exceptionX function
indexl = []
colSpecific = [] # colSpecific is an empty list
for i in range(numCol):
a = cr.exceptionX(xnum=1, l=colList) # calling exceptionX funtion
while True:
# try-except clause
cr.lineTime(sec=0.5) # calling lineTime function
try:
x = input(f'Enter Discription In {colList[a-1]} :- ').strip() # entering required information
for i in x:
if(i == ','):
x = x.replace(',', '-')
logging.info(f'{x} is entered as {colList[a-1]}') # using logging.info
break # breaking the clause when the input is valid
except ValueError:
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input') # using logging.info
colSpecific.append(x)
# appending the updated information to colSpecific list
indexl.append(a-1)
# appending index in another list indexl
logging.info(f'{colSpecific} are the column names')
infoUpdated = [] # infoSpecific is an empty list
addList = [] # updated information for the specified line
c = 1 # assiging the value 1 to variable c
for i in range(len(infoList)):
if(infoList[i] == updateFinder):
for j in range(len(colList)):
if(c <= len(colList)):
addList.append(infoList[i+j])
c += 1
# appending the specific line information to addList
c = 0 # assigning the value 0 to variable c
for i in indexl:
del addList[i-c] # deleting the list item
c += 1
for i in range(len(indexl)):
addList.insert(indexl[i], colSpecific[i])
# inserting the updated information to the addList
c = 0
for i in range(len(infoList)):
if(infoList[i] == updateFinder):
for j in range(len(colList)):
if(c <= len(colList) - 1):
del infoList[i+j-c]
c += 1
break
# deleting the x information line
for i in range(len(infoList)):
if(i == position):
for j in addList:
infoUpdated.append(j)
infoUpdated.append(infoList[i])
# appending updated information to infoUpdated
ci.csvWriteFile(fileName=new_file, col=colList, info=infoUpdated) # calling csvWriteFile function
cr.lineTime(sec=0.5) # calling lineTime function
print('Information Updated Successfully')
logging.info('Information Updated Successfully') # using logging.info
os.remove(file_name) # removing the file name
os.rename('new_file.csv', file_name) # renaming the file
except Exception as e:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def delCsvLine(self):
# this function will delete the line as specified by the user
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
UpdatedinfoList = [] # UpdatedinfoList is an empty list
find = 0 # assiging the value 0 to varaible find
with open('new_file.csv', 'w') as new_file:
# opening new file to store the updated information
while True:
# try-except clause
try:
c = 0
delFinder = input(f'Enter {colList[0]} after which you want to add another line :- ')
# entering the information
logging.info(f'{delFinder} is the element after which element will be added')
for i in range(0, len(infoList), len(colList)):
if(delFinder != infoList[i]):
c += 1
if(c == len(infoList) // len(colList)):
raise(ce.nosuchcolumnException)
break # breaking the clause when the input in valid
except ValueError:
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input')
except ce.nosuchcolumnException:
cr.lineTime(sec=0.5)
print(f'{delFinder} not present')
logging.info(f'{delFinder} not present')
try:
position = infoList.index(delFinder) # assiging the index of delFinder to variable position
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print(f'{delFinder} is not present')
ci.csvWriteFile(fileName=new_file, col=colList, info=infoList) # calling csvWriteFile function
else:
length = len(colList)
for i in range(len(infoList)):
if(i == position and length != 0):
position += 1
length -= 1
else:
UpdatedinfoList.append(infoList[i])
# deleting and appending he information into the list UpdatedinfoList
ci.csvWriteFile(fileName=new_file, col=colList, info=UpdatedinfoList) # calling csvWriteFile function
print('Information Deleted Successfully')
logging.info('Information Deleted Successfully') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
os.remove(file_name) # removing the file name
os.rename('new_file.csv', file_name) # renaming the file
except Exception as e:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print(e)
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def searchCsvFile(self):
# this function will search the content as specified by the file
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
# try-except clause
try:
with open(file_name, 'r') as my_file:
# opening the file
logging.info(f'Opening {file_name}') # using loggging.info
colList = cr.appendFileCol(file_name)
# appending column name in colList
infoList = cr.appendFileInfo(file_name)
# appending information in infoList
searchList = [] # UpdatedinfoList is an empty list
find = 0 # assiging the value 0 to varaible find
while True:
# try-except clause
try:
c = 0
searchFinder = input(f'Enter {colList[0]} after which you want to add another line :- ')
# entering the information
logging.info(f'{searchFinder} is the element after which element will be added')
for i in range(0, len(infoList), len(colList)):
if(searchFinder != infoList[i]):
c += 1
if(c == len(infoList) // len(colList)):
raise(ce.nosuchcolumnException)
break # breaking the clause when the input in valid
except ValueError:
cr.lineTime(sec=0.5) # calling lineTime function
print('Invalid Input')
logging.info('Invalid Input')
except ce.nosuchcolumnException:
cr.lineTime(sec=0.5)
print(f'{searchFinder} not present')
logging.info(f'{searchFinder} not present')
cr.lineTime(sec=0.5) # calling lineTime function
position = []
try:
for i in range(0, len(infoList), len(colList)):
if(searchFinder == infoList[i]):
position.append(i)
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print(f'{searchFinder} is not present')
ci.csvWriteFile(fileName=new_file, col=colList, info=infoList) # calling csvWriteFile function
else:
length = len(colList) # assigning the length of colList to variable length
c = 0
for i in range(len(infoList)):
if(i == position[c] and length != 0):
searchList.append(infoList[i])
length -= 1
position[c] += 1
if(length == 0):
length = len(colList)
c += 1
if(c == len(position)):
break
# appending the items to be displayed in thelist searchList
cr.lineTime(sec=0.5) # calling lineTime function
cr.displayTable(Listcol=colList, Listinfo=searchList) # calling displayTable function
# displaying the appended information in a tabular format
logging.info('Information Searched')
cr.lineTime(sec=0.5) # calling lineTime function
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime function
print('Program Confronted Some Error')
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # calling lineTime function
cr.enter_Exception() # calling enter_Exception function
def propertyCsvFile(self):
# this function will display all the property of the file
# try-except clause
try:
os.chdir('csvDocument') # chaning the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
except Exception:
# if any exception is caught
cr.lineTime(sec=0.5) # calling lineTime fucntion
print('No Such File Present')
else:
# is no error is caught
print('All The CSV Files Present in The Directory Are As Follows :- ')
cr.lineTime(sec=0.5) # stopping the time for 0.5 seconds
fileList = cr.dispFileName()
# calling dispFileName and assigning fileList with list l
cr.lineTime(sec=0.5) # calling lineTime function
logging.info('Displaying Files Present In csvDocument')
logging.info(fileList)
# using logging.info
indexFile = ci.indexFileNumber(num=0, l=fileList) # calling indexFileNumber function and assigning the value of x to indexFile
cr.lineTime(sec=0.5) # calling lineTime function
file_name = fileList[indexFile - 1] + '.csv'
logging.info(f'{file_name} is the file selected')
mod_time = os.stat(file_name).st_mtime # modification time
print(f'Properties of {file_name} :-'.center(25, ' '))
cr.lineTime(sec=0.5) # calling lineTime function
print(f'1. File Name :- {file_name}')
time.sleep(0.5) # stopping the time for 0.5 seconds
print(f'2. Size :- {os.stat(file_name).st_size}')
time.sleep(0.5) # stopping the time for 0.5 seconds
print(f'3. Modification Time :- {datetime.datetime.fromtimestamp(mod_time)}')
logging.info('Information Searched')
cr.lineTime(sec=0.5) # calling lineTime function
os.chdir('..') # comming back from the directory
logging.info(f'{os.getcwd()} is our current working directory') # using logging.info
cr.lineTime(sec=0.5) # using lineTime function
cr.enter_Exception() # calling enter_Exception function
obj = csvExecution() # making an object of csvExcution class
# the end of the program
# Programmed By :- Slothfulwave@612
|
e0eb11541c31e4b8980e41ec39d274a5ba9980a9 | All-In-Group/DanielDavtyan | /PythonExercises/SectionBasic ExerciseForBeginners/Question8.py | 158 | 3.734375 | 4 | #Print the following pattern
#1
#2 2
#3 3 3
#4 4 4 4
#5 5 5 5 5
i = 6
for num in range(i):
for i in range(num):
print(num, end=" ")
print() |
13e5fd47706fadd3cb4390802eb71f70c1bb5c09 | jikedou/webcrawler | /test1.py | 1,045 | 3.609375 | 4 | # coding:utf-8
import urllib2
import re
import BeautifulSoup
# testUrl = 'https://www.lagou.com/'
testUrl = 'http://example.webscraping.com/'
def download(url, user_agent="wswp", num_retyies=2):
# 设置用户代理
headers = {"User-agent": user_agent}
request = urllib2.Request(url, headers=headers)
# 捕获异常
try:
html = urllib2.urlopen(request).read()
except urllib2.URLError as e:
print "DownLoadError:", e.reason
html = None
# 设置重试下载次数
if num_retyies > 0:
if hasattr(e, 'code') and 500 <= e.code < 600:
# 错误代码为500到600时,重试2次(默认设置2次)--递归
return down(url, user_agent, num_retyies - 1)
return html
# 网站地图
def crawl_siteamp(url):
sitemap=download(url)
links=re.findall('<loc>(.*?)</loc>',sitemap)
for link in links:
html=download(link)
print html
if __name__ == '__main__':
# print download(testUrl)
crawl_siteamp(testUrl) |
7b811cb0541bed65dd8dddd4e4f85de9f4e3e9be | abhaykatheria/cp | /HackerEarth/Round Table.py | 249 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 22:32:42 2018
@author: Mithilesh
"""
def round_table(n,x,k):
lst=[i for i in range(1,n+1)]
while(x%k)<len(lst):
t=x%k
list2=list(lst)
for i in range(t):
|
f66d33ae2b26abcf17f27bb817455ab6303f5fa1 | AlecShang/python_lesson | /02.OOP/OOP.py | 2,851 | 3.6875 | 4 | #!/usr/local/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : OOP.py
@Time : 2019/03/16 10:45:00
@Author : Alec Shang
@Version : 1.0
@Contact : shangjingweiwork@163.com
@License : (C)Copyright 2019-2020
@Desc : None
'''
#######################
# import sys
# print('aaa')
# class StudentPython():
# student_number = '001'
# student_age = '18'
# student_major = 'computer'
# def DoHomework(self):
# print('please do homework!')
# print('then you can play!')
# return None
# shang = StudentPython()
# print(shang.student_age)
# print(shang.DoHomework())
# print(StudentPython.__dict__)
# class A():
# self._name = 'AAAA'
# def __init__(self):
# print('is print A?')
# pass
# class B(A):
# # def __init__(self):
# # pass
# # print('just see is it print?')
# pass
# b = B()
# print(b._name)
# class Student():
# _name = 'shangjingwei'
# def __init__(self):
# print('this is a Student init operation!')
# print('this is a student class!')
# def work(self):
# print('need working...')
# class PythonStudent(Student):
# name = None
# age = 18
# address = 'Yunnan university of finance and economics'
# __sex = '女'
# def __init__(self):
# self.name = 'shang'
# self.age = 20
# print('this is a PythonStudent init operation!')
# def say(self):
# print('my name is {0} and i am {1}'.format(self.name, __class__.age))
# return 1
# def work(self):
# super().work()
# self.say()
# python_student = PythonStudent()
# print(issubclass(Student, PythonStudent))
# print(PythonStudent._name)
# print(python_student.age)
# print(python_student.say())
# print(python_student.__dict__)
# print(PythonStudent.__dict__)
# property(fget, fset, fdel, fdoc)的使用
# 无论输入什么类型的数字,都将其转换为整数
# class Person():
# # _name = None
# _name = 'aaa'
# def fget(self):
# return self._name * 2
# def fset(self, name):
# self._name = name.upper()
# def fdel(self):
# del self._name
# def fdoc(self):
# print('this is a property')
# x = property(fget, fset, fdel, fdoc)
# # p.x 将触发 getter,p.x = value 将触发 setter , del p.x 触发 deleter。
# p = Person()
# p.x = "shang"
# print(p.x)
# 三种方法的实现,实例方法;类方法;静态方法
# class Student():
# # 实例方法
# def A(self):
# pass
# # 类方法
# def B(cls):
# pass
# # 静态方法
# def C():
# pass
# 抽象类的实现
import abc
# 声明一个元类,并且指定当前类的元类
class Human(metaclass=abc.ABCMeta):
# 定义一个抽象方法
@abc.abstractmethod
def eating(self):
pass
|
749b253b421826bc326eabd93df7e39abe0f58c3 | d-mead/AI-Programs | /ATBS practice/chapter2.py | 234 | 3.921875 | 4 | import random
import sys
for i in range(5):
print('hello ')
i = 0
while i < 5:
print('number: ' + str(i))
i = i + 1
for i in range(0, 10, 3):
print(i)
print('')
for i in range(5):
print(random.randint(1, 10)) |
357bb479a78bc033552b2af9db316828df3c5167 | BatiDyDx/MathiPy | /mathipy/functions/quadratic.py | 4,179 | 3.921875 | 4 | import math
from mathipy.math import calculus
class Quadratic(calculus.Function):
"""
f(x) = ax^2 + bx + c
"""
function_type = 'Quadratic'
def __init__(self, a: float = 1, **kwargs):
self.a = a
if 'b' in kwargs and 'c' in kwargs:
b, c = kwargs['b'], kwargs['c']
self.b: float = b
self.c: float = c
self.x1, self.x2 = self.roots = quadratic_roots(a=self.a, b=self.b, c=self.c)
self.xv: float = - self.b / (2 * self.a)
self.yv: float = self.a * (self.xv ** 2) + self.b * self.xv + self.c
elif 'xv' in kwargs and 'yv' in kwargs:
xv, yv = kwargs['xv'], kwargs['yv']
self.xv: float = xv
self.yv: float = yv
self.b: float = (-2 * self.xv) * self.a
self.c: float = ((self.xv ** 2) * self.a) + self.yv
self.x1, self.x2 = self.roots = quadratic_roots(a=self.a, b=self.b, c=self.c)
elif 'x1' in kwargs and 'x2' in kwargs:
x1, x2 = kwargs['x1'], kwargs['x2']
self.x1, self.x2 = x1, x2
self.b: float = -(self.x1 + self.x2) * self.a
self.c: float = (self.x1 * self.x2) * self.a
self.xv: float = - self.b / (2 * self.a)
self.yv: float = self.a * (self.xv ** 2) + self.b * self.xv + self.c
self.roots: list[float, float] = [self.x1, self.x2]
else:
raise NotImplementedError('Expression type not admitted')
if self.a == 0:
raise ValueError('a term cannot be equal to 0')
def get_roots(self) -> list[float, float]:
return self.roots
def get_vertex(self) -> tuple[float, float]:
return self.xv, self.yv
def calculate_values(self, x) -> float:
y = (self.a * (x**2)) + (self.b * x) + self.c
return y
def plot_func(self, ax) -> None:
if not isinstance(self.x1, complex):
ax.scatter(self.roots, (0,0), c=calculus.Function.function_part['roots'])
ax.scatter(*self.get_vertex(), c=calculus.Function.function_part['vertex'])
ax.scatter(0, self.c, c=calculus.Function.function_part['y-intercept'])
def vertex_expression(self) -> str:
vertex_exp = f'{self.a}'
if self.xv > 0:
vertex_exp += f'(x - {self.xv})^2'
elif self.xv < 0:
vertex_exp += f'(x + {-self.xv})^2'
else:
vertex_exp += 'x^2'
if self.yv > 0:
vertex_exp += f' + {self.yv}'
elif self.yv < 0:
vertex_exp += f' - {-self.yv}'
return vertex_exp
def factored_expression(self) -> str:
factored_exp = f'{self.a}'
if self.x1 == self.x2:
if self.x1 > 0:
factored_exp += f'(x - {self.x1})^2'
elif self.x1 < 0:
factored_exp += f'(x + {-self.x1})^2'
else:
factored_exp += 'x^2'
else:
if self.x1 > 0:
factored_exp += f'(x - {self.x1})'
elif self.x1 < 0:
factored_exp += f'(x + {-self.x1})'
else:
factored_exp += 'x'
if self.x2 > 0:
factored_exp += f'(x - {self.x2})'
elif self.x2 < 0:
factored_exp += f'(x + {-self.x2})'
else:
factored_exp += 'x'
return factored_exp
def __str__(self) -> str:
representation: str = f'{self.a}^x + {self.b}x + {self.c}'
return representation
def quadratic_roots(a, b, c):
root_body = b ** 2 - (4 * a * c)
if a == 0:
raise ValueError('a term cannot be equal to 0')
if root_body == 0:
return -b/(2*a)
elif root_body < 0:
x1_real = x2_real = - b / (2 * a)
x1_imag = math.sqrt(math.abs(root_body)) / (2 * a)
x2_imag = - math.sqrt(math.abs(root_body)) / (2 * a)
x1 = complex(x1_real, x1_imag)
x2 = complex(x2_real, x2_imag)
elif root_body > 0:
x1 = (-b + math.sqrt(root_body)) / (2 * a)
x2 = (-b - math.sqrt(root_body)) / (2 * a)
return x1, x2
|
1bf4b03de2134b2fb532c29bb1129493ad6c7e6f | BenjiFuse/aoc-2020 | /Day13/Part2.py | 1,356 | 3.640625 | 4 | def extended_euclidean(a, b):
"""Implementation of the extended euclidean algorithm for finding gcd
and x,y to satisfy a*x + b*y == gcd"""
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_euclidean(b%a, a)
x = y1 - (b//a) * x1
y = x1
return gcd, x, y
def mod_inverse(a, m):
g, x, y = extended_euclidean(a, m)
return x % m
def crt(m, x):
"""Implementation of Chinese Remainder Theorem for combining modular equations"""
while True:
an = mod_inverse(m[1], m[0]) * x[0] * m[1] + \
mod_inverse(m[0], m[1]) * x[1] * m[0]
mn = m[0] * m[1] # combine mod classes
x = x[2:] # remove first 2 remainders
x = [an % mn] + x # prepend combined remainder
m = m[2:] # remove first 2 mods
m = [mn] + m # prepend combined mod
if len(x) == 1: # final remainder found
break
return x[0], an, m # returns final Xn, An, and Mn to satisy An = Xn mod(Mn)
with open('input.txt') as f:
lines = f.read().split('\n')
pairs = {int(n):i for i, n in enumerate(lines[1].split(',')) if n != 'x'}
busses = list(pairs.keys())
offsets = list(pairs.values())
r, an, mn = crt(busses, offsets)
print(mn[0] - r) # subtract combined remainder from combined mod |
678842568a88eb671a04813c6247d807f94cdb82 | jaeinkim/Coding_Training | /Pythonic_Example.py | 820 | 3.5625 | 4 | # # acmicpc
# import sys
# input = sys.stdin.readline
# n, m = map(int, input().split())
# answer = 0
# print(answer)
#
#
# # pytest를 활용하기 위한 문법
# class Solution:
# def twoSum(self, nums: List[int], target: int) -> List[int]:
# return [1,2,3]
#
def solution(A):
A.sort() # 주어진 배열을 정렬합니다.
smallest = 1 # 최소 양의 정수는 1부터 시작합니다.
for num in A:
if num == smallest: # num이 smallest와 같으면 다음으로 넘어갑니다.
smallest += 1
elif num > smallest: # num이 smallest보다 크면 최소 양의 정수를 찾았습니다.
return smallest
return smallest # 모든 요소가 배열에 있을 경우, 다음 양의 정수를 반환합니다.
A = [1, 2, 3]
print(solution(A)) |
ff7083eae4c8c31fbf3f80695592b1acc8f5e4fb | epan-1/uni-machine-learning-2018 | /Project_1/dataset.py | 2,519 | 3.671875 | 4 | ###
# Class that represents a dataset that has been stored as a .csv file
# Written by Edmond Pan (841389)
###
from collections import defaultdict
import numpy as np
class DataSet:
def __init__(self, filename):
"""
Reads in the csv file into an appropriate data structure
:param filename: Name of the .csv file
"""
# Variables to store metadata about the table structure
self.num_rows = 0
self.num_cols = 0
self.table = []
file = open('2018S1-proj1_data/' + filename, 'r')
for line in file.readlines():
# Split based on common to get the values
row = line.split(',')
self.num_cols = len(row)
# Add row to table and increment row count
self.table.append(row)
self.num_rows += 1
file.close()
def get_num_rows(self):
"""
Gets the number of rows in the table
:return: Integer referencing number of rows in the table
"""
return self.num_rows
def get_num_cols(self):
"""
Gets the number of cols in the table
:return: Integer referring to number of cols in table
"""
return self.num_cols
def get_table(self):
"""
Gets the stored table
:return: Returns a list of rows
"""
return self.table
def random_initial(self):
"""
Function that replaces the class labels with random (non-uniform)
class distributions. NOTE ONLY USE WHEN DOING UNSUPERVISED NB
:return: None
"""
# Default dict containing all possible classes
classes = defaultdict(float)
for row in self.table:
# Keep them all at 0 since they will b replaced with
# random fractional counts that sum to 1
classes[row[-1]] = 0
# Now remove the class labels and add the classes dictionaries while
# initialising the values to random fractional counts
for row in self.table:
# Add the random values to the dictionary
values = np.random.dirichlet(np.ones(len(classes)), size=1)
i = 0
for key, value in classes.items():
classes[key] = values[0][i]
i += 1
# Replace the old class label with the random class distribution.
# Make sure to return a copy of classes instead of passing the reference
row[-1] = classes.copy()
return |
18ee268683d8fc30ff0ff0c46426c79137d81c97 | avdemidov/rosalind | /Partial Permutations/pper.py | 984 | 4.03125 | 4 | '''
Problem
A partial permutation is an ordering of only k objects taken from a collection containing n objects (i.e., k<=n).
For example, one partial permutation of three of the first eight positive integers is given by (5,7,2).
The statistic P(n,k) counts the total number of partial permutations of k objects that can be formed from a collection of n objects.
Note that P(n,n) is just the number of permutations of n objects, which we found to be equal to n!=n(n-1)(n-2)...(3)(2) in "Enumerating Gene Orders".
Given: Positive integers n and k such that 100>=n>0 and 10>=k>0.
Return: The total number of partial permutations P(n,k), modulo 1,000,000.
Sample Dataset
21 7
Sample Output
51200
'''
import math
def binomial_coefficient(n, k):
res = 1
for i in xrange(1, k+1):
res = res * (n-i+1) / i
return res
f = open('in.txt', 'r')
n, k = [int(x) for x in f.readline().strip().split(' ')]
print binomial_coefficient(n,k) * math.factorial(k) % 1000000
|
086442a7e13c4c1cc4cae17bd7053d2779f97a27 | sty515253545/pig-papa | /ApiAuto/code.py | 2,538 | 3.90625 | 4 | # coding=utf-8
# def likes(names):
# n = len(names)
# return {
# 0: 'no one likes this',
# 1: '{} likes this',
# 2: '{} and {} like this',
# 3: '{}, {} and {} like this',
# 4: '{}, {} and {others} others like this'
# }[min(4, n)].format(*names[:3], others=n-2)
#
#
# print(likes(['a', 'b', 'c', 'd']))
# def likes(names):
# length = len(names)
# others = length -2
# d = {
# 0: "no one likes this",
# 1: f"{names[0]} likes this",
# 2: f"{names[0]} and {names[1]} like this",
# 3: f"{names[0]}, {names[1]} and {names[2]} like this",
# 4: f"{names[0]}, {names[1]} and {others} others like this"
# }
# print(d[min(4, length)])
#
# likes(['a', 'a', 'a', 'a', 'a'])
# def printer_error(s):
# # your code
# length = len(s)
# error = 0
# for i in s:
# if i > 'm':
# error += 1
# result = f"{error}/{length}"
# print(result)
#
#
# printer_error("123")
# def find_missing_letter(chars):
# length = len(chars)
# for i in range(length):
# if ord(chars[i]) != ord(chars[i+1]) - 1:
# return chr(ord(chars[i])+1)
#
#
# print(find_missing_letter(['a','c']))
#
#
# def find_missing_letter(c):
# return next(chr(ord(c[i])+1) for i in range(len(c)-1) if ord(c[i])+1 != ord(c[i+1]))
#
#
# print(find_missing_letter(['a', 'b', 'd']))
# print(chr(99))
# print(ord('A'))
# def scramble(s1, s2):
# # your code here
# for i in s2:
# if i in s1:
# s1 = s1.replace(i, '', 1)
# print(s1)
# else:
# return False
# return True
#
#
# print(scramble('scriptjava', 'javascript'))
# def filter_list(l):
# result = []
# for i in l:
# if type(i) == int:
# if i >= 0:
# result.append(i)
# return result
#
#
# print(filter_list([1, 33, 'a', 'b', 66]))
def tickets(l):
money = []
for i in l:
if i == 25:
money.append(i)
elif i == 50:
if 25 not in money:
return 'NO'
elif i == 100:
if 25 and 50 not in money:
if l.count(25) < 3:
return 'NO'
return 'YES'
print(tickets([25, 25, 50]))
print(tickets([25, 100]))
print(tickets([25, 25, 50, 50, 100]))
# l = [25,25,25]
# print(l.count(25))
# if l.count(25) > 3:
# print(1) |
d0aaa3b720b08ebac8c6fffcfded42a0f0cbb898 | mag389/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 825 | 3.953125 | 4 | #!/usr/bin/python3
"""the island perimeter problem"""
def island_perimeter(grid):
"""finds the total perimeter of the island"""
perimeter = 0
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j] == 1:
if (i > 0 and grid[i - 1][j] == 0) or i == 0:
perimeter += 1
if (j > 0 and grid[i][j - 1] == 0) or j == 0:
perimeter += 1
if (i < len(grid) - 1 and grid[i + 1][j] == 0):
perimeter += 1
if i == len(grid) - 1:
perimeter += 1
if j < len(grid[i]) - 1 and grid[i][j + 1] == 0:
perimeter += 1
if j == len(grid[i]) - 1:
perimeter += 1
return perimeter
|
f92900e302c6dcf4e5490e444ccfcfdc2b54eea9 | amcharaniya/python_summer2021 | /HW/HW5_AmaanCharaniya | 2,411 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 29 16:21:12 2021
@author: amaancharaniya
"""
class Node:
def __init__(self, _value=None, _next=None):
self.value = _value
self.next = _next
def __str__(self):
return str(self.value)
class LinkedList():
def __init__(self, first = None):
self.first = first # First node
#Checks if there is a definition of the first value and if not it sets the input as first.
def addNode(self,new_value):
newNode = Node(new_value)
if self.first is None:
self.first = newNode
return
last = self.first
while (last.next):
last = last.next
last.next = newNode
def removeNode(self, node_to_remove):
firstvalue = self.first
if (firstvalue is not None):
if(firstvalue.value == node_to_remove):
self.first = firstvalue.next
firstvalue = None
return
while (firstvalue is not None):
if firstvalue.value == node_to_remove:
break
previous = firstvalue
firstvalue = firstvalue.next
if(firstvalue == None):
return
previous.next = firstvalue.next
firstvalue = None
#I tried to debug this. Code still breaks. Workaround is to include the location of the "after_node" in the command line when enterting.
def AddNodeAfter(self, after_node, new_value):
if after_node is None:
print("No Node here")
return
newNode = Node(new_value)
newNode.next = after_node.next
after_node.next = newNode
def reverse(self):
prev = None
current = self.first
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.first = prev
#Nifty function that prins the next value in the linked list to print the full list.
def listprint(self):
printvalue = self.first
while (printvalue):
print(printvalue.value),
printvalue = printvalue.next
list = LinkedList()
list.addNode(8)
list.addNode(3)
list.addNode(5)
list.AddNodeAfter(list.first.next,5)
list.removeNode(10)
list.removeNode(5)
list.listprint()
list.reverse()
|
0b5fd5b672b206c0c1748d5c207c122c6de383f2 | michellima28/python | /python_fundamentos_dsa/Cap03/Lab02/calculadora_michel_lima_2.py | 1,013 | 4.21875 | 4 | # mensagem inicial
print('\n ------------- Calculadora Python -------------\n')
# funcoes aritmericas
def soma(x, y):
return x + y
def subtracao(x, y):
return x - y
def multiplicacao(x, y):
return x * y
def divisao(x, y):
return x / y
# variaveis de input
print('1 - soma')
print('2 - subtração')
print('3 - multiplicação')
print('4 - divisão\n')
num1 = int(input('Digite o primeiro valor: '))
num2 = int(input('Digite o segundo valor: '))
operacao = int(input('\nEscolha uma das operações (1 a 4): '))
# realizando as operacoes
if operacao == 1:
print('\n{} + {} = ' .format(num1, num2), soma(num1,num2), '\n')
elif operacao == 2:
print('\n{} - {} = ' .format(num1, num2), subtracao(num1,num2), '\n')
elif operacao == 3:
print('\n{} * {} = ' .format(num1, num2), multiplicacao(num1,num2), '\n')
elif operacao == 4:
print('\n{} / {} = ' .format(num1, num2), divisao(num1,num2), '\n')
else:
print('\nDados inválidos! Por favor, digite um número de 1 a 4.\n')
|
0e4faa4ed617854517dce7047f6a9a8950e7ed93 | gabo32/UniversidadPython | /Leccion02/main.py | 3,630 | 4.1875 | 4 | operandoA = 3
operandoB = 2
# suma
suma = operandoA + operandoB
# interpolacion
print(f'Resultado suma: {suma}')
# Resta
resta = operandoA - operandoB
print(f'Resultado resta: {resta}')
# multiplicacion
multiplicacion = operandoA * operandoB
print(f'Resultado multiplicacion: {multiplicacion}')
# division
division = operandoA / operandoB
print(f'Resultado division: {division}')
division = operandoA // operandoB
print(f'DIvision parte entera {division}')
# modulo
modulo = operandoA % operandoB
print(f'Resultado del residuo: {modulo}')
# exponente
exponente = operandoA ** operandoB
print(f'Resultrado exponente: {exponente}')
# operadores de asignacion
miVariable = 10
print(miVariable)
# operadores de reasignacion
miVariable += 1
print(miVariable)
miVariable -= 2
print(miVariable)
miVariable *= 3
print(miVariable)
miVariable /= 2
print(miVariable)
# operador de comparacion
a = 4
b = 2
# igual
resultado = a == b
print(f'Resultado ==: {resultado}')
resultado = a != b
print(f'Resultado !=: {resultado}')
resultado = a > b
print(f'Resultado >: {resultado}')
resultado = a < b
print(f'Resultado <: {resultado}')
resultado = a <= b
print(f'Resultado <=: {resultado}')
resultado = a >= b
print(f'Resultado >=: {resultado}')
print("**************************************")
a = int(input('Escribe un valor numerico:'))
if a % 2 == 0:
print(f'{a} es un numero par')
else:
print(f'{a} No es un numero par')
print("*******************************************")
edadAdulto = 18
edadPersona = int(input("Proporciona tu edad: "))
if edadPersona >= edadAdulto:
print(f'La persona es un adulto')
else:
print(f'La persona es menor de edad')
print("*******************************************")
# operadores logicos
a = True
b = False
resultado = a and b
print(resultado)
resultado = a or b
print(resultado)
a = not a
print(a)
print("*******************************************")
valor = int(input('Proporciona un numero: '))
valorMinimo = 0
valorMaximo = 5
dentroDelRango = valor >= valorMinimo and valor <= valorMaximo
if dentroDelRango:
print(f'{valor} Esta dentro del rango')
else:
print(f'{valor} No esta dentro del rago')
print("*******************************************")
vacaciones = False
diaDeDescanso = False
if vacaciones or diaDeDescanso:
print('Puede asistir al juego')
else:
print('Tiene deberes que hacer')
if not (vacaciones or diaDeDescanso):
print('No puede ver el partido')
else:
print('Si puede ver el partido')
print("*******************************************")
edad = int(input('INtroduce tu edad'))
veites = edad >= 20 and edad < 30
print(veites)
treintas = edad >= 30 and edad < 40
print(treintas)
if veites or treintas:
# print('Estas en los veintes y treintas')
if veites:
print('Dentro de los 20\'s')
elif treintas:
print('Dentro de los 30\'s')
else:
print('Fuera de rango')
else:
print('No estas en los veintes ni treintas')
print("*******************************************")
print("Proporcione los siguientes datos del libro: ")
nombre = input('Proporciona el nombre del libro: ')
id = int(input('Proporciona el ID del libro: '))
precio = float(input('Proporciona el valor del libro: '))
envioGratuito = input('Indica si es envio gratuito: (True/False): ')
if envioGratuito == 'True':
envioGratuito = True
elif envioGratuito == 'False':
envioGratuito = False
else:
envioGratuito = 'Valor incorrecto, debe escribir True o False'
# imprimir en varias lineas con formato
print(f'''
Nombre: {nombre}
Id: {id}
Precio: {precio}
Envio Gratuito?: {envioGratuito}
''')
|
ba624927c3a34428624f33f43187307fa98b63fa | karanbr/python-projects | /tkinter_args_kwargs/main/kwargs.py | 505 | 3.625 | 4 | # keyword arguments
def calculate(n, **kwargs):
print(kwargs)
# for key, value in kwargs.items():
# print(key)
# print(value)
n += kwargs["add"]
n *= kwargs["multiply"]
print(n)
calculate(2, add=5, multiply=7)
class Car:
def __init__(self, **kwargs):
self.make = kwargs["make"] # mandatory with []
self.model = kwargs.get("model") # if this isn't specified it will return None
car = Car(make="Audi", model="A4")
print(car.model, car.make)
|
7ac669504ee3762a5128a90619ee951015c69fb3 | incememed0/python-notes | /30-ic_ice_fonksiyonlar.py | 3,909 | 3.84375 | 4 | # author: Ercan Atar
# linkedin.com/in/ercanatar/
#######################################################
###
#def greeting(name):
# print("hello",name)
#print(greeting("memed"))
#print(greeting)
#sayHello=greeting
#print(sayHello)
#print(greeting) # 2 adresde aynı
#print(greeting("memed"))
#print(sayHello("ali"))
#del sayHello
#print(sayHello)
#print(greeting) #### burada dikkat etmen gereken şey; bir tanımlama yapıldığında bu Adreste yer edinir, silme işlemi yapsan bile bu adres silinmez
####################
# encapsulation
#def outer(num1):
# print("outer")
# def inner(sayi1):
# print("inner")
# return sayi1+1
# num2=inner(num1)
# print(num1,num2)
#outer(10)
# inner(10) iç içe fonksiyonlarda içerdeki fonksiyonu kullanamayız
###############
def factorial(number):
if not isinstance(number,int):
raise TypeError("gönderilen bilgi integer olmalı")
if not number >=0:
raise ValueError("negatif sayı veya sıfır olamaz")
def inner_factorial(number):
if number<=1:
return 1
return number*inner_factorial(number-1)
return inner_factorial(number)
try:
print(factorial(-9))
except Exception as hata:
print(hata)
##############################
# burada öğrenmen gereken husus içerdeki fonksiyona erişebiliyor olmak
def us_alma(number):
def inner(power):
return number**power
return inner
two=us_alma(2)
three=us_alma(3)
print(two(3)) # 2^3 = 8
print(three(4)) # 3^4 = 81
####################
def yetki(page):
def iceri(role):
if role=="admin":
return f"{role} rolü {page} sayfasına ulaşabilir."
else:
return f"{role} rolü {page} sayfasına ULAŞAMAZ."
return iceri
user1=yetki("product edit") # page kısmı
print(user1("admin"))
####################
def islem(islemadi):
def toplam(*args):
toplam=0
for i in args:
toplam+=i
return toplam
def carpma(*args):
carpim=1
for i in args:
carpim*=i
return carpim
if islemadi=="toplama":
return toplam
else:
return carpma
toplama=islem("toplama")
print(toplama(1,2,3,4))
####################
def toplama(a,b):
return a+b
def cikarma(a,b):
return a-b
def carpma(a,b):
return a*b
def bolme(a,b):
return a/b
def issslem(f1,f2,f3,f4,islemadi):
if islemadi=="toplama":
print(f1(2,4))
elif islemadi=="cikarma":
print(f2(5,3))
elif islemadi=="carpma":
print(f3(3,4))
elif islemadi=="bolme":
print(f4(12,2))
else:
print("hataaaaaa")
issslem(toplama,cikarma,carpma,bolme,"toplama")
##################################
print("------------------")
##################################
# decorators fonksiyonları: bir fonksiyona özellik eklemek istediğimizde kullanırız
# bir tane decorator fonksiyonu oluşturduktan sonra diğer fonksiyonları rahatlıkla eşleştirebiliyoruz.
def my_decorator(fuck):
def wrapper(name):
print("fonksiyondan önceki işlemler")
fuck(name)
print("fonksiyondan sonraki işlemler")
return wrapper
@my_decorator # fonksiyondan önce olması önemli
def hello(name): # bu fonksiyon diğer fonksiyonlara özellik eklememizi sağlıyor
print("hello",name)
# hello=my_decorator(hello)
hello("memed")
##################################
print("------------------")
##################################
# decorator:
import math
import time
def zaman_hesapla(fuck):
def iceri(*args,**kwargs):
start = time.time()
time.sleep(1)
fuck(*args, **kwargs)
finish = time.time()
print(f"fonksiyon {str(finish - start)} saniye sürdü.")
return iceri
@zaman_hesapla
def ussu_bulma(a,b):
print(math.pow(a,b))
@zaman_hesapla
def faktoriyel(num):
print(math.factorial(num))
ussu_bulma(2,3)
faktoriyel(4) |
8aa3bbd9de2362b23ac49729e32ae886fca6ca75 | girishongit/pythonML | /sigmoidDemo.py | 230 | 3.546875 | 4 | import numpy as np
input = np.linspace(-10, 10, 100)
def sigmoid(x):
return 1/(1+np.exp(-x))
from matplotlib import pyplot as plt
import pylab
plt.plot(input, sigmoid(input), "r")
plt.show()
#print (sigmoid(input))
|
3590acb6e7d4904eabe60763d4e8f60a8db408e8 | anshgandhi4/breadboard_sim | /src/Python/hole.py | 3,017 | 3.953125 | 4 | from tkinter import *
class Hole(Canvas):
def __init__(self, master, coord):
""" Hole(master, coord): creates a new Hole object with given coordinates
Hole object comes with click listener enabled
:param master: (Simulator)
:param coord: (Tuple), coordinates given by Breadboard class """
Canvas.__init__(self, master, height = 20, width = 20, bg = "khaki1", highlightthickness = 0, relief = "sunken", bd = 2)
self.coord = coord
self.bind("<Button>", self.click)
self.group = None
self.color = "khaki1"
self.text = self.create_text(11, 11, text = "", font = ("Arial", 12))
self.root = None
self.powersupply = None
def label(self, label):
""" Hole.label(label): disables the hole and turns it into a basic label
changes the text to red if it is "+" and blue if it is "-"
:param label: (String), text to put on Hole """
self["relief"] = "flat"
self.unbind("<Button>")
self.itemconfig(self.text, text = label)
if label[:-1] == "+":
self.itemconfig(self.text, fill = "red")
elif label[:-1] == "-":
self.itemconfig(self.text, fill = "blue")
def click(self, event):
""" Hole.click(): updates Breadboard.display text with current coordinates
highlights all Holes accordingly """
if self["bg"] == "ivory4":
for element in self.master.elements:
if self.master.elements[element]["bg"] != self.master.elements[element].color:
self.master.elements[element]["bg"] = self.master.elements[element].color
elif self.coord in self.master.supplies.keys():
self.master.powersupply_edit(self.coord)
elif self.coord == (2, 1) and (1, 1) in self.master.supplies.keys():
self.master.powersupply_edit(self.coord)
elif self.coord == (16, 1) and (17, 1) in self.master.supplies.keys():
self.master.powersupply_edit(self.coord)
elif self.coord in self.master.wirestarts.keys() or self.coord in self.master.wireends.keys():
self.master.wire_edit(self.coord)
elif self.coord in self.master.resistorstarts.keys() or self.coord in self.master.resistorends.keys():
self.master.resistor_edit(self.coord)
elif self.coord in self.master.ledstarts.keys() or self.coord in self.master.ledends.keys():
self.master.led_edit(self.coord)
elif self.coord in self.master.switchstarts.keys() or self.coord in self.master.switchends.keys():
self.master.switch_edit(self.coord)
else:
for element in self.master.elements:
if self.master.elements[element]["bg"] != self.master.elements[element].color:
self.master.elements[element]["bg"] = self.master.elements[element].color
for element in self.group.holes:
element["bg"] = "ivory3"
self["bg"] = "ivory4" |
79ba6e211e66b85dd46bcd1ab91afcc6e0035833 | StephenClarkApps/AdventOfCode2019 | /DayFour/DayFour.py | 1,105 | 3.5 | 4 | # Day Four
lines = list(open('input.txt', 'r'))
input_range = lines[0].split('-')
lower_bound = int(input_range[0])
upper_bound = int(input_range[1])
def hasTwoTheSameInARow(a):
last_char = ''
for char in str(a):
if char == last_char:
return True
last_char = char
return False
def neverDecreases(b):
last_char = -1
for char in str(b):
if int(char) < int(last_char):
return False
last_char = char
return True
def hasExactlyTwoTheSameInARow(c):
string_number = str(c)
set_of_nums = set(string_number)
for x in set_of_nums:
if string_number.count(x) == 2:
return True
return False
# PART ONE
counter = 0
for password in range(lower_bound, upper_bound + 1):
if neverDecreases(password):
if hasTwoTheSameInARow(password):
counter += 1
print (counter)
# PART TWO
counter_two = 0
for password in range(lower_bound, upper_bound + 1):
if neverDecreases(password):
if hasExactlyTwoTheSameInARow(password):
counter_two += 1
print (counter_two)
|
afdb55a051fbef193c12df9c7e18fb896afde0dc | ASDMGroup/skimap | /Classes/Geomlists/Point2D.py | 3,067 | 4.1875 | 4 | #!/usr/bin/env python3
"""Point2D"""
#Setup plotting and load useful modules
import matplotlib.pyplot as plt
import matplotlib.pylab
import copy
import numpy as np
#Define 2D point class
class Point2D(object):
"""A two dimensional point.
Parameters
----------
x : float
the x coordinate
y : float
the y coordinate
"""
#Method to create a Point2D object
def __init__(self,x,y):
"""A Point2D object requires an x cooordinate and a y coordinate.
Parameters
----------
x : float
the x coordinate
y : float
the y coordinate.
Examples
--------
>>>pnt = Point2D(1,2)
"""
#the Point2D's x property should correspond to the x argument in the __init__ function
self.x = x
#the Point2D's y property should correspond to the y argument in the __init__ function
self.y = y
#define what a print statement returns
def __repr__(self):
"""The __repr__ method defines what is returned by 'print([Point2D])'.
Examples
--------
>>>print(Point2D(1,2)
1, 2
"""
#define how Point2D object are printed
print (str(self.x)+', '+str(self.y))
def plot(self, col):
"""The plot method calls matplotlib.pyplot.plot using the coordinates contained in the x and y attributes of your Point2D.
'colour' defines what colour they are plotted.
Parameters
----------
colour: str
the colour that the Point2D should be plotted in.
Examples
--------
>>>point.plot("red")
"""
#plot the Point2D object using the x and y value of the object
plt.plot(self.x,self.y,'o', color=str(col))
def translate(self,dx,dy):
"""Translate your point by dx and dy where dx is the change in the x coordinate and dy is the change in the y coordinate.
Parameters
----------
dx : float
the change in the x coordinate
dy : float
the change in the y coordinate.
Examples
--------
>>>point = Point2D(1,1)
>>>point.translate(1,-1)
>>>print (point)
2, 0
"""
#redefine the x and y values of your Point2D as (x + dx) and (y + dy)
self.x = self.x + dx
self.y = self.y + dy
def dilate(self,dilation,Sx,Sy):
"""Dilate your point from the centre (Sx,Sy), by a factor defined by the value of the dilation argument
Parameters
----------
dilation : float
the factor of dilation
dx : float
the x coordinate of the sourse of dilation
dy : float
the y coordinate of the sourse of dilation
Examples
--------
>>>point.dilate(2,0,0)
"""
#redefine the x and y values of your Point2D using the dilation equation
self.x = Sx + ((self.x-Sx) * dilation)
self.y = Sx + ((self.y-Sy) * dilation)
|
7b3dd9684c1abf6d577661b5baca2f4d450d1fcb | Airmagic/Lab-5 | /coinFlip.py | 2,938 | 4.21875 | 4 | # some of the code i got from stackoverflow
# importing random to get a random number
import random
# main program so I can call it
def main():
# printing what the program is and what to do
print("Guessing the number of times heads will land.\nPut in the number of flips and then the number of times head will show.")
# creating the variables to hold a count for them
heads, tails, timesflipped = 0, 0, 0
# getting the number of flips from user
numberFlipped = numberFlippedInput()
# getting the number of guess for heads
guessHeads = guessHeadsInput(numberFlipped)
# a while loop to get the number of random 0 or 1s
while timesflipped < numberFlipped:
# making a variable that gets a number like flipping the coin
coin_flips = random.randrange( 2 )
# if statement to add numbers to that variables heads or tales
if coin_flips == 0:
heads += 1
else:
tails += 1
# adding 1 to the variable timesFlipped
timesflipped += 1
# if statement if you guessed correct or not
if heads == guessHeads:
print("You guess correct!!!")
else:
print("Your guess was wrong")
# printing the results for the user
print("In " + str(numberFlipped) + " flips, " + str(heads) + " were heads and " + str(tails) + " were tails.")
print("Your guess was " + str(guessHeads) + " times that heads would appear")
# added a replay feature
replay()
def numberFlippedInput():
while True:
try:
# getting user input
numberFlipped = int(input('How many time do you want to flip? '))
# returning the number inputed
return numberFlipped
# exception if a number isn't inputed
except ValueError:
# print information for the user
print("Must be a number")
def guessHeadsInput(number):
while True:
try:
# getting input from the user
guessHeads = int(input("How many times do you think it will land heads? "))
# checking the range so that the user puts in a plasible number
if guessHeads < 0 or guessHeads > number:
# printing info for the user
print("Please enter a number from 0 to {}".format(number,))
else:
# returning that variable
return guessHeads
except ValueError:
print("Must be a number")
def replay():
# asking user if they want to run the program again
replay = input('Would you like to play again? Y or N ')
# if statement to open the coinFlip again if these are entered
if replay in ('y', 'Y', 'Yes', 'YES'):
# calling the main again
main()
else:
# closing the program
exit()
# calling the program at the end of the python so that it checks the program first
if __name__ == '__main__':
main()
|
b4bdd0988d5705c006213daae787918aed2b1f77 | Zaidane-E/Labs | /Devoir1_Python/Devoir1Q4.py | 743 | 3.796875 | 4 | #Auteur: Zaidane El Haouari
#Numéro d'étudiant: 300130581
print("Auteur: Zaidane El Haouari")
print("Numéro d'étudiant: 300130581")
bureau=75.9
chaise=50.9
imprimante=32.5
scanneur=28.0
article=str(input("Entrez l'article souhaité: "))
quantite=int(input("Entrez la quantité voulue: "))
def calculPrix(article, quantite):
if str.lower(article)=="bureau":
article=bureau
elif str.lower(article)=="chaise":
article=float(chaise)
elif str.lower(article)=="imprimante":
article=float(imprimante)
elif str.lower(article)=="scanneur":
article=float(scanneur)
else:
print("Veuillez entrer un article valide.")
prix=float(article*quantite)
print(prix)
return
calculPrix(article, quantite)
|
4b8cbcedc578bad0791514b1f37ae54e17af4f48 | kaustubhvkhairnar/PythonPrograms | /Pattern Printing/Assignment8.py | 446 | 3.984375 | 4 | #8. Write a program which accept one number and display below pattern.
#Input : 5
#Output : 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
def fun(number):
for i in range(1,number+1):
for n in range(1,number+1):
if (i>=n):
print(n,end=' ')
print()
if __name__ == "__main__":
fun(number=int(input("Enter number : ")))
|
d2aa1f4359eef0af7553fd951e578d7c83e63e98 | sgneves/courses | /Data_scientist_in_python/02_Python_for_data_science_Intermediate/02_Python_data_analysis_basics.py | 3,792 | 3.71875 | 4 | #**************************************************************************************************#
# #
# 02_Python_data_analysis_basics #
# #
# Authors: S.G.M. Neves #
# #
#**************************************************************************************************#
# 1. Reading our MoMA Data Set
from csv import reader
# Read the 'artworks_clean.csv' file
opened_file = open('artworks_clean.csv', encoding='utf-8')
read_file = reader(opened_file)
moma = list(read_file)
moma = moma[1:]
def convert_date(date):
if date != "": date = int(date)
return date
# Convert the birthdate values
for row in moma:
row[3] = convert_date(row[3])
row[4] = convert_date(row[4])
row[6] = convert_date(row[6])
#--------------------------------------------------------------------------------------------------#
# 2. Calculating Artist Ages
ages = []
for row in moma:
birth = row[3]
date = row[6]
if type(birth) == int:
age = date - birth
else:
age = 0
ages.append(age)
final_ages = [age if age > 20 else 'Unknown' for age in ages]
#--------------------------------------------------------------------------------------------------#
# 3. Converting Ages to Decades
decades = []
for age in final_ages:
if age != 'Unknown':
age = str(age)[:-1] + '0s'
decades.append(age)
#--------------------------------------------------------------------------------------------------#
# 4. Summarizing the Decade Data
decade_frequency = {}
for decade in decades:
if decade in decade_frequency:
decade_frequency[decade] += 1
else:
decade_frequency[decade] = 1
#--------------------------------------------------------------------------------------------------#
# 5. Inserting Variables Into Strings
artist = "Pablo Picasso"
birth_year = 1881
template = '{}\'s birth year is {}'
output = template.format(artist, birth_year)
print(output)
#--------------------------------------------------------------------------------------------------#
# 6. Creating an Artist Frequency Table
artist_freq = {}
for artwork in moma:
artist = artwork[1]
if artist in artist_freq:
artist_freq[artist] += 1
else:
artist_freq[artist] = 1
#--------------------------------------------------------------------------------------------------#
# 7. Creating an Artist Summary Function
def artist_summary(artist):
print('There are {} artworks by {} in the data set'.format(artist_freq[artist], artist))
artist_summary('Henri Matisse')
#--------------------------------------------------------------------------------------------------#
# 8. Formatting Numbers Inside Strings
pop_millions = [
["China", 1379.302771],
["India", 1281.935991],
["USA", 326.625791],
["Indonesia", 260.580739],
["Brazil", 207.353391],
]
for pop in pop_millions:
print('The population of {} is {:,.2f} million'.format(pop[0], pop[1]))
#--------------------------------------------------------------------------------------------------#
# 9. Challenge: Summarizing Artwork Gender Data
gender_freq = {}
for artwork in moma:
gender = artwork[5]
if gender in gender_freq:
gender_freq[gender] += 1
else:
gender_freq[gender] = 1
for k, v in gender_freq.items():
print('There are {:,} artworks by {} artists'.format(v, k))
|
ca7a2f46c11acb00c7cf0e08a88084e7c58615eb | ugaliguy/Python-at-Rice | /Principles-of-Computing/project-1-merge-2048.py | 1,116 | 3.71875 | 4 | """
Merge function for 2048 game.
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = []
merge_line = []
merged = False
indx2 = 0
for indx1 in range(len(line)):
new_line.append(0)
for indx1 in range(len(line)):
if (line[indx1] != 0):
new_line[indx2] = line[indx1]
indx2 += 1
for indx1 in range(len(line) - 1):
if(new_line[indx1] != 0):
if ((new_line[indx1] == new_line[indx1+1]) and (merged == False)):
merge_line.append(2*new_line[indx1])
merged = True
elif ((new_line[indx1] != new_line[indx1+1]) and (merged == False)):
merge_line.append(new_line[indx1])
elif (merged == True):
merged = False
else:
merged = True
if ((new_line[-1] != 0) and (merged == False)):
merge_line.append(new_line[-1])
while (len(merge_line) < len(line)):
merge_line.append(0)
return merge_line
|
aded423a12d062e75d310f0d6d3534352bb9181b | basantech89/code_monk | /python/MITx/6.00.1x_Introduction_to_ComputerSCience_and_Programming_using_Python/classesBasics.py | 399 | 3.78125 | 4 | class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '<'+str(self.x)+', '+str(self.y)+'>'
def distance(self, other):
return self.x+other.x-self.y-other.y
def yo(self):
return self.__str__().count('3')
c = Coordinate(3, 4)
other = Coordinate(2,1)
print c.yo() |
e7e0fe4356761323a1dafb876fa57186514c0ccf | Tedigom/Alghorithm_practice | /dfs_practice.py | 551 | 3.6875 | 4 | graph = {'A' : set(['B', 'C', 'E']),
'B' : set(['A', 'D', 'F']),
'C' : set(['A', 'G']),
'D' : set(['B']),
'E': set(['A', 'F']),
'F': set(['B', 'E']),
'G': set(['G'])
}
def dfs(graph, root):
visited = [] #각 꼭지점이 방문되었는지를 기록
stack = [root, ]
while stack: #stack이 비게 되면 탐색 끝
vertex = stack.pop() # 방문되어지고 있는 꼭지점
if vertex not in visited:
visited.add(vertex)
stack.extend(graph[vertex] - visited)
return visited
print(dfs(graph, 'A')) |
a828abdc0e472407e8cb87aaa1d9f7b4bcefba35 | arentaylor/Week3-Py-Me-Up-Charlie | /PyBank/main.py | 2,959 | 4 | 4 | #import OS and CSV libraries
import os
import csv
#create variables for calculations
count_months = 0
total_revenue = 0
total_revenue_change = 0
# create file path and save as file
budgetfile = os.path.join(".", "budget_data.csv")
#open file and create file handle
with open(budgetfile, 'r') as csvfile:
csvread = csv.reader(csvfile)
#skip header row
line = next(csvread,None)
#grab data from first line
line = next(csvread,None)
max_month = line[0]
min_month = line[0]
revenue = float(line[1])
min_revenue = revenue
max_revenue = revenue
previous_revenue = revenue
count_months = 1
total_revenue = float(line[1])
total_revenue_change = 0
#go through data to process revenue
for line in csvread:
#increase counter for number of months in dataset
count_months = count_months + 1
revenue = float(line[1])
#add to sum of revenue for data set
total_revenue = round(total_revenue + revenue)
#find change in revenue between this month and last month
revenue_change = revenue - previous_revenue
#add change in revenue to net change in revenue for data set
total_revenue_change = total_revenue_change + revenue_change
#determine if change in revenue is a max or min for data set thus far
if revenue_change > max_revenue:
max_month = line[0]
max_revenue = revenue_change
if revenue_change < min_revenue:
min_month = line[0]
min_revenue = revenue_change
#set previous revenue to revenue
previous_revenue = revenue
#averages
average_revenue = total_revenue/count_months
average_revenue_change = round(total_revenue_change/(count_months-1),2)
#print to terminal
print(f"Financial Analysis:")
print("-------------------------------------------------------")
print(f"Total Months: {count_months}")
print(f"Net Total Profit or Loss: ${total_revenue}")
print(f"Average Change: ${average_revenue_change}")
print(f"Greatest Increase in Profits: {max_month} ${round(max_revenue)}")
print(f"Greatest Decrease in Profits: {min_month} ${round(min_revenue)}")
print("")
#print analysis to file
with open('PyBank.txt', 'w') as text_file:
print(f"Financial Analysis:", file=text_file)
print("-------------------------------------------------------", file=text_file)
print(f"Total Months: {count_months}", file=text_file)
print(f"Net Total Profit or Loss: ${total_revenue}", file=text_file)
print(f"Average Change: ${average_revenue_change}", file=text_file)
print(f"Greatest Increase in Profits: {max_month} ${round(max_revenue)}", file=text_file)
print(f"Greatest Decrease in Profits: {min_month} ${round(min_revenue)}", file=text_file) |
41dcfbd9c5e58850621e13eff6a58dbbde0a908a | Macheing/log_scripts | /user_validations.py | 400 | 3.90625 | 4 | #!/usr/bin/ python3
def validate_user(username):
minlength = 3 # user name should at least be 3 characters long.
assert type(username) == str, 'User name must be of type string not a integer or a list!'
if len(username) < minlength:
return False # minimum length must be at least 3 characters long.
elif not username.isalnum():
return False
return True |
11a29b3ff03d45bf34af00f767af1a4f3dfe82cb | tuckershannon/pythonSpiralArt | /spiral.py | 3,221 | 3.796875 | 4 | """ Module spiral.py
This python program converts images into an Archimedes spiral type art made by varying
the width of spiral as it travels away from the center
Author: Tucker Shannon
"""
import numpy
from math import cos, sin, pi
from PIL import Image, ImageDraw, ImageSequence
from images2gif import writeGif
import cv2
def smooth_photo(img):
smooth_img = numpy.array(img.convert(mode="RGB"));
smooth_img = cv2.blur(smooth_img,(3,3))
cv2.imwrite("result.png",smooth_img)
def add_photo(img,imagelist):
smooth_img = numpy.array(img.convert(mode="RGB"));
smooth_img = cv2.blur(smooth_img,(3,3))
imagelist.append(smooth_img)
def plot_spiral(r,img,parray,loops=8, makeGif=False,background=0):
theta = 0
imagelist = Image.fromarray(img.astype('uint8'))
t = 0
maxInt = numpy.amax(parray)
init_radius = r
(x_limit,y_limit) = parray.shape
count = 0
while theta<2*pi*loops:
if count == 720:
count = 0
if makeGif:
add_photo(img,imagelist)
theta += float(1)/(2*r)
count = count + 1
for i in xrange(int(-t),int(t)+1):
r = (init_radius)*theta + i
x = x_limit/2 + int(r*cos(theta))
y = y_limit/2 + int(r*sin(theta))
if x >0 and x < x_limit and y > 0 and y<y_limit:
if background == 1:
img[x][y] = [0,0,0]
new_thickness=maxInt-int(parray[x,y])
else:
img[x][y] = [255,255,255]
new_thickness=(parray[x,y])
if (new_thickness>t):
t = t + .2;
if (new_thickness<t):
t = t - .2
print count
if makeGif:
writeGif("result.gif",imagelist,duration=0.02,dither=0)
def get_photo_array(width,thickness,photoName):
image = Image.open(photoName)
ratio = float(image.size[1])/image.size[0]
sizex = width
sizey = int(round(ratio * sizex))
pic = image.resize((sizex,sizey))
r, g, b = pic.split()
im = numpy.array(g)
thickness = thickness*3
im = im/(256/(thickness))
im = numpy.around(im, decimals=0, out=None)
photoarray = numpy.zeros([sizex,sizey])
for num in range(0,numpy.size(im,1)):
for num2 in range(0,numpy.size(im,0)):
photoarray[num][num2] = int(im[num2,num])
return photoarray
if __name__== '__main__':
photoName = "tree.jpg" #name of photo to convert
outputWidth = 2000 #how wide the output will be
thickness = 3 #max thickness of spiral line
background = 0; #0 for black 1 for white
photoarray = get_photo_array(outputWidth,thickness,photoName)
IMAGE_SIZE = photoarray.shape + (3,)
if background == 1:
img = numpy.full(IMAGE_SIZE,255)
else:
img = numpy.full(IMAGE_SIZE,0)
plot_spiral(thickness,img,photoarray,35,False,background)
img = numpy.swapaxes(img,0,1)
img = Image.fromarray(img.astype('uint8'))
img.save('output.png')
|
249269f1309f2e577a8d3c155ab1785cfb1e4b46 | jfoody/BME547 | /blood_calculator.py | 1,548 | 3.765625 | 4 | def interface():
print('Blood calculator')
keeprunning = True
while keeprunning:
print('make a choice')
print('1-HDL analysis')
print('2-LDL analysis')
print('9 - quit')
choice = int(input('Enter your choice: '))
if choice == 9:
keeprunning = False
elif choice == 1:
HDL_Driver()
elif choice == 2:
LDL_Driver()
print(choice)
return choice
# HDL level checker
def HDL_Driver():
HDL_value = hdl_input()
HDL_character = hdl_analysis(HDL_value)
hdl_output(HDL_value, HDL_character)
def hdl_input():
hdl_value = int(input('Enter HDL value: '))
return hdl_value
def hdl_analysis(HDL_value):
if HDL_value >= 60:
return 'Normal'
elif 40 <= HDL_value < 60:
return 'Borderline low'
else:
return 'Low'
def hdl_output(HDL_value, HDL_answer):
print('The HDL value of {} is considered {}'.format(HDL_value, HDL_answer))
return
# LDL level checker
def LDL_Driver():
LDL_value = ldl_input()
ldl_level = ldl_analysis(LDL_value)
print('The LDL value of {} is considered {}'.format(LDL_value, ldl_level))
def ldl_input():
ldl_level = int(input('Enter LDL level: '))
return ldl_level
def ldl_analysis(level):
if level < 130:
return 'Normal'
elif 130 <= level <= 159:
return 'borderline high'
elif 159 < level < 190:
return 'high'
else:
return 'very high'
if __name__ == '__main__':
interface()
|
792e4df81d9171c527e0c13f5fbbf286b29268ab | thisconnected/sztucznainteligencja | /test.py | 692 | 3.9375 | 4 | #!/usr/bin/env python
"""Hello World, fizbuzz and 99bottlesofbeer"""
print ("Hello World!\n")
for i in range(1,99):
if not i%15:
print("fizzbuzz")
elif not i%3:
print("fizz")
elif not i%5:
print("buzz")
else:
print(i)
print ("\n99 bottles of beer")
for i in range(0,99)[::-1]:
if i<1:
print("No more bottles of beer on the wall, no more bottles of beer.")
print("Go to the store and buy some more, 99 bottles of beer on the wall...")
else:
print(i, " bottles of beer on the wall, ", i ," bottles of beer")
i-= 1
print("Take one down, pass it around, " , i , " bottles of beer on the wall")
|
9c2b7c8f96616b1915e6a8daf9b71e6830e1c841 | SimonFans/LeetCode | /Sliding_Window/L1477_Find_Two_Non_Overlapping_Subarrays_Each_With_Target_Sum.py | 1,951 | 4.125 | 4 | You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.
class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
left = 0
n = len(arr)
_sum = 0
# final return result
ans = float('Inf')
# min_len array: min length of a valid subarray ends or before i
min_len_arr = ['Inf'] * n
# current minimum length
min_len = float('Inf')
for right in range(n):
_sum += arr[right]
while _sum > target:
_sum -= arr[left]
left += 1
if _sum == target:
cur_len = right - left + 1
# valid answer was found before then update the potential answer
if left > 0 and min_len_arr[left-1] != 'Inf':
ans = min(ans, min_len_arr[left-1] + cur_len)
# update the minimum valid length ends at current
min_len = min(min_len, cur_len)
min_len_arr[right] = min_len
return ans if ans < float('Inf') else -1
|
e7df56148fcbc66d75bf50880021eba33e0adbe4 | ahtornado/study-python | /day15/game.py | 639 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author :Alvin.Xie
# @Time :2018/7/15 11:14
# @File :game.py
import random
ch_list = ["石头","剪刀","布"]
win_list = [["石头","剪刀"],["剪刀","布"],["布","石头"]]
prompt = '''(0) 石头
(1) 剪刀
(2) 布
请选择(0/1/2): '''
computer = random.choice(ch_list)
ind = int(raw_input(prompt))
player = ch_list[ind]
print "Your choice: %s,Computer's choice: %s" %(player,computer)
if [player,computer] in win_list:
print "\033[31;1m你赢了!\033[0m"
elif player == computer:
print "\033[32;1m平局\033[0m"
else:
print "\033[31;1m你输了!\033[0m"
|
6ef756a9a42f2883b8a62b8612dfa58c5c469d2f | chalmerlowe/jarvis_II | /sample_puzzles/18_rising_numbers/your_code_here_rising_numbers.py | 706 | 3.640625 | 4 | # TITLE: rising numbers >> empty_rising_numbers.py
# AUTHOR: Chalmer Lowe
# DESCRIPTION:
# Identify and sum all the numbers in the file that have a
# "rising numerical pattern": meaning for each digit in the
# number, the digit is either equal to OR greater than the
# preceding digit (in this order: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
#
# For example:
# * 12345 > rising
# * 11112 > rising
# * 11229 > rising
# * 88899 > rising
# * 54321 > NOT rising
# * 88799 > NOT rising
# * 45456 > NOT rising
# Based on the numbers above, the sum would be:
# 12345 + 11112 + 11229 + 88899 = 123585
# ==============================================================
# Your code here:
|
14478c6a3c09b06575d49e76b4c0385d0744dcd9 | MaPing01/Python100 | /二分查找.py | 379 | 3.796875 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Ma Ping
def search(list,t):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
if list[mid] < t:
low = mid + 1
elif list[mid] > t:
high = mid -1
elif list[mid] == t:
return mid
return -1
a = [1,2,3,4,5]
print(search(a,6)) |
82a5d09fdbfa04ba730092057df3c97b7606761d | zhlthunder/python-study | /python 语法基础/d21_线程和协程/线程/4.使用线程锁解决数据混乱问题.py | 1,469 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
"""
两个线程同时工作,一个存钱,一个取钱
可能会导致数据异常
解决的思路:是加锁
"""
import threading
num=0
lock=threading.Lock()
def run(n):
global num
for i in range(1000000):
##加锁的方法1
lock.acquire()
##如果临界区的代码执行异常时,会导致无法解锁,会进入死锁状态,所以我们一般需要使用异常处理的方式,来确保一定会执行解锁的操作
#确保了这段代码只能由一个线程从头到尾的完整执行
#阻止了多线程的并发执行,包含锁的某段代码实际上只能以单线程的模式执行,所以执行效率降低
try:
num+=n
num-=n
finally:
lock.release()
##加锁的方法2,与上面代码功能相同; with lock 可以自动上锁与解锁;
# with lock:
# num+=n
# num-=n
if __name__ == '__main__':
t1=threading.Thread(target=run,args=(6,))
t2=threading.Thread(target=run,args=(9,))
t1.start()
t2.start()
t1.join()
t2.join()
print("num=",num)
##线程需要有锁,否则会导致数据混乱;
#由于可以存在多个锁,不同线程持有不同的锁,并试图获取其它的锁,这样可能会造成死锁,导致多个线程 挂起;这样的话,只能靠操作系统强制终止;
|
16bec3c5e6508a4cb4d2a05a6619eaf6fd28a23f | yumerov/codewars | /done/kyu-6/goldbachs-conjecture.py | 875 | 3.578125 | 4 | # https://www.codewars.com/kata/goldbachs-conjecture-1/train/python
from unittest import TestCase
primes = set()
def is_prime(num):
if num in primes:
return True
for i in range(2, num):
if (num % i) == 0: return False
primes.add(num)
return True
def goldbach_partitions(n):
if n % 2 == 1 or n <= 2 or n > 32000:
return []
partitions = []
for i in range(2, n // 2 + 1):
if is_prime(i) and is_prime(n - i):
partitions.append("{}+{}".format(i, n- i))
return partitions
test = TestCase()
test.assertEqual(goldbach_partitions(4), ['2+2'])
test.assertEqual(goldbach_partitions(7), [])
test.assertEqual(goldbach_partitions(26), ['3+23', '7+19', '13+13'])
test.assertEqual(goldbach_partitions(100), ['3+97', '11+89', '17+83',
'29+71', '41+59', '47+53']) |
eb4da1d1c605b1e8fa280671479b10948c09ba8b | nathanfonbuena/python-algorithms | /hacker_rank/athlete_sort.py | 585 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
k = int(input())
def key_sort(elem):
return elem[k]
arr.sort(key=key_sort)
new_arr = []
for i in arr:
new_arr.append(["".join(str(j)) for j in i])
for j in new_arr:
print(" ".join(j))
'''
sample input
5 3
10 2 5
7 1 0
9 9 9
1 23 12
6 5 9
1
''' |
f8023636aa8cce1415e3a8e9ed97ab6341fe50b6 | fabianaramos/URI | /URI/Python/1005.py | 207 | 3.5625 | 4 | A = float(input())
B = float(input())
formatedA = "{:.1f}".format(A)
formatedB = "{:.1f}".format(B)
wghtA = 3.5
wghtB = 7.5
C = (A * wghtA + B * wghtB) / (wghtA + wghtB)
print("MEDIA =" , "%.5f" % C) |
8a14e58ed8785ccad216bdf05019a864fed426fb | Travmatth/LeetCode | /Medium/palindrome_partitioning.py | 1,171 | 3.671875 | 4 | """
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
"""
class Solution(object):
def permute_palindrome(self, s, out, cur):
if not s:
out.append(cur)
elif len(s) == 1:
cur.append(s)
out.append(cur)
else:
for i in range(1, len(s) + 1):
substring = s[:i]
if substring == substring[::-1]:
decomposition = [c for c in cur]
decomposition.append((substring))
self.permute_palindrome(s[i:], out, decomposition)
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
out = []
self.permute_palindrome(s, out, [])
return out
if __name__ == "__main__":
s = Solution()
ex_0 = s.partition("aab")
if ex_0 != [["aa","b"], ["a","a","b"]]:
print("ERROR")
ex_1 = s.partition("banana")
if ex_1 != [["b", "anana"], ["b", "ana", "n", "a"], ["b", "a", "n", "ana"], ["b", "a", "n", "a", "n", "a"]]:
print("ERROR")
pass |
0cdb31dbd37831180026886dbe41a2400477d972 | ARI3L99/EjerciciosPython | /Clase05/estimar_pi.py | 623 | 3.59375 | 4 | import random
def generar_punto(): #genera numeros entre 0 y 1 para x e y
x = random.random()
y = random.random()
return x, y #retorna el valor de ambas variables
N = 100000 #se solicita 100000 veces generar punto
M = 0 #se inicialiaza el contador de M en 0
for i in range(N): #repite N veces
x, y = generar_punto() #llama a generar punto asignandole un valor a cada uno
if (x**2 + y**2) < 1: #comprueba que (x**2 + y**2) sea menor a 1
M += 1 #se suma 1 al contador si cumple la condición
pi = 4*M/N #se guarda el valor estimado de pi
print(f"{pi:.6f}") #se imprime pi por pantalla
|
e341970da95bd367925ef7432b74cd8dab703e22 | AlberVini/random-codes | /codes/infos_de_arquivos.py | 1,638 | 3.71875 | 4 | import os
caminho = str(input('Digite em que caminho deseja procurar: '))
termo = input('Digite algo especifico que quer procurar: ')
def formata_tamanho(tam):
base = 1024
kilo = base
mega = base ** 2
giga = base ** 3
tera = base ** 4
peta = base ** 5
if tam < kilo:
texto = 'B'
elif tam < mega:
tam /= kilo
texto = 'K'
elif tam < giga:
tam /= mega
texto = 'M'
elif tam < tera:
tam /= giga
texto = 'G'
elif tam < peta:
tam /= tera
texto = 'T'
else:
tam /= peta
texto = 'P'
tamanho1 = round(tam, 2)
return f"{tamanho1}{texto}".replace('.', ',')
cont = 0
for raiz, diretorio, arquivos in os.walk(caminho):
for arquivo in arquivos:
if termo in arquivo:
try:
cont += 1
caminho_completo = os.path.join(raiz, arquivo)
tamanho = os.path.getsize(caminho_completo)
nome_arq, ext_arq = os.path.splitext(arquivo)
print()
print('Arquivo: ', arquivo)
print('Caminho: ', caminho_completo)
print('Nome do arquivo: ', nome_arq)
print('Extensão do arquivo: ', ext_arq)
print('Tamanho do arquivo: ', formata_tamanho(tamanho))
except PermissionError:
print('Sem permissão')
except FileNotFoundError:
print('Arquivo não encontrado')
except Exception as e:
print('Erro desconhecido', e)
print()
print(f'{cont} arquivo(s) encontrado(s)') |
899c1f8bbff86d7f1778d8396f8ec08ecdcb3096 | parhamgh2020/kattis | /I've Been Everywhere, Man.py | 133 | 3.546875 | 4 | for _ in range(int(input())):
lst = list()
for _ in range(int(input())):
lst.append(input())
print(len(set(lst))) |
6ac3d992a0da1ff34a0220205191486593cf1e5f | cyberskeleton/sandbox | /2020-04-08hw2.py | 613 | 3.734375 | 4 | #20.5
from tkinter import *
root = Tk()
enter = Entry(root, bg = 'cyan', fg = 'blue', borderwidth = 50)
enter.pack()
def delete_brackets():
string = enter.get()
return cut_off(string)
def cut_off(string):
if '(' in string and ')' in string:
string1 = string[:string.find('(')]
string2 = string[string.find(')') + 1:]
string = string1 + string2
else:
print('result: ' + string)
return string
cut_off(string)
test_button = Button(root, text = 'delete', command = delete_brackets, bg = 'lightblue', fg = 'darkcyan')
test_button.pack()
root.mainloop()
|
bca30609f7e0ce7c4d4ea2deec63fec0a4e6d4fc | MaxGosselin/tkinter-tutorial | /bucky/06-bindingFunctions.py | 280 | 3.703125 | 4 | from tkinter import *
def exFunc(Event):
print("This is an example!")
root = Tk()
# first way
# b1 = Button(root, text="What is this?", command=exFunc)
# b1.pack()
# Event
b1 = Button(root, text="What is this?")
b1.bind("<Button-1>", exFunc)
b1.pack()
root.mainloop()
|
e94e7e00f5d959dc29cede1eb6d50aaae0de8f7e | GENARALBOB115/oi | /bob.py | 1,697 | 3.625 | 4 |
import turtle
wn = turtle.Screen()
wn.bgcolor("#00ffff")
bob = turtle.Turtle()
bob.width(0.001)
bob.shape("turtle")
bob.color("red")
bob.goto(0,0)
bob.hideturtle()
bob.speed(0)
for i in range(60):
bob.forward(90)
bob.left(20)
bob.color("gold")
bob.backward(90.5)
bob.right(242)
bob.forward(1)
bob.color("white")
bob.left(5)
bob.backward(10)
bob.right(5)
bob.forward(10)
bob.color("black")
bob.left(20)
bob.forward(45)
bob.right(20)
bob.backward(45)
bob.color("red")
bob.penup()
bob.goto(-150,150)
for i in range (60):
bob.pendown()
bob.color("white")
bob.left(21)
bob.forward(15)
bob.right(21)
bob.backward(23)
bob.forward(25)
bob.color("red")
bob.left(60.55)
bob.backward(20)
bob.left(129)
bob.forward(43)
bob.color("gold")
bob.right(215)
bob.backward(45)
bob.left(1)
bob.forward(7)
bob.forward(27.5)
bob.color("purple")
bob.forward(27.5)
bob.penup()
bob.goto(225,-225)
bob.pendown()
for i in range( 45):
bob.color("red")
bob.left(30)
bob.forward(35)
bob.right(30)
bob.color("white")
bob.backward(20)
bob.left(120)
bob.color("purple")
bob.forward(22.5)
bob.color("gold")
bob.forward(22.5)
bob.left(2)
bob.penup()
bob.goto(175,150)
bob.pendown()
for i in range(30):
bob.forward(70)
bob.right(55)
bob.color("#800000")
bob.forward(57)
bob.right(45)
bob.backward(46)
bob.color("#203080")
bob.left(1.5)
bob.forward(30)
bob.left(170)
bob.forward(45)
bob.color("gold")
bob.left(7)
bob.backward(40)
wn.exitonclick() |
8c0a151dfce332053853236cc9d0ebde5666b6b7 | prithivraj-rajendran/PythonProjects | /atm_machine.py | 591 | 4.1875 | 4 | # This code will tell an atm machine that how many notes at each amount to be given to user.
if __name__=="__main__":
notes = [2000, 1000, 500, 100, 50, 20, 10]
amount=int(input("Enter the amount to withdraw "))
if amount%10==0:
for note in notes:
if amount>=note and amount>0:
count=0
count=amount//note
amount=amount-(count*note)
print("{} * {} = {}".format(note,count,note*count))
else:
continue
else:
print("Please enter an amount in multiples of 10") |
5f96be51973fb703e925aa71853e3172919aabf6 | DanJamRod/codingbat | /logic-2/make_chocolate.py | 607 | 4.15625 | 4 | def make_chocolate(small, big, goal):
""" We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.
"""
if (goal - big*5 - small <= 0) and (goal % 5 - small <= 0) == True:
if goal - big*5 < 0:
return (goal - big*5) % 5
else:
return goal - big*5
else:
return -1
print(make_chocolate(4, 1, 9))
# print(make_chocolate(6, 1, 10))
# print(make_chocolate(4, 1, 10)) |
71ba5a60f8f711d02f19e698ca9d9373979a076c | Ridhwanluthra/NLMS | /first_traversal.py | 6,195 | 3.65625 | 4 | # code for making the bot move in the grid
# ALL BLOCK COMMENTS ANSWER THE QUESTION "WHAT DO I HAVE AT THIS POINT?"
# take input of the matrix of the image
# store this x,y in a different variable
# take input of the start and the end point
from bot_globals import bot
import bot_movement as bm
from time import sleep
import file_handling as file_h
from callibration import callibrate
#from click_picture import click_picture
"""
I get a matrix which has some 0's and 1's
I get a start point and an end point
"""
"""
I have a way to move in different directions
I still have to configure these functions
I am working on it lets see what happens.
so now it just becomes a problem of changing my control
from one location to the other in a matrix
"""
"""
/* values represent:
0=free path
1=blocked path
3=valid path
4=invalid path
5=goal
"""
"""
This program gives the best path to move from source to destination.
"""
mapp = [[]]
def first_look(cx, cy):
global mapp
rows = len(mapp)
columns = len(mapp[0])
if (not((cx < rows and cx >= 0) and (cy < columns and cy >= 0))):
return False
if (mapp[cx][cy]==5):
return True
if (mapp[cx][cy]!=0):
return False
mapp[cx][cy] = 3
if (first_look(cx-1,cy) == True):
return True
if (first_look(cx,cy+1) == True):
return True
if (first_look(cx+1,cy) == True):
return True
if (first_look(cx,cy-1) == True):
return True
mapp[cx][cy] = 0
return False
"""
Now I can create a matrix which has a path path of 3's
which i can follow to get my bot to the final location
"""
def first_find_path(cx, cy):
global mapp
print mapp
rows = len(mapp)
columns = len(mapp[0])
mapp[cx][cy] = 0
while True:
if cx-1 >= 0:
if (mapp[cx-1][cy] == 3 or mapp[cx-1][cy] == 5):
bm.up()
cx -= 1
callibrate(rows, columns, cx, cy, mapp)
if mapp[cx][cy] == 5:
mapp[cx][cy] = 0
print "up"
break
else:
mapp[cx][cy] = 0
print "up"
continue
if cx+1 < rows:
if (mapp[cx+1][cy] == 3 or mapp[cx+1][cy] == 5):
bm.down()
cx += 1
callibrate(rows, columns, cx, cy, mapp)
if mapp[cx][cy] == 5:
mapp[cx][cy] = 0
print "down"
break
else:
mapp[cx][cy] = 0
print "down"
continue
if cy+1 < columns:
if (mapp[cx][cy+1] == 3 or mapp[cx][cy+1] == 5):
bm.right()
cy += 1
callibrate(rows, columns, cx, cy, mapp)
if mapp[cx][cy] == 5:
mapp[cx][cy] = 0
print "right"
break
else:
mapp[cx][cy] = 0
print "right"
continue
if cy-1 >=0:
if (mapp[cx][cy-1] == 3 or mapp[cx][cy-1] == 5):
bm.left()
cy -= 1
callibrate(rows, columns, cx, cy, mapp)
if mapp[cx][cy] == 5:
mapp[cx][cy] = 0
print "left"
break
else:
mapp[cx][cy] = 0
print "left"
continue
else:
return "you have reached your destination" # put a different kind of result
"""
I have reached my final destination
using the matrix with 3's
I found where there was 3 and accordingly
I moved the bot to the location needed
"""
"""
def go_to_origin(x,y):
global mapp
global x
global y
mapp[0][0] = 5;
look(x,y)
find_path(x,y)
x = 0
y = 0
mapp[i][j] = 0
"""
"""
Now i need to create a function that can make
each location i have to go to 5 in turn so that
i can go and take pictures of each obstacle
"""
# x and y being the current position of the bot
def first_mapping(maps):
#ADD A FILE SAVING MECHANISM
global mapp
mapp = maps
rows = len(mapp)
columns = len(mapp[0])
#first_look(x,y)
#first_find_path(x,y)
for i in range(rows):
for j in range(columns):
if (mapp[i][j] == 1):
if (i-1 >= 0 and mapp[i-1][j] == 0):
global mapp
mapp[i-1][j] = 5;
first_look(bot.x, bot.y)
first_find_path(bot.x, bot.y)
bm.look_down()
sleep(2)
bot.x = i-1
bot.y = j
"""
digit = click_picture(i, j)
file_h.write_in_file(digit, i, j)
"""
mapp[i-1][j] = 0
elif (j+1 < columns and mapp[i][j+1] == 0):
global mapp
mapp[i][j+1] = 5;
first_look(bot.x,bot.y)
first_find_path(bot.x,bot.y)
bm.look_left()
sleep(2)
bot.x = i
bot.y = j+1
"""
digit = click_picture(i, j)
file_h.write_in_file(digit, i, j)
"""
mapp[i][j+1] = 0
elif (i+1 < rows and mapp[i+1][j] == 0):
global mapp
mapp[i+1][j] = 5;
first_look(bot.x,bot.y)
first_find_path(bot.x,bot.y)
bm.look_up()
sleep(2)
bot.x = i+1
bot.y = j
"""
digit = click_picture(i, j)
file_h.write_in_file(digit, i, j)
"""
mapp[i+1][j] = 0
elif (j-1 >= 0 and mapp[i][j-1] == 0):
global mapp
mapp[i][j-1] = 5;
first_look(bot.x,bot.y)
first_find_path(bot.x,bot.y)
bm.look_right()
sleep(2)
bot.x = i
bot.y = j-1
"""
digit = click_picture(i, j)
file_h.write_in_file(digit, i, j)
"""
mapp[i][j-1] = 0
else:
print "there is some error in mapping function in file traversal.py"
|
fe723810582f183015c00ad7ab70ab8dd3c0037e | guna8897/my-web | /Variables,Numbers,Strings.py | 664 | 3.703125 | 4 | # VARIABLES
text = ("Good evening")
print(text)
#1 variable two message
pet = ("dog")
print(pet)
pet = ("cat")
print(pet)
a = ("hi")
a = ("hello")
print(a)
# Multiline strings
a = '''HI welcome all to "GCIT" '''
print(a)
# Changing case
my_name = "guna"
print(my_name.title())
print(my_name.upper())
print(my_name.lower())
#concatenation
first_name = "guna"
last_name = "seelan"
full_name = first_name + last_name
print(full_name.title())
# whitespace
print("good evening".title())
print("\tgood evening".title())
print("good \tevening".title())
print("\nGood evening")
print("Good \nevening")
|
9af09db794b93b0433af821dbd9ce8ae303b5473 | Michael-Python/pub_lab_week_2_day_3 | /src/pub.py | 836 | 3.53125 | 4 | class Pub:
def __init__(self, name, till, drinks_list):
self.name = name
self.till = till
self.drinks = drinks_list
def add_money(self, amount):
self.till += amount
def drink_count(self):
return(len(self.drinks))
def add_drink(self, new_drink):
self.drinks.append(new_drink)
def find_drink_by_name(self, name_of_drink):
for drink in self.drinks:
if drink.name == name_of_drink:
return drink
def sell_drink_to_customer(self, name_of_drink, customer):
# know which drink object we need
drink_to_buy = self.find_drink_by_name(name_of_drink)
# remove money from wallet
customer.remove_money(drink_to_buy.price)
# add money to till
self.add_money(drink_to_buy.price)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.