blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c02e22d737b5fd6d67359f913faaa23eca061dc8
ebresie/MyGitStuff
/books/OReillyBooks/LearningPython/lists.py
711
4.1875
4
L=[123, 'spam',1.23]; print(L); print('len=',len(L)) # Indexing by position 123 print(L[0]) # Slicing a list returns a new list [123, 'spam'] print(L[:-1]) # Concat/repeat make new lists too [123, 'spam', 1.23, 4, 5, 6] print(L + [4, 5, 6]) print(L * 2) L.append('NI') print(L) # additional list operators L.insert(123,1) print('insert=',L) L.remove(1) print('remove=',L) L.extend( [3] ) print('extend=',L) print('before reverse=',L) L.reverse() print('reverse=',L) N=[1,5,4,2,100,2,3] N.sort() print('sort=',N) print('before reverse=',N) N.reverse() print('reverse=',N) # 0..3 (list() required in 3.X) [0, 1, 2, 3] print(list(range(4)))  # −6 to +6 by 2 (need list() in 3.X) print(list(range(-6, 7, 2)))
true
acffad6b2b6e77a9c93642e094345a1bbc1e1c91
abhijeetanand163/Python-Basic
/distance.py
2,774
4.34375
4
import numpy as np class point: def __init__(self, x, y): self.x = x self.y = y class distance(): """ This class contains three different function. 1. Rooks Distance 2. Pandemic Distance 3. Levenshtein Distance """ # 1. Rooks Distance , otherwise also called Manhattan Distance def ManhattanDistance(point1, point2): """ The Manhattan distance, also known as rectilinear distance, city block distance, taxicab metric is defined as the sum of the lengths of the projections of the line segment between the points onto the coordinate axes. In chess, the distance between squares on the chessboard for rooks is measured in Manhattan distance. It is given by |x1 - x2| + |y1 - y2| # for example I am putting it in the form of dictionary. Note : Please input the data in the following dictionary format. Check "Class point" for more detials. >>> point1 = point(2,3) >>> point2 = point(5,1) >>> ManhattanDistance(point1, point2) 5 """ x1 = point1.x x2 = point2.x y1 = point1.y y2 = point2.y manhattandistance = np.abs(x1 - x2) + np.abs(y1 - y2) return manhattandistance # 2. Pandemic Distance # 3. Levenshtein Distance def LevenshteinDistance(a, b): """ This function takes two string as input and return Levenshtein distance between them. For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits: kitten → sitten (substitution of "s" for "k") sitten → sittin (substitution of "i" for "e") sittin → sitting (insertion of "g" at the end). >>> LevenshteinDistance('cat','bat') 1 Since we only need to replace 'c' of cat to 'b' of bat Note: a and b are string so put it under a double bracket or single bracket. """ initial_cost = 0 total_cost = 0 if (len(a) != len(b)): initial_cost = np.abs(len(a) - len(b)) else: initial_cost = 0 if (len(a) <= len(b)): for i in range(len(a)): if (a[i] != b[i]): total_cost += 1 else: pass else: for i in range(len(b)): if (b[i] != a[i]): total_cost += 1 else: pass return initial_cost + total_cost
true
983505065449a5c2dec5f57c6801aa2ef81cf868
Patrick-Ali/210CT-Programming-Algorithms-Data-Structures
/FinalPrograms/vowelsRecursive.py
885
4.125
4
def check(letter, vowel, count, size): #apple = "This letter is not a vowel" #print(letter) if(count >= size): #print("Count is %d" % count) #print("Hit") return (True) #print("Vowel is: %s" % vowel[count].upper()) if letter == vowel[count] or letter == vowel[count].upper(): #print("Working") return (False) else: return check(letter, vowel, count+1, size) def main(): word = input("Please enter a word: ") vowels = "aeiou" newWord = "" count = 0 size = len(vowels) for i in word: #print(i) count = 0 isVowel = check(i, vowels, count, size) #print("This letter is %s a vowel" % isVowel) if isVowel != False: newWord = newWord + (i) print("The original word was: %s" % word) print("The word without vowels is: %s" % newWord) if __name__ == "__main__": main()
true
b26e7f0eb0e4c5b815dfa10022181c3aaa960598
coffeblackpremium/exerciciosPythonBasico
/pythonProject/EstruturaSequenciais/exercicio005/exercicio005.py
205
4.125
4
""" 005)Faça um Programa que converta metros para centímetros. """ metros = float(input('Digite o metro para ser convertido: ')) centimetros = metros * 100 print(f'Esse valor em metros é {centimetros}')
false
a5aa2e1f468b4b4ea9c2ab8ce0957fb3df0c4076
coffeblackpremium/exerciciosPythonBasico
/pythonProject/EstruturaDecisao/exercicio004/exercicio004.py
445
4.1875
4
""" 004)Faça um Programa que verifique se uma letra digitada é vogal ou consoante. """ letra_digitada = input('Digite uma letra para Saber se é vogal ou consoante: ') if letra_digitada.lower() == 'a' or letra_digitada.lower() == 'o' or \ letra_digitada.lower() == 'e' or letra_digitada.lower() == 'i' or letra_digitada.lower() == 'u': print(f'{letra_digitada} é uma Vogal') else: print(f'{letra_digitada} é uma Consoante')
false
5643af118ca27ca7d44e48b4217ef85c9b716dd1
coffeblackpremium/exerciciosPythonBasico
/pythonProject/ExerciciosListas/exercicio008/exercicio008.py
401
4.28125
4
""" 008)Faça um Programa que peça a idade e a altura de 5 pessoas, armazene cada informação no seu respectivo vetor. Imprima a idade e a altura na ordem inversa a ordem lida. """ idade_pessoa = [int(input('Digite a sua idade: ')) for nova_idade in range(5)] altura_pessoa = [float(input('Digite a sua altura: ')) for nova_altura in range(5)] print(idade_pessoa.reverse(), altura_pessoa.reverse())
false
561dd19b8f6fb46448a3287960701d2e844626d0
janina3/Python
/CS 1114/drawRectangle.py
769
4.125
4
import random def drawRectangle(numRows, numColumns): '''Draws a rectangle made up of random digits. Rectangle has length numColumns and height numRows.''' for i in range(numRows): #print string of random digits of length numColumns string = '' for j in range(numColumns): string += str(random.randint(0, 9)) print(string) def drawTriangle(numRows): '''Draws right triangle of random digits. Base and height have size numRows''' for i in range(numRows): #print string of random digits of length i+1 string = '' for j in range(i+1): string += str(random.randint(0, 9)) print(string) def main(): drawRectangle(5, 7) drawTriangle(6) main()
true
7c8041228c70e42f69d00937eaac31e8c5f7a243
trivedimargiv9/My_codes
/Faulty Calc.py
505
4.1875
4
operater = input('Enter the operator: ') num1 = int(input('Enter number 1: ')) num2 = int(input('Enter number 2: ')) if operater == '+': if num1 == 56 and num2 == 9: print('77') else: print(num1+num2) elif operater == '-': print(num1 - num2) elif operater == '*': if num1 == 45 and num2 == 3: print('555') else: print(num1*num2) else: if num1 == 56 and num2 == 6: print('4') else: print(num1/num2)
false
60f11118fcff0ed3e6258bcc99e4ab4e2d8dad00
Naif18/PythonCourse
/ForthWeek/twentieththree.py
356
4.1875
4
DayList= { "saturday" : 1 , "sunday" : 2, "monday" : 3, "tuesday" : 4, "wedneday" : 5, "Thersday" : 6, "friday":7 } if "friday" in DayList: print("Yes, it's Friday") #Dictionary Lengh print(len(DayList)) #Delete value DayList.pop("monday") print(DayList) #Delete the last value we added DayList.popitem() print(DayList)
true
725fc67e664fbc220885310e18742af8003c27c9
NickBarty/Python-Interactive-Kivy-Project
/song.py
1,433
4.5
4
class Song: """ Song class initialises the attributes every song will have, how they will be printed and the ability to mark a song as required or learned """ def __init__(self, title="", artist="", year=0, required=True): """ initialises the attributes songs will have with default values :param title: title of the song :param artist: artist of the song :param year: year the song was made :param required: if the song is learned or unlearned (defaults True for un-learned) :return: None """ self.title = title self.artist = artist self.year = year self.required = required def __str__(self): """ specifies how songs will be printed and if they are learned or not :return: formatted string """ check_learned = "" if self.required else "(learned)" return '"{}" by {} ({}) {}'.format(self.title, self.artist, self.year, check_learned) def mark_required(self): """ marks the song as required (not learned) :return: song with required set to True (not learned) """ self.required = True return self.required def mark_learned(self): """ marks the song as learned :return: song with required set to False (learned) """ self.required = False return self.required
true
3dbed07c2a122a53888c11a18c4da3cf33232614
robertross04/TreeHacks
/keyphrase.py
545
4.28125
4
#Puts the key phrases from the text into a list def generate_keyphrase_list(key_phrases): key_phrases_list = [] for value in key_phrases.values(): for tmp in value: for key in tmp.values(): for phrases in key: if len(phrases) >= 3: #only want words 3 or larger key_phrases_list.append(phrases) return key_phrases_list #prints keyphrase list: mainly for debugging def print_phrase_list(key_phrases_list): for phrase in key_phrases_list: print(phrase)
true
d9cbfc88e0d66835293a10568f4064d12cee136e
xiaolinangela/cracking-the-coding-interview-soln
/Ch10_SortingAndSearching/10.1-sortedmerge.py
586
4.25
4
def sorted_merge(nums1, m, nums2, n): index1 = m - 1 index2 = n - 1 index_merged = m + n - 1 while index2 >= 0: if index1 >= 0 and nums1[index1] > nums2[index2]: nums1[index_merged] = nums1[index1] index1 -= 1 else: nums1[index_merged] = nums2[index2] index2 -= 1 index_merged -= 1 return nums1 if __name__ == "__main__": nums1 = [1, 2, 3, 0, 0, 0] nums2 = [2, 5, 6] m = 3 n = 3 print(sorted_merge(nums1, m, nums2, n)) # Time Complexity: O(m+n) # Space Complexity: O(1)
false
228b5d62e0d5add16ee10e0704cd8ba74f874b7a
xiaolinangela/cracking-the-coding-interview-soln
/Ch2-LinkedLists/2.6-Palindrome.py
884
4.15625
4
from LinkedList import LinkedList from LinkedList import LinkedListNode def is_palindrome(l1_head): def reversed_list(node): head = None while node: n = LinkedListNode(node.val) n.next = head head = n node = node.next return head l1_reversed = reversed_list(l1_head) while l1_head and l1_reversed: if l1_head.val != l1_reversed.val: return False l1_head = l1_head.next l1_reversed = l1_reversed.next return True if __name__ == "__main__": lList = LinkedList([1, 2]) lList_1 = LinkedList([0, 0]) lList_2 = LinkedList([1, 2, 2, 1]) lList_3 = LinkedList([]) print(is_palindrome(lList.head)) print(is_palindrome(lList_1.head)) print(is_palindrome(lList_2.head)) print(is_palindrome(lList_3.head))
false
dde6d541bbd7568b9cae9d504a506eb08949da5e
Mak-maak/Python-Fundamentals
/list taking a slice out of them.py
425
4.40625
4
#list: taking slice out of them cities = ["Atlanta", "Baltimore", "Chicago", "Denver", "Los Angeles", "Seattle"] #creating another list by taking a slice of cities smallerListOfCities = cities[2:5] # here we took elements from cities from index 2-5 # it slices the list from first element to 5th smaller_list_of_cities = cities[:5] # it slices the list from second element to last smaller_list_of_cities = cities[2:]
false
6113013b9935b8862a5298c340613568329f9080
coltonneil/IT-FDN-100
/Assignment 8/Banking.py
1,294
4.5625
5
#!/usr/bin/env python3 """ requires Python3 Script defines and creates a "bank account" which takes an initial balance and allows users to withdraw, deposit, check balance, and view transaction history. """ # define class Account class Account: # initialize account with balance as initial, create empty transaction list, add initial transaction to list def __init__(self, initial): self.balance = initial self.transactions = [] self.add_transaction(initial,"+") # subtracts amount from balance and logs it in transactions def withdraw(self, amount): self.balance -= amount self.add_transaction(amount, "-") # adds amount to balance and logs it in transactions def deposit(self, amount): self.balance += amount self.add_transaction(amount, "+") # return the balance def get_balance(self): return self.balance # logs the details of a transaction def add_transaction(self, amount, symbol): log = "Trans #{} \t|\t {}${:.2f} \t|\t Balance: ${:.2f}".format( len(self.transactions)+1, symbol, amount, self.get_balance() ) self.transactions.insert(0,log) # return transaction list def get_transactions(self): return self.transactions
true
6a89874f05bb0c6f201b60f9d682fae6be3b07d5
coltonneil/IT-FDN-100
/Assignment 5/hw5.py
2,557
4.15625
4
import string """ This script reads in a file, parses the lines and creates a list of words from the lines Calculates the word frequency Gets the word with the maximum frequency Gets the minimum frequency and a list of words with that frequency Calculates the percentage of words that are unique in the file and prints it """ # open file and stores its content as a list with open("./Odyssey.txt") as file: file_contents = file.readlines() # create translator to remove punctuation translator = str.maketrans('', '', string.punctuation) # put the words in the file into a list split on spaces and no trailing whitespace words_in_file = [] for line in file_contents: striped_line = line.strip() # lower case all words and remove punctuation words_in_file.extend(striped_line.translate(translator).lower().split(" ")) # remove empty strings words_in_file = list(filter(None, words_in_file)) # get number of words in file num_words_in_file = len(words_in_file) # store the unique words and their occurrences in a dict words_dict = {} # loop through word list for word in words_in_file: # if word is already in the words_dict, increment if word in words_dict: words_dict[word] += 1 # if word is not in the words_dict, add it and set its value to 1 else: words_dict[word] = 1 # store the occurrence rate of each word in a dict occurrence_rate = {} for word in words_dict: word_occurrence_rate = words_dict[word] / num_words_in_file occurrence_rate[word] = word_occurrence_rate num_unique_words = len(words_dict) # get most and least frequent word most_frequent = max(words_dict, key=words_dict.get) least_frequent = min(words_dict, key=words_dict.get) print("The most frequently used word is: {}".format(most_frequent)) # get the rate of occurrence for the least frequent word min_occurrence_rate = words_dict[least_frequent]/num_words_in_file # get all of the words that have the min occurrence rate min_occurrence_list = [] for word in words_dict: if words_dict[word] == 1: min_occurrence_list.append(word) # get a count for the number of words with the min occurrence rate num_min_occurrence_words = len(min_occurrence_list) # print frequency results print("The minimum frequency is {:.5f}%, {} words have this frequency.".format(min_occurrence_rate, num_min_occurrence_words)) # print the total words and number of unique words print("There are {} words and {}({:.2f}%) unique words".format(num_words_in_file, num_unique_words, num_min_occurrence_words/num_words_in_file))
true
5dcb6b3a1ae292cd38048b560d0d4c7639aedffd
elliebui/technical_training_class_2020
/data_structures/week_2_assignments/list_without_duplicate.py
595
4.3125
4
""" Write a function that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. The order should remain the same. """ def get_list_without_duplicate(input_list): new_list = [] for item in input_list: if item not in new_list: new_list.append(item) return new_list # Test list_a = [1, 3, 3, 5, 2, 5, 7, 8, 6] list_b = ['a', 'z', 'd', 's', 'a', 'h', 's'] print(get_list_without_duplicate(list_a)) print(get_list_without_duplicate(list_b)) """ Answer: [1, 3, 5, 2, 7, 8, 6] ['a', 'z', 'd', 's', 'h'] """
true
095a73e1207ffba761275a8d58aaa3e12111abf6
elliebui/technical_training_class_2020
/data_structures/arrays_and_linked_lists/strings/reverse_string.py
558
4.5625
5
def string_reverser(our_string): """ Reverse the input strings Args: our_string(string): String to be reversed Returns: string: The reversed strings """ return our_string[::-1] # Test Cases print("Pass" if ('retaw' == string_reverser('water')) else "Fail") print("Pass" if ('!noitalupinam sgnirts gnicitcarP' == string_reverser('Practicing strings manipulation!')) else "Fail") print("Pass" if ('3432 :si edoc esuoh ehT' == string_reverser('The house code is: 2343')) else "Fail") """ Answer: Pass Pass Pass """
false
e73a0badae7a610694bae4ef619262523befcdae
Mapashi/Ejercicios-Python
/act_2.2.b.py
299
4.15625
4
'''1.2 Realizar un programa que sea capaz de convertir los grados centígrados em grados Farenheit y viceversa.ºF = 1,8 x ºC + 32''' #print("los grados en farenheit ", farenheit) print("Dime los farenheit") farenheit = float(input()) grado = (farenheit - 32) / 1.8 print("Los grados son ", grado)
false
0dc4b3eecae4758c29efe3ce551efde7ed93475c
vincentnti/vincent_sinclair_TE19C
/Programmering1/Mer Programmering/listor.py
890
4.21875
4
#Create list fruits = ["apple", "pear", "kiwi", "banana", "strawberry", "blueberry"] #Indexing and access operator print(fruits) print(fruits[0]) print(fruits[-1]) print(fruits[3]) print(fruits[::-1]) #Loop for fruit in fruits: print(fruit) #Create new lists greens = ["tomat", "gurka", "majs", "sallad"] fruktsallad= [] #Append for green in greens: fruktsallad.append(green) for fruit in fruits: fruktsallad.append(fruit) print(fruktsallad) #List comprehension y = [2*x-2 for x in range(10)] print(y) x = [x for x in range(10)] print(x) #Plot import matplotlib.pyplot as plt plt.plot(x,y) plt.xlabel="x" plt.ylabel="y" plt.title("Graf") plt.show() #2D lista tabell = [] for i in range(11): rad = [x*i for x in range(11)] tabell.append(rad) for j in range(11): print(f"{tabell[i][j]:3}", end=" ") print(tabell) print(tabell[3]) print(tabell[3][2])
false
d5bce067160ae04d3f173217ac0d3e015e917da4
xushubo/learn-python
/learn46.py
2,004
4.34375
4
#枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能: from enum import Enum, unique Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'sep', 'Oct','Nov', 'Dec')) print(Month.Jan) print(Month.Jan.value) for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value) #value属性则是自动赋给成员的int常量,默认从1开始计数。 #如果需要更精确地控制枚举类型,可以从Enum派生出自定义类: @unique #@unique装饰器可以帮助我们检查保证没有重复值。 #如果要限制定义枚举时,不能定义相同值的成员。可以使用装饰器@unique class Weekday(Enum): #定义枚举时,成员名称不允许重复 Sun = 0 # Sdd = 1 # 默认情况下,不同的成员值允许相同。但是两个相同值的成员,第二个成员的名称被视作第一个成员的别名 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 #枚举支持迭代器,可以遍历枚举成员 for week in Weekday: #如果枚举有值重复的成员,循环遍历枚举时只获取值重复成员的第一个成员 print(week) #如果想把值重复的成员也遍历出来,要用枚举的一个特殊属性__members__ for name, member in Weekday.__members__.items(): print(name, '=>', member, ',', member.value) day1 = Weekday.Mon print(day1) print(Weekday.Tue) print(Weekday['Tue']) #通过成员的名称来获取成员 print(Weekday.Tue.value) print(day1 == Weekday.Mon) print(day1 == Weekday.Tue) print(Weekday(1)) #通过成员值来获取成员,如果枚举中存在相同值的成员,在通过值获取枚举成员时,只能获取到第一个成员 print(day1 == Weekday(1)) print(day1.name) #通过成员,来获取它的名称和值 print(day1.value) print(Weekday.Mon is Weekday.Mon) print(Weekday.Mon is not Weekday.Sun) #枚举成员不能进行大小比较 #Weekday.Mon > Weekday.Sun
false
89c5b83a6b8cb4bb8ccb405dbee0511cb1263baf
figengungor/Download-EmAll
/500px.py
816
4.15625
4
#Author: Figen Güngör #Year: 2013 #Python version: 2.7 ################ WHAT DOES THIS CODE DO? ############################## ####################################################################### ###############Download an image from 500px############################ ####################################################################### import urllib link = raw_input("Enter the photo link: ") name = raw_input("Enter a name for the photo: ") f = urllib.urlopen(link) pageResource = f.read() pattern="{\"size\":2048,\"url\":" start = pageResource.find(pattern)+20 end = pageResource.find("\"", start+2) imgLink = pageResource[start:end] imgLink=imgLink.replace("\\", "") urllib.urlretrieve(imgLink, name+".jpg") print("Photo is successfully downloaded into the directory where your 500px.py file is.")
true
defeadae77a82c2f897efa0d84653ebe0f199d31
wassen1/dbwebb-python
/kmom10/prep/analyze_functions.py
978
4.1875
4
""" Functions for analyzing text """ # text = "manifesto.txt" def read_file(filename): """ Returns the file from given filename """ with open(filename) as fh: return fh.read() def number_of_vowels(filename): """ Calculate how many vowels a string contains """ content = read_file(filename) nr_of_vowels = 0 vowel_string = "aeiouy" str_lower = str.lower(content) for vowel in vowel_string: nr_of_vowels += str_lower.count(vowel) return nr_of_vowels def number_of_dots(filename): """ Calculate number of dots """ content = read_file(filename) nr_of_dots = 0 nr_of_dots = content.count(".") return nr_of_dots def number_of_upper(filename): """ Returns number of upper case letters in text """ nr_of_upper = 0 content = read_file(filename) for letter in content: if letter.isupper(): nr_of_upper += 1 return nr_of_upper
true
0fefdd08af95b8b6e671a8507102e34362e83c5c
Octaith/euler
/euler059.py
2,785
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher1.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. ''' import time import json import sys import itertools start = time.clock() commonwords = set(["the","be","to","of","and","a","in","that","have","I","it","for","not","on","with","he","as","you","do","at","this","but","his","by","from","they","we","say","her","she","or","an","will","my","one","all","would","there","their","what","so","up","out","if","about","who","get","which","go","me","when","make","can","like","time","no","just","him","know"]) with open('cipher1.txt', 'r') as f: cipher = json.load(f) #print cipher def decode(key): #print 'decoding with', key str = '' key = list(key) for i in xrange(len(key)): key[i] = ord(key[i]) c = 0 for i in cipher: str += chr(i ^ key[c]) c += 1 if c == len(key): c = 0 return str variants = itertools.permutations('abcdefghijklmnopqrstuvwxyz', 3) mk = '' for i in variants: t = decode(i) cw = 0 for w in commonwords: if w in t: cw += 1 if cw > 0.5*len(commonwords): mk = i print '%s words decoded with key %s' % (cw, i) print t break t = decode(mk) c = 0 for i in t: c += ord(i) print c print time.clock()-start
true
012dc26cf8d7b28a0764bc4a3df1cda6c4f772f6
samullrich/crawl_project
/queueADT.py
478
4.125
4
class QueueADT: def __init__(self): self.container = [] self.the_queue = [] #self.visited = [starting_node] def push(self, value): # First item is at front of the list/index 0 self.container.append(value) def pop(self): return self.container.pop(0) # How would this work with an empty list? def is_empty(self): if self.container == []: return True else: return False
true
5636c7334fc22f08ca1963d675e7d4a52b0fca15
Lucass96/Python-Faculdade
/Python-LP/aula06/VerificandoCaracteres.py
359
4.3125
4
s1 = 'Logica de Programacao e Algoritmos' s1.startswith('Logica') s1 = 'Logica de Programacao e Algoritmos' s1.endswith('Algoritmos') s1 = 'Logica de Programacao e Algoritmos' s1.endswith('algoritmos') s1 = 'Logica de Programacao e Algoritmos' s1.lower().endswith('algoritmos') s1 = 'Logica de Programacao e Algoritmos' print(s1.upper()) print(s1.lower())
false
37e893393b4b18703ea2849ee396910eb12950f1
GitError/python-lib
/Learn/Udemy/decorators.py
1,214
4.5625
5
""" Intro to decorators """ # decorator - adding additional functionality on the runtime # commonly used in web frameworks such as flask and django e.g. routing etc. # @ is used to declare decorators # returning a function from within a function def func(): print('upper function') def func2(): print('nested function') def func3(): print('nested 2 levels') return 72 return func3() return func2() test = func() print(test) def cool(): def super_cool(): return 'I''m so fancy' return super_cool # pointer/ delegate some_func = cool() print(some_func) # decorator example - long way using a wrapper function def new_decorator(original_function): def wrap_func(): print('Some extra code, before the original function') original_function() print('Some extra code, after the original function') return 42 return wrap_func() def func_needs_decorator(): print('I need to be decorated') decorated_func = new_decorator(func_needs_decorator) print(decorated_func) # short way using @ declaration @new_decorator def func_needs_decorator2(): print('I want to be decorated 2')
true
01b99094424f74626070c04e754c0fc32430ceb7
kaiaiz/python3
/Python 4 高级特性(生成器,迭代器).py
1,985
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #如果列表元素可以按照某种算法推算出来, #那我们是否可以在循环的过程中不断推算出后续的元素呢? #这样就不必创建完整的list,从而节省大量的空间。 #在Python中,这种一边循环一边计算的机制,称为生成器:generator L = [x * x for x in range(10)] print(L) g = (x * x for x in range(10)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) for n in g: print(n) #函数是顺序执行,遇到return语句或者最后一行函数语句就返回。 #而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回, #再次执行时从上次返回的yield语句处继续执行 def fib(max): n, a, b = 0, 0, 1 while n < max: #print(b) yield b a, b = b, a + b n = n + 1 return "done" #print(fib(6)) def odd(): print("step 1") yield 1 print("step 2") yield 2 print("step 3") yield 3 o = odd() print(next(o)) print(next(o)) print(next(o)) for n in fib(6): print(n) g = fib(6) while True: try: x = next(g) print("g:", x) except StopIteration as e:#拿到返回值 print("Generator return value:", e.value) break def triangles(): i = 0 L = [1] while True: yield L L.append(0) L = [L[i] + L[i - 1] for i in range(len(L))] return "done" n = 0 for t in triangles(): print(t) n = n + 1 if n == 10: break #可以使用isinstance()判断一个对象是否是Iterable对象 from collections import Iterable print(isinstance([], Iterable)) #集合数据类型如list、dict、str等是Iterable但不是Iterator, #不过可以通过iter()函数获得一个Iterator对象 for x in [1, 2, 3, 4, 5]: print(x) it = iter([1, 2, 3, 4, 5]) while True: try: x = next(it) except StopIteraation: break
false
0afbfb4deb70181e4ea434f63c3d4968fb3aa332
dikshit22/PathaPadha-Python-DS-P-1
/Assignment-3/1. Making String From String.py
543
4.40625
4
#Program to get a string made of the first 2 and the last 2 chars from a given #string. If the string length is less than 2, print 'empty string'. string = input("Enter a string:\t") if(len(string) >= 2): newstr = string[:2]+string[-2:] print("\tThe new string is:", newstr) else: print("\tEmpty string") ''' OUTPUT Enter a string: Hello The new string is: Helo Enter a string: Hit The new string is: Hiit Enter a string: Hi The new string is: HiHi Enter a string: H Empty string '''
true
a170005cece2a46858802ec6ecbef9c4e2fdf8e8
dikshit22/PathaPadha-Python-DS-P-1
/Assignment-4/1. Highest In List.py
311
4.40625
4
#Program to find the highest element in a list l = eval(input('Enter the list: ')) h = l[0] for i in l: if(i > h): h = i print('\tThe highest element in the list is:', h) ''' OUTPUT Enter the list: [1, 4, 2, 6, 3, 5, 9, 7, 8] The highest element in the list is: 9 '''
true
d689b639f06393b670f5b1e4b08bd0eeaa534efd
dikshit22/PathaPadha-Python-DS-P-1
/Assignment-3/2. Adding 'ing' Or 'ly'.py
670
4.5
4
#Program to add 'ing' at the end of a given string (length should be at least 3). #If the given string already ends with 'ing' then add 'ly' instead. If the #string length of the given string is less than 3, leave it unchanged.  string = input("Enter a string:\t") if(len(string) >= 3): if(string[-3:] != 'ing'): string = string+'ing' else: string = string+'ly' print("\tThe new string is:", string) else: print("\tThe string is:", string) ''' OUTPUT Enter a string: Help The new string is: Helping Enter a string: Loving The new string is: Lovingly Enter a string: Do The string is: Do '''
true
8244082d74426f04bcd25d8f0013cf8d4f7a94fb
ramkishor-hosamane/Coding-Practice
/Optum Company/11.py
469
4.21875
4
''' In a given String return the most frequent vowel coming. ''' def most_frequent_vowel(string): string = string.lower() hashmap = {'a':0,'e':0,'i':0,"o":0,"u":0} for letter in string: if hashmap.get(letter)!=None: hashmap[letter]+=1 max_freq = 0 max_freq_vowel = None for letter in hashmap: if hashmap[letter] > max_freq: max_freq = hashmap[letter] max_freq_vowel = letter return max_freq_vowel print(most_frequent_vowel("I love icecream"))
true
390cd4a7fe778a936274eea5cad6e0022a61c2a8
ramkishor-hosamane/Coding-Practice
/Optum Company/3.py
620
4.1875
4
''' 3. Find the middle element of the linked lists in a single pass (you can only traverse the list once). ''' class Node: def __init__(self,val=None): self.data = val self.next = None class Linked_List: def __init__(self): self.head = None def insert(self,val): cur = self.head if cur==None: self.head = Node(val) else: while cur.next!=None: cur = cur.next cur.next = Node(val) def get_middle_element(self): turtle = self.head rabbit = self.head if turtle.next == None: while rabbit != None: rabbit = rabbit.next.next turtle = turtle.next return turtle.data
true
07c1e3fb46417cbc98eea6db5c3207c35aa3f6a4
FranklinA/CoursesAndSelfStudy
/PythonScript/PythonBasico/clases.py
1,216
4.125
4
#Los atributos describen las caracteristicas de los objetos, las clases es donde declaramos estos atributos,el atributo se utiliza segun las variables o tipos de datos que disponemos en python # Metodos son acciones/funciones # Constructor o inicializador para inicializar los objetos de una forma predeterminada que podemos indicar. class Persona: #pass nBrazos=0 # atributos nPiernas=0 cabello=True cCabello="Defecto" hambre=0 # con hmabre sera 10 y sin hambre 0 def __init__(self): # Constructor self.nBrazos=2 self.nPiernas=2 def dormir(): pass def comer(self): # con self modifica el atributo hambre de mis mismo es de cir de Persona self.hambre=5 class Hombre(Persona):#Herencia Simple de la clase hombre se le incluye a la clase entre parentesis la clase de la que esta herendando #pass nombre="Defecto" sexo="M" def cambiarNombre(self,nombre):#Metodo que modifica nuestro atributo y reciben parametros. self.nombre=nombre class Mujer(Persona): #pass nombre="Defecto" sexo="F" #Ejecutando el metodo comer de la clase Persona con la clase Hombre jose=Hombre() jose.comer()#Asi accedemos a los metodos del objeto print(jose.hambre)#Asi accedemos a los atributos del objeto
false
deac09987b6d4f6ea09c2806efdf36a55fc63729
rookiy/Leetcode
/SymmetricTree_3th.py
1,300
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 使用迭代。分别访问对称的节点。 class Solution: # @param {TreeNode} root # @return {boolean} def isSymmetric(self, root): if not root: return True queue_l, queue_r = [root.left], [root.right] while len(queue_l)>0 and len(queue_r)>0: left, right = queue_l.pop(0), queue_r.pop(0) if not left and not right: continue if not left or not right or left.val != right.val: return False queue_l.append(left.left) queue_l.append(left.right) queue_r.append(right.right) queue_r.append(right.left) return True def main(): #root = None root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) #root.right.left = TreeNode(4) root.right.right = TreeNode(3) #root.left.left.left = TreeNode(-1) #root.right.right.left = TreeNode(-1) solution = Solution() print solution.isSymmetric(root) if __name__ == '__main__': main()
true
c9f6c5e7e26087552034fe851306c1e43485d163
SabastianMugazambi/Word-Counter
/act_regex3.py
1,271
4.6875
5
# Regular expressions activity III # Learning about regex match iterators. import re def main(): poem = readShel() printRegexMatches(r'.\'.', poem) def readShel(): '''Reads the Shel Silverstein poem and returns a string.''' filename = 'poem.txt' f = open(filename,'r') poem = f.read() f.close() return poem def printRegexMatches(pattern, text): '''Prints all occurrences of the regular expression.''' match_iter = re.finditer(pattern, text) # New type! match_iter is a sort of "iterator". print "re.finditer() returned an object of type: " + str(type(match_iter)) # An iterator is something that a for-loop can loop over. # A match iterator, specifically, is one that makes the loop variable be # a match object each time. So now, rather than just finding the first # match, we can iterate over *all* matches. print 'Your pattern, "%s", matches the text:' % pattern for occurrence in match_iter: print ' %s at indices %d--%d' % ( occurrence.group(0), occurrence.start(0), occurrence.end(0)) # Note: inside parentheses, I can continue a single statement on the # next line. This is preferable to making my line of code way too # long. main()
true
e1a8dba62fe06205d1dd1cfa8262c45d51449439
yuvrajschn15/Source
/Python/14-for_loop.py
341
4.65625
5
# to print from 1 to 20 we can use print statement for 20 times or use loops # range is used to define the range(kinda like limit) of the for loop print("this will print from 0 to 19") for i in range(20): print(i, end=" ") print("\n") print("this will print from 1 to 20") for j in range(20): print(j + 1, end=" ") print("\n")
true
7d00cae2fdac22e0ce5c78c67fcc7844cb608c32
vinayakgaur/Algorithm-Problems
/Split a String in Balanced Strings.py
784
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 18 10:32:00 2021 @author: VGaur """ #Balanced strings are those who have equal quantity of 'L' and 'R' characters. #Given a balanced string s split it in the maximum amount of balanced strings. #Return the maximum amount of splitted balanced strings. #Example 1: #Input: s = "RLRRLLRLRL" #Output: 4 #Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. class Solution: def balancedStringSplit(self, s: str) -> int: r,l,c = 0,0,0 for i in s: if i == "R": r += 1 elif i == "L": l += 1 if r == l: c +=1 r= l =0 return c
true
280804ce0568b0e832b2ed3a530d475d2a919332
martvefun/I-m-Human
/CustomError.py
1,395
4.25
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- class Error(Exception): """Base class for exceptions""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expr -- input expression in which the error occurred msg -- explanation of the error """ def __init__(self, expr, msg): self.expr = expr self.msg = msg def __str__(self): return self.expr+" : "+self.msg class NotValidIntError(Error): """Exception raised if a parameter passed is not a valid int Attributes: i -- the integer """ def __init__(self, i): self.i = i def __str__(self): return str(self.i)+" is not a valid integer" class NotValidButtonError(Error): """Exception raised if a button is incorrect Attributes: b -- the button """ def __init__(self, b): self.b = b def __str__(self): return str(self.b)+" is not a valid button" class OutOfScreenError(Error): """Exception raised if the position is out of the screen Attributes: x, y -- the coordinates """ def __init__(self, x, y): self.x = x self.y = y def __str__(self): return str(self.x)+", "+str(self.y)+" is out of the screen"
true
39f9d0b9f3d60ce8f55ccb09bfdaa58da9db8166
NileshNehete/Learning_Repo
/Python_Pro/Python_if-else.py
1,048
4.125
4
# Enter tree numbers and print the biggest and lowest number num1 = input("Enter First Number :") num2 = input("Enter Second Number :") num3 = input("Enter Third Number :") if (( num1 > num2 ) and ( num1 > num3 )): print ("First number %d is the biggest number" %num1) if ( num2 > num3 ): print ("Third number %d is the lowest number" %num3) else: print ("Second number %d is the lowest number" %num2) if (( num2 > num1 ) and ( num2 > num3 )): print ("Second number %d is the biggest number" %num2) if ( num1 > num3 ): print ("Third number %d is the lowest number" %num3) else: print ("First number %d is the lowest number" %num1) if (( num3 > num2 ) and ( num3 > num1 )): print ("Third number %d is the biggest number" %num3) if ( num2 > num1 ): print ("First number %d is the lowest number" %num1) else: print ("Second number %d is the lowest number" %num2) print ( "="* 20 ) int = 0 while ( int < 10 ): print int int = int + 1
true
b88a5762d830799a96266825de4ebabb7ab2ec65
arensdj/snakes-cafe
/snakes_cafe.py
2,198
4.40625
4
# data structures containing lists of the various menu items and customer name appetizers = ['Wings', 'Cookies', 'Spring Rolls'] entrees = ['Salmon', 'Steak', 'Meat Tornado', 'A Literal Garden'] desserts = ['Ice Cream', 'Cake', 'Pie'] drinks = ['Coffee', 'Tea', 'Unicorn Tears'] customer_name = input("Please enter your name: ") # an intro message and restaurant menu that gets displayed when program is invoked MENU = f""" *********************************************** ** Welcome, {customer_name}, to the Snakes Cafe! ** ** Please see our menu below. ** ** ** ** To quit at any time, type "quit" ** *********************************************** Appetizers ---------- {appetizers[0]} {appetizers[1]} {appetizers[2]} Entrees ------- {entrees[0]} {entrees[1]} {entrees[2]} {entrees[3]} Desserts -------- {desserts[0]} {desserts[1]} {desserts[2]} Drinks ------ {drinks[0]} {drinks[1]} {drinks[2]} """ print(MENU) order_prompt = """ *********************************** ** What would you like to order? ** ** Enter 'quit' when done ** *********************************** """ # the user input is assigned to item identifier. Initially, it is blank so that # while loop can be entered into item = ' ' # a dictionary to contain the item key, value of times ordered customer_order = {} # user is prompted for an order and the order(s) are added to dictionary and # printed to show what was entered item = input(order_prompt) while (item != 'quit'): if item not in customer_order: customer_order[item] = 1 else: customer_order[item] += 1 # checks if order is in the dictionary and increments value. Also formats the # order plurals for the output message. for order in customer_order: if customer_order[order] > 1: order_plural = 'orders' have_plural = 'have' else: order_plural = 'order' have_plural = 'has' print(f'** {customer_order[order]} {order_plural} of {order} {have_plural} been added to your meal **') # prompt user again for another item to order item = input(order_prompt) print(f'Thank you {customer_name} for visiting Snakes Cafe.')
true
310bf320e2e333e36cda462a8d4dbbd38faf8fe5
bragon9/leetcode
/21MergeTwoSortedListsRecursive.py
1,252
4.125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not(l1) and not(l2): return None if not(l1): return l2 if not(l2): return l1 # Set min and max node if l1.val <= l2.val: min_node = l1 max_node = l2 else: min_node = l2 max_node = l1 if min_node.next: # If next min node is lesser than the current max node, keep it where it is if min_node.next.val < max_node.val: self.mergeTwoLists(min_node.next, max_node) # Max node should come next, so insert it else: save_min_next = min_node.next save_max_next = max_node.next min_node.next = max_node min_node.next.next = save_min_next self.mergeTwoLists(min_node.next, save_max_next) # There is nothing else on this linked list, link the rest of the other list else: min_node.next = max_node return min_node
true
fb42140b29d698b9c5fee762211ecc934c25be7c
luiz-alt/Python-LP2-git
/Questao_4_aula_4.py
598
4.125
4
''' Quest ̃ao 4: Crie um programa que leia o nome de 5 pessoas e os armazena em uma lista. Em seguida, construa uma fun ̧c ̃ao que recebe como parˆametros essa lista e uma posi ̧c ̃ao ( ́ındice da lista) e devolve o nome contido naquela posi ̧c ̃ao. B Essa fun ̧c ̃ao deve gerar uma exce ̧c ̃ao do tipo IndexError caso o ́ındice n ̃ao exista na lista. ''' def error(lista): return lista[8] nome = [] for i in range(5): nome_novo = input("Digite um nome: ") nome.append(nome_novo) print(error(nome)) # Causando o erro IndexError, pois o indice da lista não existe.
false
185f85d5d9a23e9b2eaa2e03f1069e0884823f30
leonhostetler/undergrad-projects
/numerical-analysis/12_matrices_advanced/givens_rotation_matrix.py
1,251
4.21875
4
#! /usr/bin/env python """ Use Givens rotation matrices to selectively zero out the elements of a matrix. Leon Hostetler, Mar. 2017 USAGE: python givens-rotation-matrix.py """ from __future__ import division, print_function import numpy as np n = 3 # Size of matrix A = np.array([(1, 2, 0), (1, 1, 1), (2, 1, 0)]) print("A = \n", A) def givens(i, j, A): """ This function returns an n x n Givens rotation matrix G that will zero the A[i, j] element when you multiply G*A. """ G = np.zeros([n, n]) # Initialize rotation matrix as matrix of zeros for k in range(n): # Set diagonal elements to 1 G[k, k] = 1.0 d = np.sqrt(A[j, j]**2 + A[i, j]**2) c = A[j, j]/d s = A[i, j]/d G[j, j] = c G[i, j] = -s G[i, i] = c G[j, i] = s return G # Zero out A[1,0] with a Givens rotation matrix G1 = givens(1, 0, A) print("\nG1 = \n", G1) A = np.dot(G1, A) print("A is now = \n", A) # Zero out A[2,0] with a Givens rotation matrix G2 = givens(2, 0, A) print("G2 = \n", G2) A = np.dot(G2, A) print("A is now = \n", A) # Zero out A[2,1] with a Givens rotation matrix G3 = givens(2, 1, A) print("G3 = \n", G3) A = np.dot(G3, A) print("A is now = \n", A)
true
f7f22d37ce06b19e8c501540460a956c402d53c4
leonhostetler/undergrad-projects
/computational-physics/04_visual_python/newtons_cradle_damped.py
1,612
4.40625
4
#! /usr/bin/env python """ Shows an animation of a two-pendulum newton's cradle. This program shows only the spheres--think of the pendulum rods as being invisible. Additionally, this program features a damping parameter mu = 0.11 such that the motion decays to zero in approximately 12 collisions. Leon Hostetler, Feb. 16, 2017 USAGE: python newtons_cradle_damped.py """ from __future__ import division, print_function from visual import * import numpy as np # Constants g = 9.80 # (m/s^2) L = 10 # Length of the pendulums (m) initialAngle = 0.5 # In radians mu = 0.11 # Damping parameter # Create the spheres pend = sphere(pos=(L*np.sin(initialAngle), -L*np.cos(initialAngle), 0), radius=1, color=color.yellow) pend2 = sphere(pos=(-2, -L, 0), radius=1, color=color.red) def position(right, t): """ Only one of the pendulums is in motion at a given time. This function moves the moving pendulum to its new position. We use the equation: theta(t) = theta_0*cos(sqrt(g/L)*t) """ theta = initialAngle*exp(-mu*t)*np.cos((g/L)**(1/2)*t) if right: pend.pos = [L * np.sin(theta), -L * np.cos(theta), 0] # Update position of bob else: pend2.pos = [L * np.sin(theta) - 2, -L * np.cos(theta), 0] # Update position of bob # Once the moving pendulum reaches theta = 0, switch to the other one if theta <= 0: return False # Return else: return True # Increment time i = 0 Right = True # The right pendulum is the first in motion while True: rate(200) Right = position(Right, i) i += 0.01
true
3cf2c99c7e05ef76b41823e28b68c940753cd1fe
leonhostetler/undergrad-projects
/computational-physics/11_classes/rectangles.py
1,370
4.59375
5
#! /usr/bin/env python """ Defines a Rectangle class with two member variables length and width. Various member functions, such as area and perimeter, are defined, and the addition operator is overloaded to define rectangle addition. Leon Hostetler, Mar. 30, 2017 USAGE: python rectangles.py """ from __future__ import division, print_function class Rectangle: """Rectangle object declaration""" def __init__(self, length=1, width=1): """Initialize.""" self.length = length self.width = width def area(self): """Compute and print the area of a rectangle.""" return self.length * self.width def perimeter(self): """Compute and print the perimeter of a rectangle.""" return 2*self.length + 2*self.width def print(self): """Print the length, width, area, and circumference.""" print("Length = ", self.length, sep="") print("Width = ", self.width, sep="") print("Area = ", self.area(), sep="") print("Perimeter = ", self.perimeter(), sep="") def __add__(self, other): """Define what it means to add two rectangles.""" return Rectangle(self.length + other.length, self.width + other.width) A = Rectangle(20, 10) print("\nArea of first rectangle = ", A.area(), sep="") B = Rectangle() C = A + B print("\nSecond Rectangle:") C.print()
true
226bd859ee5daa32acaec0afe3d6de4539c708e4
leonhostetler/undergrad-projects
/computational-physics/09_integration_modular/hypersphere_volume.py
1,233
4.46875
4
#! /usr/bin/env python """ Compute the volume of an n-dimensional hypersphere using the Monte Carlo mean-value method. The volume is computed for hyperspheres with dimensions from 0 to 12 and plotted. Leon Hostetler, Mar. 7, 2017 USAGE: python hypersphere_volume.py """ from __future__ import division, print_function import mymodule_integration as mmi import matplotlib.pyplot as plt import numpy as np def f(x): """ The integrand of the integral being evaluated. """ s = 0 for k in range(dim): s += x[k]**2 if s <= 1: fx = 1 else: fx = 0 return fx x = np.arange(0, 13) # x-values y = [] # y-values for k in range(13): dim = k # For every dimension, the limit of integration is [-1, 1] limit = [] for i in range(dim): limit.append([-1, 1]) # Compute the integral for this dimension integral = mmi.integrate_monte_carlo_nd(f, dim, limit) print("The ", k, "-dimensional hypersphere has volume ", integral, ".", sep="") y.append(integral) # Plot the results plt.rc('text', usetex=True) plt.plot(x, y) plt.title("Volume of n-dimensional Unit Hypersphere") plt.xlabel("Dimension") plt.ylabel("Volume") plt.show()
true
d9b906bd062339dcbf45944dc6c5f6f7f3c3e033
leonhostetler/undergrad-projects
/computational-physics/03_plotting/polar_plot.py
659
4.15625
4
#! /usr/bin/env python """ Plot a polar function by converting to cartesian coordinates. Leon Hostetler, Feb. 3, 2017 USAGE: polar_plot.py """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt # Main body of program theta = np.linspace(0, 10*np.pi, 1000) # The values of theta r = theta**2 # The function r = f(theta) x = r*np.cos(theta) # Convert to cartesian coordinates y = r*np.sin(theta) # Plot the results plt.rc('text', usetex=True) plt.plot(x, y) plt.legend([r"$r = \theta^2$"]) plt.title("Polar Galilean Spiral") plt.savefig("polar_plot.png") plt.show()
true
d6be4afe4ab27720853d615d1b0cc2578e753704
jazzlor/LPTHW
/ex4.py
685
4.15625
4
name = 'Jazzy' age = 36 # not a like height = 54 # inches weight = 200 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' cm = 2.54 #single cm kg = 0.453592 #singl kg print(f"Let's talk about {name}.") print(f"She's {height} inches tall") print(f"She's {weight} pounds heavy") print(f"Actually that's not too heavy.") print(f"She's got {eyes} eyes and {hair} hair") print(f"Her teeth are usually {teeth} depending on the coffee") #tHer line is tricky, try to get it exactly right total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.") total1 = height * cm print(f"she is {total1} cm tall") total2 = weight * kg print(f"She is {total2} kgs")
true
6faaf0768daada7527f0b0f31abbb7cfa2e8c6f2
d3m0n4l3x/python
/file_io.txt
876
4.21875
4
#!/usr/bin/python #https://www.tutorialspoint.com/python/file_methods.htm #Open a file fo = open("foo.txt", "r+") print "Name of the file: ", fo.name print "Closed or not : ", fo.closed print "Opening mode : ", fo.mode print "Softspace flag : ", fo.softspace ''' Name of the file: foo.txt Closed or not : False Opening mode : r+ #Read and Write Softspace flag : 0 ''' #Write the file fo.write( "Python is a great language.\nYeah its great!!\n"); #Read the file str = fo.read(10); print "Read String is : ", str # Check current position position = fo.tell(); print "Current file position : ", position # Reposition pointer at the beginning once again position = fo.seek(0, 0); str = fo.read(10); print "Again read String is : ", str ''' Read String is : Python is Current file position : 10 Again read String is : Python is ''' #Close a file fo.close()
true
67b837859fd7ab86aa4d246840a207daa326d535
kpbochenek/algorithms
/codingame/easy/skynet-the-chasm.py
514
4.125
4
R = int(input()) # the length of the road before the gap. G = int(input()) # the length of the gap. L = int(input()) # the length of the landing platform. while 1: S = int(input()) # the motorbike's speed. X = int(input()) # the position on the road of the motorbike. if X < R - 1: if G > S - 1: print("SPEED") elif G < S - 1: print("SLOW") else: print("WAIT") elif X > R - 1: print("SLOW") else: print("JUMP")
false
07fb525464c530a2d0c4e9a16560e2dc0ab98e29
Amenable-C/software-specialLectureForPython
/ch005.py
202
4.1875
4
num1 = int(input("What is the first number?")) num2 = int(input("What is the second number?")) num3 = int(input("What is the third number?")) answer = (num1 + num2) * num3 print("The answer is", answer)
true
1247bf7c34fc646e011f35d599dc229427980cc2
brianramaswami/NLP
/PROJECT2/proj2.py
2,586
4.375
4
#Brian Ramaswami #bramaswami@zagmail.gonzaga.edu #CPSC475 #Project2 types of substring searches. ''' GO TO MAIN AND SELECT WHICH PROGRAM TO RUN ''' import sys ''' HELPER FUNCTIONS ''' def readInFile(fileName): f = open(fileName, "r") print(f.read()) ''' OPENS FILE TO READ IN CONTENT ''' def my_open(): print ("This program will ask you to enter the name of an existing file.") print ("Be sure to put quotation marks around the file name") while(True): fin = input('Enter an input file name\n') try: fin = open(fin, 'r') break except: print("Invalid file name. Try again.") return fin ''' READS FILE IN AS A STRING ''' def read_file_as_string(fin): string = fin.read() return string ''' READS FILE IN LINE BY LINE ''' def read_file_as_line(fin): for line in fin: print(line.rstrip('\n')) #rstrip removes '\n' from each line because #print inserts '\n' def searchSub(string,subStr,posStr_in): posSub = 0; posStr = posStr_in while(posSub < len(subStr)): if string[posStr] == subStr[posSub]: posSub = posSub + 1 posStr = posStr + 1 else: return -1 return posStr_in def naiveSearch(string,subStr, stringCount): posStr = 0 lastSub = len(string) - len(subStr) while (posStr <= lastSub): pos = searchSub(string,subStr,posStr) if (pos >= 0): #print "substring starts at " + str(pos) newSpot = int(str(pos)) + len(subStr) stringCount = stringCount + 1 #print(string) string = string[newSpot: ] #print(string) #print(stringCount) naiveSearch(string,subStr,stringCount) #print(stringCount) break else: posStr = posStr + 1 if posStr > lastSub: print ("substring not found or finished searching") print("final string count is : " , stringCount) sys.exit() ''' ''' def program1(): fileName = raw_input("Please enter a file name: ") #type(fileName); #readInFile(fileName) f = open(fileName, "r").read() subString = raw_input("Please enter a substring: ") count = f.count(subString) #print(f) print(count) f.close() def program2(): fin = my_open() string = read_file_as_string(fin) subString = input("Please enter a substring: ") fin.close stringCount = 0 naiveSearch(string, subString, stringCount) def main(): #program1() program2() main()
true
79c841fcf7f088f02b1f148fb500f1164049623f
Cenibee/PYALG
/python/fromBook/chapter6/sort/bubble.py
271
4.125
4
from typing import List def bubble_sort(arr: List[int]): for i in range(0, len(arr) - 1): for j in range(1, len(arr)): if arr[j - 1] > arr[j]: arr[j - 1], arr[j] = arr[j], arr[j-1] a = [6,4,2,1,7,8,3,9,0,5] bubble_sort(a) print(a)
false
c290eac1e0eb4f0aeb77ebeb2cbc8857bfdae226
becerra2906/jetbrains_academy
/airmile/air_mile_calculator.py
1,901
4.625
5
### By: Alejandro Becerra #done as part of Jet Brains Academy Python learning Path #serves to calculate the number of months required to pay for a #flight with miles generated with customer credit card purchases. #print welcome message print("""Hi! Welcome to your credit card miles calculator. This program will help you understand how many months do you need to spend at your current rate to get enough miles to travel to several destinations!""") monthly_expenditure = abs(float(input("How much do you spend with your credit card? "))) #definition of point rate per dollar spent point_earning_rate = abs(float(input("How many points per dollar do you get with your card? "))) #distances to different world renowned cities new_york_distance = abs(int(input("How far away in miles are you from New York? "))) paris_distance = abs(int(input("How far away in miles are you from Paris? "))) mumbai_distance = abs(int(input("How far away in miles are you from Mumbai? "))) # miles earnt per month miles_per_month = (monthly_expenditure * point_earning_rate) # calculation of months needed to get round trip # to different destinations using miles months_ny = int((new_york_distance * 2) / miles_per_month) months_paris = int((paris_distance * 2) / miles_per_month) months_mumbai = int((mumbai_distance* 2) / miles_per_month) #print function for resulting months required to get tickets message_part_1 = 'It would take you ' message_part_2 = ' months to get a round trip to ' new_york_str = 'New York. ' paris_str = 'Paris. ' mumbai_str = 'Mumbai. ' ny = (message_part_1 + str(months_ny) + message_part_2 + new_york_str) paris = (message_part_1 + str(months_paris) + message_part_2 + paris_str) mumbai = (message_part_1 + str(months_mumbai) + message_part_2 + mumbai_str) print(ny) print(paris) print(mumbai) # print farewell message print("Thank you for using our program! Fly far away!")
true
ad46457d7f8e3837cb3628d0d703376a34208dd9
rcmoura/aulas
/prg_inverso_absoluto.py
215
4.125
4
# programa inverso absoluto numero = float(input("Digite um numero: ")) if numero > 0: inverso = 1 / numero; print ("Inverso: ", inverso) else: absoluto = numero * -1 print ("Absoluto: ", absoluto)
false
9e914e1d5f56cd6079bad7b3f3c5cbdb148778f9
team31153/test-repo
/Aaryan/Chapter5HW/C5Problem2.py
597
4.15625
4
#!/usr/bin/env python3 def daysOfTheWeek(x): if x == 0: return("Sunday") elif x == 1: return("Monday") elif x == 2: return("Tuesday") elif x == 3: return("Wednesday") elif x == 4: return("Thursday") elif x == 5: return("Friday") elif x == 6: return("Saturday") else: return("Invalid input") def vacation(): EnterDay = int(input("Input the day of the week.")) VacationLength = int(input("Input the amount of time you are on vacation.")) ReturnDate = (EnterDay + VacationLength) % 7 print(daysOfTheWeek(ReturnDate)) vacation()
true
373a78cc034227556576c08d4af934dde44ea391
team31153/test-repo
/Ryan/RyanChapter5HW/10findHypot.py
312
4.125
4
#!/usr/bin/env python3 firstLength = int(input("Enter the length for the first side: ")) secondLength = int(input("Enter the length for the second side: ")) hypot = 0 def findHypo(f, s, h): f2 = f * f s2 = s * s h = f2 + s2 h = h ** 0.5 print(h) findHypo(firstLength, secondLength, hypot)
true
e86b9c57eb5c8577ca8fe42015584dbb9bdef94a
leemiracle/use-python
/taste_python/cook_book/files_io.py
855
4.75
5
# 1. Reading and Writing Text Data # 2. Printing to a File # 3. Printing with a Different Separator or Line Ending # 4. Reading and Writing Binary Data # 5. Writing to a File That Doesn’t Already Exist # 6. Performing I/O Operations on a String # 7. Reading and Writing Compressed Datafiles # 8. Iterating Over Fixed-Sized Records # 9. Reading Binary Data into a Mutable Buffer # 10. Memory Mapping Binary Files # 11. Manipulating Pathnames # 12. Testing for the Existence of a File # 13. Getting a Directory Listing # 14. Bypassing Filename Encoding # 15. Printing Bad Filenames # 16. Adding or Changing the Encoding of an Already Open File # 17. Writing Bytes to a Text File # 18. Wrapping an Existing File Descriptor As a File Object # 19. Making Temporary Files and Directories # 20. Communicating with Serial Ports # 21. Serializing Python Objects
true
9873594ba403b3dea2f0dd65ddbb289e6c5f5ddb
sedychl2/sr-4-5-6-2
/инд задание в питоне.py
441
4.15625
4
V = 3 A = 1 R = 1 H = 2 if V <= A**3 and V <= 3.14 * R**2 * H: print("Жидкость может заполнить обе ёмкости") elif V <= A**3: print("Жидкость может заполнить первую ёмкость") elif V <= 3.14 * R**2 * H: print("Жидкость может заполнить вторую ёмкость") else: print("Слишком большой объём жидкости")
false
ccf258949439b444ead45f58513ba3e91e60b19d
fiolisyafa/CS_ITP
/01-Lists/3.8_SeeingTheWorld.py
477
4.15625
4
places = ["London", "NYC", "Russia", "Japan", "HongKong"] print(places) #temporary alphabetical order print(sorted(places)) print(places) #temporary reverse alphabetical order rev = sorted(places) rev.reverse() print(rev) print(places) #permanently reversed places.reverse() print(places) #back to original places.reverse() print(places) #permanent alphabetical order places.sort() print(places) #permanent reverse alphabetical order places.sort(reverse=True) print(places)
true
8c03b0bc52759815166152c93555c912f05482ca
fiolisyafa/CS_ITP
/03-Dictionaries/6.11_Cities.py
733
4.1875
4
cities = { "Canberra": { "country": "Australia", "population": "6573", "fact": "Capital city but nothing interesting happens." }, "London": { "country": "England", "population": "5673", "fact": "Harry Potter grew up here." }, "Jakarta": { "country": "Indonesia", "population": "903659306239659302", "fact": "Not livable." }, } for city, information in cities.items(): print(city + ":") country = information["country"] population = information["population"] fact = information["fact"] print('\t' + "Located in", country) print('\t' + "Has a population of", population, "people") print('\t' + fact)
true
79268b3094c685df6c9471c733c92f4ac1a059bb
Br111t/pythonIntro
/pythonStrings.py
2,022
4.65625
5
string_1 = "Data Science is future!" string_2 = "Everybody can learn programming!" string_3 = "You will learn how to program with Python" #Do not change code above this line # #prints the length of the string including spaces # print(len(string_2)) # #Output: 32 # #print the index of the first 'o'; the indices are counted useing the zeroeth #index rule # print(string_3.index('o')) # #Output:1 counter = 0 string_3 = "Being a Data Scientist has provided great opportunities for me!" #To find the number of occurences of a given character in a string, use a for loop and iterate over the given string for char in string_3: if (char == 'o'): counter += 1 print(counter) #Output is 4 string_3 = "Being a Data Scientist has provided great opportunities for me!" #count is a quicker method to count the identified alpha/numeric character in a string print(string_3.count('o')) #Output is 4 # Print the index within string_3 of the first character of the substring 'ovi' print(string_3.index('ovi')) #Output: 29 # print a count of the occurrences of 'ovi' in string_3 print(string_3.count('ovi')) #Output: 1 list_1 = [1, 2, 3, 4, 5] #Slicing from index to index print(list_1[1:3]) #Slicing from the beginning of a list up to an index print(list_1[:3]) #Slicing from an index up to the ending of a list print(list_1[4:]) ''' Output: [2, 3] [1, 2, 3] [5] ''' string_1 = "Hello world!" print(string_1[:5]) #Output: Hello print(string_1[6:]) #Output: world! print(string_1[1:5]) #Output: ello string_4 = "Hello World!" print(string_4.upper()) print(string_4.lower()) ''' Output HELLO WORLD! hello world! ''' string_5 = "Today is a very nice day!" print(string_5.split(" ")) #split on space #Output: ['Today', 'is', 'a', 'very', 'nice', 'day!'] string_6 = "Artificial Intelligence is cool!" print(string_6.startswith("Artificial")) print(string_6.endswith("nice!")) ''' Output True False '''
true
a953212a542bde4920cd0361dc18769538bb4bfb
sridivyapemmaka/PhythonTasks
/dictionaries.py
419
4.15625
4
#dictonaries methods() #clear() "removes all the elements from the list" list1={1:"sri",2:"java",3:"python"} list2=list1.clear() print(list1) output={} #copy() "returns a copy of the list" list1={1,2,3,4} list2=list1.copy() print(list2) output={1,2,3,4} #get() "returns the values of the specified list" list1={1:"python",2:"java",3:"program"} list2=list1.get(2) print(list2) output={"java"}
true
bd2aa8788af65e20d7b261860e66a02635de5ff8
zssvaidar/code_py_book_data_structures_and_algo
/chap03_recursion/reverse_list_another_way.py
568
4.21875
4
from typing import List IntList = List[int] def reverse_list(l: IntList) -> IntList: """Reverse a list without making the list physically smaller.""" def reverse_list_helper(index: int): if index == -1: return [] rest_rev: IntList = reverse_list_helper(index - 1) first: IntList = [l[index]] result: IntList = first + rest_rev return result return reverse_list_helper(index=len(l) - 1) def main() -> None: assert reverse_list([1, 2, 3]) == [3, 2, 1] if __name__ == "__main__": main()
true
ecbfb19bb09dd71d1a832dbbf71553cf306cacdd
zssvaidar/code_py_book_data_structures_and_algo
/chap04_sequences/stack.py
1,123
4.21875
4
class Stack: """ Last in, first out. Stack operations: - push push the item on the stack O(1) - pop returns the top item and removes it O(1) - top returns the top item O(1) """ def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise RuntimeError("Attempt to pop an empty stack") top_index = len(self.items) - 1 item = self.items[top_index] del self.items[top_index] return item def top(self): if self.is_empty(): raise RuntimeError("Attempt to get top of empty stack") top_index = len(self.items) - 1 item = self.items[top_index] return item def is_empty(self): return len(self.items) == 0 def main() -> None: st = Stack() assert st.is_empty() is True st.push(10) st.push(20) assert st.top() == 20 # 20 remain unchanged assert st.pop() == 20 if "__main__" == __name__: main()
true
d712835020e89a2909bfaf1c6d8c01be181be89a
Marcus893/algos-collection
/cracking_the_coding_interview/8.1.py
390
4.15625
4
Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. def triple_step(n): lst = [0] * (n+1) lst[0] = 1 lst[1] = 1 lst[2] = 2 for i in range(3, n+1): lst[i] = lst[i-3] + lst[i-2] + lst[i-1] return lst[-1]
true
06c573fce10ea205d810c7d62e86681a29554d7f
Marcus893/algos-collection
/cracking_the_coding_interview/4.6.py
737
4.15625
4
Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.parent = None def successor(node): successor = None if node.right: successor = node.right while successor.left: successor = successor.left elif node.parent: currNode = node while currNode.parent and successor == None: if currNode.parent.left == currNode: successor = currNode.parent currNode = currNode.parent return successor
true
8ed0786f818d82c26edc14d46b405b7c602fafc2
Marcus893/algos-collection
/cracking_the_coding_interview/2.4.py
1,080
4.34375
4
Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x . lf x is contained within the list, the values of x only need to be after the elements less than x (see below) . The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. EXAMPLE Input: 3 -> 5 -> 8 -> 5 - > 10 -> 2 -> 1 [partition = 5) Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head, x): l1, l2 = ListNode(None), ListNode(None) head1, head2 = l1, l2 while head: if head.val >= x: l2.next = ListNode(head.val) l2 = l2.next head = head.next else: l1.next = ListNode(head.val) l1 = l1.next head = head.next l1.next = head2.next return head1.next
true
2c00d4fb1a570e9d053eb1e9283ecea2c343e48b
Marcus893/algos-collection
/cracking_the_coding_interview/3.5.py
505
4.125
4
Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. def sortStack(stack): res = [] while(len(stack) > 0): item = stack.pop() while len(res) > 0 and item < res[-1]: stack.append(res.pop()) res.append(item) return res
true
023986d7eda3cad02f6a783dd88764eb1a939cf6
s3icc0/Tutorials
/DBTut/Lesson 009 Object Oriented Programming/pytut_009_001.py
1,178
4.34375
4
# OBJECT ORIENTED PROGRAMMING """ Real World Objects : Attribute & Capabilities DOG Attributes (Fields / Variables) : Height, Weight, Favorite Food Capabilities (Methods / Functions): Run, Walk, Eat """ # Object is created for a template called Class # Classes defines Attributes and Capabilities of an Object class Dog: # __init__ : initial equation # self is used to enable refering to 'Myself' # attributes with default values e.g. Dog with no name def __init__(self, name='', height=0, weight=0): # define attributes self.name = name self.height = height self.weight = weight # define methods def run(self): print('{} the dog runs'.format(self.name)) def eat(self): print('{} the dog eats'.format(self.name)) def bark(self): print('{} the dog barks'.format(self.name)) def main(): # create Dog with name Spot (height 66, width 26) spot = Dog('Spot', 66, 26) # make the spot bark spot.bark() # create new John Doe Dog bowser = Dog() # unknown Dog barking bowser.bark() # name a Dog bowser.name = 'Bowser' bowser.run() main()
true
fd7a49e1c672cf48f42228ebf83969de974dbf4c
s3icc0/Tutorials
/DBTut/Lesson 006 Lists/pytut_006_exe_002.py
1,413
4.375
4
# GENERATE THE MULTIPLICATION TABLE # With 2 for loops fill the cells in a multidimensional list with a # multiplication table using values 1-9 ''' This should be the result: 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 6, 9, 12, 15, 18, 21, 24, 27, 4, 8, 12, 16, 20, 24, 28, 32, 36, 5, 10, 15, 20, 25, 30, 35, 40, 45, 6, 12, 18, 24, 30, 36, 42, 48, 54, 7, 14, 21, 28, 35, 42, 49, 56, 63, 8, 16, 24, 32, 40, 48, 56, 64, 72, 9, 18, 27, 36, 45, 54, 63, 72, 81 ''' import random import math # Create the multiD list # create list with any value * 10 index positions (0-9) multiTable = [[1] * 10 for i in range(10)] # increment with outer for # perform the calculation from x-th to y-th list for i in range(0, 10): # increment with inner for # perform the calculation from x-th to y-th index in the lists for j in range(0, 10): # assign the value to the cell # for list number * index number multiTable[i][j] = i * j print() # output the data # skip list 0 by starting at 1 for i in range(1, 10): # skip index 0 in the lists by starting at 1 for j in range(1, 10): # print format print(multiTable[i][j], end=', ') print() # so in reality the data are created just by the index values, therefore any # index (both i and j) with 0 value will return 0 - that is the reason why we # are hiding the first list and the first index
true
9ea520cffdffe7d5a3e69cce58048b6b8a51cbe5
s3icc0/Tutorials
/DBTut/Lesson 008 Reading Writing Files/pytut_008_001.py
1,488
4.40625
4
# READING AND WRITING TEXT TO A FILE # os module help to manipulate files import os # with helps to properly close the file in case of crash # locate the file # mode='w' will override anything already in the file # mode='a' will enable appending to the file only # UTF-8 store text using Unicode # define where to store the file object : as myFile with open('mydata.txt', mode='w', encoding='utf-8') as myFile: # write to file # insert end of line as python does not do it automatically myFile.write('Some random text\nMore random text\nAnd some more') # open the file for reading with open('mydata.txt', encoding='utf-8') as myFile: """Reading methods: read() : read everything as one string until newline (no newline) readline() : read everything including newline as string readlines() : return list of lines including newline """ print(myFile.read()) # check file is closed (with method closes automatically) print(myFile.closed) # return filename print(myFile.name) # return the last mode used print(myFile.mode) # rename the file in the OS os.rename('mydata.txt', 'mydata2.txt') # remove the file os.remove('mydata2.txt') # create directory # os.mkdir('mydir') # cannot create existing dir # change path to the directory os.chdir('mydir') # check current directory print('Current Directory: ', os.getcwd()) # remove directory # 1st move backwards level up os.chdir('..') print('Current Directory: ', os.getcwd()) os.rmdir('mydir')
true
7cbb06c3818d3343558ff13e08f4c98825bdb943
s3icc0/Tutorials
/DBTut/Lesson 001 Learn to Program/pytut_001_exe_002.py
871
4.21875
4
# If age is 5 Go to Kindergarten # Ages 6 through 17 goes to grades 1 through 12 # If age is greater then 17 say go to college # Try to complete with 10 or less lines # Input age # Convert age to Integer age = eval(input('Enter age: ')) # Evaluate age and print correct result if age == 5: print('Go to Kindergarten') elif 6 <= age <= 17: # as the distance is always 5 we can assign class linearly grade = age - 5 # added to handle 1st if grade == 1: print('Go to {}st grade'.format(grade)) # added to handle 2nd elif grade == 2: print('Go to {}nd grade'.format(grade)) elif grade == 3: print('Go to {}rd grade'.format(grade)) else: print('Go to {}th grade'.format(grade)) elif age > 17: print('Go to college') else: print('Sorry, you are to young to be terrorized by the educational system')
true
fe8fa2c1030929f662e9ed24224999a7c1919053
s3icc0/Tutorials
/DBTut/Lesson 009 Object Oriented Programming/pytut_009_002.py
1,542
4.125
4
# GETTERS and SETTERS # protects our objects from assigning bad fields and values # provides improved output class Square: def __init__(self, height='0', width='0'): self.height = height self.width = width # Getter - property will allow us to access the fields internally @property def height(self): print('Retrieving the height') # 2x_ access private field ????? return self.__height @height.setter def height(self, value): # protect height entry for bad values # are we testing that input is non-negative int or float? if value.isdigit(): self.__height = value else: print('Please only enter numbers for height') @property def width(self): print('Retrieving the width') return self.__width @width.setter def width(self, value): if value.isdigit(): self.__width = value else: print('Please only enter numbers for width') def getarea(self): return int(self.__width) * int(self.__height) def getperimeter(self): return int(self.width) * 2 + int(self.height) * 2 def main(): asquare = Square() height = input('Enter height :') width = input('Enter width :') asquare.height = height asquare.width = width print('Height :', asquare.height) print('Width :', asquare.width) print('The perimeter is :', asquare.getperimeter()) print('The area is :', asquare.getarea()) main()
true
301028f45991ec452118fb86b9c4f0fb8c42f2fc
s3icc0/Tutorials
/Sebastiaan Mathôd Tutorial/001 Enumerate.py
452
4.1875
4
# ------------------------------------------------------------------------------ # WALK THROUGH THE LIST citties = ['Marseille', 'Amsterdam', 'New York', 'London'] """ # The bad way i = 0 # create counter variable for city in citties: print(i, city) i += 1 """ # The good way - Pythonic way # enumerate returns both indices and values (keep track of both) # less lines, easier to read for i, city in enumerate(citties): print(i, city)
true
24fb622a60d869b5bfdc639dec4c0de71826dd1c
s3icc0/Tutorials
/Corey Schafer Tutorial/OOP 2 Class Variables.py
1,209
4.15625
4
""" Python Object-Oriented Programming https://www.youtube.com/watch?v=ZDa-Z5JzLYM """ class Employee: num_of_emps = 0 raise_amount = 1.04 # class variable def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' # class variable applied to the class Employee.num_of_emps += 1 # increase with every employee def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): # class variable applied to an instance self.pay = int(self.pay * self.raise_amount) print(Employee.num_of_emps) emp_1 = Employee('Ondrej', 'Sisler', 50000) emp_2 = Employee('Test', 'User', 10000) print(Employee.num_of_emps) # print(emp_1.__dict__) # print instance name space # print(Employee.__dict__) # print instance name space # print(emp_1.pay) # emp_1.apply_raise() # print(emp_1.pay) # # print(Employee.raise_amount) # print(emp_1.raise_amount) # print(emp_2.raise_amount) # # emp_1.raise_amount = 1.05 # # print(Employee.raise_amount) # print(emp_1.raise_amount) # print(emp_2.raise_amount) # # print(emp_1.__dict__)
true
70c317bf1feded53134e4df778b22ce1aa0ec127
lundergust/basic
/intro/basic_calulator.py
225
4.34375
4
num1 = input("enter a number") num2 = input("enter another number") # float allows us to read as decimals. For some reason it is not needed # although the tutorial says it is result = float(num1) + float(num2) print(result)
true
c5d6e949aebb669ffa1ef835817c829bc65b76ad
sami-mai/examples
/conditional-flow.py
798
4.28125
4
#example 1 # name ="Bertha" # female = "Bertha" # if name == female: # print "welcome" # else: # print "NO" # #example 2 # name ="Bertha" # female = "Alex" # if name == female: # print "welcome" # else: # print "NO" #example 3 # name = raw_input("what is your favourite car?") # if name == "Range Rover": # print "Tata" # else: # print name #example 4 # name = raw_input("what is your favourite car?") # if name == "Range Rover": # print "was manufactured by Tata" # else: # new_name = raw_input("manufactured by?") # print "was manufactured by Tata " + new_name #example 5 name = raw_input("what is your favourite car?") if name == "Range Rover": print "was manufactured by Tata" elif name == "toyota": print "was manufactured by Toyota" else: print "I don't know"
false
c83b32a848d04303ae3ee36696623f7fb12f73b9
Dzhano/Python-projects
/nested_loops/train_the_trainers.py
452
4.21875
4
n = int(input()) total_average_grade = 0 grades = 0 presentation = input() while presentation != "Finish": average_grade = 0 for i in range(n): grade = float(input()) average_grade += grade total_average_grade += grade grades += 1 print(f"{presentation} - {(average_grade / n):.2f}.") presentation = input() total_average_grade /= grades print(f"Student's final assessment is {total_average_grade:.2f}.")
true
bb3fda8131f7ab620bd3e00f66286c13bf8d9b1b
SarthakSingh2010/PythonProgramming
/basics/MapFuncAndLamdaExp.py
999
4.4375
4
# Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) # Double all numbers using map and lambda numbers = (1, 2, 3, 4) result = map(lambda x: x + x, numbers) print(list(result)) # Add two lists using map and lambda numbers1 = [1, 2, 3] numbers2 = [4, 5, 6] result = map(lambda x, y: x + y, numbers1, numbers2) print(list(result)) # List of strings l = ['sat', 'bat', 'cat', 'mat'] # map() can listify the list of strings individually test = list(map(list, l)) print(test) #sum of digits or how to convert 123 into [1,2,3] print(list(map(int,str(123)))) print(sum(map(int,str(123)))) #lambda func : small anonymous func #A lambda func can take any #args, but one expression x = lambda a : a + 10 print(x(5)) x = lambda a, b : a * b print(x(5, 6)) x = lambda a, b, c : a + b + c print(x(5, 6, 2))
true
b326edc311b92b85f80ce03bc646a67db167ccc5
Cationiz3r/C4T-Summer
/Session-6 [Absent]/dictionary/lookUp.py
426
4.21875
4
colors = { "RED": "Hex: #FF0000", "GREEN": "Hex: #00FF00", "BLUE": "Hex: #0000FF", "MAGENTA": "Hex: #FF00FF", "CYAN": "Hex: 00FFFF", "YELLOW": "Hex: FFFF00", "ORANGE": "Hex: FF8000", } while True: print() color = input(" Input color: ") if color.upper() in colors: print(" ", colors[color.upper()]) else: print(" Color doesn't exist (in current data)")
false
146ccde11f165c54bfed745d5109f9f4dbd764f4
IrakliDevelop/python-small-projects
/generateAlphabetDictionary.py
323
4.21875
4
''' the purpose of this program is to generate for you sequence that you can use to create dictionary of alphabetical characters with numeric values of place in alphabet assigned to them ''' char = 'a' i = 1 while char <="z": print("\"" + char + "\" : " + str(i) + ", ", end="") char = chr(ord(char)+1) i += 1
true
1e57af8593237c7663f6c6d7318ba3e58be8a3b9
Zzechen/LearnPython2.7
/container/list_tuple.py
1,091
4.21875
4
# -*- coding:utf-8 -*- # list:一种有序的集合,使用 [] 声明 # 创建一个list classmates = ['A','B','C'] print classmates # 获取长度 print len(classmates) # 根据下标获取元素 正向从0开始 print classmates[1] # 使用负数获取倒数第几个,反向从-1开始 print classmates[-1] # 遍历 for item in classmates: print item # 追加 classmates.append('D') print len(classmates) # 插入 classmates.insert(1,'Tom') print classmates # 删除 classmates.pop(1) print classmates # 替换 classmates[1] = 'Tom' print classmates # 可以存储不同类型的元素 list = [1,'a',0.1,100L] print list # tuple:不可变的list,包括长度和元素,使用 () 声明。 # 可以将元素指定为list,从而达到变相可变 t = (1,2) print t # 当定义一个元素时,需要这样. t = (1,) print t # 因为 () 既可以表示tuple,有可以表示数学公式中的小括号,由于歧义的存在,所以1个元素的tuple定义是需要多加个',' # 实现一个”可变“的tuple t = (1,2,[2,3,4]) print t[2] t[2].append(5) print t
false
6c8a3860e9ff8dddccffd99b44aaad48524badca
gurpreet00793/jarvis
/string part 2.py
561
4.15625
4
my_string ='hello' print(my_string) my_string="hello" print(my_string) my_string='''hello''' print(my_string) #triple quotes string can be extend multiple lines my_string="""hello,welcome to the world of python""" print(my_string) b="welcometopython" print('b[9:15]=',b[9:15]) b="welcometopython" print('b[-6:15]=',b[-6:15]) b="welcometopython " print('b[-7:-1]=',b[-7:-1]) b="welcome to python " print('b[-7:17]=',b[-7:17]) a="i am" b="ironman" s=a+" "+b print(s) my_string="welcome to python" del my_string print(my_string)
false
a106f67cd4e5b01ded6754d9c19f869ecc16e572
gurpreet00793/jarvis
/input.py
591
4.125
4
"""math=input("enter your maths") physics=input("enter your physics") chemistry=input("enter your chemistry") val=int(math)+int(physics) print(val)""" name=input("enter name") math=input("enter marks") physics=input("enter marks") chemistry=input("enter marks") english=input("enter marks") val=(((int(math)+int(physics)+int(chemistry)+int(english))/400)*100) print(val) if val>=90: print('name:',name ,"grade A") elif (val<90)and(val>=75): print("grade B") elif (val>=60)and (val<75): print("grade c") elif (val>=30)and (val<60): print("grade d") else: print("fail")
false
d28d3be648383b7b2ded438ef25814c31c3a96f5
manjupoo/manjureddy
/max3fun.py
226
4.28125
4
def max(m,n,o): if m>n and n>o: print(m,"is larger then n") elif n>o and o>m: print(n,"is larger then o") else: print(o,"is larger then m and n") print ("enter three values") m=input() n=input() o=input() max(m,n,o)
false
ea2b440a310eead72ebb03def89eeff21b4c60da
afrokoder/csv-merge
/loops.py
393
4.15625
4
outer_loop = 1 while outer_loop < 10: inner_loop = 1 while inner_loop < outer_loop + 1: print (outer_loop, end="") inner_loop = inner_loop + 1 print() outer_loop = outer_loop + 1 #outer_loop = 10 for outer_loop in range (9,0,-1): for inner_loop in range (9,0,-1): if inner_loop <= outer_loop: print(outer_loop, end="") print()
true
50b22625006adb5db8fc1c57eaa3d0cc6fa97848
afrokoder/csv-merge
/food_list_exercise.py
607
4.25
4
#creating a list of food items for each day of the week mon_menu = ["white_rice", "stir_fry", "sesame_chicken", "beef", "fried_rice"] tue_menu = ["bread", "stir_fry", "sesame_chicken", "beef", "fried_rice", "potatoes"] user_selection = input("Enter Your Order: ") user_selection = user_selection.lower() #for x in mon_menu or tue_menu: if user_selection not in mon_menu: print(user_selection,"is not available") elif user_selection not in tue_menu: print(user_selection,"is not xxvailable") else: print("your order of " + user_selection + " has been entered!") #break print()
true
64e5a24e7b43691b706769be21a938f9db548197
smallest-cock/python3-practice-projects
/End-of-chapter challenges in ATBS/Chapter 03 – Functions/Collatz sequence.py
1,447
4.40625
4
def collatz(number): try: while number != 1: if number % 2 == 0: print(number // 2) number = number // 2 elif number % 2 == 1: print(number * 3 + 1) number = number * 3 + 1 except ValueError: print("Error: That's not an integer.") return def repeat(): while True: try: chosenInteger = int(input("\nEnter an integer: ")) collatz(chosenInteger) keepGoing = input("\nDo you want to try another integer? (y/n): ") if keepGoing == "y" or keepGoing == "Y": continue elif keepGoing == "n" or keepGoing == "N": print("Peace...") break else: print("I assume that means no. Peace...") break except ValueError: print("Error: That's not an integer.") return print("Hello! Today we will explore the Collatz sequence...\n") try: chosenInteger = int(input("Enter an integer: ")) collatz(chosenInteger) keepGoing = input("\nDo you want to try another integer? (y/n): ") if keepGoing == "y" or keepGoing == "Y": repeat() elif keepGoing == "n" or keepGoing == "N": print("Peace...") else: print("I assume that means no. Peace...") except ValueError: print("Error: That's not an integer.")
true
abe9db15437d1d72d1b33b6690ebf34c456fc72e
smallest-cock/python3-practice-projects
/End-of-chapter challenges in ATBS/Chapter 08 – Reading and Writing Files/RegexSearch.py
1,921
4.46875
4
#! /usr/bin/python3 # RegexSearch.py - Searches all text files in a given folder using a (user supplied) # regex, and prints the lines with matched regex on the screen import re, os, sys # creates regex object to be used to find text files regexTxt = re.compile(r'.txt$') # checks to see if 2nd argument is a directory path, and is a folder. If folder, # creates new list containing (string) contents of that folder if len(sys.argv) < 2: print("Error: You didn't supply a directory path.") exit() elif len(sys.argv) > 2: print('Error: Too many arguments.') exit() elif os.path.isdir(sys.argv[1]) == True: fileList = os.listdir(sys.argv[1]) else: print("Error: That's not a folder") exit() print('Jews are bad.') # creates new textFileList and appends the directory path of each text file in the folder textFileList = [] textFileCount = 0 for file in fileList: if regexTxt.search(file) != None: textFileList.append(os.path.join(sys.argv[1], file)) textFileCount += 1 # prints the amount of text files in the folder if textFileCount > 0: print("There are " + str(textFileCount) + ' text file(s) in this folder.') else: print('There aren\'t any text files in this folder..') # promts user for search term and creates regex from user input userInput = input('\nEnter a term or phrase to search for (case sensitive): ') userRegex = re.compile(r'' + userInput) noMatch = True # prints search results of lines containing regex matches print('\nSearch results:') for directory in textFileList: textFile = open(directory) stringList = textFile.readlines() for line in stringList: if userRegex.search(line) != None: print(line) noMatch = False # if no matches were found, prints message saying so if noMatch == True: print('\nThere are no lines containing "' + userInput + '" in any of this folder\'s text files :(' )
true
651bf3c14990ee438469cc56377f0ea7df00c605
filhomarlon/python
/exercicio-1.py
608
4.125
4
""" Escreva um Programa que imprime dois numeros de sua escolha e que depois imprime a soma, a subtração, a multiplicação, a divisão normal e a divisão inteira, e o resto da divisão do maior pelo menor (coloque na mensagem a palavra resto ao invez do símbolo %) EXEMPLO DE SAÍDA: >>> x = 15 y = 10 15 + 10 = 25 15 - 10 = 5 15 x 10 = 150 15 / 10 = 1.5 15 // 10 = 1 15 resto 10 = 5 >>> """ x = 15 y = 10 print(x,"+",y,"=",x+y) print(x,"-",y,"=",x-y) print(x,"*",y,"=",x*y) print(x,"/",y,"=",x/y) print(x,"//",y,"=",x//y) print(x,"resto",y,"=",x%y)
false
0b241218404ab2aecf9090d2a939f5ad3de1af91
hcarvente/jtc_class_code
/class_scripts/bootcamp_scripts/nested_data_practice.py
2,164
4.34375
4
# lists inside lists shopping_list = [['mangos', 'apples', 'oranges'], ['carrots,', 'broccoli','lettuce'], ['corn flakes', 'oatmeal']] # print(shopping_list) #access an inner list # print(shopping_list[1]) # ONE MORE LEVEL DOWN # access an ITEM inside an inner list # print(shopping_list[1][0]) shopping_list[1].append('avocados') # shopping_list[1].append('peach') # shopping_list[1].append('kiwi') print(shopping_list) # nested loops with nested list for food_group in shopping_list: print(food_group) for food_group in shopping_list: for food in food_group: print(food) # dictionaries inside lists users = [{'username': 'ash', 'password': 'ilovepython'}, {'username': 'paul', 'password': 'ilovegit'}, {'username': 'aryn', 'password': 'ilovepython', 'last_login': '9/28'}] # print(users) # print a dictionary inside the list print(users[2]) # print out an item in a dictionary, in a list print(users[2]['last_login']) # loop through a list of dictionaries, and get the same info from each one for user in users: print(user['password']) # lists inside dictionaries cart = {'fruits': ['mangos', 'apples'], 'veggies': ['spinach','peas'], 'grains':['rice'], 'total_price': 15.78} print(cart) # access a specific list inside a dictionary print(cart['veggies']) #add items to a list inside a dictionary cart['veggies'].append('peach') cart['veggies'].append('carrots') cart['veggies'].remove('peach') print(cart['veggies']) print(cart) # braket indexing on a list inside a dictionary print(cart['fruits'][0]) # loop through a list INSIDE a dictionary for food in cart['fruits']: print(food.upper()) #dictionaries inside dictionaries restaurant = {'El Basurero': {'address': '32-17 Steinway Street', 'menu_url': 'menu.com'}, 'Joes Pizza': {'address': '7 Carmine Street', 'phone_number':'718-882-9012'}} print(restaurant) # specific restaurants -- search by the key print(restaurants['Joes Pizza']) ​ ​ # specific items inside the nested dictionaries print(restaurants['Joes Pizza']['phone_number']) ​ ​ restaurants['Joes Pizza']['phone_number'] = '718-902-6354' print(restaurants['Joes Pizza']['phone_number'])
true
aedccc4e66cd18e351eccae9fa706c61405dd998
hcarvente/jtc_class_code
/class_scripts/bootcamp_scripts/functions_practice.py
2,300
4.34375
4
#RUNNING EXISTING FUNCTIONS # print is a function # print('hi') # # name of the function comes first, followed by parentheses # # what is inside the parenthese is called 'parameters' or 'argument' # print(int(2.0)) # CREATING A FUNCTION # DEFININF a function def say_hello(): #anything inside as part of the function is indended print('hello world!') # RUN the function (calling a function) say_hello() # include a function inside a logical statement a= 1 if a > 0: print('greater than 0') say_hello() else: print('less than or equal to 0') # run a function in a for loop for num in range(1): print(num) say_hello() # parameter / arguments / inputs # these let us make our functions more FLEXIBLE #add parameters inside the parenthese def say_hello_personal(person_name): print(f'hello, {person_name}!') # running the function with parameters say_hello_personal(person_name = 'Yusuf') say_hello_personal(person_name ='Ash') say_hello_personal(person_name ='Aeshna') say_hello_personal(person_name ='Aedan') #function to multiple numbers by 2 def times_two(number): print(number*2) times_two(100) times_two(True) # function to multiply any numbers def multiply(number_a, number_b, number_c): print(number_a*number_b*number_c) multiply(5, 10, 3) multiply(500, 10.2368, 12) #default arguments def say_hello_personal(person_name='there'): print(f'Hello, {person_name}') say_hello_personal() say_hello_personal('Aryn') def greeting(first_name, last_name, middle_name = ''): print(f'Hello, {first_name} {middle_name} {last_name}') greeting(first_name = 'Paul', last_name = 'Bloom', middle_name = 'A') # RETURN statements # return vs print # print - for display not manipulating data # print - puts the output on the consile (command line) where you # print - does NOT save anything, cant be saved to variabke # return function - give you actual output from function # output returnd by functions can be saved to variable def multiply(number_a, number_b): return(number_a*number_b) answer = multiply(2,3) print(answer+4.0) def capitalize_first_letter(word): return(word[0].upper()) + word[1:] a = capitalize_first_letter('paul') print(a) # func() object.fun() # .upper() # .join() # .append() # functions with the . in front are called 'methods'
true
a75e26f1173c782f29c254c092cf40a446154a5c
TrueNought/AdventOfCode2020
/Day3/Day3.py
907
4.125
4
def count_trees(route, right, down): total_trees = 0 index = 0 index_length = len(route[0]) - 1 height = 0 while height < len(route): if route[height][index] == '#': total_trees += 1 index += right height += down if index > index_length: index -= index_length + 1 print('Total trees encountered: {}'.format(total_trees)) return total_trees def main(): with open('day3input.txt', 'r') as file: path = file.read().splitlines() # Part 1 print('Part 1') count_trees(path, 3, 1) # Part 2 print('\nPart 2') r_increments = [1, 3, 5, 7, 1] d_increments = [1, 1, 1, 1, 2] product = 1 for i in range(len(r_increments)): product *= count_trees(path, r_increments[i], d_increments[i]) print('Product is {}'.format(product)) if __name__ == "__main__": main()
true
d295238e7d3b549ff31956008f2620fcec5529ba
GiTJiMz/Advanced-programming
/10-09-2020/W37/greeter.py
415
4.15625
4
#!/usr/bin/env python3 import random def simple_greeting(name): return "hello! " + name def time_greeting(name): from datetime import datetime return f"It's {datetime.now()}, {name}" greetings = [ simple_greeting , time_greeting ] greeting = random.choice(greetings) print(greeting("Christian")) # 1. Add another greeting # 2. Make all greetings take an name as input.
true
f4225c3e3ae3588dbfaa7ab8b0ebb0bb555dbf67
idzia/Advent_of_code
/day_6/day_6.py
1,860
4.4375
4
""" How many redistribution cycles must be completed, to repeat the value For example, imagine a scenario with only four memory banks: The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution. Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2. Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3. Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4. The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1. The third bank is chosen, and the same thing happens: 2 4 1 2. At this point, we've reached a state we've seen before: 2 4 1 2. So an answer in this example is 5. """ with open("day6.txt") as file: row = file.readlines() row = list(map(str.strip, row)) row = row[0].split("\t") row = list(map(int, row)) list_of_str = [] steps = 0 condition = 1 while condition == 1: max_value = max(row) index = row.index(max_value) row[index] = 0 for i in range(0, max_value): index += 1 if index == len(row): index = 0 row[index] += 1 str_to_add = "".join(list(map(str, row))) steps += 1 if (str_to_add in list_of_str): condition = 0 list_of_str.append(str_to_add) print(steps)
true
12d273ecfd2c3b7603d23ab272905f8108af167b
dovewing123/LehighHacksFall2016
/scientist.py
2,315
4.15625
4
__author__ = 'Alexandra' def scientist(scientistCount): if scientistCount == 0: #print("\"Oh no! The parade is going to be ruined! It's supposed to go by the river, but ", #"the river is a mess!\"") input("\"Oh no! The parade is going to be ruined! I'm supposed to make the float, but the river is a mess!\"") input("\"I can't focus until the river problem is solved! I don't know what's wrong with it.\"") #print("The scientist looks up at you, eyes filled with hope.", " \"Do you think...\"") input("The scientist looks up at you, eyes filled with hope. \"Do you think...\"") scientistCount+=1 if scientistCount == 1 or scientistCount == 2: #print("\"Do you think you could go figure out what's wrong with the river?") input("\"Do you think you could go figure out what's wrong with the river?") print("Do you:\na: nod, agreeing to check out the river, and exit\nor\nb: slowly back away from the hopeful " "scientist before running out the door?") resp = checkInput(input()) scientistCount=2 return scientistCount elif scientistCount == 3: input("You tell the scientist what was going on with the river and the farmer. A look of relief washes over the scientist's face.") input("\"Wow, that little contaminated stream was really messing up the ecosystem of the river. It just goes to show that " "a little pollution is a big problem. Thanks for figuring out what was wrong; your observations and reasoning really saved the day!\"") input("\"Oh, but I should start working on that float! Thanks again for your help!\"") input("The scientist heads into the back room to start working of the float, and you head to the front door to go somewhere else.") scientistCount+=1 return scientistCount elif scientistCount == 4: input("You can only see glimpses of the float, but it looks great. You leave the scientist to their work, and go somewhere else.") return scientistCount def checkInput(string): string = string.strip().lower() while string not in ['a', 'b']: string = input("Please answer a or b: ").strip().lower() return string
true
40268822e0159f88ca821c98b72d4318f06c38ef
L0ganhowlett/Python_workbook-Ben_Stephenson
/25 Units of Time ( Again).py
402
4.15625
4
#Units of Time (Again) #asjking the number of seconds. s = float(input("Enter the number ofseconds = ")) #Assigning d for days, h fro hours, m for minutes, s for seconds. d = int(s // (24 * 60 * 60 )) s = (s % ( 24 * 60 * 60 )) h = int(s // (60 * 60)) s = s % ( 60 * 60) m = int(s // 60) s = int(s % 60) print('The equivalent amount of time in the form of %d:%02d:%02d:%02d is '%(d,h,m,s))
false
b70c555b5db3fb86ec842b042ed7439978d0f55b
L0ganhowlett/Python_workbook-Ben_Stephenson
/47 Birth date to Astrological; Sign.py
1,459
4.34375
4
#47 Birth Date to Astrological Sign #Asking user to input day of birth and month. x = int(input("Day of birth : ")) y = input("Enter the name of birth month : ") if y == "January": if x <= 19: z = "Capricorn" elif 19 < x <= 31: z = "Aquarius" if y == "February": if x <= 18: z = "Aquarius" elif 18 < x <= 29: z = "Pisces" if y == "March": if x <= 20: z = "Pices" elif 20 < x <= 31: z = "Aries" if y == "April": if x <= 19: z = "Aries" elif 19 < x <= 30: z = "Taurus" if y == "May": if x <= 20: z = "Taurus" elif 20 < x <= 31: z = "Gemini" if y == "June": if x <= 20: z = "Gemini" elif 20 < x <= 30: z = "Cancer" if y == "July": if x <= 22: z = "Cancer" elif 22 < x <= 31: z = "Leo" if y == "August": if x <= 22: z = "Leo" elif 22 < x <= 31: z = "Virgo" if y == "Septemebr": if x <= 22: z = "Virgo" elif 22 < x <= 30: z = "Libra" if y == "October": if x <= 22: z = "Libra" elif 22 < x <= 31: z = "Scorpio" if y == "November": if x <= 21: z = "Scorpio" elif 21 < x <= 30: z = "Sagittarius" if y == "December": if x <= 21: z = "Sagittarius" elif 21 < x <= 31: z = "Capricorn" print("Astological sign is :",z)
false