blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
6587705a15a43d121ada8b53d580f45b36d1e2c8
eronekogin/leetcode
/2023/maximum_ascending_subarray_sum.py
439
3.546875
4
""" https://leetcode.com/problems/maximum-ascending-subarray-sum/ """ class Solution: def maxAscendingSum(self, nums: list[int]) -> int: i, n = 0, len(nums) maxSum = 0 while i < n: currMax = nums[i] while i + 1 < n and nums[i + 1] > nums[i]: i += 1 currMax += nums[i] maxSum = max(maxSum, currMax) i += 1 return maxSum
c4b51157af0a2f83dbb36fbf9d2b45872a6377f5
artificially-ai/nltk_tutorial
/src/hello_nltk.py
2,837
4.03125
4
""" Organisation: ekholabs Author: wilder.rodrigues@ekholabs.ai """ ''' Understand the context of a text. concordance() - Displays all occurrences of a word along with the contexy. similar() - Returns a list of words that appear in similar context - usually synonyms. common_context() - Returns context shared by two words. dispersion_plot() - Prints a plot of all the occurrences of the words relative to the beginning of the text. Processing text sent_tokenize(), word_tokenize() - Tokenize text into lists of sentences (or) lists of words. stopwords.words() - Get a list of stopwords (e.g. the, an, a) commonly occurring words. bigrams(), ngrams() - Generate bigrams (pairs of words) or n-grams (groups of n-words) for a sentence or a text. collocations() - Find the most commonly occurring bigrams. E.g. New York is a collocation because it most commonly comes together. ''' # It is not advisable to download all corpora. Instead, try nltk.download('book_name') # or from nltk.corpus import gutenberg (for instance). # When downloading everything, if any book is missing, you will get an error and should try # to download manually by executing: nltk.download('book_name'). After that, the import * should work. #from nltk.book import * from nltk.book import text1, text2 def find_occurrences(book, word = 'monstrous'): # Returns occurrences with some context. print('\n','Word occurrences on', book.name, '\n') print(book.concordance(word), '\n') def find_similar_words(book, word = 'monstrous'): # Returns a list of words appearing in the context of 'word' print('\n','Words in similar context on', book.name, '\n') print(book.similar(word), '\n') def find_common_context(book, word1 = 'monstrous', word2 = 'very'): # Returns the context where two words appear. print('\n','Contexts wher two words appear on', book.name, '\n') print(book.common_contexts([word1, word2]), '\n') def plot_changes_in_use_of_words(book, words): # Dispersion plot of the use of natural language in different contexts or situations. For example, # the use of certain words used by Presidents over the years. book.dispersion_plot(words) if __name__ == '__main__': # Observe the different connotations in the use of the word 'monstrous' by Melville and Austen find_occurrences(text1) find_occurrences(text2) find_similar_words(text1) find_similar_words(text2) # Observe that Melville doesn't use 'monstrous' followed by 'very' find_common_context(text1) # However, observe that Austen does. # This call should return: a_pretty am_glad a_lucky is_pretty be_glad # She uses 'a very pretty' and 'a very monstrous'. find_common_context(text2)
7bc3c03c37cb86d00fc41aa3cbe43fedf00c3991
karanjakhar/python-programs
/ty.py
2,122
4.125
4
print("1.Program to find whether a number is Even or Odd using function") def number(): x=int(input("Enter the Number : ")) if(x%2==0): print("Even Number") else: print("odd Number") number() print("2.Program to Display calculator using function") def cal(): print("1. Add 2.Sub 3.Mul 4.Div ") n=int(input("Enter the choice : ")) if(n==1): a=int(input("Enter the Number :")) b=int(input("Enter the Number :")) c=a+b print("Sum is : ",c) elif(n==2): a=int(input("Enter the Number :")) b=int(input("Enter the Number :")) c=a-b print("Subtraction is : ",c) elif(n==3): a=int(input("Enter the Number :")) b=int(input("Enter the Number :")) c=a*b print("Product is : ",c) elif(n==4): a=int(input("Enter the Number :")) b=int(input("Enter the Number :")) c=a/b print("Division is : ",c) else: print("invalid choice") cal() print("3.Program to swap two numbers using function") def swap(): a=int(input("Enter the first Number: ")) b=int(input("Enter the Second Number: ")) c=a a=b b=c print("FIRST NUMBER: ",a) print("SECOND NUMBER: ",b) swap() print("4.Program to find fibonacci of number using function") def fibbo(): a=int(input("Enter the First Number of series- ")) b=int(input("Enter the Second Number of series- ")) n=int(input("Enter the Number of Terms needed- ")) print(a,b,end =" ") while(n-2): c=a+b a=b b=c print(c,end=" ") n-=1 fibbo() print() print("5.Program to find Palindrome of number using function") def palin(a): c=a; s=0; d=0; while(a!=0): d=a%10; s=(s*10)+d; a=a/10; a=int(a); if(c==s): print("Palindrome"); else: print("Not palindrome") a=int(input("Enter the Number: ")) palin(a);
6f03e6d4331aa5d194dc6281320da6565ac087bd
TypeKazt/CS260
/hw5/make_heap.py
1,050
3.671875
4
#!/usr/bin/env python def left(H, i): result = (i+1)*2 if result > len(H): return None return result - 1 def right(H, i): result = (i+1)*2 if result >= len(H): return None return result def parent(H, i): if i == 1: return None result = int((i+1)/2) return result - 1 def swap(H, nodeA, nodeB): temp = H[nodeA] H[nodeA] = H[nodeB] H[nodeB] = temp def last_in_node(H): return len(H)//2 - 1 def down_heap(H, i): if H == None: return False child = left(H, i) if child == None: return True r = right(H, i) if r != None and H[r] > H[child]: child = r if H[i] > H[child]: return None swap(H, i, child) down_heap(H, child) def make_heap(H): node = last_in_node(H) for i in range(node + 1): down_heap(H, node - i) if __name__ == "__main__": import random import timeit print("n\tT(n)") for i in range(1,7): n = 10 ** i x = [random.randint(0,1000) for i in xrange(n)] time = timeit.Timer('make_heap(x)', 'from __main__ import make_heap,x') delta = time.timeit(1) print str(n) + "\t" + str(delta)
dc7d9ff423e3d6a8fca2463e258e1e4aee826537
Coliverfelt/Desafios_Python
/Desafio039.py
1,066
4.1875
4
# Exercício Python 039: Faça um programa que leia o ano de nascimento de um jovem e informe, # de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, # se é a hora exata de se alistar ou se já passou do tempo do alistamento. # Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. from datetime import date anoNascimento = str(input('Digite o seu ano de nascimento: ')) tamanho = len(anoNascimento) if (int(tamanho) > 4) or (int(tamanho) < 4): print('Não é possível realizar os cálculos com esta quantidade de dígitos.') elif (int(tamanho) == 4): anoNascimento = int(anoNascimento) anoAtual = date.today().year idade = anoAtual - anoNascimento tempoAlista = idade - 18 if idade < 18: print('Você precisará se alistar em {} anos.'.format((tempoAlista * (-1)))) elif idade > 18: print('Seu tempo de alistamento ultrapassou {} anos.'.format(tempoAlista)) elif idade == 18: print('Sua idade ({} anos), é a apropriada para o alistamento.'.format(idade))
72a307fee0909cb767cc94b6de139738e92f9163
mattecora/AmI-Labs
/python-lab1/ex02.py
179
3.875
4
my_str = input("Insert a string: ") my_len = len(my_str) if my_len < 4: print("String too short!") else: print(my_str[0] + my_str[1] + my_str[my_len-2] + my_str[my_len-1])
b2b2d1816132a8ae7fad5de203377ef1cf3fa777
Kalaiselvan1503/Guvi1
/fibonaci_till_n.py
124
3.65625
4
#huhduiofhio n=int(input()) a=1 b=1 print(1,1,end=" ") while(n-2): c=a+b a=b b=c print(c,end=" ") n=n-1
97321458b6e591457dab39c96319bfb93b5abd7f
igorvalamiel/material-python
/Exercícios - Mundo 1/013.py
176
3.671875
4
x = float(input('Digite o seu salário:')) p = (15 / 100) * x a = x + p print('Se seu chefe te premiasse com um aumento de 15%, o seu salário seria de {} reais.'.format(a))
7097e8e4f67363d584b1e94bfa40f000dcb132ce
larryokubasu5460/Algorithms
/brute force/bubble sort.py
342
4.25
4
def bubble_sort(array): for i in range(len(array)-1): index=i for j in range(i+1,len(array)): if array[index]>=array[j]: array[index], array[j]=array[j],array[index] array=[100,234,45,3,67,895,32,4,8,67,3,2,4,67,841,34,6] print("array ",array) bubble_sort(array) print("Sorted array", array)
4902fae3babb5b92a207ad45786e12c7014023a1
gituser182/PythonFiles
/TestCode/Reversing.py
418
3.6875
4
#test reverse print ('...Inversing a string...') message = input('Typ een bericht:') translated = '' i = len(message) - 1 #-1: telt vanaf nul! Eerste element staat op message[0] print('lengte bericht = ', len(message)) while i >=0: print ('bericht[', i ,']', message[i]) translated = translated + message[i] i = i-1 print ('nieuwe waarde van i=',i) print (message, ' achterstevoren = ',translated)
85b8e65cdec6313ead22529a193bd3177060450e
Elsabalabala/LearnGit
/nwmath.py
420
3.71875
4
#!usr/bin/env python #coding=utf-8 def add(a, b): return a + b def subtract(a, b): if isinstance(a,int) and isinstance(b,int): return a - b else: return "error input" def multiply(a, b): return a * b def divide(numerator, denominator): if denominator!=0 and isinstance(denominator,int): return float(numerator) / denominator else: return "wrong input"
7a47f38a8939f15871306f5090248b4e4e32912b
iordanistavridis/-
/ergasia1.py
1,133
3.53125
4
from random import shuffle measurement = input("Enter the size of the square:") measurement = int(measurement) list1 = [] x = measurement/2 pl = int(x) rest = measurement-pl count=0 for v in range(100): for j in range(measurement): examplelist = [] examplelist = [0] * rest + [1] * pl shuffle(examplelist) list1.append(examplelist) for i in range(measurement): for j in range(measurement): if j <= measurement-4: if list1[i][j]==1 and list1[i][j+1]==1 and list1[i][j+2]==1 and list1[i][j+3]==1: count = count + 1 if i <= measurement-4: if list1[i][j]==1 and list1[i+1][j]==1 and list1[i+2][j]==1 and list1[i+3][j]==1: count = count + 1 if i <= measurement-4 and j <= measurement-4: if list1[i][j] == 1 and list1[i+1][j+1] == 1 and list1[i+2][j+2] == 1 and list1[i+3][j+3] == 1: count = count + 1 if i <= measurement-4 and j >= measurement-4: if list1[i][j] == 1 and list1[i+1][j-1] == 1 and list1[i+2][j-2] == 1 and list1[i+3][j-3] == 1: count = count + 1 print ("the average number of groups is:") print (count/100)
1dccd108be9057d4d28a3cec2e17565f87179bfb
aiaurora/hy
/hy.py
302
3.71875
4
name=input("姓名:") print('嗨!',name) a = int(input('今天有沒有下雨? 0:無,1:有' )) if a == 1: print('留在家裡吧!') elif a == 0: print('出去玩吧!') else : print('???') b = float(input('今天氣溫攝氏幾度?')) b = b * 9 / 5 + 32 print('華氏:', b, '度')
5b027cc5029f8c1895298db12fc3f6ec0d2c4ba8
hongliang5623/vanyar
/script/sort/quick_sort.py
2,687
3.625
4
# -*- coding: utf-8 -*- def QuickSort(arr,firstIndex,lastIndex): if firstIndex<lastIndex: divIndex = Partition(arr,firstIndex,lastIndex) print divIndex QuickSort(arr, firstIndex, divIndex) QuickSort(arr,divIndex+1,lastIndex) else: return def Partition(arr,firstIndex,lastIndex): print arr i=firstIndex-1 for j in range(firstIndex,lastIndex): if arr[j]<=arr[lastIndex]: i=i+1 arr[i],arr[j]=arr[j],arr[i] arr[i+1],arr[lastIndex]=arr[lastIndex],arr[i+1] return i arr=[1,4,7,1,5,5,3,85,34,75,23,75,2,0] print("initial array:\n",arr) QuickSort(arr,0,len(arr)-1) print("result array:\n",arr) def QuickSort(myList, start, end): #判断low是否小于high,如果为false,直接返回 if start < end: i, j = start, end #设置基准数 base = myList[i] while i < j: #如果列表后边的数,比基准数大或相等,则前移一位直到有比基准数小的数出现 while (i < j) and (myList[j] >= base): j = j - 1 #如找到,则把第j个元素赋值给第个元素i,此时表中第i,j个元素相等 myList[i] = myList[j] #同样的方式比较前半区 while (i < j) and (myList[i] <= base): i = i + 1 myList[j] = myList[i] #做完第一轮比较之后,列表被分成了两个半区,并且i=j,需要将这个数设置回base myList[i] = base print myList #递归前后半区 QuickSort(myList, start, i - 1) QuickSort(myList, j + 1, end) return myList myList = [49,38,65,97,76,13,27,49] print 'init array', myList print("Quick Sort: ") QuickSort(myList,0,len(myList)-1) print(myList) def hh(): ''' 快速排序基本思想是: 通过一趟排序将要排序的数据分割成独立的两部分, 其中一部分的所有数据都比另外一部分的所有数据都要小, 然后再按此方法对这两部分数据分别进行快速排序, 整个排序过程可以递归进行,以此达到整个数据变成有序序列。 如序列[6,8,1,4,3,9], 选择6作为基准数。 从右向左扫描,寻找比基准数小的数字为3,交换6和3的位置,[3,8,1,4,6,9], 接着从左向右扫描,寻找比基准数大的数字为8,交换6和8的位置,[3,6,1,4,8,9]。 重复上述过程,直到基准数左边的数字都比其小,右边的数字都比其大。 然后分别对基准数左边和右边的序列递归进行上述方法 ''' return 'success'
941d2f5a9dd8c68fd172d8cbb623427f3fa91fc0
mleef/PSS
/scripts/line_breaks.py
423
3.5
4
# Helper script to add line breaks between newly concatenated FASTA file. import sys def addLineBreaks(file): f = open(file, 'r+').read() # For every sequence, insert a line break before it out = f.replace(">", "\n>") print(out) def main(argv = sys.argv): f1 = argv[1] addLineBreaks(f1) if __name__ == "__main__": try: main(sys.argv) except KeyboardInterrupt: pass
d47d5227a23921efbb42201b4a887fd42bff53ee
AndrewDunham/BasicPython
/getIcalDetails.py
314
3.515625
4
file = open(inputFile,"r") #Read each line and split them into the type and details lines = file.readlines() for line in lines: #Get the line type and details of each line lineType = line.split(':')[0] lineDetails = line.split(':')[1] lineDetails = lineDetails.rstrip()
566bc6c5e45bc43c7d7448afd29304c7fd8321ab
danelia1998/pycharm-projects
/checkerr.py
918
3.734375
4
def method_friendly_decorator(method_to_decorate): def wrapper(self, lie, datvirtva): if datvirtva == 100: print("luci must take {} dollars".format(100)) elif 100 > datvirtva >= 80: print("luci must take {} dollars".format(80)) elif 80 > datvirtva >= 60: print("luci must take {} dollars".format(60)) elif 60 > datvirtva >= 40: print("luci must take {} dollars".format(40)) elif 40 > datvirtva >= 20: print("luci must take {} dollars".format(20)) elif 20 > datvirtva >= 0: print("luci must take {} dollars".format(0)) lie -= 3 return method_to_decorate(self, lie, datvirtva) return wrapper class lucy: def __init__(self): self.age = 32 @method_friendly_decorator def sayYourAge(self, lie, datvirtva): print() l = lucy() l.sayYourAge(-3, 80)
c5a802d24b8a8da2e75503f071dad2b1de5fbeed
whitej9406/cti110
/P3LAB_White .py
697
4.15625
4
# CTI-110 # P3LAB - Debugging # Jacob White # 10/4/2018 # This program takes numeric grade input and outputs the letter grade. def main(): # system uses 10-point grading scale # Define scores A_score = 90 B_score = 80 C_score = 70 D_score = 60 # user input score = input('Enter grade: ') # display output if score >= A_score: print('Your grade is: A') elif score >= B_score: print('Your grade is: B') elif score >= C_score: print('Your grade is: C') elif score >= D_score: print('Your grade is: D') else: print('Your grade is: F') # program start main()
50f516d0cc49c2e3bf247270f826b201dd3033cf
LukeOsburn/K-Nearest-Neighbours-Explained-Simply
/KNearestNeighboursCalculatingTheSkilloftheModel.py
3,104
3.53125
4
import numpy as np from sklearn import cross_validation import pandas as pd from math import sqrt from collections import Counter import matplotlib.pyplot as plt from operator import itemgetter #Lets predict the class for the test data and compare with actual and calculate the percentage of succcesful predictions #lets read our data into a nice dataframe df=pd.read_csv("breastdata.txt") #lets replace missing values with a more recognised value df=df.replace('?',-99999) #many alogirthims recognise -99999 as an outlier #lets drop id, it is of no value df=df.drop(['id'],1) #lets do a simple 2 dimensional example #Full=np.array(df.drop(['clump_thickness','unif_cell_size','class','unif_cell_shape','marg_adhesion','single_epith_cell_size','bare_nuclei','bland_chrom','norm_nucleoli','mitoses'],1)) #drop all except 2, any 2, so we can visualise the algorithim #lets turn into numpy arrays X = np.array(df.drop(['class','unif_cell_shape','marg_adhesion','single_epith_cell_size','bare_nuclei','bland_chrom','norm_nucleoli','mitoses'],1)) #this is our output, benign or malignant #lets turn into numpy arrays y = np.array(df['class']) #randomly split the data into a training and test sets #we will use the training test to "predict" benign or malignant from the test set X_train, X_test, y_train, y_test=cross_validation.train_test_split(X,y,test_size=0.2) #lets only take 20 data points for training, so we can visualise the results more easily #X_train=X_train[0:40] #y_train= y_train[0:40] k=3 #number of neighbours #okay, lets test all data points in our test conditions and calculate the success of the model successes=0.0 fails=0.0 count=-1 for i in X_test: distances=[] count=count+1 count2=-1 for ii in X_train: count2=count2+1 #this calculated the distance to each point in the training set in turn dist=sqrt(((i[0]-ii[0])**2 +(i[1]-ii[1])**2)) #this is a list of lists of distances to each point and benign/malignant class distances.append([float(dist),float(y_train[count2])]) #this sorts our list of lists by distance while preserving the benign/malignant class dist=sorted(distances, key=itemgetter(0)) sortedT=map(list, zip(*dist)) #this selects the first k members with the shortest distances Votes=sortedT[1][0:k] #this prints the most common class (benign/malignant and the number) #print(Counter(Votes).most_common(1)) print("Data Point") print(i) print("Actual value") print(y_test[count]) print("Predicted value") #this returns the most common class (benign/malignant and the number) predicted=Counter(Votes).most_common(1)[0][0] print(predicted) if predicted==y_test[count]: successes=successes+1 print("Success") else: fails=fails+1 print("Fail") print(y_test) skill=(round((successes/(successes+fails)),2))*100 print(successes/(successes+fails)) print("%s percent of the tumors were predicted correctly" %(skill))
ef73dec02c04e1b7d3aea00dcb21a309ccfc3cce
jannejaago/prog_alused
/3/yl3.1.py
115
3.8125
4
kord = int(input("Sisestage mitu korda äratada: ")) while kord >= 1: print("Tõuse ja sära!") kord -= 1
c8710f2df1a2a0b886e8d9f56ebe5cad6554f781
ChinmayaKinnarkar/Python
/python-numerical-computing-with-numpy.py
28,044
4.3125
4
#!/usr/bin/env python # coding: utf-8 # # Numerical Computing with Python and Numpy # # ![](https://i.imgur.com/mg8O3kd.png) # # ### Part 6 of "Data Analysis with Python: Zero to Pandas" # # # This tutorial series is a beginner-friendly introduction to programming and data analysis using the Python programming language. These tutorials take a practical and coding-focused approach. The best way to learn the material is to execute the code and experiment with it yourself. Check out the full series here: # # 1. [First Steps with Python and Jupyter](https://jovian.ai/aakashns/first-steps-with-python) # 2. [A Quick Tour of Variables and Data Types](https://jovian.ai/aakashns/python-variables-and-data-types) # 3. [Branching using Conditional Statements and Loops](https://jovian.ai/aakashns/python-branching-and-loops) # 4. [Writing Reusable Code Using Functions](https://jovian.ai/aakashns/python-functions-and-scope) # 5. [Reading from and Writing to Files](https://jovian.ai/aakashns/python-os-and-filesystem) # 6. [Numerical Computing with Python and Numpy](https://jovian.ai/aakashns/python-numerical-computing-with-numpy) # 7. [Analyzing Tabular Data using Pandas](https://jovian.ai/aakashns/python-pandas-data-analysis) # 8. [Data Visualization using Matplotlib & Seaborn](https://jovian.ai/aakashns/python-matplotlib-data-visualization) # 9. [Exploratory Data Analysis - A Case Study](https://jovian.ai/aakashns/python-eda-stackoverflow-survey) # # This tutorial covers the following topics: # # - Working with numerical data in Python # - Going from Python lists to Numpy arrays # - Multi-dimensional Numpy arrays and their benefits # - Array operations, broadcasting, indexing, and slicing # - Working with CSV data files using Numpy # ### How to run the code # # This tutorial is an executable [Jupyter notebook](https://jupyter.org) hosted on [Jovian](https://www.jovian.ai). You can _run_ this tutorial and experiment with the code examples in a couple of ways: *using free online resources* (recommended) or *on your computer*. # # #### Option 1: Running using free online resources (1-click, recommended) # # The easiest way to start executing the code is to click the **Run** button at the top of this page and select **Run on Binder**. You can also select "Run on Colab" or "Run on Kaggle", but you'll need to create an account on [Google Colab](https://colab.research.google.com) or [Kaggle](https://kaggle.com) to use these platforms. # # # #### Option 2: Running on your computer locally # # To run the code on your computer locally, you'll need to set up [Python](https://www.python.org), download the notebook and install the required libraries. We recommend using the [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/) distribution of Python. Click the **Run** button at the top of this page, select the **Run Locally** option, and follow the instructions. # # > **Jupyter Notebooks**: This tutorial is a [Jupyter notebook](https://jupyter.org) - a document made of _cells_. Each cell can contain code written in Python or explanations in plain English. You can execute code cells and view the results, e.g., numbers, messages, graphs, tables, files, etc., instantly within the notebook. Jupyter is a powerful platform for experimentation and analysis. Don't be afraid to mess around with the code & break things - you'll learn a lot by encountering and fixing errors. You can use the "Kernel > Restart & Clear Output" menu option to clear all outputs and start again from the top. # ## Working with numerical data # # The "data" in *Data Analysis* typically refers to numerical data, e.g., stock prices, sales figures, sensor measurements, sports scores, database tables, etc. The [Numpy](https://numpy.org) library provides specialized data structures, functions, and other tools for numerical computing in Python. Let's work through an example to see why & how to use Numpy for working with numerical data. # # # > Suppose we want to use climate data like the temperature, rainfall, and humidity to determine if a region is well suited for growing apples. A simple approach for doing this would be to formulate the relationship between the annual yield of apples (tons per hectare) and the climatic conditions like the average temperature (in degrees Fahrenheit), rainfall (in millimeters) & average relative humidity (in percentage) as a linear equation. # > # > `yield_of_apples = w1 * temperature + w2 * rainfall + w3 * humidity` # # We're expressing the yield of apples as a weighted sum of the temperature, rainfall, and humidity. This equation is an approximation since the actual relationship may not necessarily be linear, and there may be other factors involved. But a simple linear model like this often works well in practice. # # Based on some statical analysis of historical data, we might come up with reasonable values for the weights `w1`, `w2`, and `w3`. Here's an example set of values: # In[1]: w1, w2, w3 = 0.3, 0.2, 0.5 # Given some climate data for a region, we can now predict the yield of apples. Here's some sample data: # # <img src="https://i.imgur.com/TXPBiqv.png" style="width:360px;"> # # To begin, we can define some variables to record climate data for a region. # In[2]: kanto_temp = 73 kanto_rainfall = 67 kanto_humidity = 43 # We can now substitute these variables into the linear equation to predict the yield of apples. # In[3]: kanto_yield_apples = kanto_temp * w1 + kanto_rainfall * w2 + kanto_humidity * w3 kanto_yield_apples # In[4]: print("The expected yield of apples in Kanto region is {} tons per hectare.".format(kanto_yield_apples)) # To make it slightly easier to perform the above computation for multiple regions, we can represent the climate data for each region as a vector, i.e., a list of numbers. # In[5]: kanto = [73, 67, 43] johto = [91, 88, 64] hoenn = [87, 134, 58] sinnoh = [102, 43, 37] unova = [69, 96, 70] # The three numbers in each vector represent the temperature, rainfall, and humidity data, respectively. # # We can also represent the set of weights used in the formula as a vector. # In[6]: weights = [w1, w2, w3] # We can now write a function `crop_yield` to calcuate the yield of apples (or any other crop) given the climate data and the respective weights. # In[7]: def crop_yield(region, weights): result = 0 for x, w in zip(region, weights): result += x * w return result # In[8]: crop_yield(kanto, weights) # In[9]: crop_yield(johto, weights) # In[10]: crop_yield(unova, weights) # ## Going from Python lists to Numpy arrays # # # The calculation performed by the `crop_yield` (element-wise multiplication of two vectors and taking a sum of the results) is also called the *dot product*. Learn more about dot product here: https://www.khanacademy.org/math/linear-algebra/vectors-and-spaces/dot-cross-products/v/vector-dot-product-and-vector-length . # # The Numpy library provides a built-in function to compute the dot product of two vectors. However, we must first convert the lists into Numpy arrays. # # Let's install the Numpy library using the `pip` package manager. # In[11]: get_ipython().system('pip install numpy --upgrade --quiet') # Next, let's import the `numpy` module. It's common practice to import numpy with the alias `np`. # In[12]: import numpy as np # We can now use the `np.array` function to create Numpy arrays. # In[13]: kanto = np.array([73, 67, 43]) # In[14]: kanto # In[15]: weights = np.array([w1, w2, w3]) # In[16]: weights # Numpy arrays have the type `ndarray`. # In[17]: type(kanto) # In[18]: type(weights) # Just like lists, Numpy arrays support the indexing notation `[]`. # In[19]: weights[0] # In[20]: kanto[2] # ## Operating on Numpy arrays # # We can now compute the dot product of the two vectors using the `np.dot` function. # In[21]: np.dot(kanto, weights) # We can achieve the same result with low-level operations supported by Numpy arrays: performing an element-wise multiplication and calculating the resulting numbers' sum. # In[22]: (kanto * weights).sum() # The `*` operator performs an element-wise multiplication of two arrays if they have the same size. The `sum` method calculates the sum of numbers in an array. # In[23]: arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) # In[24]: arr1 * arr2 # In[25]: arr2.sum() # ## Benefits of using Numpy arrays # # Numpy arrays offer the following benefits over Python lists for operating on numerical data: # # - **Ease of use**: You can write small, concise, and intuitive mathematical expressions like `(kanto * weights).sum()` rather than using loops & custom functions like `crop_yield`. # - **Performance**: Numpy operations and functions are implemented internally in C++, which makes them much faster than using Python statements & loops that are interpreted at runtime # # Here's a comparison of dot products performed using Python loops vs. Numpy arrays on two vectors with a million elements each. # In[26]: # Python lists arr1 = list(range(1000000)) arr2 = list(range(1000000, 2000000)) # Numpy arrays arr1_np = np.array(arr1) arr2_np = np.array(arr2) # In[27]: get_ipython().run_cell_magic('time', '', 'result = 0\nfor x1, x2 in zip(arr1, arr2):\n result += x1*x2\nresult') # In[28]: get_ipython().run_cell_magic('time', '', 'np.dot(arr1_np, arr2_np)') # As you can see, using `np.dot` is 100 times faster than using a `for` loop. This makes Numpy especially useful while working with really large datasets with tens of thousands or millions of data points. # # Let's save our work before continuing. # In[29]: import jovian # In[41]: jovian.commit() # In[ ]: # In[ ]: # ## Multi-dimensional Numpy arrays # # We can now go one step further and represent the climate data for all the regions using a single 2-dimensional Numpy array. # In[31]: climate_data = np.array([[73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70]]) # In[32]: climate_data # If you've taken a linear algebra class in high school, you may recognize the above 2-d array as a matrix with five rows and three columns. Each row represents one region, and the columns represent temperature, rainfall, and humidity, respectively. # # Numpy arrays can have any number of dimensions and different lengths along each dimension. We can inspect the length along each dimension using the `.shape` property of an array. # # <img src="https://fgnt.github.io/python_crashkurs_doc/_images/numpy_array_t.png" width="420"> # # # In[33]: # 2D array (matrix) climate_data.shape # In[34]: weights # In[35]: # 1D array (vector) weights.shape # In[37]: # 3D array arr3 = np.array([ [[11, 12, 13], [13, 14, 15]], [[15, 16, 17], [17, 18, 19.5]]]) # In[38]: arr3.shape # All the elements in a numpy array have the same data type. You can check the data type of an array using the `.dtype` property. # In[38]: weights.dtype # In[39]: climate_data.dtype # If an array contains even a single floating point number, all the other elements are also converted to floats. # In[40]: arr3.dtype # We can now compute the predicted yields of apples in all the regions, using a single matrix multiplication between `climate_data` (a 5x3 matrix) and `weights` (a vector of length 3). Here's what it looks like visually: # # <img src="https://i.imgur.com/LJ2WKSI.png" width="240"> # # You can learn about matrices and matrix multiplication by watching the first 3-4 videos of this playlist: https://www.youtube.com/watch?v=xyAuNHPsq-g&list=PLFD0EB975BA0CC1E0&index=1 . # # We can use the `np.matmul` function or the `@` operator to perform matrix multiplication. # In[41]: np.matmul(climate_data, weights) # In[42]: climate_data @ weights # ## Working with CSV data files # # Numpy also provides helper functions reading from & writing to files. Let's download a file `climate.txt`, which contains 10,000 climate measurements (temperature, rainfall & humidity) in the following format: # # # ``` # temperature,rainfall,humidity # 25.00,76.00,99.00 # 39.00,65.00,70.00 # 59.00,45.00,77.00 # 84.00,63.00,38.00 # 66.00,50.00,52.00 # 41.00,94.00,77.00 # 91.00,57.00,96.00 # 49.00,96.00,99.00 # 67.00,20.00,28.00 # ... # ``` # # This format of storing data is known as *comma-separated values* or CSV. # # > **CSVs**: A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. A CSV file typically stores tabular data (numbers and text) in plain text, in which case each line will have the same number of fields. (Wikipedia) # # # To read this file into a numpy array, we can use the `genfromtxt` function. # In[43]: import urllib.request urllib.request.urlretrieve( 'https://hub.jovian.ml/wp-content/uploads/2020/08/climate.csv', 'climate.txt') # In[44]: climate_data = np.genfromtxt('climate.txt', delimiter=',', skip_header=1) # In[45]: climate_data # In[46]: climate_data.shape # We can now perform a matrix multiplication using the `@` operator to predict the yield of apples for the entire dataset using a given set of weights. # In[47]: weights = np.array([0.3, 0.2, 0.5]) # In[48]: yields = climate_data @ weights # In[49]: yields # In[50]: yields.shape # Let's add the `yields` to `climate_data` as a fourth column using the [`np.concatenate`](https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html) function. # In[51]: climate_results = np.concatenate((climate_data, yields.reshape(10000, 1)), axis=1) # In[52]: climate_results # There are a couple of subtleties here: # # * Since we wish to add new columns, we pass the argument `axis=1` to `np.concatenate`. The `axis` argument specifies the dimension for concatenation. # # * The arrays should have the same number of dimensions, and the same length along each except the dimension used for concatenation. We use the [`np.reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) function to change the shape of `yields` from `(10000,)` to `(10000,1)`. # # Here's a visual explanation of `np.concatenate` along `axis=1` (can you guess what `axis=0` results in?): # # <img src="https://www.w3resource.com/w3r_images/python-numpy-image-exercise-58.png" width="300"> # # The best way to understand what a Numpy function does is to experiment with it and read the documentation to learn about its arguments & return values. Use the cells below to experiment with `np.concatenate` and `np.reshape`. # In[ ]: # In[ ]: # In[ ]: # Let's write the final results from our computation above back to a file using the `np.savetxt` function. # In[53]: climate_results # In[54]: np.savetxt('climate_results.txt', climate_results, fmt='%.2f', delimiter=',', header='temperature,rainfall,humidity,yeild_apples', comments='') # The results are written back in the CSV format to the file `climate_results.txt`. # # ``` # temperature,rainfall,humidity,yeild_apples # 25.00,76.00,99.00,72.20 # 39.00,65.00,70.00,59.70 # 59.00,45.00,77.00,65.20 # 84.00,63.00,38.00,56.80 # ... # ``` # # # Numpy provides hundreds of functions for performing operations on arrays. Here are some commonly used functions: # # # * Mathematics: `np.sum`, `np.exp`, `np.round`, arithemtic operators # * Array manipulation: `np.reshape`, `np.stack`, `np.concatenate`, `np.split` # * Linear Algebra: `np.matmul`, `np.dot`, `np.transpose`, `np.eigvals` # * Statistics: `np.mean`, `np.median`, `np.std`, `np.max` # # > **How to find the function you need?** The easiest way to find the right function for a specific operation or use-case is to do a web search. For instance, searching for "How to join numpy arrays" leads to [this tutorial on array concatenation](https://cmdlinetips.com/2018/04/how-to-concatenate-arrays-in-numpy/). # # You can find a full list of array functions here: https://numpy.org/doc/stable/reference/routines.html # ### Save and upload your notebook # # Whether you're running this Jupyter notebook online or on your computer, it's essential to save your work from time to time. You can continue working on a saved notebook later or share it with friends and colleagues to let them execute your code. [Jovian](https://www.jovian.ai) offers an easy way of saving and sharing your Jupyter notebooks online. # In[55]: # Install the library get_ipython().system('pip install jovian --upgrade --quiet') # In[56]: import jovian # In[57]: jovian.commit() # The first time you run `jovian.commit`, you'll be asked to provide an API Key to securely upload the notebook to your Jovian account. You can get the API key from your [Jovian profile page](https://jovian.ai) after logging in / signing up. # # # `jovian.commit` uploads the notebook to your Jovian account, captures the Python environment, and creates a shareable link for your notebook, as shown above. You can use this link to share your work and let anyone (including you) run your notebooks and reproduce your work. # ## Arithmetic operations, broadcasting and comparison # # Numpy arrays support arithmetic operators like `+`, `-`, `*`, etc. You can perform an arithmetic operation with a single number (also called scalar) or with another array of the same shape. Operators make it easy to write mathematical expressions with multi-dimensional arrays. # In[58]: arr2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3]]) # In[59]: arr3 = np.array([[11, 12, 13, 14], [15, 16, 17, 18], [19, 11, 12, 13]]) # In[60]: # Adding a scalar arr2 + 3 # In[61]: # Element-wise subtraction arr3 - arr2 # In[62]: # Division by scalar arr2 / 2 # In[63]: # Element-wise multiplication arr2 * arr3 # In[64]: # Modulus with scalar arr2 % 4 # ### Array Broadcasting # # Numpy arrays also support *broadcasting*, allowing arithmetic operations between two arrays with different numbers of dimensions but compatible shapes. Let's look at an example to see how it works. # In[65]: arr2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3]]) # In[66]: arr2.shape # In[67]: arr4 = np.array([4, 5, 6, 7]) # In[68]: arr4.shape # In[69]: arr2 + arr4 # When the expression `arr2 + arr4` is evaluated, `arr4` (which has the shape `(4,)`) is replicated three times to match the shape `(3, 4)` of `arr2`. Numpy performs the replication without actually creating three copies of the smaller dimension array, thus improving performance and using lower memory. # # <img src="https://jakevdp.github.io/PythonDataScienceHandbook/figures/02.05-broadcasting.png" width="360"> # # Broadcasting only works if one of the arrays can be replicated to match the other array's shape. # In[70]: arr5 = np.array([7, 8]) # In[71]: arr5.shape # In[72]: arr2 + arr5 # In the above example, even if `arr5` is replicated three times, it will not match the shape of `arr2`. Hence `arr2 + arr5` cannot be evaluated successfully. Learn more about broadcasting here: https://numpy.org/doc/stable/user/basics.broadcasting.html . # ### Array Comparison # # Numpy arrays also support comparison operations like `==`, `!=`, `>` etc. The result is an array of booleans. # In[73]: arr1 = np.array([[1, 2, 3], [3, 4, 5]]) arr2 = np.array([[2, 2, 3], [1, 2, 5]]) # In[74]: arr1 == arr2 # In[75]: arr1 != arr2 # In[76]: arr1 >= arr2 # In[77]: arr1 < arr2 # Array comparison is frequently used to count the number of equal elements in two arrays using the `sum` method. Remember that `True` evaluates to `1` and `False` evaluates to `0` when booleans are used in arithmetic operations. # In[78]: (arr1 == arr2).sum() # ## Array indexing and slicing # # Numpy extends Python's list indexing notation using `[]` to multiple dimensions in an intuitive fashion. You can provide a comma-separated list of indices or ranges to select a specific element or a subarray (also called a slice) from a Numpy array. # In[79]: arr3 = np.array([ [[11, 12, 13, 14], [13, 14, 15, 19]], [[15, 16, 17, 21], [63, 92, 36, 18]], [[98, 32, 81, 23], [17, 18, 19.5, 43]]]) # In[80]: arr3.shape # In[81]: # Single element arr3[1, 1, 2] # In[82]: # Subarray using ranges arr3[1:, 0:1, :2] # In[83]: # Mixing indices and ranges arr3[1:, 1, 3] # In[84]: # Mixing indices and ranges arr3[1:, 1, :3] # In[85]: # Using fewer indices arr3[1] # In[86]: # Using fewer indices arr3[:2, 1] # In[87]: # Using too many indices arr3[1,3,2,1] # The notation and its results can seem confusing at first, so take your time to experiment and become comfortable with it. Use the cells below to try out some examples of array indexing and slicing, with different combinations of indices and ranges. Here are some more examples demonstrated visually: # # <img src="https://scipy-lectures.org/_images/numpy_indexing.png" width="360"> # In[ ]: # In[ ]: # In[ ]: # In[ ]: # ## Other ways of creating Numpy arrays # # Numpy also provides some handy functions to create arrays of desired shapes with fixed or random values. Check out the [official documentation](https://numpy.org/doc/stable/reference/routines.array-creation.html) or use the `help` function to learn more. # In[88]: # All zeros np.zeros((3, 2)) # In[89]: # All ones np.ones([2, 2, 3]) # In[90]: # Identity matrix np.eye(3) # In[91]: # Random vector np.random.rand(5) # In[92]: # Random matrix np.random.randn(2, 3) # rand vs. randn - what's the difference? # In[93]: # Fixed value np.full([2, 3], 42) # In[94]: # Range with start, end and step np.arange(10, 90, 3) # In[95]: # Equally spaced numbers in a range np.linspace(3, 27, 9) # ### Save and commit # # Let's record a snapshot of our work using `jovian.commit`. # In[96]: # Install the library get_ipython().system('pip install jovian --upgrade --quiet') # In[97]: import jovian # In[ ]: jovian.commit() # ## Exercises # # Try the following exercises to become familiar with Numpy arrays and practice your skills: # # - Assignment on Numpy array functions: https://jovian.ml/aakashns/numpy-array-operations # - (Optional) 100 numpy exercises: https://jovian.ml/aakashns/100-numpy-exercises # # ## Summary and Further Reading # # With this, we complete our discussion of numerical computing with Numpy. We've covered the following topics in this tutorial: # # - Going from Python lists to Numpy arrays # - Operating on Numpy arrays # - Benefits of using Numpy arrays over lists # - Multi-dimensional Numpy arrays # - Working with CSV data files # - Arithmetic operations and broadcasting # - Array indexing and slicing # - Other ways of creating Numpy arrays # # # Check out the following resources for learning more about Numpy: # # - Official tutorial: https://numpy.org/devdocs/user/quickstart.html # - Numpy tutorial on W3Schools: https://www.w3schools.com/python/numpy_intro.asp # - Advanced Numpy (exploring the internals): http://scipy-lectures.org/advanced/advanced_numpy/index.html # # You are ready to move on to the next tutorial: [Analyzing Tabular Data using Pandas](https://jovian.ai/aakashns/python-pandas-data-analysis). # ## Questions for Revision # # Try answering the following questions to test your understanding of the topics covered in this notebook: # # 1. What is a vector? # 2. How do you represent vectors using a Python list? Give an example. # 3. What is a dot product of two vectors? # 4. Write a function to compute the dot product of two vectors. # 5. What is Numpy? # 6. How do you install Numpy? # 7. How do you import the `numpy` module? # 8. What does it mean to import a module with an alias? Give an example. # 9. What is the commonly used alias for `numpy`? # 10. What is a Numpy array? # 11. How do you create a Numpy array? Give an example. # 12. What is the type of Numpy arrays? # 13. How do you access the elements of a Numpy array? # 14. How do you compute the dot product of two vectors using Numpy? # 15. What happens if you try to compute the dot product of two vectors which have different sizes? # 16. How do you compute the element-wise product of two Numpy arrays? # 17. How do you compute the sum of all the elements in a Numpy array? # 18. What are the benefits of using Numpy arrays over Python lists for operating on numerical data? # 19. Why do Numpy array operations have better performance compared to Python functions and loops? # 20. Illustrate the performance difference between Numpy array operations and Python loops using an example. # 21. What are multi-dimensional Numpy arrays? # 22. Illustrate the creation of Numpy arrays with 2, 3, and 4 dimensions. # 23. How do you inspect the number of dimensions and the length along each dimension in a Numpy array? # 24. Can the elements of a Numpy array have different data types? # 25. How do you check the data type of the elements of a Numpy array? # 26. What is the data type of a Numpy array? # 27. What is the difference between a matrix and a 2D Numpy array? # 28. How do you perform matrix multiplication using Numpy? # 29. What is the `@` operator used for in Numpy? # 30. What is the CSV file format? # 31. How do you read data from a CSV file using Numpy? # 32. How do you concatenate two Numpy arrays? # 33. What is the purpose of the `axis` argument of `np.concatenate`? # 34. When are two Numpy arrays compatible for concatenation? # 35. Give an example of two Numpy arrays that can be concatenated. # 36. Give an example of two Numpy arrays that cannot be concatenated. # 37. What is the purpose of the `np.reshape` function? # 38. What does it mean to “reshape” a Numpy array? # 39. How do you write a numpy array into a CSV file? # 40. Give some examples of Numpy functions for performing mathematical operations. # 41. Give some examples of Numpy functions for performing array manipulation. # 42. Give some examples of Numpy functions for performing linear algebra. # 43. Give some examples of Numpy functions for performing statistical operations. # 44. How do you find the right Numpy function for a specific operation or use case? # 45. Where can you see a list of all the Numpy array functions and operations? # 46. What are the arithmetic operators supported by Numpy arrays? Illustrate with examples. # 47. What is array broadcasting? How is it useful? Illustrate with an example. # 48. Give some examples of arrays that are compatible for broadcasting? # 49. Give some examples of arrays that are not compatible for broadcasting? # 50. What are the comparison operators supported by Numpy arrays? Illustrate with examples. # 51. How do you access a specific subarray or slice from a Numpy array? # 52. Illustrate array indexing and slicing in multi-dimensional Numpy arrays with some examples. # 53. How do you create a Numpy array with a given shape containing all zeros? # 54. How do you create a Numpy array with a given shape containing all ones? # 55. How do you create an identity matrix of a given shape? # 56. How do you create a random vector of a given length? # 57. How do you create a Numpy array with a given shape with a fixed value for each element? # 58. How do you create a Numpy array with a given shape containing randomly initialized elements? # 59. What is the difference between `np.random.rand` and `np.random.randn`? Illustrate with examples. # 60. What is the difference between `np.arange` and `np.linspace`? Illustrate with examples. # # In[ ]:
8495e9311f5e23b4bb0ca76993ee1f3edc8ba0ec
Wenbin-Xiao/LeetCode
/code/125.py
548
3.671875
4
# 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 # 说明:本题中,我们将空字符串定义为有效的回文串。 class Solution: def isPalindrome(self, s: str) -> bool: s_temp = "" for i in range(len(s)): if s[i].isdigit() | s[i].isalpha(): s_temp = s_temp + s[i] if s_temp == "": return True if s_temp[::1].upper() == s_temp[::-1].upper(): return True return False
06fe9d9f0fcd8c22d379d0fa2a902a908d855b38
iEuler/leetcode_learn
/q1286.py
2,106
3.78125
4
""" 1286. Iterator for Combination Medium https://leetcode.com/problems/iterator-for-combination/ Design an Iterator class, which has: A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. A function next() that returns the next combination of length combinationLength in lexicographical order. A function hasNext() that returns True if and only if there exists a next combination. Example: CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator. iterator.next(); // returns "ab" iterator.hasNext(); // returns true iterator.next(); // returns "ac" iterator.hasNext(); // returns true iterator.next(); // returns "bc" iterator.hasNext(); // returns false Constraints: 1 <= combinationLength <= characters.length <= 15 There will be at most 10^4 function calls per test. It's guaranteed that all calls of the function next are valid. Accepted 35,249 Submissions 49,782 """ # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext() class CombinationIterator: def __init__(self, characters: str, combinationLength: int): self.chs = characters self.comblen = combinationLength self.totlen = len(self.chs) self.idx = [_ for _ in range(self.comblen)] self.idx[-1] -= 1 def next(self) -> str: k = self.comblen # the digit where the calculation stop propagating while k > 0: k -= 1 self.idx[k] += 1 if self.idx[k] < self.totlen + k + 1 - self.comblen: break for i in range(k+1, self.comblen): self.idx[i] = self.idx[i-1] + 1 return ''.join([self.chs[k] for k in self.idx]) def hasNext(self) -> bool: return self.idx[0] != self.totlen - self.comblen s = 'abc' l = 2 x = CombinationIterator(s, l) print(x.next()) print(x.hasNext()) print(x.next()) print(x.hasNext()) print(x.next()) print(x.hasNext())
b6a6d6fa0c4b72f7629031f607dbdc1f4e30d016
weihsuanchou/algorithm_py
/counterfeit.py
3,174
3.75
4
#AVG190500T # Hello World program in Python #1: reqirement first 3 eng_chars, upper and distinct #2: reqirement year 1900~2019 #3: reqirement index faceamount before last letter #4: reqirement after faceamount must be a len=1 eng_char serialNumber = ["AVG190420T", "RTF20001000Z","QWER201850G","AAA2019100B","QWER201850GH"] ###### From Here OK _3_chars_valid = True year_valid = True facemount_valid = True last_char_valid = True valid_amount_set = ["10","20", "50", "100", "200","500", "1000"] #1 check cahr #2 check year #3 check faceamount def get_index_of_digit(string): index = 0 for c in string: if c.isdigit(): break; index +=1 return index def is_distinct(string): char_map = [False] * 128 for i in string: ascii_val = ord(i) if char_map[ascii_val]: return False char_map[ascii_val] = True return True def get_year(s_num, first_index_of_digits): index_of_year = first_index_of_digits+4 if index_of_year > len(s_num): return 0 year_string = s_num[first_index_of_digits:first_index_of_digits+4] year_val = int(year_string) if year_string.isdigit() else 0 return year_val def get_amt_string(s_num, index_of_amt_start): index_of_amt_end = len(s_num)-1 if index_of_amt_end <= index_of_amt_start: facemount_valid=False return "0" return s_num[index_of_amt_start:index_of_amt_end] def get_faceamount(s_num): serialnum_len = len(s_num) first_index_of_digits = get_index_of_digit(s_num) if serialnum_len <= 9 or serialnum_len > 12: return 0 if first_index_of_digits != 3: #the first indext of digit must be 3 _3_chars_valid = False return 0 if s_num[0:3].isupper()==False: #First 3 chars must be upper letter _3_chars_valid = False return 0 if is_distinct(s_num[0:3])==False: #First 3 chars must be distinct letter _3_chars_valid = False return 0 if s_num[-2].isalpha() or (not (s_num[-1].isalpha())): #only last digits can be alpha last_char_valid = False return 0 year_val = get_year(s_num, first_index_of_digits) if not (year_val >= 1900 and year_val <=2019): year_valid = False return 0 #finally get faceamount , end of year index till s_num -1 index_of_amt_start = first_index_of_digits+4 amt_string = get_amt_string(s_num, index_of_amt_start) if not amt_string in valid_amount_set: facemount_valid=False return 0 amt_val = int(amt_string) if amt_string.isdigit() else 0 return amt_val def countCounterfeit(serialNumber): sum = 0 for i in serialNumber: sum += get_faceamount(i) return sum ###### To a: serialNumber = ["AVG190420T", "RTF20001000Z","QWER201850G","AAA2019100B","QWER201850GH"] # print("ans", get_faceamount("RFV201111T")) print("ans", get_faceamount()) # print("ans", get_faceamount(serialNumber[2])) # print("ans", get_faceamount(serialNumber[3])) # print("ans", get_faceamount(serialNumber[4])) serialNumber2 = ["QDB2012R20B", "RED190250E","RFV201111T","TYU20121000E","AAA198710B", "Abc200010E"] sum = 0 # for i in serialNumber2: # print("ans", get_faceamount(i)) # sum += get_faceamount(i) # print(sum)
eb4535d30b54c529181b4e30fedec00dd76b0845
sagnikghoshcr7/DSA-AlgoExpert-Practice_Solutions
/Dynamic Programming/maxSubsetSumNoAdjacent.py
1,112
3.671875
4
""" Maximum Subset Sum With No Adjacent Elements Write a function that takes in an array of positive integers and returns an integer representing the maximum sum of non-adjacent elements in the array. If a sum cannot be generated, the function should return 0. Sample input: [75, 105, 120, 75, 90, 135] Sample output: 330 (75, 120, 135) """ # SOLUTION 1 # O(n) time | O(n) space def maxSubsetSumNoAdjacent1(array): if not len(array): return 0 elif len(array) == 1: return array[0] maxSums = array[:] maxSums[1] = max(array[0], array[1]) for i in range(2, len(array)): maxSums[i] = max(maxSums[i-1], maxSums[i-2] + array[i]) return maxSums[-1] # SOLUTION 2 # O(n) time | O(1) space def maxSubsetSumNoAdjacent2(array): if not len(array): return 0 elif len(array) == 1: return array[0] second = array[0] first = max(array[0], array[1]) for i in range(2, len(array)): current = max(first, second + array[i]) second = first first = current return first
410102283d361cb272da43539da4dedbeba57aa8
hartantosantoso7/Belajar-Python
/program_for_loop.py
582
3.796875
4
# membuat program menggunakan For-loop, List dan Range banyak = int(input("Berapa banyak data? ")) nama = [] umur = [] for data in range(0, banyak): print(f"data {data}") print("==========================") input_nama = input("Nama: ") input_umur = int(input("Umur: ")) print("==========================") nama.append(input_nama) umur.append(input_umur) for n in range(0, len(nama)): data_nama = nama[n] data_umur = umur[n] print(f"{data_nama} berumur {data_umur} tahun") print("==========================") print(nama) print(umur)
7ff206fd06700318b72a52a87b586da736e7de64
sksr99/grade-calculator
/grade_calculator.py
2,348
4.28125
4
def main(): """Takes user grade inputs and puts them into grade calculator function""" reading_amt = [] quiz_amt = [] exam_amt = [] lab_amt = [] readings = input("Reading grades: ").split() for reading in readings: reading = int(reading) reading_amt.append(reading) reading_total = sum(reading_amt) reading_avg = reading_total / len(reading_amt) quizzes = input("Quiz grades: ").split() for quiz in quizzes: quiz = int(quiz) quiz_amt.append(quiz) quiz_total = sum(quiz_amt) quiz_avg = quiz_total / len(quiz_amt) exams = input("Exam grades: ").split() for exam in exams: exam = int(exam) exam_amt.append(exam) exams_total = sum(exam_amt) exam_avg = exams_total / len(exam_amt) labs = input("Lab grades: ").split() for lab in labs: lab = int(lab) lab_amt.append(lab) lab_total = sum(lab_amt) lab_avg = lab_total / len(lab_amt) project = int(input("Project grade: ")) grade_calc(reading_avg, quiz_avg, exam_avg, lab_avg, project) gpa_calc(final_average=final_grade) letter_calc(final_average=final_grade) def grade_calc(reading, quiz, exam, lab, project): """Calculates average grade using categorical average input from main""" global final_grade final_grade = (reading * .1) + (quiz * .1) + (exam * .45) + (lab * .25) + (project * .1) print(f'Your final grade is: {final_grade:.2f}') def gpa_calc(final_average): """This function computes final grade on a 4.0 scale""" gpa = '' if final_average >= 90: gpa = 4.0 elif 80 <= final_average <= 89: gpa = 3.0 elif 70 <= final_average <= 79: gpa = 2.0 elif final_average <= 69: gpa = 1.0 else: gpa = 0 print(f'GPA Scale: {gpa}') def letter_calc(final_average): """This function computes final grade on a letter scale""" letter = '' if final_average >= 90: letter = 'A' elif 80 <= final_average <= 89: letter = 'B' elif 70 <= final_average <= 79: letter = 'C' elif final_average <= 69: letter = 'D' else: letter = 'F' print(f'Letter grade: {letter}') if __name__ == '__main__': main()
4c865e27cd4fc70f05ef4154077c72825f55eceb
Mongoose556/RSR
/main.py
2,702
3.984375
4
#BASED ON :http://www.miielz.com/WWIII/Media/Red%20Storm%20Rising%20Board%20Game%20Basic%20Rules.pdf # class factory example http://code.activestate.com/recipes/86900/ # generate random integer values import random from unit import Unit ############################################################################ #Dice roll function def dice_roll(): roll = random.randint(1, 10)# generate some integers print("Dice roll: ", roll) #dice roll return roll #get number of turns def get_number_of_turns(): while True: try: turns = int(input("Number of turns (max 10): ")) except ValueError: print ("Please enter a valid number between 1 and 10") else: if turns > 10: turns = 10 elif turns <= 0: turns = 1 return turns def game_loop(t): #(turns) ''' this loop puts one unit against another until destroyed or out of turns. ''' # turn 1, player attacks, # if enemy alive then # enemy attack else win = true # if player alive then # turn 2 num_turns = t win = False player_unit = Unit("BLUE") # name enemy_unit = Unit("RED") # enemy while player_unit.is_alive and num_turns > 0: print(player_unit.name, " turn:") player_unit.attack(dice_roll(), enemy_unit) print("Status: ", player_unit.unit_status()) num_turns -= 1 print("Turns remaining: ", num_turns) input("Press a key.") if enemy_unit.is_alive: # win = False print(enemy_unit.name, " turn:") enemy_unit.attack(dice_roll(), player_unit) print("Status: ", enemy_unit.unit_status()) else: win = True print("You Win") else: print("Game Over") if __name__ == "__main__": num_turns=(get_number_of_turns()) game_loop(num_turns) #call game loop function, number of turns #Add an attribute to unit called hits_remaining. And set it to the number of hits that each unit type can survive #Then you can simplify the game loop to just impose a hit on a unit, then do: #If not unit.is_alive(): print(“unit dead”) or whatever #The other thing to think about maybe is writing tests to verify that the code does what you want #So you’d write another method that would do something like, create a unit, call hit, and then test that it’s dead #And then maybe have a different one for rank 3 units where you call hit once, check that it’s not dead, call it twice more, then check that it is
d218aa7eef3c1579d6155b3bcf18fe8d8534886a
Amisha328/reinforcement-learning-implementation
/WindyGridWorld/windyGridWorld.py
5,389
3.796875
4
import numpy as np class State: def __init__(self, state=(3, 0), rows=7, cols=10): self.END_STATE = (3, 7) self.WIND = [0, 0, 0, 1, 1, 1, 2, 2, 1, 0] self.ROWS = 7 self.COLS = 10 self.state = state # starting point self.isEnd = True if self.state == self.END_STATE else False def giveReward(self): if self.state == self.END_STATE: return 1 else: return 0 def nxtPosition(self, action): """ action: up, down, left, right ------------------ 0 | 1 | 2| 3| ... 1 | 2 | ...| return next position on board based on wind strength of that column (according to the book, the number of steps shifted upward is based on the current state) """ currentWindy = self.WIND[self.state[1]] if action == "up": nxtState = (self.state[0] - 1 - currentWindy, self.state[1]) elif action == "down": nxtState = (self.state[0] + 1 - currentWindy, self.state[1]) elif action == "left": nxtState = (self.state[0] - currentWindy, self.state[1] - 1) else: nxtState = (self.state[0] - currentWindy, self.state[1] + 1) # if next state is legal positionRow, positionCol = 0, 0 if (nxtState[0] >= 0) and (nxtState[0] <= (self.ROWS - 1)): positionRow = nxtState[0] else: positonRow = self.state[0] if (nxtState[1] >= 0) and (nxtState[1] <= (self.COLS - 1)): positionCol = nxtState[1] else: positionCol = self.state[1] # if bash into walls return (positionRow, positionCol) def showBoard(self): self.board = np.zeros([self.ROWS, self.COLS]) self.board[self.state] = 1 self.board[self.END_STATE] = -1 for i in range(self.ROWS): print('-----------------------------------------') out = '| ' for j in range(self.COLS): if self.board[i, j] == 1: token = 'S' if self.board[i, j] == -1: token = 'G' if self.board[i, j] == 0: token = '0' out += token + ' | ' print(out) print('-----------------------------------------') class Agent: def __init__(self, lr=0.2, exp_rate=0.3): self.END_STATE = (3, 7) self.START_STATE = (3, 0) self.ROWS = 7 self.COLS = 10 self.states = [] # record position and action taken at the position self.actions = ["up", "down", "left", "right"] self.State = State() self.lr = lr self.exp_rate = exp_rate # initial Q values self.Q_values = {} for i in range(self.ROWS): for j in range(self.COLS): self.Q_values[(i, j)] = {} for a in self.actions: self.Q_values[(i, j)][a] = 0 # Q value is a dict of dict def chooseAction(self): # choose action with most expected value mx_nxt_reward = 0 action = "" if np.random.uniform(0, 1) <= self.exp_rate: action = np.random.choice(self.actions) else: # greedy action for a in self.actions: current_position = self.State.state nxt_reward = self.Q_values[current_position][a] if nxt_reward >= mx_nxt_reward: action = a mx_nxt_reward = nxt_reward # print("current pos: {}, greedy aciton: {}".format(self.State.state, action)) return action def takeAction(self, action): position = self.State.nxtPosition(action) # update State return State(state=position) def reset(self): self.states = [] self.State = State() def play(self, rounds=10): i = 0 while i < rounds: # to the end of game back propagate reward if self.State.isEnd: if i % 5 == 0: print("round", i) # back propagate reward = self.State.giveReward() for a in self.actions: self.Q_values[self.State.state][a] = reward print("Game End Reward", reward) for s in reversed(self.states): current_q_value = self.Q_values[s[0]][s[1]] reward = current_q_value + self.lr * (reward - current_q_value) self.Q_values[s[0]][s[1]] = round(reward, 3) self.reset() i += 1 else: action = self.chooseAction() # append trace self.states.append([(self.State.state), action]) # by taking the action, it reaches the next state self.State = self.takeAction(action) if __name__ == "__main__": print("training ...") ag = Agent(exp_rate=0.3) ag.play(50) print("playing ...") ag_op = Agent(exp_rate=0) ag_op.Q_values = ag.Q_values while not ag_op.State.isEnd: action = ag_op.chooseAction() print("current state {}, action {}".format(ag_op.State.state, action)) ag_op.State = ag_op.takeAction(action)
b60c4b374805b49175dc0ca3892512c7bcc6d1f8
DebabrataSharma/atlantis-assignment
/assignment-3/general.py
2,111
3.984375
4
from math import radians, cos, sin, asin, sqrt, atan2,pi from config import * def split_coordinates(city1_coordinate,city2_coordinate): ''' split the coordinates of both cities and store in an array ''' city1_arr = city1_coordinate.split(", ") city2_arr = city2_coordinate.split(", ") result = transform_coordinates(city1_arr, city2_arr) return result def transform_coordinates(city1_arr,city2_arr): ''' transform coordinates as positive or negative values latitude - North -> positive South -> negative longitutes - East -> positive West -> negative ''' try: city1_lat = transform_latitude(city1_arr[0]) city2_lat = transform_latitude(city2_arr[0]) city1_lon = transform_longitude(city1_arr[1]) city2_lon = transform_longitude(city2_arr[1]) except Exception as e: return None if not city1_lat or not city1_lon or not city2_lat or not city2_lon: return None distance = calc_distance(city1_lat,city1_lon,city2_lat,city2_lon) return distance def transform_latitude(latitude): return radians(float(latitude[:-2])) if latitude[-1].lower()=="n"\ else radians(-float(latitude[:-2])) if latitude[-1].lower()=="s"\ else None def transform_longitude(longitude): return radians(float(longitude[:-2])) if longitude[-1].lower()=="e"\ else radians(-float(longitude[:-2])) if longitude[-1].lower()=="w"\ else None def calc_distance(city1_lat,city1_lon,city2_lat,city2_lon): ''' calculate distance between two cities using Haversine formula ''' dist_lon = (city2_lon - city1_lon) dist_lat = (city2_lat - city1_lat) a = (pow(sin(dist_lat / 2), 2) + pow(sin(dist_lon / 2), 2) * cos(city1_lat) * cos(city2_lat)) radius = r_earth c = 2 * asin(sqrt(a)) return radius * c def distance_cities(city1_coordinate,city2_coordinate): dist = split_coordinates(city1_coordinate,city2_coordinate) return dist
bcbebf353ed42d1d978f1a7a1d380b845712e61f
xuongtrantrieu/Basic-Python
/level_2/question 7.py
227
3.5625
4
def xy_dimension(n, m): xy = [[0 for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): xy[i][j] = i * j return xy if __name__ == '__main__': print(xy_dimension(3, 4))
7be0266fd9cefcb2cb4a47c42cc0894dc6a2ad05
oscarhscc/algorithm-with-python
/剑指offer/树的子结构.py
1,023
3.90625
4
''' 题目描述 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) ''' # -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 将pRoot1的本身或者左右子树和pRoot2进行比较,看是否有相同的树结构 def HasSubtree(self, pRoot1, pRoot2): # write code here if not pRoot1 or not pRoot2: return False return self.is_subtree(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2) # 判断两棵树是否具有一样的结构,递归比较判断 def is_subtree(self, A, B): if not B: return True if not A: return False if A.val != B.val: return False return self.is_subtree(A.left,B.left) and self.is_subtree(A.right, B.right)
af8a43a3bb0ee6aa95117fa5dc16377b4f1dde64
eechoo/Algorithms
/LeetCode/EditDistance.py
1,341
3.9375
4
#!/usr/bin/python ''' Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a character b) Delete a character c) Replace a character ''' class Solution: # @return an integer def minDistance(self, word1, word2): if(word1==''): return len(word2) elif(word2==''): return len(word1) DP = [] for i in range(len(word1)+1): DP.append([0 for j in range(len(word2)+1)]) for j in range(len(word2)+1): if( i==0): DP[i][j] = j elif(j==0): DP[i][j] = i else: a=DP[i-1][j]+1 b=DP[i][j-1]+1 if(word1[i-1] == word2[j-1]): c=DP[i-1][j-1] else: c=DP[i-1][j-1]+1 if(a<b and a<c): DP[i][j]=a elif(b<a and b<c): DP[i][j]=b else: DP[i][j]=c return DP[-1][-1] def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) def main(): ins=Solution() test(ins.minDistance("zoologicoarchaeologist", "zoogeologist"),1) test(ins.minDistance("ab", "a"),1) if __name__ == '__main__': main()
a9b07569cd2b813904c475007434564d929f68b6
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4178/codes/1679_1100.py
471
3.625
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Ao testar sua solução, não se limite ao caso de exemplo. var1 = int(input("Entrada: ")) if var1 == 2: msg="Tartaruga" elif var1 == 5: msg="Garca" elif var1 == 10: msg="Arara" elif var1 == 20: msg="Micro-leao-dourado" elif var1 == 50: msg="Onca-pintada" elif var1 == 100: msg="Garoupa" else: msg="Invalido" print("Entrada:", var1) print("Animal:", msg)
861f6918f6c1a63fe9bf513a7caece1602474e62
cmdtvt/R421-python-course
/Chapter9/task9-1.py
995
4.5
4
''' The exercise in the 9th chapter focuses on one of the most powerful tools in the Python language, the datatype list, and the first assignment is a simple exercise to create. Define a list which has four items, strings "Blue","Red","Yellow" and "Green". After this, make a slice from the list which contains only the first item of the list (list place 0), and print out all of the items with one for-structure. When the code works properly, the program prints the following: #################### >>> The first item in the list is: Blue The entire list printed one item a time: Blue Red Yellow Green >>> ##################### Example output: ####################### The first item in the list is: Blue The entire list printed one item a time: Blue Red Yellow Green ######################### ''' items = ["Blue","Red","Yellow","Green"] print("The first item in the list is: {item}".format(item=items[0])) print("The entire list printed one item a time:") for i in items: print(i)
f8bb42ec80ca07a20cdb56f3e77d41e2ecfb2d73
Lucas-Guimaraes/Reddit-Daily-Programmer
/Easy Problems/201-210/204easy.py
855
3.515625
4
#https://www.reddit.com/r/dailyprogrammer/comments/2xoxum/20150302_challenge_204_easy_remembering_your_lines/ #Unfortunately, macbeth.txt was deleted from this challenge. lines = open("macbeth.txt").read().splitlines() phrase = "Eye of newt" #can be replaced with input #Function to grab start of dialogue first_not_dialog = lambda lines: next(i for i, line in enumerate(lines) if not line.startswith(" ")) #grabs the index for the line in phrase index = next(i for i, line in enumerate(lines) if phrase in line) #Grabs the start of the phrase IDX dialog_start = index + 1 - first_not_dialog(lines[index::-1]) #Grabs the end of the phrase IDX dialog_end = index + first_not_dialog(lines[index:]) #Finishes the phrase dialog = lines[dialog_start:dialog_end] #String formatting print("\n".join(line.strip() for line in dialog))
3d32cb71877e361472084166551286e7f4180f15
motrembley/databaseProject
/DBProjMain.py
4,447
4.15625
4
def patient(): print("---PATIENT FUNCTION---") x = -1 while x == -1: print("What would you like to do?") print("1. Enter your information\n2. check your results\n3. Find a nearby hospital") temp = int(input()) if temp == 1: #Enter Information print("---Enter Info---") print("Enter your name:") name = input() print("Enter your address:") addr = input() print("Enter your date of birth(mm/dd/yyyy):") date = input() print("Any health complaints as of late?") comment = input() #---insert into person x = 0 elif temp == 2: #Check Results print("---Check Results---") print("Do you know your case number?") print("1. YES\n2. NO") temp = int(input()) if temp == 1: print("Enter your case number:") case = int(input()) #---search DB for case and return result and print else: print("Enter your name:") name = input() #---search DB for name and return case result and print x = 0 elif temp == 3: #Find Hospital print("---Find Hospital---") x = 0 else: print("---Invalid Entry!---") print("Would you like to try again?") print("1. YES\n2. NO") temp = int(input()) if temp == 1: x = -1 else: x = 0 def doctor(): print("---DOCTOR FUNCTION---") x = -1 while x == -1: print("What would you like to do?") print("1. Enter new case\n2. Update existing Case") temp = int(input()) if temp == 1: #Enter new case print("---Enter Case---") x = 0 elif temp == 2: #Update existing Case print("---Update Case---") x = 0 else: print("---Invalid Entry!---") print("Would you like to try again?") print("1. YES\n2. NO") temp = int(input()) if temp == 1: x = -1 else: x = 0 def visitor(): print("---VISITOR FUNCTION---") x = -1 while x == -1: print("What would you like to do?") print("1. Browse public databases\n2. Check local lockdown status\n3. View statistics") temp = int(input()) if temp == 1: #Browse Public Databases print("---Browse---") x = 0 elif temp == 2: #Check Local Lockdown Status print("---Lockdown Status---") x = 0 elif temp == 3: #View Statistics print("---View Stats---") x = 0 else: print("---Invalid Entry!---") print("Would you like to try again?") print("1. YES\n2. NO") temp = int(input()) if temp == 1: x = -1 else: x = 0 print("Would you like to look around some more?") print("1. YES\n2. NO") temp = int(input()) if temp == 1: x = -1 else: x = 0 print("---WELCOME MEESAGE---") x = 0 while x != -1: y = -1 while y == -1: print("Are you a doctor, patient or visitor?") print("1. Patient\n2. Doctor\n3. Visitor") y = int(input()) if y == 1: #call patient function patient() elif y == 2: #call doctor function doctor() elif y == 3: #call visitor function visitor() else: print("---Invalid Entry!---") print("Would you like to try again?") print("1. YES\n2. NO") temp = int(input()) if temp == 1: y = -1 else: y = 0 print("Would you like to Exit?\n1. YES\n2. NO") temp = int(input()) if temp == 2: x = 0 else: print("---Exiting---") x = -1
a0e7efbfa84d866b62966916fc74dcd45eb09138
skyeaaron/ICU
/datefunctions.py
1,543
4.1875
4
# -*- coding: utf-8 -*- """ Module with functions for handling dates in buildmon """ from datetime import datetime, timedelta def generate_datestrings(date2 = datetime.now()): """ returns today's date and yesterday's date as strings formatted %YYYYMMDD if date2 is supplied, must be in datetime format """ date1 = date2 - timedelta(days = 1) return (date1.strftime('%Y%m%d'), date2.strftime('%Y%m%d')) def add_days_to_string(date2, days, date_format = '%Y%m%d'): """ given a string represeting a date, number of days to add (could be negative), and date_format return datestring shifted over by number of days """ datetime_object = datetime.strptime(date2, date_format) + timedelta(days = days) return datetime_object.strftime(date_format) def make_datelist(startdate, enddate, date_format = '%Y%m%d'): """ given strings representing start and end dates output list of all dates from start to end including endpoints """ try: date1 = datetime.strptime(startdate, date_format) date2 = datetime.strptime(enddate, date_format) except: print("start or end date could not be converted to date") raise assert date1 <= date2, "start date is after end date." currentdate = startdate datelist = [currentdate] while(currentdate != enddate): currentdate = add_days_to_string(currentdate, 1, date_format = date_format) datelist.append(currentdate) return datelist
c96789816affb3da605627b0f0cbfad2bb5779b7
Mohit2597/Python
/Data Structure/lists.py
3,263
4.4375
4
#!/usr/bin/env python3 my_list=[2,3,4,"Python",6,7,5.8] my_empty_list=[] # ****IMPORTTANT**** # modificatin don't use the print # if you want to modify the data assign it to new variable and print that variable # dir(list) # without __something__ these are the opertions you can perform on the lists # lists are mutable (means the data of the lists can be modified) # id(my_list) to print the memory location of the my_list variable #-->bool(my_list) # bool is useful when you want to find out weather the given list is empty or not #-->print(my_list[3]) # $ Python # to print the character of the my_list #-->print(my_list[3][1]) # $ P # my_list[3] will give out the output as string and as the output is also an string we can perform # all the strings operations #-->print[:] will print out the entire string # print[2:4] from 2 to 4 it will print out the entire my_list # print[1:] print 1 to last #-->mylist[0]=45 # modifying the index 0 data to 45 #-->index() # print(my_list.index("Python")) # $ 3 # to find out the index value of the python in the list #-->count() # print(my_list.count('Python')) # how many times count is there in the the list #-->clear() # my_list.clear[] # it will clear the list values and will provide the empty list #-->copy() # my_new_list=my_list # my_new_list=my_list.copy # without the copy module whatever the memory location allocated to the my_list variable same memory # location will be pointing towards the my_new_list and if you delete the my_list varible you will not # be able to use the variable # but in my_list.copy a new memory location will be allocated and will be pointint towards this varible # to verfiy you can use the commands below # print(id(my_list),id(my_new_list)) # $ 4464209472 4464209472 # # print(id(my_list),id(my_list.copy())) # $ 4464209472 4463592320 #-->my_list.append(56) # by default it will add 56 at the end of the list # my_list.insert(1,56) # (at index of 1 you have added a new value 56) #-->my_list.extend() # if you have another string and you want to iclude that data of that string into our list # if you will use apped() it will add it as an list (list inside the list) but if you want to use # 2nd list elements inside our exisitng list use extend() to add new_list data in out list as elements # my_new_list=[4,5] # my_list=[89,1,2,3,4,5] # my_list.apped(my_new_list) # #$ my_list=[89,1,2,3,4,5,[4,5]] # my_new_list=[4,5] # my_list=[1,2,3,4,5,6] # my_list.extend(my_new_list) # #$ my_list=[1,2,3,4,5,6,4,5] #-->my_list.remove('Python') # (it will remove the value from the list based upon value) #-->my_list.pop() # remove operations are done based upon index values # by default it will remove the last value from the list # # my_list.pop(3) # (it will remove the element on index value 3) #-->my_list.reverse() # (it is like the reverse image of your data) #-->my_list.sort() # my_list.sort(reverse=True) sort and reverse #@ lacture 1
d13906287c6290398246581cdd2cc92b3d9c4a34
qz5e20/Data-Structure
/fibnacci.py
639
3.6875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 8 23:58:54 2021 @author: user """ def fibnacci(n): if n==1 or n==2: return 1 else: return fibnacci(n-1)+fibnacci(n-2) print(fibnacci(10)) def fibnacci_no_recurision(n): f=[0,1,1] if n>2: for i in range (n-2): num = f[-1]+f[-2] f.append(num) return f[n] #第一个慢第二个块,递归效率比较慢,子问题的重复计算 #下部分就是动态规划 #最优子结构=递推式+重复子问题 #python可以再递归前加@lru_cache就能自动缓存子问题的部分
e8f6b53623aa240eb25087a0c731f065871814b0
404232077/python-course
/ch08/8-1-9-組合.py
410
3.75
4
class Leg(): def __init__(self, num, look): self.num = num self.look = look class Animal(): def __init__(self, name, leg): self.__name = name self.leg = leg def show_name(self): return self.__name def show(self): print(self.show_name(),'有', self.leg.num, '隻', self.leg.look, '腿') leg = Leg(4, '短短的') a = Animal('小狗', leg) a.show()
749529c91a4c34b7b3f989b7e489be785b08302a
arimontoya/GWC.SIP
/practice.py
147
3.53125
4
def calc_total(list): total = sum(list) print (total) return total my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] calc_total(my_list)
bef2ee2e61378ae5221c76d0d05b9d7bd80492f3
xs2pranjal/data_structures
/non_linear/min_heap.py
1,670
3.625
4
import sys class MinHeap: def __init__(self): self.maxsize = sys.maxsize self.size = 0 self.Heap = [0] * (self.maxsize + 1) self.Heap[0] = sys.maxsize self.FRONT = 1 def leftChild(self, pos): return 2 * pos def isLeaf(self, pos): if 2 * pos >= self.size and pos <= self.size: return True return False def rightChild(self, pos): return (2 * pos) + 1 def parent(self, pos): return pos // 2 def swap(self, fpos, spos): self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos] def insert(self, element): if self.size >= self.maxsize: return self.size += 1 current = self.size self.Heap[current] = element while self.Heap[current] < self.Heap[self.parent(current)]: self.swap(current, self.parent(current)) current = self.parent(current) def extractMin(self): popped = self.Heap[self.FRONT] self.Heap[self.FRONT] = self.Heap[self.size] self.size -= 1 self.minHeapify(self.FRONT) return popped def minHeapify(self, pos): if not self.isLeaf(pos): if self.Heap[self.leftChild(pos)] < self.Heap[pos] or self.Heap[self.rightChild(pos)] < self.Heap[pos]: if self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]: self.swap(pos, self.leftChild(pos)) self.minHeapify(self.leftChild(pos)) else: self.swap(self.rightChild(pos)) self.minHeapify(self.rightChild(pos))
334ca4d0067ec0190e7ee412b9f7d3735e9ed266
leonardotdleal/python-basic-course
/decision-structure/decision-structure.py
1,135
4.25
4
age = 25 if age < 18: print('Age less than 18') else: print('Age more than 18') vehicle = {'type': 'motorcycle', 'brand': 'Honda', 'potency': 140} if vehicle['type'] == 'motorcycle' and vehicle['brand'] == 'Honda': print('Vehicle is a motorcycle') else: print('Vehicle isn\'t a motorcycle') result = vehicle['type'] == 'motorcycle' print(result) if vehicle['type'] == 'car' or vehicle['potency'] < 120: print('You have a very fast vehicle') else: print('You haven\'t a very fast vehicle') if (vehicle['type'] == 'car' or vehicle['potency'] < 120) or vehicle['brand'] == 'Honda': print('You have a very fast vehicle') if vehicle['type'] == 'car': print('You have a car') elif vehicle['type'] == 'truck': print('You have a truck') elif vehicle['type'] == 'motorcycle': print('You have a motorcycle') name = 'Leonardo' if name: print('True') else: print('False') positive = 1 zero = 0 negative = -1 if positive: print('Positive "1" is valid') if zero: print('Zero "0" is valid') else: print('Zero "0" is not valid') if negative: print('Negative "-1" is valid')
6c48c4bc1574a657d3da5b60c6ad28263d1f9a78
tonmoy50/uiu
/Simultion Lab/extra/sumu_1.py
3,310
3.796875
4
import numpy as np import random as rnd def demand(): random_digit = rnd.randint(1, 100) daily_demand = 0 if ( random_digit >= 1 and random_digit <= 10 ): daily_demand = 0 elif ( random_digit >= 11 and random_digit <= 35 ): daily_demand = 1 elif ( random_digit >= 36 and random_digit <= 70 ): daily_demand = 2 elif ( random_digit >= 71 and random_digit <= 91 ): daily_demand = 3 else: daily_demand = 4 return [daily_demand, random_digit] def lead_time(): random_lead = rnd.randint(0, 9) if (random_lead >= 1 and random_lead <= 6): lead = 1 elif (random_lead >= 7 and random_lead <= 9): lead = 2 else: lead = 3 return [lead, random_lead] def orders(m, end_inv): order_unit = m - end_inv return order_unit def main(): #n = 5 #m = 11 #inventory = 3 #order_unit = 8 #order_arrives = 1 n,m,inventory,order_unit,order_arrives = input("Enter N, M, Begining_Inventory, Order_Unit, Order_Arrival Sequentially with comma: ").split(',') n = int(n) m = int(m) inventory = int(inventory) order_unit = int(order_unit) order_arrives = int(order_arrives) ending_inventory = [] shortage_quantity = [] print( "Cycle", "Days", "Beg'n_Inventory", "Rand_Demand", "Demand", "End_Inventory", "Shortage", "Order_number", "Rand_Lead", "Order_Arrives" ) for i in range(1, n+1): lead = lead_time() for j in range(1, n+1): temp_order = order_arrives if temp_order == -1: temp_order = '_' if order_arrives == -1: #check krchi j order arrive koreche kina krle inventory te order amount add korechi inventory = inventory + order_unit - (shortage_quantity[-1] if shortage_quantity[-1] != '_' else 0) order_arrives = '_' else: if order_arrives != '_': order_arrives = order_arrives - 1 demands = demand() if (inventory-demands[0]) >= 0: shortage_quantity.append('_') ending_inventory.append(inventory-demands[0]) else: temp_val = demands[0] - inventory shortage_quantity.append(temp_val) ending_inventory.append(0) print(" {}\t{}\t {}\t\t{}\t{}\t{}\t\t{}\t{}\t {}\t\t {}".format(i if j==1 else ' ', j, inventory, demands[1], demands[0], ending_inventory[-1], shortage_quantity[-1], orders(m, ending_inventory[-1]) if j==n else '_', lead[1] if j==n else '_', temp_order) ) #print('\n') inventory = ending_inventory[-1] #order_unit = m - ending_inventory[-1] order_arrives = lead[0] print('\n') print("Average Number of Ending Inventory: {}".format( (sum(ending_inventory)/len(ending_inventory)) ) ) print("Average Number of Shortage in Days: {}".format( sum( i!='_' for i in shortage_quantity )/(n*n) ) ) if __name__ == "__main__": main()
0823c11bc0a96b72078384fd0afcc1759ba4fe62
deepali1232/divya-coding-classes
/numpy_library_function/numpy_shape.py
167
3.65625
4
import numpy as np n1=np.array([[1,2,3],[4,5,6]]) print(n1.shape) n1.shape=(3,2) print(n1.shape) n2=np.array([[1,2,3,4],[4,3,2,1]]) print(n2) n2.shape=(4,2) print(n2)
a639ef8f75ecb9e064bdf026a638229241b2e292
JenishLunagariya/BasicPython
/collection.py
383
3.859375
4
# program compare inputed key with keys in database and answer the value if any,otherwise shows # wrong key message def dic(key): dic1 = { 'car': 'tesla', 'bike': 'ktm', 'plane': 'honda', } if key in dic1.keys(): return dic1[key] else: return 'key is unavailable in dictionary' key=str(input('input you key:')) print(dic(key))
0c698b79cb85efbb5ed52de25c5f96f2d0271e41
VSablin/numpy_for_your_grandma
/5_Challenges.py
2,508
4
4
# In this script, we go through lesson 5 of Python NumPy for your # Grandma course: Challenges. Web link here: # https://www.gormanalysis.com/blog/python-numpy-for-your-grandma-challenges/ # %% Import libraries import numpy as np # %% Challenge 1: # Given a 10x2 array of floats where the 1st column contains some nan values, # create a 3rd column equal to column 1 where it's not nan and column 2 where it # is nan. In other words, set column 3 equal to column 1, but fall back on # column 2 where column 1 has a missing value. # Setup np.random.seed(123) foo = np.random.uniform(low=0.0, high=1.0, size=(10, 2)) foo[np.random.randint(low=0, high=10, size=5), np.repeat(0, 5)] = np.nan foo = np.round(foo, 2) # Solution: out3 = np.where(~np.isnan(foo[:, 0]), foo[:, 0], foo[:, 1]) out = np.concatenate((foo, out3.reshape((len(out3), 1))), axis=1) print(out) # %% Challenge2: # Given a 1d array of integers, identify the first three values < 10 and replace # them with 0. # Setup moo = np.array([0, 15, 32, 11, 5, 5, 24, 99, 81, 3, 45, 9, 41]) # Solution: ind = np.where(moo < 10) moo[ind[0][:3]] = 0 print(moo) # Gorm solution: moo = np.array([0, 15, 32, 11, 5, 5, 24, 99, 81, 3, 45, 9, 41]) moo[(moo < 10).nonzero()[0][:3]] print(moo) # %% Challenge 3: # Insert 10 random normal values into a 5x5 array of 0s at random locations. # Setup oof = np.zeros(shape=(5, 5)) # Solution: size = 10 rand = np.round(np.random.normal(loc=0.0, scale=1.0, size=size), 2) pos = np.random.choice(np.arange(0, 25, 1), size=size, replace=False) dim1, dim2 = oof.shape oof_1d = oof.reshape(dim1 * dim2) oof_1d[pos] = rand oof = oof_1d.reshape((dim1, dim2)) print(oof) # Alternative: oof.ravel()[pos] = rand print(oof) # %% Challenge 4: # Given peanut, a 4x5 array of 0s, and butter, a 5-element array of indices, # fill the rows of peanut with 1s starting from the column indices given by # butter. # Setup peanut = np.zeros(shape=(4, 5)) butter = np.array([3, 0, 4, 1]) # Solution for i in range(len(butter)): peanut[i][butter[i]::] = 1 print(peanut) # Alternative (butter[:, None] <= np.arange(peanut.shape[1])).astype('int') # %% Challenge 5: # Given an array of integers, one hot encode it into a 2d array. # Setup yoyoyo = np.array([3, 1, 0, 1]) # Solution: size = np.max(yoyoyo) + 1 (yoyoyo[:, None] == np.arange(size)).astype('int') # Gorm 1: result = np.eye(size)[yoyoyo] print(result) # Gorm 2: result = np.zeros(shape=(len(yoyoyo), size)) result[np.arange(result.shape[0]), yoyoyo] = 1 print(result)
a2e495fdc47015c860dc2e716dfa6d8a401a6538
HareshNasit/LeetCode
/Array/third_max.py
366
3.796875
4
def thirdMax(self, nums): """ https://leetcode.com/problems/third-maximum-number/submissions/ :type nums: List[int] :rtype: int """ nums_set = set(nums) nums_list = list(nums_set) nums_list.sort(reverse = True) if len(nums_list) > 2: return nums_list[2] return nums_list[0]
5902db7897e29d0b10adf47e0398a5ba1c4d51a9
UzairJ99/PythonLeetCode
/uniqueOccurancesCount.py
689
3.734375
4
class Solution: def uniqueOccurrences(self, arr): count = {} #count occurances of each item and add to dictionary for x in arr: if (checkKey(count,x)): count[x] += 1 else: count[x] = 1 print(count) unique = [] #check if dictionary contains only unique values for x in count.keys(): if count[x] in unique: return False else: unique.append(count[x]) return True #check if key exists def checkKey(d,x): if d.get(x): return True else: return False
d1603ebe9f16caa9ce55ee4b109c114be143ef54
vnikos/CodeBootcamp
/ex3.py
216
3.953125
4
import math a = float(input("Enter side a: ")) b = float(input("Enter side b: ")) c = float(input("Enter side c: ")) r = (a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c) A = math.sqrt(r)/4 print ("The triangle area is: ", A)
b1da4221179e54d76064d0a06b0ea8c3bb057139
hiroshees/mypygame2
/chapter02/test05.py
129
3.625
4
import random for i in range(5): print(random.random()) print("*"*10) for i in range(10): print(random.randint(1,6))
cf1054d06fee5fabcd7495239a2e43612bf32d64
Xithriub/Future
/EDUCATION/using_list.py
1,552
3.890625
4
shoplist=['Яблоки','Манго','Морковь','Бананы'] print('Я должен сделать',len(shoplist),'покупки.') print('Покупки:',end='^-^') for item in shoplist: print(item,end=' ') print('\nТакже нужно купить риса') shoplist.append('Рис') print('Теперь мой список покупок таков:',shoplist) print('ОТсортирую-ка я свой список') shoplist.sort() print('Отсортированный спиок выглядит вот так:',shoplist) print('Первое что мне нужно купить, это', shoplist[0]) olditem=shoplist[0] del shoplist[0] print('Я купил',olditem) print('Теперь мой список покупок таков:', shoplist) print('\nБлин я забыл купить колу и чипсы^-^') shoplist.append('Кола')# Добавляем новый товар в конец списка shoplist.append('Чипсы')# Добавляем новый товар в конец спика после Колы print('Теперь мой список таков:',shoplist) toy=shoplist[0] toi=shoplist[1] del shoplist[0];del shoplist[1] print('Я купил =',toy,'и',toi) print('Мне осталось купить:',shoplist) print('А еще надо купить самое важное, а это картошка') shoplist.append('Картошка') wer=shoplist[0] wir=shoplist[1] del shoplist[0];shoplist[1] print('Мой новый список товаров:',shoplist)
8e3a5077bd2a0bff80b4e621221dde01a71d9ce1
PauloVilarinho/algoritmos
/ListasFabio/Lista2/fabio02_q16.py
553
3.765625
4
""" Questão: Lista 2 16 Descrição: calcula aprovação de um aluno """ def main(): #entrada nota1 = float(input("digite sua primeira nota: ")) nota2 = float(input("digite sua segunda nota: ")) #processamento media = (nota1+nota2)/2 if media >= 7 : resultado = "Aprovado" else : exame_final = float(input("digite a nota do seu exame final: ")) media = (media+exame_final)/2 if media >= 5 : resultado = "Aprovado" else : resultado = "Reprovado" #saida print("O aluno está %s" %resultado) if __name__ == '__main__': main()
bf9a569ab9dbd9c0e02835cf49447530b7d0ad96
svanis71/codewars
/codewars.python/tests/write_out_numbers_test.py
1,879
3.6875
4
import unittest from write_out_numbers import number2words class WriteOutNumbersTests(unittest.TestCase): """ Tests for https://www.codewars.com/kata/52724507b149fa120600031d/train/python """ def test_low(self): self.assertEqual(number2words(0), "zero") self.assertEqual(number2words(1), "one") self.assertEqual(number2words(8), "eight") def test_tens(self): self.assertEqual(number2words(10), "ten") self.assertEqual(number2words(19), "nineteen") self.assertEqual(number2words(20), "twenty") self.assertEqual(number2words(22), "twenty-two") self.assertEqual(number2words(54), "fifty-four") self.assertEqual(number2words(80), "eighty") self.assertEqual(number2words(98), "ninety-eight") def test_hundreds(self): self.assertEqual(number2words(100), "one hundred") self.assertEqual(number2words(301), "three hundred one") self.assertEqual(number2words(793), "seven hundred ninety-three") self.assertEqual(number2words(800), "eight hundred") self.assertEqual(number2words(650), "six hundred fifty") def test_thounsands(self): self.assertEqual(number2words(1000), "one thousand") self.assertEqual(number2words(1003), "one thousand three") self.assertEqual(number2words(3051), "three thousand fifty-one") self.assertEqual(number2words(7200), "seven thousand two hundred") self.assertEqual(number2words(7219), "seven thousand two hundred nineteen") self.assertEqual(number2words(8330), "eight thousand three hundred thirty") self.assertEqual(number2words(99999), "ninety-nine thousand nine hundred ninety-nine") self.assertEqual(number2words(888888), "eight hundred eighty-eight thousand eight hundred eighty-eight") if __name__ == '__main__': unittest.main()
05231e00271f4f9a9377146e2950bdb30baaa427
salimuddin87/Python_Program
/python3/Tutorial/inheritance/overloading.py
939
4.28125
4
""" python does not supports method overloading by default. But there are different ways to achieve method overloading in Python. """ class Student: def add(self, datatype, *args): if datatype == 'int': answer = 0 if datatype == 'str': answer = '' for x in args: answer += x print("Answer = ", answer) def hello_function(self, name=None): if name is not None: print("Hello " + name) else: print("Hello") def product(a, b): print("First product", a * b) def product(a, b, c=1): print("Second product", a * b * c) if __name__ == '__main__': std = Student() std.hello_function() std.hello_function("Nick") # Operator overloading print(5 + 5) print("py" + "thon") product(4, 5) # Always 2nd function will be called std.add('int', 5, 6) std.add('str', 'Hi', 'Salim')
81e79a296274f695e51e55cda45af668a5e07e04
Takayoshi-Matsuyama/study-of-deep-learning
/10_数値微分.py
3,669
3.578125
4
import numpy as np import matplotlib.pylab as plt import matplotlib.pyplot as plt2 from mpl_toolkits.mplot3d import axes3d from matplotlib import cm def numerical_diff(f, x): h = 1e-4 # 0.0001 return (f(x + h) - f(x - h)) / (2 * h) def function_1(x): return 0.01*x**2 + 0.1*x def function_2(x): return x[0]**2 + x[1]**2 def tangent_line(f, x): d = numerical_diff(f, x) print(d) y = f(x) - d*x return lambda t: d*t + y def numerical_gradient(f, x): h = 1e-4 # 0.0001 grad = np.zeros_like(x) # xと同じ形状の配列を生成 for idx in range(x.size): tmp_val = x[idx] # f(x+h)の計算 x[idx] = tmp_val + h fxh1 = f(x) # f(x-h)の計算 x[idx] = tmp_val - h fxh2 = f(x) grad[idx] = (fxh1 - fxh2) / (2*h) x[idx] = tmp_val # 値を元に戻す return grad # 勾配降下法 def gradient_descent(f, init_x, lr=0.01, step_num=100): x = init_x for i in range(step_num): grad = numerical_gradient(f, x) x -= lr * grad return x x = np.arange(0.0, 20.0, 0.1) # 0から20まで、0.1刻みのx配列 y = function_1(x) plt.xlabel("x") plt.ylabel("f(x)") tf = tangent_line(function_1, 5) y2 = tf(x) plt.plot(x, y) plt.plot(x, y2) plt.show() #print(numerical_diff(function_1, 5)) #print(numerical_diff(function_1, 10)) fig = plt2.figure() ax = fig.add_subplot(111, projection='3d') x1 = x2 = np.arange(-3, 3, 0.1) X1, X2 = np.meshgrid(x1, x2) Z = np.power(X1, 2) + np.power(X2, 2) print(Z) ax.plot_wireframe(X1, X2, Z, rstride=2, cstride=2) plt2.xlabel("x0") plt2.ylabel("x1") plt2.show() # x0 = 3, x1 = 4 のときのx0に対する偏微分 def function_tmp1(x0): return x0*x0 + 4.0**2.0 print(numerical_diff(function_tmp1, 3.0)) # x0 = 3, x1 = 4 のときのx1に対する偏微分 def function_tmp2(x1): return 3.0**2.0 + x1*x1 print(numerical_diff(function_tmp2, 4.0)) # 勾配の計算 print(numerical_gradient(function_2, np.array([3.0, 4.0]))) print(numerical_gradient(function_2, np.array([0.0, 2.0]))) print(numerical_gradient(function_2, np.array([3.0, 0.0]))) # 問:f(x0, x1) = x0^2 + x1^2 の最小値を勾配法で求めよ def function_2(x): return x[0]**2 + x[1]**2 init_x = np.array([-3.0, 4.0]) print(gradient_descent(f=function_2, init_x=init_x, lr=0.1, step_num=100)) # 学習率が大きすぎる例:lr = 10.0 init_x = np.array([-3.0, 4.0]) print(gradient_descent(f=function_2, init_x=init_x, lr=10.0, step_num=100)) # 学習率が小さすぎる例:lr = 1e-10 init_x = np.array([-3.0, 4.0]) print(gradient_descent(f=function_2, init_x=init_x, lr=1e-10, step_num=100)) ''' arg = np.c_[X1.ravel(), X2.ravel()] print(x1) print(x2) print(X1) print(X2) print(arg) ''' # 【Python】ふたつの配列からすべての組み合わせを評価 # http://kaisk.hatenadiary.com/entry/2014/11/05/041011 """ Matplotlibのmplot3dで3Dグラフを作成 https://note.nkmk.me/python-matplotlib-mplot3d/ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = y = np.arange(-15, 15, 0.5) X, Y = np.meshgrid(x, y) sigma = 4 Z = np.exp(-(X**2 + Y**2)/(2*sigma**2)) / (2*np.pi*sigma**2) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm) plt.savefig("data/dst/matplotlib_mplot3d_surface.png") ax.clear() ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2) plt.savefig("data/dst/matplotlib_mplot3d_wireframe.png") ax.clear() ax.scatter(X, Y, Z, s=1) plt.savefig("data/dst/matplotlib_mplot3d_scatter.png") """
ef5795ae36a69d0c1330598680afd4618d42b328
Rokesshwar/Coursera_IIPP
/week 4/week 4a/week 4aPractise_exercise_2.py
380
4.0625
4
# List reference problem ################################################### # Student should enter code below a = [5, 3, 1, -1, -3, 5] b=a b[0]=0 print(b) ################################################### # Explanation #this is because when we give a new element in the existing #elements position it replaces the the existing one #with the new one
8e6b8da50abad89beae18889b2f987fd587fb639
fchikwekwe/tkinter-by-example
/root.py
260
3.5
4
import tkinter as tk class Root (tk.Tk): def __init__(self): super().__init__() self.label = tk.Label(self, text ="Hello World", padx=20, pady=20) self.label.pack() if __name__=="__main__": root = Root() root.mainloop()
c3f2d1d93db241cf9094aea86b4e3504f8ab84f5
W-R-Ramirez/Scrabble-Solver
/GUI.py
2,339
4.25
4
import Tkinter, tkFont from starter import numbers_to_letters def make_board(board): for i in range(8): i = i+1 line = board.create_line(i*50,100,i*50,600) line = board.create_line(0,(i*50)+100, 450,(i*50)+100) for i in range(2): i = i+1 line = board.create_line(0,99+i*150, 450, 99+i*150) line = board.create_line(0,101+i*150, 450, 101+i*150) line = board.create_line(-1+i*150, 100, -1+i*150, 550) line = board.create_line(1+i*150, 100, 1+i*150, 550) """ get_board uses the make_board function to open up the GUI, and links a text box with a name (it puts them in the dict space_values). Then, it uses retrieve, which is called by the button, and returns a list of tuples in the form (Column, Row, Value) """ def get_board(): top = Tkinter.Tk() board = Tkinter.Canvas(top, width = 450, height = 550, bg = "white") top_line = board.create_line(0,100,450,100) font = tkFont.Font(size = 18) space_values = {} game_board = [] make_board(board) for i in range(9): i = i+1 for j in range(9): j = j+1 name = numbers_to_letters[i]+str(j) space = Tkinter.Entry(top, width = 1, font = font) space.place(x = (i-1)*50+15, y = (j-1)*50+110) space_values[name] = space def retrieve(): for name, value in space_values.iteritems(): if value.get() == "": game_board.append((name[0], int(name[1]), 0)) else: game_board.append((name[0], int(name[1]), int(value.get()))) top.destroy() b = Tkinter.Button(board, text="Solve", command = retrieve) b.place(x = 195, y = 50) board.pack() top.mainloop() return game_board def show_board(spaces): top = Tkinter.Tk() board = Tkinter.Canvas(top, width = 450, height = 550, bg = "white") top_line = board.create_line(0,100,450,100) font = tkFont.Font(size = 18) make_board(board) for i in range(9): i = i+1 for j in range(9): j = j+1 number = spaces[numbers_to_letters[i]+str(j)].value space = Tkinter.Label(top, text = number, font = font) space.place(x = (i-1)*50+15, y = (j-1)*50+110) board.pack() top.mainloop()
e5443b2cef49826d6516c44869eaff665af1201b
cakarlen/School
/Python/Lab Test 2/KarlenChase.py
1,566
3.875
4
# Author: Chase Karlen # Email: chase@uky.edu # Section: 002 from graphics import * from math import sqrt def distance(point1, point2): # all four parameters are integers # they represent the coordinates of two points # the distance between the two points is returned return float(sqrt((point2.getX() - point1.getX()) ** 2 + (point2.getY() - point1.getY()) ** 2)) def main(): win = GraphWin("Lab Test 2", 450, 550) counter = 0 click_text = Text(Point(225, 10), "Click 6 times") close_text = Text(Point(220, 535), "Click to close") click_text.draw(win) for i in range(3): first_click = win.getMouse() second_click = win.getMouse() actual_distance = distance(first_click, second_click) click_rectangle = Rectangle(Point(first_click.getX(), first_click.getY()), Point(second_click.getX(), second_click.getY())) click_rectangle.draw(win) dist_line = Line(Point(first_click.getX(), first_click.getY()), Point(second_click.getX(), second_click.getY())) dist_line.draw(win) if actual_distance > 250: click_rectangle.setFill("blue") else: click_rectangle.setFill("green") counter = actual_distance + counter distance_point = "Total distance", round(counter, 1) distance_text = Text(Point(220, 520), distance_point) click_text.undraw() distance_text.draw(win) close_text.draw(win) win.getMouse() win.close() main()
689da854fc52105fe33bd0698a375e1ea20635a5
nuSapb/basic-python
/Day1/class/lib/class_encapsulation.py
755
3.875
4
class Base(object): def __init__(self): print('__init__ base class') class User(Base): __name = None __is_staff = False def __init__(self, name='Anonymous'): self.__name = name super(User, self).__init__() @property def is_authorized(self): return self.__is_staff @is_authorized.setter def is_authorized(self, value): self.__is_staff = value @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value ''' anonymous = User() print(anonymous.name) print(anonymous.is_authorized) anonymous.name = 'Anu' anonymous.is_authorized = True print(anonymous.name, anonymous.is_authorized) '''
2b556ccd096f0998bc374302b9d4d6102e26baf2
mash716/Python
/base/array/array0006.py
371
4.09375
4
#removeは指定の引数に該当する要素を削除します。最初に見つかった要素のみ削除が行われる #ので、指定の要素がリスト内に複数存在する場合は注意が必要です。 test_list_1 = ['1','2','3','2','1'] print(test_list_1) print('------------------------------') test_list_1.remove('2') print(test_list_1)
d8872d8cd83656373c7f45b431de31eaec918f9c
sam1208318697/Leetcode
/Leetcode_env/2019/7_29/Middle_of_the_Linked_List.py
1,521
4.09375
4
# 876.链表的中间结点 # 给定一个带有头结点head的非空单链表,返回链表的中间结点。 # 如果有两个中间结点,则返回第二个中间结点。 # 示例1: # 输入:[1, 2, 3, 4, 5] # 输出:此列表中的结点3(序列化形式:[3, 4, 5])返回的结点值为3。 # (测评系统对该结点序列化表述是[3, 4, 5])。 # 注意,我们返回了一个ListNode类型的对象ans,这样:ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及ans.next.next.next = NULL. # 示例2: # 输入:[1, 2, 3, 4, 5, 6] # 输出:此列表中的结点4(序列化形式:[4, 5, 6])由于该列表有两个中间结点,值分别为3和4,我们返回第二个结点。 # 提示: # 给定链表的结点数介于1和100之间。 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: length = 0 i = head while i : length = length + 1 i = i.next times = length//2 j = head while times != 0: j = j.next times = times - 1 return j node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(8) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node1.next = node2 node2.next = node3 node3.next = node4 # node4.next = node5 # node5.next = node6 sol = Solution() print(sol.middleNode(node1).val)
d0efc5ef74accf02b1739196b798871ce6b07567
ziwnchen/kattis
/2016-17/calendar.py
441
3.65625
4
import sys line=sys.stdin.readline() date_line=list(map(int,line.split())) def judge(date_line): if date_line[0]>31: return 'Format #3' elif (date_line[0]>12) & (date_line[0]<=31): if date_line[2]>31: return 'Format #2' else: return 'Ambiguous' else: if date_line[1]>12: return 'Format #1' else: return 'Ambiguous' print(judge(date_line))
b60914f9e190a43132be5943e41c8ec9cad4a3d8
leticiadesouza/AulasParticulares
/Preparatorios/exerciciosTeste2/exercicio28.py
125
3.875
4
valor = int(input('Informe um numero: ')) if (valor % 2 == 0): print ('Valor eh par') else: print ('Valor eh impar')
01df6c5d9a684750938d8455a7dc6c2b2a2a55b8
changethisusername/uzh
/Informatik1/Ex 3/friendlyPair.py
701
3.65625
4
#You are completely free to change this variables to check your algorithm. __author__ = "Mert Erol" num1 = 6 num2 = 28 def isFriendlyPair(): sum1 = 0 sum2 = 0 validity = True if type(num1) != int: return "Invalid" if type(num2) != int: return "Invalid" if num1 == num2: return "Invalid" if num1 <= 0: return "Invalid" if num2 <= 0: return "Invalid" for i in range(1,num1): if(num1 % i == 0): sum1 = sum1 + i for i in range(1,num2): if(num2 % i == 0): sum2 = sum2 + i if(sum1/sum2 == num1/ num2): return True else: return False print(isFriendlyPair())
468a31c913d5c3b4d4f779588f6dc0dfa7d41ca6
feigaoxyz/gist-collection
/gui/tk/grid.py
1,453
3.5625
4
# http://www.tkdocs.com/tutorial/grid.html from tkinter import * from tkinter import ttk root = Tk() content = ttk.Frame(root, padding=(3, 3, 12, 12)) frame = ttk.Frame(content, borderwidth=5, relief='sunken', width=200, height=100) namelbl = ttk.Label(content, text='Name') name = ttk.Entry(content) one_var = BooleanVar() two_var = BooleanVar() three_var = BooleanVar() one_var.set(True) two_var.set(False) three_var.set(True) one = ttk.Checkbutton(content, text='One', variable=one_var, onvalue=True) two = ttk.Checkbutton(content, text='Two', variable=two_var, onvalue=True) three = ttk.Checkbutton(content, text='Three', variable=three_var, onvalue=False) ok = ttk.Button(content, text='Okey') cancel = ttk.Button(content, text='Cancel') content.grid(column=0, row=0, sticky=(N, S, E, W)) frame.grid(column=0, row=0, columnspan=3, rowspan=2, sticky=(N, S, E, W)) namelbl.grid(column=3, row=0, columnspan=2, sticky=(N, W), padx=5) name.grid(column=3, row=1, columnspan=2, sticky=(N, E, W), pady=5, padx=5) one.grid(column=0, row=3) two.grid(column=1, row=3) three.grid(column=2, row=3) ok.grid(column=3, row=3) cancel.grid(column=4, row=3) root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) content.columnconfigure(0, weight=3) content.columnconfigure(1, weight=3) content.columnconfigure(2, weight=3) content.columnconfigure(3, weight=1) content.columnconfigure(4, weight=1) content.rowconfigure(1, weight=1) root.mainloop()
d2538aeba269de5cf6cbeffba063d3d00d436c67
Strigina/Pyladies
/ukol20.py
236
4
4
while True: is_even = input("Napiš mi číslo: ") if (is_even == "konec"): break elif (int(is_even) % 2) == 0: print ("Číslo je sudé") elif(int(is_even) % 2) != 0: print ("Číslo je liché")
b31ed47000da92358f19843293339a38d6fed65a
abhishekzambre/Python_Programs
/EPI/enumerate.py
72
3.609375
4
l = ["a","b","c"] for item in enumerate(l): print(item) print(l[2])
e4107f706ea375929c5fd380be2478bf7d1f8315
Yashasvii/Project-Euler-Solutions-hackerrank
/forHackerRank/002.py
386
3.984375
4
""" Project Euler Problem 2 ======================= """ def fibonacci_sum(n): i = 1 j = 2 sum = 0 while i < n: temp = i if i % 2 == 0: sum += i i = j j = j + temp return sum if __name__ == '__main__': t = int(input().strip()) for a0 in range(t): n = int(input().strip()) print(fibonacci_sum(n))
1f7d16535fb0ba393c75a5f971faf2e67a9346a3
icanttakeitanymore/python_study
/random_ip.py
2,386
3.5625
4
#!/usr/bin/env python3 import random class GetAddress: """Класс генерации экземпляра адреса и перезагрузки оператора вывода. Аргументы a,b,c,d - октеты адреса""" def __init__(self,a,b,c,d): self.a = a self.b = b self.c = c self.d = d def __str__(self): return '{0}.{1}.{2}.{3}'.format(self.a,self.b,self.c,self.d) def get_random_address(): """Функция генерации адреса""" addr = {'a':0,'b':0,'c':0,'d':0} for key in addr.keys(): oktet = random.randrange(0,254) addr[key] = oktet if addr['d'] == 0: # Если последний октет равен 0, get_random_address() # функция вызывает себя рекурсивно. return addr def get_random_mask(random_addr): """Функция генерации маски""" # Private Networks if random_addr['a'] == 127: return {'a':255,'b':255,'c':255,'d':0} if random_addr['a'] == 10: cidr = random.randint(8,32) rand = '1'*cidr+'0'*(32-cidr) return {'a':255,'b':int(rand[8:16],2),'c':int(rand[16:24],2),'d':int(rand[24:32],2)} if random_addr['a'] == 172 and random_addr['b'] >= 16 and random_addr['b'] < 32: cidr = random.randint(12,16) rand = '1'*cidr+'0'*(32-cidr) return {'a':255,'b':int(rand[8:16],2),'c':int(rand[16:24],2),'d':int(rand[24:32],2)} if random_addr['a'] == 192 and random_addr['b'] == 168: cidr = random.randint(24,32) rand = '1'*cidr+'0'*(32-cidr) return {'a':255,'b':255,'c':int(rand[16:24],2),'d':int(rand[24:32],2)} # Global Networks. bugged cidr = random.randint(1,32) rand = '1'*cidr+'0'*(32-cidr) return {'a':int(rand[0:8],2),'b':int(rand[8:16],2),'c':int(rand[16:24],2),'d':int(rand[24:32],2)} if __name__ == '__main__': # Получаем адрес. random_addr = get_random_address() address = GetAddress(random_addr['a'],random_addr['b'],random_addr['c'],random_addr['d']) # Получаем маску. random_mask = get_random_mask(random_addr) mask = GetAddress(random_mask['a'],random_mask['b'],random_mask['c'],random_mask['d']) print('Адрес : {0}, Маска : {1}'.format(address,mask))
218927ec69fffa2373ab50442467fd72c55b8184
Evoniuk/Fractals-with-Turtle
/Turtle.py
1,889
4.03125
4
""" These programs use the turtle to draw images by transformation rules """ import turtle turtle.speed(0) turtle.delay(0) turtle.hideturtle() def drawCell(c, size): # draws a cell colorMap = {0: 'blue', 1: 'yellow', 2: 'orange', 3: 'red'} turtle.color('black', colorMap[c]) turtle.begin_fill() for i in range(4): turtle.forward(size) turtle.left(90) turtle.end_fill() def drawPile(sandpile, size=25): # uses drawCell to draw a pile for x in sandpile: turtle.back(3 * size) turtle.right(90) turtle.forward(size) turtle.left(90) for y in x: drawCell(y, size) turtle.forward(size) def rewrite(word, productions, n): # performs transformation rules on an input z = [word] for a in range(n): c = '' for b in z[a]: try: c += productions[b] except KeyError: c += b z.append(c) return z[n] def render(word, angle=25, forward=8, position=(0, -300), heading=90): stack = [] # translates transformations into instructions for turtle for char in word: if char == 'F' or char == 'R': turtle.forward(forward) if char == '-': turtle.right(angle) if char == '+': turtle.left(angle) if char == '[': stack.append((turtle.position(), turtle.heading())) if char == ']': position, heading = stack.pop() def kochSnowflake(n=4): # forms a Koch Snowflake render(rewrite('F++F++F', {'F':'F-F++F-F'}, n), angle=60, forward=600/3**n, position=(-300, -200), heading=60) def fassCurve(n=4): # forms a Fass Curve render(rewrite('F', {'F':'F+R++R-F--FF-R+', 'R':'-F+RR++R+F--F-R'}, n), angle=60, position=(-300, -200), heading=120)
f9bf99b34b505dbb1c46ebb8192337e42f5ffb6f
charliedavidhoward/Learn-Python
/whatsTheWeather.py
1,593
4.09375
4
# Create a program that pulls data from OpenWeatherMap.org that prints out information about the current weather, such as the high, the low, and the amount of rain for wherever you live. Depending on how skilled you are, you can actually do some neat stuff with this project. # # Subgoals # # Print out data for the next 5-7 days so you have a 5 day/week long forecast. # # Print the data to another file that you can open up and view at, instead of viewing the information in the command line. # # If you know html, write a file that you can print information to so that your project is more interesting. Here is an example of the results from what I threw together. # # Tips # # APIs that are in Json are essentially lists and dictionaries. Remember that to reference something in a list, you must refer to it by what number element it is in the list, and to reference a key in a dictionary, you must refer to it by it's name. # # Don't like Celsius? Add &units=imperial to the end of the URL of the API to receive your data in Fahrenheit. import requests import math API_key = YOUR_API city_name = input("Enter a city name for next five day forecast: ") base_url = "http://api.openweathermap.org/data/2.5/forecast?" final_url = base_url + "appid=" + API_key + "&q=" + city_name.lower() + "&units=metric" weather_data = requests.get(final_url).json() print("") try: for day in weather_data['list'][::8]: print("{} celsius ({})".format(math.floor(day['main']['temp']), day['weather'][0]['main'])) except KeyError: print("No records for that city")
242bf3e84a72080ee7d37f0144c0da49bb36105a
telandis/pythonexercises
/reversing_coins_solution.py
278
3.796875
4
def reversing_coins_solution(coins): # write your solution here headsCount = 0 tailsCount = 0 for x in coins: if x == 0: headsCount += 1 else: tailsCount += 1 return headsCount if headsCount < tailsCount else tailsCount
197a7039459df5fb04c54bfef2a52738e946c069
younes38/Daily-Coding-Problem
/vmware_problems/problem_1.py
1,070
4.25
4
"""This problem was asked by VMware. The skyline of a city is composed of several buildings of various widths and heights, possibly overlapping one another when viewed from a distance. We can represent the buildings using an array of (left, right, height) tuples, which tell us where on an imaginary x-axis a building begins and ends, and how tall it is. The skyline itself can be described by a list of (x, height) tuples, giving the locations at which the height visible to a distant observer changes, and each new height. Given an array of buildings as described above, create a function that returns the skyline. For example, suppose the input consists of the buildings [(0, 15, 3), (4, 11, 5), (19, 23, 4)]. In aggregate, these buildings would create a skyline that looks like the one below. ______ | | ___ ___| |___ | | | | B | | | C | | A | | A | | | | | | | | | ------------------------ As a result, your function should return [(0, 3), (4, 5), (11, 3), (15, 0), (19, 4), (23, 0)]. """
2eca1dcf36fe10fbb2d67337c1a477155e523d23
lordpews/python-practice
/osmoduleex.py
1,720
4.1875
4
import os # print(dir(os)) print(os.getcwd()) # shows the current directory # example if you want to open a file as f= open("file.txt") # and you do not provide the exact location it ll check the requested file in your current directory ie the directory # where program is currently located that's what 'os.cwd()' will print or return or display """os.chdir("C://")""" # changes the current working directory # print(os.getcwd()) x = (os.listdir()) # Returns a list of all the files or folders present in current working directory # in this case the current working directory is C:// """os.mkdir("this")""" # creates a directory os.chdir("C:/Users/piyush thakur/PycharmProjects") """os.makedirs("lol/lmao")""" # used make a directory inside a directory print(os.getcwd()) # os.makedirs("lol") """os.rename("pepe.txt", "pepee.txt")""" # changes name of a file # syntax os.rename("oldname","newname") print(os.environ.get('path')) print(os.path.join("C://", "pepee.txt")) """ It joins one or more path components. We can join the paths by simply using a + sign, but the benefit of using this function is that we do not have to worry about extra slashes between the components. So less accuracy still provides us with the same result. """ print(os.path.exists("C:/Users/piyush thakur/PycharmProjects")) # checks whether a 'PATH' exists or not if it exists it'll return true else it'll return falls print(os.path.isfile("jila2.py")) # checks whether a 'FILE' exists or not if it exists it'll return true else it'll return falls print(os.path.isdir("exercise 5")) # checks whether a 'DIRECTORY' exists or not if it exists it'll return true else it'll return falls print(x[0]) print(type(x[0]))
79ac58b430fcaa57eaf7373b33987c57a2fb74ae
Nikkuniku/AtcoderProgramming
/ABC/ABC100~ABC199/ABC171/C.py
613
3.671875
4
n=int(input()) # alp='abcdefghijklmnopqrstuvwxyz' # ########関数部分############## # def Base_10_to_n(X, n): # if (int(X/n)): # return Base_10_to_n(int(X/n), n)+' '+str(X%n) # return str(X%n) # ############################ # l=list(Base_10_to_n(n,26).split()) # print(l) # ans='' # for i in range(len(l)): # ans+=alp[int(l[i])-1] # 数値→アルファベット def num2alpha(num): if num<=26: return chr(64+num) elif num%26==0: return num2alpha(num//26-1)+chr(90) else: return num2alpha(num//26)+chr(64+num%26) ans=num2alpha(n).lower() print(ans)
292441006158605b32e02d5f14e18257ad62e8f5
jakubfolta/CodecademyPython
/lesson11.py
6,235
3.984375
4
#Class syntax class Animal(): pass #Classier Classes class Animal(): def __init__(self): pass #Let's not get too selfish class Animal(): def __init__(self, name): self.name = name #Instantiating Your First Object class Animal(): def __init__(self, name): self.name = name zebra = Animal('Jeffrey') print(zebra.name) #More on __init__() and self class Animal(object): def __init__(self, name, age, is_hungry): self.name = name self.age = age self.is_hungry = is_hungry zebra = Animal("Jeffrey", 2, True) giraffe = Animal("Bruce", 1, False) panda = Animal("Chad", 7, True) print(zebra.name, zebra.age, zebra.is_hungry) print(giraffe.name, giraffe.age, giraffe.is_hungry) print(panda.name, panda.age, panda.is_hungry) #Class Scope class Animal(object): is_alive = True def __init__(self, name, age): self.name = name self.age = age zebra = Animal('Jeffrey', 2) giraffe = Animal('Bruce', 1) panda = Animal('Po', 7 ) print(zebra.name, zebra.age, zebra.is_alive) print(giraffe.name, giraffe.age, giraffe.is_alive) print(panda.name, panda.age, panda.is_alive) #A methodical approach class Animal(object): is_alive= True def __init__(self, name, age): self.name = name self.age = age def description(self): print(self.name) print(self.age) hippo = Animal('Max', 3) hippo.description() #They're multiplying class Animal(object): is_alive = True health = 'good' def __init__(self, name, age): self.name = name self.age = age def description(self): print(self.name) print(self.age) hippo = Animal('Max', 5) sloth = Animal('John', 6) ocelot = Animal('Ray', 5) hippo.description() print(hippo.health) print(sloth.health) print(ocelot.health) #It's not all animals and fruits class ShoppingCart(object): def __init__(self, customer_name): self.customer_name = customer_name self.items_in_cart = {} def add_items(self, product, price): if not product in self.items_in_cart: self.items_in_cart[product] = price print(product + ' added') else: print(product + 'is already in the cart') def remove_items(self, product): if product in self.items_in_cart: del self.items_in_cart[product] print(product + ' removed.') else: print(product + 'is not in the cart.') my_cart = ShoppingCart('Qba') my_cart.add_items('Book', 7) #Warning: Here be dragons class Customer(object): def __init__(self, customer_id): self.customer_id = customer_id def display_cart(self): print('I\'m a string that stands in for the contents of your shopping cart.') class ReturningCustomer(Customer): def display_order_history(self): print('I\'m a string thatstands in for your order history.') monthy_python = ReturningCustomer('ID: 12345') monthy_python.display_cart() monthy_python.display_order_history() #Inheritance syntax class Shape(object): def __init__(self, number_of_sides): self.number_of_sides = number_of_siides class Triangle(Shape): def __init__(self, side1, side2, side3): self.side1 = side1 self.side2 = side2 self.side3 = side3 #Override! class Employee(object): def __init__(self, employee_name): self.employee_name = employee_name def greet(self, other): print('Hello %s, welcome!' % other.employee_name) def calculate_wage(self, hours): self.hours = hours return hours * 20.00 class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours * 12.00 lothar = PartTimeEmployee('Lothar') print(lothar.calculate_wage(130)) lothar.greet(lothar) #This looks like a job for... class Employee(object): def __init__(self, employee_name): self.employee_name = employee_name def calculate_wage(self, hours): self.hours = hours return hours * 20.00 class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours * 12.00 def full_time_wage(self, hours): return super(PartTimeEmployee, self).calculate_wage(hours) milton = PartTimeEmployee('John') print(milton.full_time_wage(10)) #Class basics class Triangle(object): def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 #Class it up class Triangle(object): def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def check_angles(self): total = [self.angle1, self.angle2, self.angle3] if sum(total) == 180: return True else: return False triangle = Triangle(32, 43, 66) print(triangle.check_angles()) #Instantiate an object class Triangle(object): def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def check_angles(self): if (self.angle1 + self.angle2 + self.angle3) == 180: return True else: return False my_triangle = Triangle(90, 30, 60) print(my_triangle.number_of_sides) print(my_triangle.check_angles()) #Inheritance class Triangle(object): def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def check_angles(self): if (self.angle1 + self.angle2 + self.angle3) == 180: return True else: return False my_triangle = Triangle(90, 30, 60) print(my_triangle.number_of_sides) print(my_triangle.check_angles()) class Equilateral(Triangle): angle = 60 def __init__(self): self.angle1 = self.angle self.angle2 = self.angle self.angle3 = self.angle
d4b86d091af13f3d6d5afdf0370a5705cfa77835
zenmeder/leetcode
/492.py
371
3.5625
4
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" from math import sqrt,ceil class Solution(object): def constructRectangle(self, area): """ :type area: int :rtype: List[int] """ l = int(ceil(sqrt(area))) while l < area: if not area % l: return [l, area//l] l += 1 return [area, 1] print(Solution().constructRectangle(1))
0abe0aa355a00875b66cf982631b91231c6c5a11
MahanthMohan/Python-Programs
/SolveMatrix.py
1,236
4.125
4
import numpy as np print("*** A solver for the systems of equations Ax + By = C ***") R = int(input("Enter the number of rows: ")) C = int(input("Enter the number of columns: ")) print("Enter the entries in a single line for the A matrix, rowwise , and spaced out using commas ") # single line separated by space enter_values = list(map(float, input().split(","))) # Logic - seperates the float values by taking ',' as a reference, and the map operator accepts values until all rows and columns are maxed out # For printing the matrix A = np.matrix(enter_values).reshape(R, C) # "Reshapes" it into a matrix print("\nThis is the A Matrix") print(A) print("Enter the entries in a single line for the C matrix, rowwise , and spaced out using commas ") # single line separated by space enter_values = list(map(float, input().split(","))) # Logic - seperates the float values by taking ',' as a reference, and the map operator accepts values until all rows and columns are maxed out # For printing the matrix C = np.matrix(enter_values).reshape(2, 1) # "Reshapes" it into a matrix print("\nThis is the C Matrix") print(C) B = np.linalg.solve(A,C) print("\nThis is the vector solution to the systems of equations") print(B)
8a06e45c15c1c30c065a32dd288bac9ae12d8936
TheTurtle3/Python-Mega-Course
/Section 2 - Getting Started/basics.py
134
3.65625
4
day_hours = 24 week_days = 7 week_hours = week_days * day_hours print(week_hours) user_input = input("Testing: ") print(user_input)
d586b18214e53d8044ddd031b0ca49140a89b6c7
abilkht/attendance-bot
/code.py
644
3.65625
4
def miniproject(filename): f = open(filename, 'r') Bluelist = [] List = [] for line in f.readlines(): List.extend(line.split()) for c in List: if c not in Bluelist: Bluelist.append(c) return Bluelist d = miniproject("database.txt") def data(filename): f = open(filename, 'r') List = [] Bluelist = [] Studentlist = [] for line in f.readlines(): List.extend(line.split()) a = len(List) b = {} for x in range(a - 1): if x % 2 == 0: b[List[x + 1]] = List[x] return b a = data("databank.txt") def check(L1,D1): for x in range(len(L1)): if L1[x] in D1: print (D1[L1[x]] + " is Present!") print(check(d, a))
3198ea7524858e62a5618c77d73c81fce4568bf2
as1k/webdev-labs
/week8/codingbat/8_list2/1.py
95
3.65625
4
def count_evens(nums): cnt = 0 for n in nums: if n % 2 == 0: cnt+=1 return cnt
6abce29aaa6e8c8c475fc3f00367b08b0479ce4a
LizinczykKarolina/Python
/Regex/ex10.py
224
4.375
4
#12. Write a Python program that matches a word containing 'z'. import re my_string = "My owlz likes me and is now zzz." p = (re.search(r'\w*z.', my_string)) if p: print "found a match!" else: print "Not matched!"
65eba48c9fdf51d6d80b4b3921d4044e2cd48c3a
igortereshchenko/amis_python
/km72/Zinchuk_Kostyantin/5/task3.py
268
3.765625
4
_list=(input("enter list : ")).split() _list2=[] for i in range(len(_list)): for j in range(len(_list)): if (_list[i] == _list[j]) and (i != j): break else: _list2.append(_list[i]) print(' '.join([str(i) for i in _list2]))
737eeca8f927f982ad47a0bdb4b5390afd19e12f
JacksonJLam/python
/3.1/HoP9.py
517
4.03125
4
#HoP9.py #Jackson Lambert 1-4-19 #calculates easter date def main() : print("This script will find the date of easter in a given year") year = int(input("Enter a year: ")) if year >=1982 and year <=2048 : a = year % 19 b = year % 4 c = year % 7 d = (19 * a + 24) % 30 e = (2*b + 4*c + 6*d + 5) % 7 date = 22 + d + e date = date - 31 print("Easter is on April",date,"in", year) else : print("Year out of range") main()
8a41441beb3b53d81241bdd569ab73156dc6df52
amber1406/leecode
/link/reverseList.py
847
3.96875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if not head or not head.next: return head # #迭代 # cur=head # nexts=head.next # cur.next=None # while nexts: # temp=nexts.next # nexts.next=cur # cur=nexts # nexts=temp # return cur # #递归 last_head = self.reverseList(head.next) head.next.next = head head.next = None return last_head l1 = ListNode(1) l1.next = l11 = ListNode(2) l11.next = l12 = ListNode(3) l12.next = l13 = ListNode(4) s = Solution() num = s.reverseList(l1) while num: print(num.val,end="") num = num.next
af7b7f87e7c9d20cb3cfb0ec84ca7b90a839b8cf
aman0864/CWH_1-Python3
/tutorial 26.py
948
4.34375
4
# Date 18-3-2021 file1 = open("tutorial 26.txt", "r") content = file1.read() print(content) file1.close() # Note: Do not forget to close a file, it is very important to close a file after it's use is finished # The upper syntax will help you to read and print a file print(10*"\n") file1 = open("tutorial 26.txt", "r") content = file1.read(30) print(content) file1.close() # The upper syntax will help you to read and print only first 30 characters of the given file print(10*"\n") file1 = open("tutorial 26.txt", "r") print(file1.readline()) print(file1.readline()) print(file1.readline()) print(file1.readline()) file1.close() # The upper syntax will help you to read and print only first four lines of the given file print(10*"\n") file1 = open("tutorial 26.txt", "r") print(file1.readlines()) file1.close() # The upper syntax will help you to read and print lines of the given file in the form of list
8f4cb28d276575e1122521990bac85e11f7b786c
gnikesh/project-euler
/problem26.py
1,578
4.03125
4
''' A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. ''' ''' My Solution: Length of repeating decimal n, L(n) = n - 1 if and only if n is prime and 10 is primitive root modulo n. So, the longest length of repeating digit sequence (reptend) would be 1 less than n, for the largest n that satiesfies above condition. Not sure if largest non-prime number less than 1000 will have repeating digit sequence that would be longer than that of the largest prime number less than 1000 (983 in this case). source: https://en.wikipedia.org/wiki/Repeating_decimal ''' from math import gcd # Function to test if n is prime or not def is_prime(n): for i in range(2, int(n ** (1/2)) + 1): if n % i == 0: return False return True # Function to test if rt(10) is primitive root modulo n def has_primitive_root(n, rt=10): true_set = set([i for i in range(1, n)]) result_set = set() for i in range(1, n + 1): result_set.add(10 ** i % n) if true_set == result_set: return True return False if __name__ == "__main__": maximum = 0 for i in range(1, 1000): if is_prime(i) and has_primitive_root(i): maximum = i print(maximum)
b1f3efc88845b399ceb068625f7c6902ccefc009
dgore7/project-euler
/largest_prime_factor.py
408
4
4
# Problem 3 import math def largest_prime_factor(number): largest_prime = 2 while number % 2 == 0: number = number // 2 for i in range(3, int(math.sqrt(number)), 2): if number % i == 0: largest_prime = i while number % i == 0: number //= i return largest_prime if __name__ == '__main__': print(largest_prime_factor(600851475143))
e1325cd61cd8cba7e26623927cc67159e03b963b
RuslanMakeev/python_automation
/Functions/func_return.py
561
4.28125
4
def maximum(x, y): if x > y: return x elif x == y: return 'Числа равны.' else: return y print(maximum(2, 3)) '''Функция maximum возвращает максимальный из двух параметров, которые в данном случае передаются ей при вызове. Она использует обычный условный оператор if..else для определения наибольшего числа, а затем возвращаетэто число.'''
95d7b8d59bc14b48c5b275176d71dde892d7135a
cpe202spring2019/lab1-JillianQuinn
/location_tests.py
1,885
3.796875
4
import unittest from location import * class TestLab1(unittest.TestCase): def test_repr(self): loc = Location("SLO", 35.3, -120.7) """Test the string representation format""" self.assertEqual(repr(loc), "Location('SLO', 35.3, -120.7)") """Whole number check.""" loc = Location('Mercer Island', 20, 19) self.assertEqual(repr(loc), "Location('Mercer Island', 20, 19)") def test_eq(self): loc = Location("SLO", 35.3, -120.7) loc2 = Location("SLO", 35.3, -120.7) loc3 = loc loc4 = Location("Mercer Island", 20, 19) """Test same location.""" self.assertEqual(loc, loc2) self.assertTrue(loc == loc2) """Test different locations.""" self.assertFalse(loc == loc4) """Test same pointed location.""" self.assertTrue(loc == loc3) """Test wrong type.""" self.assertFalse(loc == "SLO") def test_init(self): loc = Location("SLO", 35.3, -120.7) """Test the name""" self.assertEqual(loc.name, "SLO") """Test the lat.""" self.assertAlmostEqual(loc.lat, 35.3) """Test the lon.""" self.assertAlmostEqual(loc.lon, -120.7) other = Location("SLO", 35.3, -120.7) """Test the equal function for different locations, same values""" self.assertEqual(loc, other) loc = Location("SLO", 35.3, -120.7) other = loc """Test the equal function for same location""" self.assertEqual(loc, other) def test_init(self): loc = Location("SLO", 35.3, -120.7) """Test the location name""" self.assertEqual(loc.name, "SLO") """Test the lat.""" self.assertEqual(loc.lat, 35.3) """Test the lon.""" self.assertEqual(loc.lon, -120.7) if __name__ == "__main__": unittest.main()
479c7d3e5f82fb135b5dc6fdb440c8d968358c59
Arjun-Pythonista/Python_Scripts-Arjun
/Palindrome.py
456
4.3125
4
# 1) Palindrome # TASK 1: By-Arjun # Enter a string to check if it is palindrome using a function. # Write a function that takes string as input and returns if that string is palindrome or not print ("What is the word you would like to check?") def isPalindrome(): word1 = input ('>') word2 = word1[::-1] if word1 == word2: print('%s is a palindrome'% word1) else: print("%s is not a palindrome!" %word1) isPalindrome()
48ac2a863dfab9c737d6d7838b0e23074de9cb93
flipthedog/CS4341
/Homework_1/ex1.py
4,150
3.75
4
# Floris van Rossum # CS4341 - Homework 1 # Professor Carlo Pinciroli # Exercise 1 # ex1.py class ConnectFour: """Connect four game""" def __init__(self, board, w, h): """Class constructor""" # Board data self.board = board # Board width self.w = w # Board height self.h = h def isLineAt(self, x, y, dx, dy): """Return True if a line of identical tokens exists starting at (x,y) in direction (dx,dy)""" # The player (1 or 2) we are testing the line for to see if they won player = self.board[y][x] # Test for directional line if dx == 0 and dy == 1: # Vertical line # Move out 3 more spaces for i in range(1, 4): # Check if the square is the same as the player square if (y + i) < self.h: cell = self.board[y + i][x] if not cell == player: # Cell is not same as player, not a line return False else: # End of board reached, not a line return False # print("Won because vertical line") # Line at this point return True elif dx == 1 and dy == 0: # Horizontal line for i in range(1, 4): if (x + i) < self.w - 1: cell = self.board[y][x + i] if not cell == player: return False else: return False # print("Won because horizontal line") return True elif dx == 1 and dy == 1: # Diagonal down for i in range(1, 4): if ((x + i) < self.w - 1) and ((y + i) < self.h - 1): cell = self.board[y + i][x + i] if not cell == player: return False else: return False # print("Won because down diagonal") return True elif dx == 1 and dy == -1: # Diagonal up for i in range(1, 3): if ((x + i) < self.w - 1) and ((y - i) > 0): cell = self.board[y - i][x + i] if not cell == player: return False else: return False # print("Won because up diagonal") return True def isAnyLineAt(self, x, y): """Return True if a line of identical symbols exists starting at (x,y) in any direction""" # Debugging Statement: # print("Checking: " + str(self.board[y][x]) + " at " + "(" + str(x) + " ," + str(y) + ")") return (self.isLineAt(x, y, 1, 0) or # Horizontal self.isLineAt(x, y, 0, 1) or # Vertical self.isLineAt(x, y, 1, 1) or # Diagonal up self.isLineAt(x, y, 1, -1)) # Diagonal down def getOutcome(self): """Returns the winner of the game: 1 for Player 1, 2 for Player 2, and 0 for no winner""" # Your code here, use isAnyLineAt() # Loop through all spaces for width in range(0, self.w): for height in range(0, self.h): # If the space is not 0, test for line if not self.board[height][width] == 0: # See if there is a line if self.isAnyLineAt(width, height): # Check who won if self.board[height][width] == 1: # Cell contains a 1, player 1 won return 1 if self.board[height][width] == 2: # Cell contains a 2, player 2 won return 2 return 0 def printOutcome(self): """Prints the winner of the game""" o = self.getOutcome() # Find the outcome of the game if o == 0: print("No winner") else: print("Player", o, " won")
605bfc32eef2e9134d3aa5e1facd6859fad3a189
vporta/python-calculator
/HW03-VincentPorta.py
12,758
3.90625
4
""" Created on Monday Sept 19 2017 @author: Vincent Porta Special Topics, Homework 03 Implement a class for fractions that supports addition, subtraction, multiplication, division, <, <=, !=, ==, >, and >=. """ import unittest class Fraction: """ A Fraction class calculator that prompts the user for numeric input of two fractions and an operator, and performs the appropriate mathematical operation. """ __slots__ = ['numerator', 'denominator'] def __init__(self, numerator=0, denominator=1): """ Create new numerator and denominator""" self.numerator = numerator self.denominator = denominator if self.denominator == 0: raise(ValueError("Denominator cannot be 0")) def __add__(self, other): """ Return a Fraction with the sum of self """ greatest_common_denom = self.denominator * other.denominator fraction_one_numerator = self.numerator * other.denominator fraction_two_numerator = other.numerator * self.denominator sum_of_numerators = fraction_one_numerator + fraction_two_numerator # common = self.simplify(sum_of_numerators, greatest_common_denom) return Fraction(sum_of_numerators, greatest_common_denom) def __sub__(self, other): """ Return a Fraction with the difference of self """ greatest_common_denom = self.denominator * other.denominator fraction_one_numerator = self.numerator * other.denominator fraction_two_numerator = other.numerator * self.denominator sum_of_numerators = fraction_one_numerator - fraction_two_numerator return Fraction(sum_of_numerators, greatest_common_denom) def __mul__(self, other): """ Return a Fraction with the product of self """ greatest_common_denom = self.denominator * other.denominator numerator = self.numerator * other.numerator return Fraction(numerator, greatest_common_denom) def __truediv__(self, other): """ Return a Fraction with the quotient of self """ reciprocal = self.numerator * other.denominator greatest_common_denom = self.denominator * other.numerator return Fraction(reciprocal, greatest_common_denom) def __eq__(self, other): """ Return True/False if the two fractions are equal """ first_num = self.numerator * other.denominator second_num = other.numerator * self.denominator return first_num == second_num def __ne__(self, other): """ Check if the fractions are not equal """ first_num = self.numerator * other.denominator second_num = other.numerator * self.denominator return first_num != second_num def __lt__(self, other): """ Check if the fraction is less than """ return (self.numerator/self.denominator) < (other.numerator/other.denominator) def __le__(self, other): """ Check if the fraction is less than or equal to """ return (self.numerator/self.denominator) <= (other.numerator/other.denominator) def __gt__(self, other): """ Check if the fraction is greater than """ return (self.numerator/self.denominator) > (other.numerator/other.denominator) def __ge__(self, other): """ Check if the fraction is greater than or equal to """ return (self.numerator/self.denominator) >= (other.numerator/other.denominator) def __str__(self): """ Return a string to represent the Fraction """ return str(self.numerator) + '/' + str(self.denominator) def operation_logic(self, fraction_one, fraction_two, operator): """ Performs arithmetic logic for each operator """ if fraction_two == fraction_one: return print (fraction_one == fraction_two) elif operator == "+": return print(fraction_one + fraction_two) elif operator == "-": return print(fraction_one - fraction_two) elif operator == "*": return print(fraction_one * fraction_two) elif operator == "/": return print(fraction_one / fraction_two) elif operator == '!=': return print(fraction_one != fraction_two) elif operator == '<': return print(fraction_one < fraction_two) elif operator == '<=': return print(fraction_one <= fraction_two) elif operator == '>': return print(fraction_one > fraction_two) elif operator == '>=': return print(fraction_one >= fraction_two) else: return print("Invalid operator.") def simplify(self): """ Simplify the fraction by finding the greatest common factor """ gcf = 1 for i in range(min(abs(self.numerator), abs(self.denominator)), 1, -1): print(i) if self.numerator % i == 0 and self.denominator % i == 0: gcf = i num = int(self.numerator/gcf) denom = int(self.denominator/gcf) return Fraction(num, denom) return self def main(self): """ Ask the user for the first numerator and denominator, the operator, and the second numerator and denominator, then prints the result of applying the operator to the two fractions """ print("Welcome to the Fraction Calculator!") try: numerator = int(input("Fraction 1 numerator: ")) denominator = int(input("Fraction 1 denominator: ")) operation_input = input("Operation (+, -, *, /, !=, ==, <, <=, >, >=): ") numerator_two = int(input("Fraction 2 numerator: ")) denominator_two = int(input("Fraction 2 denominator: ")) fraction_one = Fraction(numerator, denominator) fraction_two = Fraction(numerator_two, denominator_two) self.operation_logic(fraction_one, fraction_two, operation_input) except ValueError: return "Please enter a number." class FractionTest(unittest.TestCase): def test_init(self): """ Verify that the numerator and denominator args are set properly """ fraction = Fraction(3, 4) fraction_default_args = Fraction() self.assertIsInstance(fraction, Fraction) self.assertEqual(fraction.numerator, 3) self.assertEqual(fraction.denominator, 4) self.assertIsInstance(fraction_default_args, Fraction) self.assertEqual(fraction_default_args.numerator, 0) self.assertEqual(fraction_default_args.denominator, 1) def test_zero_denominator(self): """ Verify that an exception is raised when the denominator is equal to 0 """ fraction = Fraction(1, 1) self.assertRaises(ValueError, Fraction.__init__, fraction, 1, 0) def test_str(self): """ Verify that __str__() works properly """ fraction = Fraction(3, 4) self.assertEqual(str(fraction), '3/4') def test_eq(self): """ Test fraction equality """ f1 = Fraction(3, 4) f2 = Fraction(6, 8) f3 = Fraction(9, 12) f4 = Fraction(3, 4) f5 = Fraction(123456782345, 1234567892343) f6 = Fraction(123456782345, 1234567892343) self.assertEqual(f1, f4) self.assertAlmostEqual(f5, f6) self.assertTrue(f1 == f1) self.assertTrue(f1 == f2) self.assertTrue(f1 == f3) self.assertTrue(f2 == f3) self.assertFalse(f1 == Fraction(3, 5)) def test_plus(self): """ Test fraction addition """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) self.assertTrue((f1 + f1) == Fraction(6, 4)) self.assertTrue((f1 + f2) == Fraction(5, 4)) self.assertTrue((f1 + f3) == Fraction(13, 12)) def test_subtract(self): """ Test fraction subtraction """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(-2, 3) f5 = Fraction(-2, -5) self.assertTrue((f1 - f1) == Fraction(0, 16)) self.assertTrue((f1 - f2) == Fraction(1, 4)) self.assertTrue((f1 - f3) == Fraction(5, 12)) self.assertTrue((f1 - f4) == Fraction(17, 12)) def test_divide(self): """ Test fraction divide """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(-2, 3) f5 = Fraction(-2, -5) self.assertTrue((f1 / f1) == Fraction(1, 1)) self.assertTrue((f1 / f2) == Fraction(3, 2)) self.assertTrue((f1 / f3) == Fraction(9, 4)) def test_multiply(self): """ Test fraction multiply """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(-2, 3) f5 = Fraction(-2, -5) self.assertTrue((f1 * f1) == Fraction(9, 16)) self.assertTrue((f1 * f2) == Fraction(3, 8)) self.assertTrue((f1 * f3) == Fraction(1, 4)) self.assertTrue((f1 * f4) == Fraction(-1, 2)) def test_ne(self): """ Test fraction not equal """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(-2, 3) f5 = Fraction(-2, -5) f6 = Fraction(2, 3) self.assertNotEqual(f1, f4) self.assertNotEqual(f6, f4) self.assertFalse((f1 != f1) == True) self.assertTrue((f1 != f2) == True) self.assertTrue((f1 != f3) == True) self.assertTrue((f1 != f4) == True) def test_lt(self): """ Test fraction less than """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(2, 3) f5 = Fraction(-2, -5) self.assertLess(f3, f1) self.assertLess(f5, f1) self.assertFalse((f1 < f2) == True) self.assertFalse((f4 < f2) == True) self.assertTrue((f3 < f2) == True) self.assertTrue((f3 < f1) == True) self.assertTrue((f5 < f2) == True) def test_le(self): """ Test fraction less than or equal to """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(3, 4) f5 = Fraction(-2, -5) self.assertLessEqual(f5, f1) self.assertLessEqual(f1, f4) self.assertLessEqual(f2, f4) def test_gt(self): """ Test fraction greater than """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) f4 = Fraction(0, 4) self.assertGreater(f1, f2) self.assertGreater(f1, f3) self.assertGreater(f1, f4) def test_ge(self): """ Test fraction greater than or equal to """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 3) self.assertGreaterEqual(f1, f1) self.assertGreaterEqual(f1, f2) self.assertGreaterEqual(f1, f3) def test_operation_logic(self): """ Test for correct logic and operators """ f1 = Fraction(3, 4) f2 = Fraction(1, 2) f3 = Fraction(1, 2) operators = { 'plus': '+', 'minus': '-', 'multiply': '*', 'divide': '/', 'equal': '==', 'notequal': '!=', 'lessthan': '<', 'lessthan_equal': '<=', 'greaterthan': '>', 'greaterthan_equal': '>=' } self.assertEqual(operators['plus'], '+') self.assertEqual(operators['minus'], '-') self.assertEqual(operators['multiply'], '*') self.assertEqual(operators['divide'], '/') self.assertEqual(operators['equal'], '==') self.assertEqual(operators['notequal'], '!=') self.assertEqual(operators['lessthan'], '<') self.assertEqual(operators['lessthan_equal'], '<=') self.assertEqual(operators['greaterthan'], '>') self.assertEqual(operators['greaterthan_equal'], '>=') def test_simplify(self): f1 = Fraction(10, 8).simplify() f2 = Fraction(20, 5).simplify() f3 = Fraction(9, 27).simplify() f4 = Fraction(-10, 20).simplify() f5 = Fraction(10, -20).simplify() f6 = Fraction(-10, -20).simplify() self.assertEqual(str(f1), '5/4') self.assertEqual(str(f2), '4/1') self.assertEqual(str(f3), '1/3') self.assertEqual(str(f4), '-1/2') self.assertEqual(str(f5), '1/-2') # self.assertEqual(str(f6), '1/2') if __name__ == '__main__': fraction = Fraction() unittest.main(exit=False, verbosity=2) # print(fraction.main())
8198a94c5b7747d03f956884562d793bdccf0d45
Knighthawk-Leo/CODE-CHEF
/COOK-OFF/WhichDivision.py
198
3.578125
4
# cook your code here t=int(input()) for x in range (t): r=int(input()) if(r<1600): print('3') elif(1600<=r and r<2000): print('2') elif(r>=2000): print('1')
f6d73921fd19cc540a90eaca4e2704f7c5162122
ioannischristou/popt4jlib
/testdata/cluster_data/random_weights_vector_maker.py
401
3.5
4
if __name__ == '__main__': import random n = int(input('Enter # non-negative random numbers to generate:')) maxw = float(input('Enter maximum (positive) weight value:')) fname = input('Enter filename to write numbers onto:') f = open(fname, 'w') for i in range(n): r = random.random()*maxw if r <= 0: r = maxw f.write(str(r)+'\n') f.flush() f.close()
b4cfa464e288babfc82bac07e3c653ef2cd968ec
jingweiwu26/Practice_code
/141. Linked List Cycle.py
740
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 22 18:34:23 2017 @author: Wu Jingwei """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: return False first=head.next second=head.next.next while first and second: if first==second: return True if not second.next: return False first=first.next second=second.next.next return False
9156a3f1d99983584f71ee0648f5d9293fc0ac7c
SWB-Dev/PracticePython.org-Exercises
/Exercise9.py
797
3.953125
4
#Exercise 9 - Guessing Game One #PracticePython.org from random import randint def get_user_guess(): guess = int(input("Pick a number between 1 and 9. ")) if guess not in range(1,10): print("Number was not a valid guess. Please try again. ") get_user_guess() return guess numToGuess = randint(1,9) print("Are you ready to please the game?") userGuesses = [] while numToGuess not in userGuesses: guess = get_user_guess() if guess in userGuesses: print("You have already guessed that number!") else: if guess > numToGuess: print("Your guess was too high!") elif guess < numToGuess: print("Your guess was too low!") elif guess == numToGuess: print("You guessed correctly!") userGuesses.append(guess) print(userGuesses)