blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
af836194f73c6958669c1c24e692e83a0b8b5a17
emanueldumitru/flask-bootcamp-marcial
/complete-python-developer-2021/First sections/generators.py
1,401
3.59375
4
from decorators import performance @performance def long_time(): print('1') for i in range(10000000): i * 5 @performance def long_time2(): print('2') for i in range(10000000): yield i * 5 long_time() long_time2() # generators under the hood def special_for(iterable): ite...
625c32d7271bb36aa123978ff5d138d75e1bdc36
Stella2019/unique-fenlei
/字符串/8.有效的字母异位词.py
1,564
3.921875
4
#!/usr/bin/python # coding:utf-8 """ @author: yyhaker @contact: 572176750@qq.com @file: 8.有效的字母异位词.py @time: 2019/7/23 20:33 """ # [242] 有效的字母异位词 # # https://leetcode-cn.com/problems/valid-anagram/description/ # # algorithms # Easy (63.29%) # Likes: 354 # Dislikes: 0 # Total Accepted: 210.6K # Total Submissions:...
fd460755a93915092ba06611e83dd98944ad9c5b
shashank-shark/Math-and-python
/NumericalMath/Complex-Numbers/Basic.py
331
3.8125
4
# declaring complex num 1 cNum1 = 1 + 2j # declaring complex num 2 cNum2 = 2 + 6j # addition cAdd = cNum1 + cNum2 print ("CN1 + CN2 = ", cAdd) # subtraction cSub = cNum1 - cNum2 print ("CN1 - CN2 = ", cSub) # multiplication cMul = cNum1 * cNum2 print ("CN1 * CN2", cMul) # division cDiv = cNum1 / cNum2 print ("CN1 / ...
b794bcfe0b7f200adafe6186c8173e523865fa22
AaronVillanueva/InteractivePythonRunestone
/Capitulo 5/ParesYNones.py
179
3.703125
4
def parOnon(n): if n % 2 == 0: return (True) else: return (False) x=int(input("Ingrese un número entero para determinar si es par: ")) print(parOnon(x))
ba894980217a9b6299f78f8f8bfb98c9740531a9
AaronVillanueva/InteractivePythonRunestone
/Capitulo 6/PoligonosRegulares.py
721
3.671875
4
#coding: UTF-8 #Triangulo import turtle wn = turtle.Screen() Andii = turtle.Turtle() for i in range(3): Andii.forward(100) Andii.left(360/3) wn.exitonclick() #Cuadrado import turtle wn = turtle.Screen() Mel = turtle.Turtle() for i in range(4): Mel.forward(100) Mel.left(360/4) wn.exitonclick() #...
8cd44bccfe83253148683a8ad433bc97a223cdd9
AaronVillanueva/InteractivePythonRunestone
/Capitulo 5/Pascua.py
619
3.75
4
#encoding: UTF-8 def analisisPascua(year): a = year % 19 b = year % 4 c = year % 7 d = (19*a + 24) % 30 e = (2*b + 4*c + 6*d + 5) % 7 fecha = 22 + d + e if year == 1954 or year == 2981 or year == 2049 or year == 2076: fecha = fecha - 7 return(fecha) def Main(): year = int(i...
8105f10e00e0e93211d4aff9cbc30149a3adcf22
kv1792/MachineLearning
/RegressionPractice/polynomial_linear_regression.py
988
3.5
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import r2_score # Extracting data dataset = pd.read_csv('Data.csv') X =...
1711c57090c422749d8c50d3d9cd90765d94d285
vvdwivedi/self-study
/algorithms/max_pairwise_product/maximum_pairwise_product_fast.py
716
3.84375
4
# Uses Python3 n = int(input()) a = [int(x) for x in input().split()] largest_index = 0 second_largest_index = 0 for i in range(0, n): if a[i] > a[largest_index]: largest_index = i largest, last = a[largest_index], a[n - 1] a[largest_index] = last a[n - 1] = largest for i in range(0, n - 1): if a[i] ...
c63e42f64f9ec8a71676dd2179aeca6beda3eff4
hack301/PythonTest
/runoob/data-structure.py
500
3.9375
4
#! /usr/bin/env python3 # 列表 //列表可以修改,而字符串和元组不能。 a=[66.25,333,333,1,1234.5] print(len(a)) a.append(6.22) del a[0:2] #a.remove(1) #a.reverse() print(a.index(333)) print(a) # 集合 //集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。 basket={'apple','orange','apple','pear','orange','banana'} print(basket) # 元组 //不可修改 t=(1,2,3,4,5,6) print(...
af0274e92bc514d8def3241f40100854d07de372
debdutgoswami/python-beginners-makaut
/day-2/palindrome.py
200
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 21 21:35:14 2019 @author: debdut palindrome """ n = input("enter: ") if n[::-1]==n: print("palindrome") else: print("not palindrome")
fc7376086c6c59f67ab1009af30a49a5491079f1
debdutgoswami/python-beginners-makaut
/day-6/ascendingdescending.py
344
4.34375
4
dictionary = {"Name": "Debdut","Roll": "114", "Dept.": "CSE"} ascending = dict(sorted(dictionary.items(), key=lambda x: x[1])) descending = dict(sorted(dictionary.items(), key=lambda x: x[1], reverse=True)) print("the dictionary in ascending order of values is",ascending) print("the dictionary in descending order o...
3b368b6434b1e5becb83d76c630fe6a35316debd
debdutgoswami/python-beginners-makaut
/day-3/removeduplicate.py
100
3.78125
4
l = [i for i in input("enter the elements: ").split()] l = list(set(l)) print("the new list is",l)
509aabacc8ebde4572b29f38024a033b741f6763
debdutgoswami/python-beginners-makaut
/day-4/addtotuple.py
148
4.25
4
tup = (1,2,3,4) n = int(input("enter the element to be inserted: ")) print("the initial tuple is",tup) tup += (n,) print("the new tuple is",tup)
bb8d4ad58d5a555c42dd719c5baa759592c17520
debdutgoswami/python-beginners-makaut
/day-4/4thand4thlast.py
143
3.984375
4
l = tuple(int(i) for i in input("enter the elements: ").split()) print("the 4th element is {} and 4th last element is {}".format(l[3], l[-4]))
b5ff676c84fb38e88756f066f29acc4a440999c0
debdutgoswami/python-beginners-makaut
/day-3/maxminoddeven.py
246
3.953125
4
l = [int(i) for i in input("enter the elements: ").split()] even, odd = [],[] [odd.append(i) for i in l if i%2] [even.append(i) for i in l if not(i%2)] print("The maximum odd number is",max(odd)) print("The minimum even number is",min(even))
666210b8cd62901397205388d016525fc4100b1a
JakeHaustveit/Dinos_vs_Robots
/robot.py
674
3.625
4
from weapon import Weapon class Robot: def __init__(self, name): self.name= name self.health= int(100) self.weapon= int(4) def attack(self, dinosaur): attack= self.weapon return attack def pick_weapon(self): print(' pick "1" for laser pointer, pick...
0b798eb574831e71931fcdcfbf0fa280612b5616
d-weeteling/calc_the_game_solver
/game.py
4,235
3.765625
4
import sys class Game: def __init__(self, value_start, value_wanted, rounds_total, ops): """ A Game instance must consist of the following entities: DATA: - value_start :: constant - int - value_current :: var - int - value_wanted :: constant - int ...
fe4559bfb2e6009624f79c9e23630bb803c3ab05
anaquinpm/python
/quickPython/theBasic/05_lists_tuples_sets.py
5,303
4.375
4
#Las listas son como los arreglos en C ## Asigno una lista de 3 elemento a x x = [1, "two", [1, 2 ,3]] # Los elementos pueden ser de cualquier tipo len (x[2]) # "largo de la lista" en la posición 2 de la variable x x[2] # Referencia a un elemento de la lista, tomando como posi...
2f5b3a5b054195f99bb6def3d1509b66f71c6334
anaquinpm/python
/quickPython/theBasic/ch05/ordenando.py
356
3.984375
4
#!/usr/bin/env python3 """ Ordena la lista principal según el segundo elemento de la listas que contiene """ def ordena_listas(lista): return lista[1] x = [[1, 2, 3], [2, 1, 3], [4, 0, 1]] print("Ordena la lista principal según el segundo elemento de la listas que contiene ") print(x) x.sort(key=ordena_listas) pr...
3c8eed932cc767c6fe046102ced7f6957a325c66
anaquinpm/python
/quickPython/theBasic/08_LoopsIf.py
601
3.921875
4
""" Remover los elementos negativos de la lista """ x = [1, 3, -5, 0, -1, 3, -2] for i, n in enumerate(x): if n < 0: del x[i] print(x) """ Contar los numeros negativos """ y = [[1, -1, 0], [2, 5, -9], [-2, -3, 0]] count = 0 for tuple in y: for v in tuple: if v < 0: count += 1 print(f"'y' tiene {count...
ac304eebb10be844ada5c38244b813a2063bce48
dawgware/stemlab
/stemlab_client/common/measurement_types.py
2,731
3.625
4
""" Created: June 22, 2016 Author: Carl Wilen Lists the various measurement types that can be returned by various Sensors. """ PERCENTAGE = 'Percentage' CELSIUS = 'Celsius' FAHRENHEIT = 'Fahrenheit' KELVIN = 'Kelvin' class MeasurementType(object): _description = '' _name = '' _unitsofmeasur...
4f6b962f858e4cef243c9939170f669f67d5ded5
cindychea/python_reinforcement_exercises
/june11exercise.py
1,589
3.5625
4
project = { "committee": ["Stella", "Salma", "Kai"], "title": "Very Important Project", "due_date": "December 14, 2019", "id": "3284", "steps": [ {"description": "conduct interviews", "due_date": "August 1, 2018"}, {"description": "code of conduct", "due_date": "January 1, 2018"}, ...
99177cb8c831b4ff2d5ca742fca24ba46f8ac372
cindychea/python_reinforcement_exercises
/june13exercise.py
1,017
3.828125
4
import requests import json # Check out the documentation. # Make request to get the countries.json file that they talk about in the documentation. # Examine the structure of the JSON data. res = requests.get('https://raw.githubusercontent.com/everypolitician/everypolitician-data/master/countries.json') body = json.lo...
75137c0a141244e97f8c5a638aaecd0556925348
jtcass01/DailyAnalyzer
/src/utilities.py
8,771
4.15625
4
import numpy as np def optimize(input_matrix, targets, num_iterations, learning_rate, log_cost = False, storage_frequency=100): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar ...
a35096f3c4fdf080a712f07c9de92075feca9b94
ChineseChengHaiLong/C123
/dieryue/飞机/私有.py
602
3.640625
4
class People(object): def __init__(self): self.__money = 50 def get_a(self): self.__money = 500 return self.__money def set_a(self,value): self.__money = value qian = property(get_a,set_a) huahua = People() ll=huahua.get_a() print(ll) huahua.money = 99999999999 print(hua...
83261f9b88844e27ab6822c525b509d835187533
samiwolf/SDP-Math
/phy2/copy_and_pickle.py
3,968
3.5625
4
"""This example shows how you can copy, save and load a space using pickle. """ import pickle import pygame import sys from pygame.locals import * from pygame.color import * import pymunk from pymunk import Vec2d import pymunk.pygame_util width, height = 400, 500 def run(): pygame.init() pygame.display.set...
2e416f0a3d3bfca9bb85c2713a9b85e1e6f399a1
samiwolf/SDP-Math
/math2/scatter_plot.py
478
3.71875
4
from matplotlib import pyplot as plt import pandas as pd import numpy as np # Create data df = pd.DataFrame({'x': range(1, 101), 'y': np.random.randn(100) * 15 + range(1, 101), 'z': (np.random.randn(100) * 15 + range(1, 101)) * 2}) # plot with matplotlib plt.plot('x', 'y', data=df, marker='o', colo...
565e054d62b83bf8a0ab1ea39a9f8ce016736116
chelseacastelli/CS-1.2-Intro-Data-Structures
/Tweet-Generator/scripts/stochastic.py
1,319
3.859375
4
from histogram import read_in_data, dictogram from random import randrange, choices def random_word(histogram_DS): rand_index = randrange(len(histogram_DS) - 1) return list(histogram_DS)[rand_index] # Divide num of occurances by total words def sample_by_frequency(histogram_DS): histo_keys = [key for key ...
2b15fcdb42b48bdfb425dafca3b479bad6f0a30c
wahid1099/python-problemsolvin
/basic problems/word_count.py
132
3.734375
4
text='Love to watching Movie khh' count = 0 for char in text: if char=='': count=count+1 count = count + 1 print(count)
73724bfc7f5a04511e204dd93c6f299e505c80da
wahid1099/python-problemsolvin
/easy ones/math_pow.py
192
4.25
4
base_num=int(input('Give me the base number:')) power_num=int(input('give me the power number:')) # result = base_num**power_num result=pow(base_num,power_num) print('Your result is',result)
3f200a0dc712108ec5140b9ecdb7dc332a5e5c08
samhithaaaa/Array-2
/maxmin.py
533
3.546875
4
class Solution(object): def maxmin(self,nums): if not nums: return None minn=nums[0] maxx=nums[0] for i in range(1,len(nums),2): if i==len(nums)-1: minn=min(minn,nums[i]) maxx=max(maxx,nums[i]) elif nums[i]>nums[i+1]...
6e0325d2767f092bda33cd54579559826dd18a1f
broccoli-smuggler/algorithms
/union/union_find.py
1,065
3.796875
4
class UnionFind(object): def __init__(self, size): self._roots = list(range(0, size)) self._depths = [1] * size def __str__(self): return str(self._roots) + str(self._depths) # O(1) def union(self, a, b): if a >= len(self._roots) or b >= len(self._roots): re...
9b2e6ada5318d7eecc9797368fa73b53fef11943
MikeWooster/reformat-money
/reformat_money/arguments.py
1,405
4.125
4
class Argument: """Parses a python argument as string. All whitespace before and after the argument text itself is stripped off and saved for later reformatting. """ def __init__(self, original: str): original.lstrip() start = 0 end = len(original) - 1 while orig...
5c20454db8c58a864501de85402ba1313b5b320c
Dun-Yan-opq/Machine-learning
/LSTM/LSTM_sample_code.py
10,450
3.515625
4
# -*- coding: utf-8 -*- """ 09/17/2020 簡單的 LSTM 模型建立與訓練 透過輸入一個訊號去擬合另一個訊號來感受 LSTM模型的優勢 This is a easy LSTM code! Wave signal A Wave signal B -------------> LSTM Model -------------> """ import torch import torch.nn as nn from torch import optim import torch.nn.init as init from torch...
d2590edfd88a4aad83fbf6ef461720fe5405dac0
dxz6228/Code-Examples
/Python Projects/trending.py
2,848
4.03125
4
""" file: trending.py language: python3 author: Denis Zhenilov description: This program calculates, which words are the most and the least "trending" in a given period of time. It relies on wordData to work. """ import wordData def trending(words, startYr, endYr): """ This function creates a list ...
12dcca9cb8569d12e50bd69d346d422886ebcb3b
Hossamyehiaa/Explore-US-Bikeshare-Data-With-Python
/bikeshare.py
8,996
4.4375
4
import time import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } months = ['january', 'february', 'march', 'april', 'may', 'june'] weekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', ...
eb7d5fd2d03c64f653154cc27012f990a0b70439
wtokarz80/Python
/fibonacci/fibonacci.py
884
3.96875
4
def fibonacci(): i = 0 j = 1 k = 0 fib = 0 fib_list = [] while i < int(number): fib_list.append(fib) fib = j + k j = k k = fib i += 1 max_n = max(fib_list) for z, e in enumerate(fib_list): z += 1 print(f"{z}. " + str(e).rjust(len(st...
6efeb3345f8eb779f5dbc797ba6d5ed195966330
dyhmzall/geekbrains_python
/lesson3/task3.py
1,276
4.21875
4
# 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def my_func(*args): """ Принимает любое количество аргументов (в том числе три) и возвращает сумму наибольших двух из них :param args: list любое количество аргументов :...
0188c7f2937617b489e1a523e791aa7cc9504cc3
dyhmzall/geekbrains_python
/lesson2/task3.py
1,349
3.953125
4
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. # Сообщить к какому времени года относится месяц (зима, весна, лето, осень). # Напишите решения через list и через dict. month = 0 while (month < 1) or (month > 12): try: month = int(input("Введите месяц в виде целого числа (от 1 до 12): ")) ...
e8fb73a519a0c178a0fcd46dc96e2f30210a717e
dyhmzall/geekbrains_python
/lesson1/task3.py
358
4
4
# 3. Узнайте у пользователя число n. # Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. n = input("Введите число: ") summa = int(n) summa += int(n * 2) summa += int(n * 3) print(f"Сумма равна: {summa}")
0dfef379be5b49397f87b5b63a5705d3599c7c76
fdoperezi/algorithmic_trading
/stocks.py
4,199
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[6]: import pandas as pd import io import requests import time import random # In[3]: # gets the hidden API keys api_key = pd.read_csv('secrets.csv').api_key.to_string().split()[1] # In[124]: # gets data using user's parameters def get_data(symbol, interval): """...
da13f16c9bf364961e1ad9d1f981801b17846c12
thatsokay/digital-deck-builder
/star_realms/player.py
4,070
3.765625
4
from random import shuffle from .card import Base class Player(object): """ Represents a player. Stores a player's draw and discard piles, hand, and resources. """ def __init__(self, deck=[]): """ Initialises the player's deck and hand. Args: deck: The player's...
490ecf5f4f7847afa1bbb5cebecc47843b3d541a
florian-corby/Pylearn
/hangman/hangman.py
2,469
4.21875
4
#!/usr/bin/env python3 import word_manipulations import get_random_word import hangman_ascii import sys import os def print_ends(hangman_end, guess_word): if hangman_end == "defeat": print("") print("You lost! Hangman is now dead...") print("Guess word was: " + "".join(guess_word)) ...
3adffc3289a2bbc46051b618b644bce205bd3624
sdamico23/sort-methods
/mergeSort.py
923
4.125
4
#LAB 13 #Due Date: 11/18/2018, 11:59PM ######################################## # # Name:Collin Michaels # Collaboration Statement: # ######################################## def merge(list1, list2): #write your code here newList = [] z = 0 y...
888d20e277c237e69c1d78c679770af8d7d2f126
jot1/Workshops
/Workshops1/Prac01/shippingcalculator.py
382
4.03125
4
__author__ = 'jc450453' NumberofItem=1 while NumberofItem>0: NumberofItem=int(input("Enter Number of Items :")) Costperitem=float(input("Enter your cost per item :$")) Totalshipcost=NumberofItem*Costperitem; if(Totalshipcost>100): Totalshipcost=Totalshipcost - (10/100*Totalshipcost) print("the...
58399b06fcec170c0b0b93af806a1e146f80fe08
Zer0xPoint/NowCoder_OJ
/1.29.py
706
3.78125
4
# 题目描述 # 假设你正在玩跳格子(所有格子排成一个纵列)游戏。需要 跳完n 个格子你才能抵达终点。 # 每次你可以跳 1 或 2 个格子。你有多少种不同的方法可以到达终点呢? # 注意:给定 n 是一个正整数。 # 输入描述: # 格子数n # 输出描述: # 跳完n个格子到达终点的方法 # 示例1 # 输入 # # 2 # 输出 # # 2 # 阶乘 def factorial(x): f = 1 for i in range(1, x + 1): f *= i return f elements = int(input()) quotient = elements // 2 n ...
72c6974c6db63ba09e386cd9cf077a61687d3a6d
Zer0xPoint/NowCoder_OJ
/1.43.py
925
3.671875
4
# 题目描述 # # 通过键盘输入一串小写字母(a~z)组成的字符串。 # 请编写一个字符串归一化程序,统计字符串中相同字符出现的次数,并按字典序输出字符及其出现次数。 # 例如字符串"babcc"归一化后为"a1b2c2" # # # # 输入描述: # 每个测试用例每行为一个字符串,以'\n'结尾,例如cccddecca # 输出描述: # 输出压缩后的字符串ac5d2e # 示例1 # 输入 # # dabcab # 输出 # # a2b2c1d1 n = input() n_dict = {} for i in n: if i not in n_dict: # 若dict中不包含此元素 n_dict...
77744f1caebe60f241227e17cb0a8772220495d1
Zer0xPoint/NowCoder_OJ
/1.15.py
725
3.5
4
# 题目描述 # 今天上课,老师教了小易怎么计算加法和乘法,乘法的优先级大于加法,但是如果一个运算加了括号,那么它的优先级是最高的。例如: # 1+2*3=7 # 1*(2+3)=5 # 1*2*3=6 # (1+2)*3=9 # 现在小易希望你帮他计算给定3个数a,b,c,在它们中间添加"+", "*", "(", ")"符号,能够获得的最大值。 # 输入描述: # 一行三个数a,b,c (1 <= a, b, c <= 10) # 输出描述: # 能够获得的最大值 # 示例1 # 输入 # # 1 2 3 # 输出 # # 9 num_list = list(map(int, input().split())) num_list...
9248c08f7d14b9121a8a7f7c0c97da645a395b92
Zer0xPoint/NowCoder_OJ
/1.30.py
1,015
4.09375
4
# 题目描述 # 你有3个需要完成的任务,完成这3个任务是需要付出代价的。 # 首先,你可以不花任何代价的完成一个任务;然后,在完成了第i个任务之后,你可以花费|Ai - Aj|的代价完成第j个任务。|y|代表x的绝对值。 # 计算出完成所有任务的最小代价。 # 输入描述: # 一行3个整数A1,A2,A3,每个数字之间用一个空格分隔。所有数字都是整数,并且在[1,100]范围内。 # 输出描述: # 一个整数,代表最小的代价。 # 示例1 # 输入 # # 1 6 3 # 输出 # # 5 # 示例2 # 输入 # # 10 10 10 # 输出 # # 0 a_list = list(map(int, input().spli...
5670d584215ddaeceef37018336b3795a95e3917
diego-cc/python_assessment_3
/task_b/server/server.py
1,397
3.84375
4
""" Project: python_assessment_3 Author: Diego C. <20026893@tafe.wa.edu.au> Created at: 10/11/2020 7:27 pm File: server.py """ import socket import random import task_b.answers.answer as answer all_answers = answer.Answer.get_list() def get_random_answer() -> answer.Answer: """Chooses a random answer from the on...
2d75c379c24fc87753ab6d92fd84c1ba0518eec2
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_21_strip.py
620
4.5
4
""" string method - strip() returns a copy of the string by removing both the leading and the trailing characters """ # case 1. s = ' xoxo python xoxo ' print(f"|{s}|") print(f"|{s.strip()}|") # case 2. s = ' xoxo python xoxo ' print(f"|{s}|") print(f"|{s.strip('xo')}|") print(f"|{s.strip(' xo')}|") s = ' oxo...
9b06637c7aa4f6a89cb4f4759f29238a3c537570
edu-athensoft/ceit4101python
/stem1400_modules/module_2_basics/c6_type_convertion/conversion/int2float.py
74
3.609375
4
# conversion of datatypes # float() a = 2 b = float(a) print(a,"=>",b)
af0e5c715b8b68a792f4bef781994ee8598ec66c
edu-athensoft/ceit4101python
/evaluate/evaluate_1_exercise/m6_list/combination.py
555
3.984375
4
""" Write a Python program to generate all sublists of a list. No. 33 w3rsc """ from itertools import combinations def sub_lists(my_list): subs = [] for i in range(0, len(my_list)+1): temp = [list(x) for x in combinations(my_list, i)] if len(temp)>0: subs.extend(temp) return sub...
3c054ee6c110b6b95ee5bebdcd1036dcccc7b4e2
edu-athensoft/ceit4101python
/evaluate/evaluate_3_project/python3_advanced/myplotter/pro/v2/shapes.py
4,006
3.5625
4
""" module: shapes author: Athensoft Inc. version: v1 """ import shapename as shn import colorname as color import math class Shape: def __init__(self, shapeName, shapeType, shapeColor=color.DEFAULT_COLOR): self.__shapeName = shapeName self.__shapeType = shapeType self.__shapeC...
4c4d257c45ecda6c962c2168b2ffb3e198339907
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_6_dictionary/demo_customer_info.py
418
3.921875
4
""" represent customer info with dictionary """ customer = { "name": "John Smith", "age": 30, "is verified": True } print(customer) # error # print(customer["birthday"]) # None for undefined key customer.get("birthday") print(customer) print(customer.get("birthday")) # print(customer.get("birthday","20...
156038274b09d849bb6842117c6aab8865c13296
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo2_super_multilevel/multilevel_init_1.py
308
3.515625
4
""" multi-level init grandson directly inherits init() of GrandParent grandson looks up for the init() by MRO rules. """ class GrandParent: def __init__(self): print('GrandParent __init__() called.') class Son(GrandParent): pass class GrandSon(Son): pass # main gs1 = GrandSon()
097359cac58c4798be5d18a3b76bcd9a863ddb93
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0412_text/text_5_selecttext_1.py
713
3.640625
4
""" text select text """ from tkinter import * def selectedText(): try: selText = text.get(SEL_FIRST, SEL_LAST) print("Selected text:") print(selText) except TclError: print("No text selected.") root = Tk() root.title("Python GUI | Text Selecting") root.geometry("640x480+300...
8b2aadc3171527ad7c2880ee3d5167cd0542ba85
edu-athensoft/ceit4101python
/stem1400_modules/module_4_function/func1_define/function_3.py
392
4.15625
4
""" function - without returned value - with returned value """ def showmenu(): print("egg") print("chicken") print("fries") print("coke") print("dessert") return "OK" # call it and lost returned value showmenu() print() print(showmenu()) print() # call it and keep returned value isdone = s...
444c7a1db3370612ea5361725e065cb7381e8ed8
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0412_text/text_6_xscrollbar_1.py
578
3.703125
4
""" text adding X-scrollbar """ from tkinter import * root = Tk() root.title("Python GUI | Text X-Scrollbar") root.geometry("320x180+300+200") # text text = Text(root, height=5, width=30, wrap=NONE) text.insert(END, "aaaabbbbcccc1111\n") text.insert(END, "aaaabbbbcccc2222\n") text.insert(END, "aaaabbbbcccc3333") # ...
7a13ea84858a0824e09630477fe3861eb26571ae
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_06_instance/s5_add_attribute/instance_attribute_2.py
593
4.46875
4
""" Adding attributes to an object """ # defining a class class Cat: def __init__(self, name, age): self.name = name self.age = age # self.color does not exist. def sleep(self): print('sleep() is called') def eat(self): print('eat() is called') # def antimeth...
420933e86e4ecad7a1108f09fcbf2531af0ee7df
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_func_03_len.py
1,458
4.125
4
# len() # How len() works with tuples, lists and range? testList = [] print(testList, 'length is', len(testList)) testList = [1, 2, 3] print(testList, 'length is', len(testList)) testTuple = (1, 2, 3) print(testTuple, 'length is', len(testTuple)) testRange = range(1, 10) print('Length of', testRange, 'is', len(test...
abf7b2cfe1d7d7c171855ca4dad7e57f6fd6943d
edu-athensoft/ceit4101python
/evaluate/evaluate_3_project/python1_beginner/guessing_number/guessing_number_v1.py
1,689
4.25
4
""" Guessing number version 1.0 problems: 1. how to generate a random number/integer within a given range 2. how to validate the number and make it within your upper and lower bound 3. comparing your current number with the answer case #1: too small case #2: too big case #3: bingo 4. max 5 times failed...
dd5074132b5f74a3390d7b502cdfac39ed5b549e
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_10_polymorphism/case_2_bank/v6/bankentity.py
679
3.671875
4
""" bank system entities """ class Bank: def __init__(self, bankName, interestRate): self.__bankName = bankName self.__interestRate = interestRate def getInterestRate(self): return self.__interestRate def getBankName(self): return self.__bankName class BankA(Bank): ...
34b792230c27e819e3a59baeddc171e3b1dcccb8
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s06_layout/s062_grid/grid_03.py
515
3.65625
4
""" Tkinter using grid layout relative position ref: #2 """ from tkinter import * root = Tk() root.geometry('640x480+200+200') root.config(bg='#ddddff') # create label widgets label1 = Label(root, text='Label 0,0',bg='yellow') label2 = Label(root, text='Label 0,1') label3 = Label(root, text='Label 1,0') label4 ...
5378ef0faa41bacd228ee02bc616d4fc74fd8bfb
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_func_04_sorted.py
1,380
4.375
4
# sorted() # sorted(iterable[, key][, reverse]) # sorted() Parameters # sorted() takes two three parameters: # # iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator # reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order) # key (Opti...
4fbf6cc6d51892c9a80e5d4266be5ad184d5ff30
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_7_array/array_3_search.py
571
4.21875
4
""" Searching element in a Array """ import array # initializing array with array values # initializes array with signed integers arr = array.array('i', [1, 2, 3, 1, 2, 5]) # printing original array print("The new created array is : ", end="") for i in range(0, 6): print(arr[i], end=" ") print("\r") # using in...
c1fe6f37a7e4522a78a2e1d2922bdb6102636941
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0401_label/label_7_justify.py
1,117
4.1875
4
""" Tkinter place a label widget justify=left|center(default)|right """ from tkinter import * root = Tk() root.title('Python GUI - Label justify') root.geometry("{}x{}+200+240".format(640, 480)) root.configure(bg='#ddddff') # create a label widget label1 = Label(root, text='Tkinter Label 1', hei...
529f575c0379b8aeda63f09b1a04e81d2eb2b3cd
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_6_dictionary/dictionary_06_fromkeys.py
802
3.875
4
# Create a dictionary from a sequence of keys # vowels keys keys_set = {'a', 'e', 'i', 'o', 'u'} vowels = dict.fromkeys(keys_set) print(vowels) keys_list = ['a', 'e', 'i', 'o', 'u'] vowels = dict.fromkeys(keys_list) print(vowels) keys_tuple = ['a', 'e', 'i', 'o', 'u'] vowels = dict.fromkeys(keys_tuple) print(vowels) ...
845282c41034ea8dd5595f6d9f41bc9dff50bfee
edu-athensoft/ceit4101python
/stem1400_modules/module_9_datetime/s93_strptime/s3_strptime/datetime_17_strptime.py
420
4.1875
4
""" datetime module Python format datetime Python has strftime() and strptime() methods to handle this. The strptime() method creates a datetime object from a given string (representing date and time) """ from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) date_object =...
0d2a0519a262bfd7abba4229cca774252f97b1bb
edu-athensoft/ceit4101python
/stem1400_modules/module_9_datetime/s91_datetime/s4_datetime/datetime_2_datetime_attr.py
322
3.75
4
""" datetime module datetime class 1.4.2 Get year, month, hour, min, second """ from datetime import datetime a = datetime(2019, 6, 21, 23, 55, 59, 342380) print("year =", a.year) print("month =", a.month) print("day =", a.day) print("hour =", a.hour) print("minute =", a.minute) print("timestamp =", a.timestamp())...
cf3efe7bedcf40ace6b4070ccc5e1b434121cfa4
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/old/s1_class_instance/myclass3.py
420
3.984375
4
# define a class # create instance class Employee: def __init__(self, first, last, email, pay): self.first = first self.last = last self.email = email self.pay = pay emp1 = Employee('Athens','Zhang','a1@163.com', 6000) emp2 = Employee('Lada','Zhang','a2@263.com', 9000) print(emp...
d9c9059d76f389301e115cae2c79743ffc69e794
edu-athensoft/ceit4101python
/stem1400_modules/module_9_datetime/s91_datetime/s7_timezone/datetime_23_timezone.py
371
4.03125
4
""" get date and time by timezone """ from datetime import datetime import pytz mydatetime = datetime.now() print(mydatetime) tz = pytz.timezone('Asia/Jakarta') mydatetime = datetime.now(tz) print(mydatetime) tz = pytz.timezone('Asia/Shanghai') mydatetime = datetime.now(tz) print(mydatetime) tz = pytz.timezone('UT...
7b97eec2bef56c7cdfc4577d5838ba2d7c1cd4b3
edu-athensoft/ceit4101python
/stem1471_projects/p00_file_csv_processor_2/csv_append_row.py
824
4.25
4
""" csv processor append a row In this example, we first define the data that we want to append to the CSV file, which is a list of values representing a new row of data. We then open the CSV file in append mode by specifying 'a' as the file mode. This allows us to append data to the end of the file rather than over...
7708fabec7e64fa51646e485729c1384f5283b63
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_4_string/string_2_accessing.py
425
4.375
4
""" string - accessing char """ str1 = 'athensoft inc' print('str = ', str1) # accessing char in a string by index # first character print('str[0] = ', str1[0]) # last character print('str[-1] = ', str1[-1]) # slicing - substring # slicing 2nd to 5th character print('str[1:5] = ', str1[1:5]) # slicing 6th to 2...
e30e10ee53adcce75ea7c4bb625576cfdc0a68c8
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_11_classmember/s03_static_method/demo_4_dog_2.py
184
3.546875
4
""" example of static method static method """ class Dog: @staticmethod def run(): # no need to use 'self' print("A dog runs.") # main Dog.run() Dog.run()
4391e60dc118ccb4a050b9f43f1d871f7c3f4fde
edu-athensoft/ceit4101python
/stem1400_modules/module_2_basics/c6_type_convertion/explicit_conversion.py
226
3.96875
4
# explicit conversion # a = 123 # b = "456" # c = a + b # print(c) a = 123 b = "456" c = str(a) + b print(c, type(c)) a = 123 b = "456" c = a + int(b) print(c, type(c)) a = 123 b = "456" c = a + float(b) print(c, type(c))
eaaf4969cb40b102ab2d7bfec0fb10e2a15ed4d9
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0403_entry/entry_05_insert_1_index.py
1,047
3.578125
4
""" Entry insert by index of position """ from tkinter import * def printInfo(): print(f"You've input: {entry1.get()}") def insertInfo(): """ hard code the index (position for insertion) :return: """ pos=2 entry1.insert(pos,"-insert-") print(f"You've input: {entry1.get()}") # de...
dfd2d8cedd22ab7f2bbba00f7013e3df8eb6bdd6
edu-athensoft/ceit4101python
/evaluate/evaluate_1_exercise/m6_dictionary/ex_add_key_1.py
279
4.15625
4
""" module 6. datatype chapter 6-6. dictionary Question: 3. Write a program to add a key to a dictionary Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30} Hints: """ mydict = {'a': 10, 'b': 20} print(mydict) mydict['c'] = 30 print(mydict)
afe27efe048ba096fa6d78fc81c3e99099bdc777
edu-athensoft/ceit4101python
/mytest/s2c_assignment/assignment.py
114
3.625
4
# compare the sign of equal/assignment with the one in maths x = 10 x = x + 2 # understand this syntax print(x)
8598415ec99ab168a06cf186e5889a954a89d7bc
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_3_tuple/tuple5_change.py
165
4
4
# changing items of a tuple my_tuple = (4, 2, 3, [6, 5]) # my_tuple[0] = 4 #TypeError my_tuple[3][0] = 66 print(my_tuple) my_tuple = (4,5,6,7) print(my_tuple)
4255ae3b264f62665c2dcc71964e6083058d9261
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_26_replace.py
627
3.921875
4
""" string method - replace(original, new [, times] ) A string is immutable. """ # case 1. song = "cold, cold heart" # replace 'cold' with 'hurt' res = song.replace('cold', 'hurt') print(res) # case 2. str1 = "a b c d e f g" # "a,b,c,d,e,f,g" # print('====') # print(str1.replace(' ',';')) # print('====') # option...
872fc8afb9407650e4f0c193a20df1807d861017
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0412_text/text_6_scrolledtext_2.py
699
3.734375
4
""" text ScrolledText with x-scrollbar and y-scrollbar """ from tkinter import * from tkinter.scrolledtext import ScrolledText root = Tk() root.title("Python GUI | ScrolledText") root.geometry("320x180+300+200") # tk version print(TkVersion) # scrolled text text = ScrolledText(root, height=5, width=30, wrap='none')...
42195ba48b72cb8f5f360781b259020d8f030050
edu-athensoft/ceit4101python
/evaluate/evaluate_3_project/python3_advanced/myplotter/starter/v1/plotter.py
2,400
3.5625
4
""" Plotter """ import shapename as shn class Plotter: pass class Plotter2D(Plotter): def __init__(self, shape2dObj): self.shapeObj = shape2dObj # def draw(self, shape2dObj): # print(f"draw({shape2dObj}) called.") # def fillColor(self, shapeObj, colorName): # print(f"fillC...
3b6787992ee0243273898e71eafa3bb8060ea8ed
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_3_tuple/tuple1.py
444
4.09375
4
# create/declare/define my_tuple = (1,2,3) print(my_tuple, type(my_tuple)) # create an empty tuple my_tuple = () # [] print(my_tuple, type(my_tuple)) # create a tuple with only one item my_tuple = (1,) print(my_tuple, type(my_tuple)) # create a mix tuple my_tuple = (1,2,'b',3,'c') print(my_tuple) # create a neste...
404df730be3ae60c3e7de349dbc4914e53babb34
edu-athensoft/ceit4101python
/stem1400_modules/module_2_basics/c8_operators/c8_6_assignment/operator_assignment.py
84
4.125
4
# assignment operator # = x = 5 x += 5 # x = x + 5 print(x) x -= 5 print(x)
9ba6f0b0303c1287bfc28a289e4afe878b85cd34
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo1_super_single/super_init_2c.py
736
4.375
4
""" super and init child overrides init() of parent and use its own init() child has its own property: age parent has a property: name child cannot inherit parent's property due to overriding, properties defined in parent do not take effect to child. """ class Parent: def __init__(self, name): print('P...
ba671e89c9244cd5969667d0f9aca6bec71a825d
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_09_inheritance/s10_super/demo1_super_single/super_init_2e.py
672
4.21875
4
""" super and init child overrides init() of parent and use its own init() child has its own property: age parent has a property: name child inherit parent's property by super(), child init() must accept all parameters the order of parameter matters """ class Parent: def __init__(self, name): print('P...
6810fd51b20b0958e2647e6c181e43700117f700
edu-athensoft/ceit4101python
/mytest/s2e_string/stringreplace.py
73
3.8125
4
s = "Athensoft Learning" s= s.replace("Athensoft","ATHENSOFT") print(s)
ce96efd0da7f5e01a2e37b056b17a8c50182c409
edu-athensoft/ceit4101python
/stem1471_projects/p00_file_csv_processor_8/get_lineno_by_firstfield.py
362
3.640625
4
""" get line no by first field """ import csv search_value = '1' search_value = '2' line_number = None with open('data/input.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') for i, row in enumerate(reader): if row[0] == search_value: line_number = i...
aaba8ca8136fbb564b3c3a6869e57ec0be0b0fbf
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_1_capitalize.py
761
4.46875
4
""" string method - capitalize() string.capitalize() return a new string """ # case 1. capitalize a sentence str1 = "pyThOn is AWesome." result = str1.capitalize() print(f"old string: {str1}") print(f"new string: {result}") print() # case 2. capitalize two sentence str1 = "pyThOn is AWesome. pyThOn is AWesome." ...
e43a4bdd09eb0f178c0ddcf0b9fc446739e2a6f1
edu-athensoft/ceit4101python
/stem1400_modules/module_4_function/func2_recursive/recursive_problem_03_c.py
581
3.921875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Fibonacci sequence 0,1,1,2,3,5,8,13,21,... Input n and get the sequence up to the n-th number key point: f(n)=f(n-2)+f(n-1) when n>2 f(1) = 0 f(2) = 1 """ # iteration def fib(n): a, b = 0, 1 fib_numbers = [] for i in range(n): # a, b = b, a + b ...
e8beb53f159933978745cec0d453798992e3c514
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_11_classmember/s01_class_attribute/demo_4_add_property.py
482
4.25
4
""" adding properties by assignment """ class Tool: count = 0 def __init__(self, name): self.name = name Tool.count += 1 # test tool1 = Tool("hammer") print(f'{tool1.count} tool(s) is(are) created.') print() tool1.count = 99 print(f'The instance tool1 has extra property: count') print(f'{t...
9ba15f7081621f42d5b7cef12d977fcf28e6e8bd
edu-athensoft/ceit4101python
/stem1500_modules/module_19_concurrent/multiprocessing/multiprocessing_4.py
459
3.5625
4
""" multiprocessing process process class """ import multiprocessing as mp import time class ClockProcess(mp.Process): def __init__(self, interval): mp.Process.__init__(self) self.interval = interval def run(self): n = 5 while n > 0: print("the time is {0}".format...
c958faae61b8d8a3f1a85cba789bbf87d87a1388
edu-athensoft/ceit4101python
/stem1400_modules/module_6_datatype/m6_7_array/array_2_add_2.py
347
4.34375
4
""" Python array Adding Elements to a Array append() extend() source: """ import array as arr numbers = arr.array('i', [1, 2, 3]) numbers.append(4) print(numbers) # Output: array('i', [1, 2, 3, 4]) # extend() appends iterable to the end of the array numbers.extend([5, 6, 7]) print(numbers) # Output: array('...
8d6e55411ed6611fd652b0fcba151a3c4a08a3df
edu-athensoft/ceit4101python
/evaluate/evaluate_3_project/python2_intermediate/minicalculator/project_calculator_v2.py
4,336
4.3125
4
""" project: calculator version 2. step 1. allow to do the calculation for infinite times step 2. set a condition for terminating the loop option 1. to input 'q' or 'quit' to stop the loop or exit the program option 2. to input a number other than 1-10 to exit the program """ def add(x, y): return x+y def subt...
25db0c94feb3cc48451091d4b538a15d074f5adb
edu-athensoft/ceit4101python
/stem1400_modules/module_12_oop/oop_09_inheritance/s3_inherit_single/zoo_1_baseclass.py
390
3.84375
4
""" OOP - inheritance Animals v1. Parent class only """ class Animal: def eat(self): print("Animal eats.") def drink(self): print("Animal drinks.") def run(self): print("Animal runs.") def sleep(self): print("Animal sleeps.") # client app, main creature1 = Animal() ...
8eba7a6bc69d83f63b823ae9adb9a0e9ef3511ed
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0406_scale/scale_02.py
793
3.921875
4
""" Scale usage of Scale binding a variable change a value via variable get a value set a value """ from tkinter import * # here source is mandantory def changeNum(source): print("change value to",var1.get()) def getNum(): print("get value ",var1.get()) def setNum(): var1.set(5) print("set value ...
4a5ca15f00ebf97484032636a9bf7a10458bc914
edu-athensoft/ceit4101python
/stem1400_modules/module_10_gui/s04_widgets/s0401_label/label_1_create.py
342
4.3125
4
""" Tkinter place a label widget Label(parent_object, options,...) using pack() layout ref: #1 """ from tkinter import * root = Tk() root.title('Python GUI - Text Label') root.geometry("{}x{}+200+240".format(640, 480)) # create a label widget label1 = Label(root, text='Tkinter Label') # show on screen label1.pa...
470d8c6ae00263ac59ec5a350bbc0eac9960bb9b
edu-athensoft/ceit4101python
/evaluate/evaluate_2_quiz/stem1401_python1/quiz_m283.py
170
3.828125
4
""" Python 1. Quiz M283 """ # 5 a = True b = False print(not a) print(not b) # 6 print(not not a) print(not a and b, not (a and b)) print(not b or a, not (b or a))
dd1b7f436a1d5b62a802cdc048ec6f4e9cb51eff
edu-athensoft/ceit4101python
/stem1500_modules/module_19_concurrent/multiprocessing/multiprocessing_1.py
476
3.515625
4
""" multiprocessing process multicore """ import multiprocessing as mp import time def job(x, y): print("multiprocessing job") time.sleep(10) # it is necessary to place main logic into if-main-body if __name__ == '__main__': # check at task manager # related tasks appeared when the process get star...