blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ee0c50c7586746a4dfdbf6348592f561246942c4
UjjwalP08/Basics-Of-Python
/No_55_Functioncaching.py
2,008
4.65625
5
""" --------------------> Function Caching <--------------------------- some times we are call the same function in program again and again so our time of program is taken more than expected so reduce this we are use the function caching this method is inside the functool module and method is lur_cache """ # import time # # def work(n): # # This is my function of work # time.sleep(n) # return n # # if __name__ == '__main__': # print("This is first time") # work(3) # print("This is Second time") # work(3) # print("Completed") # """ In this program we are call the work function 2 time but it contain 6 sce but suppose if we have call function 10 times so taken time 30 sec that has not mean to speed for us so we want to first store that time value and when we want to that is printed using this to or call this is known as function caching """ from functools import lru_cache import time @lru_cache(maxsize=10) # store the capacity of this function call is 10 now # for different value of it stores after again call the time is reduce def work(n): # This is my function of work time.sleep(n) return n if __name__ == '__main__': print("This is first time") work(5) print("This is Second time") work(3) print("Completed") work(5) print("Again") work(3) print("Again") work(4) print("call Again") work(3) print("again call") work(4) print("Over") # In this program the file or work function call 6 or 7 time like work(5) and work(3) etc # after when we call the work(5) 2nd time that is not take 5sec to run it """ In simple or gujarati language ma kahu to work(5) 2nd time call thase tyare te 5 sce jetlo time nahi le execution mate tevi j rite jo work(3) pacho call thaay to 3 sec nahi le aabadha function only ek j vaar tema aapeli integer value hisabe run tahvaa mate time lese biji vaar jo te pachu call thay tyare speed ma execute thasee vadhare samay nahi lee """
true
4a89663ccb22ff3f3a9138af70b346b60aa43ab1
aravinthusa/python-prgramme
/file1.py
479
4.40625
4
program: #to find the radius of the circle r=float(input("input the radius of the circle:")) a=(22*r*r)/7 print("the area of circle with radius",r,"is:",a) output: input the radius of the circle:1.1 the area of circle with radius 1.1 is: 3.8028571428571434 program: #to find the extension of the file a=input("Input the Filename: ") b=a.split(".") c=print ("The extension of the file is : " ,b[-1]) output: Input the Filename: abc.py The extension of the file is : py
true
9665330448fa691346f1117e65665b734cd79aa3
hungnd11111984/DataCamp
/pandas Foundation/Build a DataFrame.py
2,933
4.28125
4
# 1 Zip lists to build a DataFrame # Display tuple print(list_keys) # ['Country', 'Total'] print(list_values) # [['United States', 'Soviet Union', 'United Kingdom'], [1118, 473, 273]] # Zip the 2 lists together into one list of (key,value) tuples: zipped zipped = list(zip(list_keys,list_values)) # Inspect the list using print() print(zipped) # [('Country', ['United States', 'Soviet Union', 'United Kingdom']), ('Total', [1118, 473, 273])] # Build a dictionary with the zipped list: data data = dict(zipped) # Build and inspect a DataFrame from the dictionary: df df = pd.DataFrame(data) print(df) # Country Total #0 United States 1118 #1 Soviet Union 473 #2 United Kingdom 273 # 2 Building DataFrames with broadcasting # Make a string with the value 'PA': state state = 'PA' # print cities list print(cities) # ['Manheim', 'Preston park', 'Biglerville', 'Indiana', 'Curwensville', 'Crown', 'Harveys lake', 'Mineral springs', 'Cassville', 'Hannastown', 'Saltsburg', 'Tunkhannock', 'Pittsburgh', 'Lemasters', 'Great bend' # Construct a dictionary: data data = {'state':state, 'city':cities} # Construct a DataFrame from dictionary data: df df = pd.DataFrame(data) # Print the DataFrame print(df) # city state #0 Manheim PA #1 Preston park PA #2 Biglerville PA #3 Indiana PA #4 Curwensville PA # 3: Import / Export Data # 3.1 Reading Flat File # Read in the file: df1 df1 = pd.read_csv('world_population.csv') # Create a list of the new column labels: new_labels new_labels = ['year','population'] # Read in the file, specifying the header and names parameters: df2 df2 = pd.read_csv('world_population.csv', header=0, names=new_labels) # Print both the DataFrames print(df1) # Year Total Population #0 1960 3.034971e+09 #1 1970 3.684823e+09 print(df2) # year population #0 1960 3.034971e+09 #1 1970 3.684823e+09 # 3.2 Delimiters, headers, and extensions # print(file_messy) # messy_stock_data.tsv # Read the raw file as-is: df1 df1 = pd.read_csv(file_messy) # Print the output of df1.head() print(df1.head()) # .... # .... # IBM 156.08 160.01 159.81 165.22 172.25 167.15 1... NaN # name Jan Feb Mar Apr May Jun Jul Aug \ #0 IBM 156.08 160.01 159.81 165.22 172.25 167.15 164.75 152.77 # Read in the file with the correct parameters: df2 df2 = pd.read_csv(file_messy, delimiter=' ', header=3, comment='#') # Print the output of df2.head() print(df2.head()) # Sep Oct Nov Dec #0 145.36 146.11 137.21 137.96 #1 43.56 48.70 53.88 55.40 # Save the cleaned up DataFrame to a CSV file without the index df2.to_csv(file_clean, index=False) # Save the cleaned up DataFrame to an excel file without the index df2.to_excel('file_clean.xlsx', index=False) #
true
7b4645a593d068c7ab87dc7a71a3022740223ad7
Luedman/MiscMath
/Collatz.py
1,267
4.125
4
from matplotlib import pyplot as plt import numpy as np number = int(input("Starting Number: ")) def collatz(number: int, plot=False): series = [] odd_series = [] while number > 1: if number % 2 == 0: number /= 2 else: odd_series.append(int(number)) number = 3*number + 1 series.append(int(number)) if plot: plt.plot(series) print(series) print(odd_series) print() return series, odd_series series, odd_series = collatz(number) def is_prime(number): if number > 1: for i in range(2,number): if (number % i) == 0: result = False break else: result = True else: pass return result def primes(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) # supposing you want multiple factors repeated n //= d d += 1 if n > 1: primfac.append(n) return primfac for num in odd_series: print(str(num) + "\t " + str(primes(num))) plt.plot(odd_series) print() for num in series: print(str(num) + "\t " + str(primes(num))) print() try: plt.show() except: pass
false
3bfa1389d2d43bcbdda5995b99c01a8fb16b6496
yuede/Lintcode
/Python/Reverse-Linked-List.py
495
4.125
4
class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the reversed linked list. Reverse it in-place. """ def reverse(self, head): # write your code here if head is None or head.next is None: return head pre = None while head is not None: temp = head.next head.next = pre pre = head head = temp return pre
true
51aa90a32ee61c3e3891f4cad80c6a06d59a81dd
chunweiliu/leetcode2
/insert_interval.py
1,286
4.21875
4
"""Insert a new interval << [[1, 2], [3, 5], [7, 9]], [4, 8] => [[1, 2], [3, 9]] << [[1, 2]], [3, 4] => [[1, 2], [3, 4]] - Insert a number [0, 1, 2, 10], 3 Seperate the intervals to left and right half by comparing them with the target interval - If not overlap, put them in to left or right - Otherwise, update the start and end interval Time: O(n) Space: O(n) """ # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e # # def __repr__(self): # return '({}, {})'.format(self.start, self.end) class Solution(object): def insert(self, intervals, target): """ :type intervals: List[Interval] :type target: Interval :rtype: List[Interval] """ left, right = [], [] for interval in intervals: if interval.end < target.start: left.append(interval) elif interval.start > target.end: right.append(interval) else: target.start = min(target.start, interval.start) target.end = max(target.end, interval.end) return left + [target] + right
true
0c5d9e1322959ea228ef2e8ac23076caa162a192
chunweiliu/leetcode2
/the_skyline_problem.py
1,998
4.21875
4
"""Use a dict to represent heights. For each critical point, pop the heightest. << [[1, 10, 5], [3, 8, 7]] => [[1, 5], [3, 7], [8, 5], [10, 0]] A good illustration of the skyline problem https://briangordon.github.io/2014/08/the-skyline-problem.html Time: O(nlogn) Space: O(n) """ from heapq import * class Solution(object): def getSkyline(self, LRH): """ :type LRH: List[List[int]] :rtype: List[List[int]] """ skyline = [] # liveHR is a max heap of (-height, -right). Pairs are kept in the # priority queue and they stay in there as long as there's a larger # height in there, not just until their building is left behind. liveHR = [] i, n = 0, len(LRH) while i < n or liveHR: # If the next building has a smaller x, comparing with the largest # right point in the heap, add it to the liveHR heap. # # ------ <- roof (liveHR[0]) # ------- <- LRH[i] should be added to the live HR # ------- <- liveHR[1] if not liveHR or (i < n and LRH[i][0] <= -liveHR[0][1]): x = LRH[i][0] while i < n and LRH[i][0] == x: heappush(liveHR, (-LRH[i][2], -LRH[i][1])) i += 1 # Otherwise, we need to update liveHR. # # ------ <- liveHR that is going to be removed # ------- <- LRH[i] # -------- <- liveHR will not be removed at this time, but soon else: x = -liveHR[0][1] while liveHR and -liveHR[0][1] <= x: heappop(liveHR) if liveHR: height = -liveHR[0][0] else: height = 0 if not skyline or height != skyline[-1][1]: skyline.append([x, height]) return skyline
true
309df73c581fbddafb1d952ef24b7d107e445da4
chunweiliu/leetcode2
/implement_trie_prefix_tree.py
1,849
4.3125
4
""" Each Trie node has a dict and a flag. For inserting a word, insert each character to the Trie if the character is not there yet. For distiguish a word and a prefix, use the '#' symbol. Trie (f) (b) (o) (a) (o)T (r)T """ from collections import defaultdict class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.chars = defaultdict(TrieNode) self.is_word = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root # If the key is missing in the dict, __missing__ is called and a default # value will be generated for the missing key, according to the the dict's # default_factory argument (for example, Trie here). for char in word: node = node.chars[char] node.is_word = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.traverse(word) return node and node.is_word def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.traverse(prefix) return bool(node) def traverse(self, word): node = self.root for char in word: if char not in node.chars: return False node = node.chars[char] return node # Your Trie object will be instantiated and called as such: # trie = Trie() # trie.insert("somestring") # trie.search("key")
true
23c498871baaf75458fb1f6180d7aa9aaa5bf7f0
premkumar0/30DayOfPython
/Day-12/day_12_Premkumar.py
648
4.28125
4
def linearSearch(n, k, arr): """ This function takes k as the key value and linear search for it if the value is found it returns the index of the key value else it will return -1 Example:- n, k = 4, 5 arr = [2, 4, 5, 8] returns 2 """ for i in range(n): if arr[i] == k: return i else: return -1 if __name__ == "__main__": n = int(input("Enter number of elements you want \n")) arr = [float(num) for num in input("Enter space seperated {} numbers for array \n".format(n)).split()] k = float(input("Enter the search key \n")) print("index of the search key is {}".format(linearSearch(n, k, arr)))
true
a7c25e91839df58225d7978d02a44f3069f4e74d
Wjun0/python-
/day03/01-下标.py
735
4.375
4
# 下标:又称为索引,其实就是数字 # 下标的作用:就是根据下标获取数据的 # 下标的语法格式: # my_str = "abc" # my_str[0] => 变量名[下标] # 下标可以结合range,字符串,列表,元组 my_str = "hello" # 正数下标取值 result = my_str[3] print(result) # 负数下标取值 result = my_str[-2] print(result) # 正数下标取值 result = my_str[0] print(result) # 负数下标取值 result = my_str[-1] print(result) # 总结:在python里面下标可以分为正数下标和负数下标,下标就是用来获取数据的 # 扩展: ---- my_range = range(3) # [0,2] result = my_range[0] print(result) result = my_range[-1] print(result)
false
ddad14d92093d19c4abad6272676be512523fc47
Wjun0/python-
/day06/15-高阶函数.py
1,260
4.15625
4
# 高阶函数: 函数的参数或者返回值是一个函数类型,那么这样的函数称为高阶函数 # 学习高阶函数目的: 为高级讲闭包和装饰器做铺垫 # 高阶函数1:函数的参数是一个函数类型 # def show(new_func): # 此时new_func参数是一个函数类型 # print("show函数开始执行了") # # 调用传入过来的函数 # new_func("人生苦短,我用python!") # # print("show函数执行结束了") # # # 调用函数的时候进行传参使用匿名函数进行代码的简化 # # 高阶函数结合匿名函数一起使用 # show(lambda msg: print(msg)) # 高阶函数2: 函数的返回值是一个函数类型 def show(): print("外部函数开始执行了") # 在python里面可以在一个函数里面再次定义一个函数,这样的函数称为函数的嵌套 # 内部函数执行在当前函数内部进行调用 def inner(): print("内部函数执行了") # inner() # 注意点:返回一个函数不要加上小括号,加上小括号表示返回的是一个函数调用后的结果 return inner # 只要函数的返回值是一个函数类型,此时show函数就是高阶函数 new_func = show() # new_func = inner new_func()
false
7fe0b7f1a2b35d7ee75157b74df3ec7c395c8645
gabipires/ExerciciosImpactaADS
/media_conjunto_notas.py
1,105
4.40625
4
# Em uma escola, um professor deve realizar três avaliações por semestre. Para o cálculo da nota final, ele pode usar # três diferentes métodos de cálculo de médias: # Média aritmética ("a"); # Média ponderada ("p"): nesse caso, o programa deve perguntar também os pesos de cada nota; # Média harmônica ("h"): pode ser definida pela quantidade de notas dividida pela soma do inverso de cada nota. # Faça um programa que calcula as três médias para um conjunto de 3 notas. Na saída também deve ser identificado a # qual média cada valor se refere. nota1= float(input("Nota 1: ")) nota2= float(input("Nota 2: ")) nota3= float(input("Nota 3: ")) peso_nota1=int(input("Peso 1: ")) peso_nota2=int(input("Peso 2: ")) peso_nota3=int(input("Peso 3: ")) aritmetica= (nota1 + nota2 + nota3)/3 a=round(aritmetica,1) ponderada=((nota1*peso_nota1) + (nota2*peso_nota2) + (nota3*peso_nota3))/(peso_nota1+peso_nota2+peso_nota3) p=round(ponderada,1) harmonica= 3/((1/nota1) + (1/nota2) + (1/nota3)) h=round(harmonica,1) print("a: {}".format(a)) print("p: {}".format(p)) print("h: {}".format(h))
false
699f261fc02664f070af9158f6a1d158d28f70cc
KuroCharmander/Turtle-Crossing
/player.py
602
4.15625
4
from turtle import Turtle STARTING_POSITION = (0, -280) MOVE_DISTANCE = 10 FINISH_LINE_Y = 280 class Player(Turtle): """The turtle in the Turtle Crossing game.""" def __init__(self): """Initialize the turtle player.""" super(Player, self).__init__("turtle") self.penup() self.setheading(90) self.reset_start() def move(self): """Move the turtle up.""" self.forward(MOVE_DISTANCE) def reset_start(self): """Reset the turtle to the starting position at the bottom of the screen.""" self.goto(STARTING_POSITION)
true
17ec9865fa01cf14e1a90715110b98138c182093
lekasankarappan/PythonClasses
/Day2/Userinput.py
470
4.25
4
name =input("Enter your name: ") print("hey",name) #input method takes only string so we have to convert into integer num1=int(input("Enter first num:")) num2=input("Enter second num:") print("Addition of",num1,"and",num2,"is",num1+int(num2)) print("subtraction of",num1,"and",num2,"is",num1-int(num2)) print("multiplication of",num1,"and",num2,"is",num1*int(num2)) print("Division of",num1,"and",num2,"is",num1/int(num2)) #% is reminder print(53%3) print((2/20)*100)
false
ddd53c5798d033ce7d85b51b3805aeca263a2ad8
d1l0var86/Dilovar
/classes/cars.py
2,200
4.5
4
class Car(): """This is class to represent a car.""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.color = 'White' self.odometer_reading = 0 # getter and setter def get_description(self): msg = f"Your car: \nmanufacture: {self.make},\nmodel: {self.model}\nYear: {self.year}\nColor: {self.color}" return msg def set_color(self, new_color): print(f"Changing the color {self.color} to {new_color}") self.color = new_color def read_odometer(self): """Get the odometr miles of the car.""" msg = f"Car has {self.odometer_reading} miles on it." return msg def set_odometer(self, new_miles): if new_miles >= self.odometer_reading: print(f"Setting odometer reading from {self.odometer_reading} to {new_miles}") self.odometer_reading = new_miles else: print(f"You can not roll back odometer from {self.odometer_reading} to {new_miles}.") def increment_odometer(self, miles): """:param miles to odometer_reading""" # self.odometer_reading = self.odometer_reading + miles if miles > 0: print(f"Incrementing odometer with more {miles} miles") self.odometer_reading += miles else: print(f"Negative value cannot be passed to odometer : {miles}") class ElectricCar(Car): """Represents Electric car , inherits all features of Car.""" def __init__(self, make,model,year): """child class constructor , Overriding the parent constructor""" super().__init__(make,model,year) # calling the constructor of parent class self.battery_size =80 def get_description(self): msg = f"Your car: \n\tmanufacture: {self.make},\n\tmodel: {self.model}\n\tYear: {self.year}"\ f"\n\tColor: {self.color}\n\tBattery size: {self.battery_size}" return msg def test_method(self): print(self.get_description()) # current class get_description() method, with battery_size print(super().get_description()) # parent class get_description() method
true
66c2a539db2169fc48436f2faff1ff287765d0ff
JagadishJ4661/Mypython
/Numbers.py
759
4.25
4
'''Take 2 numbers from the user, Print which number is 2 digit number and which number is 3 digit number If it neither, then print the number as it is''' def entry(): num1 = input("Select any number that you wish.") num1 = int(num1) num2 = input("select any number that you wish again.") num2 = int(num2) print(num1, num2) if num1>=10 and num1<100: print(num1,"is a two digit number") if num2>=10 and num2<100: print(num2, "is a two digit number") if num1>=100 and num2<1000: print(num1,"is a three digit number") if num2>=100 and num2<1000: print(num2,"is a two digit number") if num1<10 and num1>=1000: print(num1) if num2<10 and num2>=1000: print(num2) entry()
true
0911c018b5024d7dc525ebc285e67ba1d2e2663b
p-ambre/Python_Coding_Challenges
/125_Leetcode_ValidPalindrome.py
821
4.25
4
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false """ class Solution: def isPalindrome(self, s: str) -> bool: letters = [c for c in s if c.isalpha() or c.isdigit()] new = [] for letter in letters: if letter.isupper(): new.append(letter.lower()) else: new.append(letter) val = "".join(new) i = 0 j = len(val)-1 while i < j: if val[i] != val[j]: return False i += 1 j -= 1 return True
true
2e74ccb9169f92530d7e4eaac320b0786e94bf5c
p-ambre/Python_Coding_Challenges
/M_6_Leetcode_ZigZagConversion.py
1,712
4.40625
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I ALGORITHM- 1) Create an array of n strings, arr[n] 2) Initialize direction as "down" and row as 0. The direction indicates whether we need to move up or down in rows. 3) Traverse the input string, do following for every character. a) Append current character to string of current row. b) If row number is n-1, then change direction to 'up' c) If row number is 0, then change direction to 'down' d) If direction is 'down', do row++. Else do row--. 4) One by one print all strings of arr[]. """ class Solution: def convert(self, word: str, numRows: int) -> str: if numRows == 1: return(word) len_word = len(word) arr = ["" for x in range(len_word)] row = 0 for i in range(len_word): arr[row] += word[i] if row == 0: down = True elif row == numRows - 1: down = False if down: row += 1 else: row -= 1 return(''.join([arr[i] for i in range(len_word)])) """ Time complexity: O(len of the string) """
true
f14e9ec92efde63bc05a013bcb323be89cd123ec
retroxsky06/Election_Analysis
/Python.practice.py
931
4.125
4
# counties = ["Arapahope", "Denver", "Jefferson"] # if counties[1] == 'Denver': # print(counties[1] # temperature = int(input("What is the temperature outside? ")) # if temperature > 80: # print("Turn on the AC.") # else: # print("oooh you cold boo") # counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} # for county in counties_dict: # print(counties_dict.get(county)) # for key, value in dictionary_name.items(): # print(key, value) voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] # for county_dict in voting_data: # print(county_dict) # range() function to iterate over the list of dictionaries and print the counties in voting_data for county in range(len(voting_data)): print(voting_data[county]['county'])
false
8c09eac5594829eb922e78688f3d91a6378cdd68
graag/practicepython_kt
/exercise_9.py
888
4.25
4
import random takes = 0 print("Type 'exit' to end game.") outer_loop_flag = True while outer_loop_flag: #Generate number number = random.randint(1,9) print('Try to guess my number!') takes = 0 while True: user_input = input("Type your guess: ") try: user_input = int(user_input) except ValueError: if user_input == 'exit': outer_loop_flag = False break else: print(user_input + " is not a valid input.") else: takes += 1 if user_input > number: print("My number is lower.") elif user_input < number: print('My number is higher.') else: print('Congrats! You have guessed my number in ' + str(takes) +' takes! Let\'s do it again!') break
true
aa88db0d81a38fb2d62e01e69d460c166aa2b22e
pranshu798/Python-programs
/Data Types/Strings/accessing characters in string.py
277
4.1875
4
#Python Program to Access characters of string String = "PranshuPython" print("Initial String: ") print(String) #Printing first character print("\nFirst character of String: ") print(String[0]) #Printing last character print("\nLast character of String: ") print(String[-1])
true
8e4d2c3b574445d7e36dfb1e6b3726551f7ec4d8
pranshu798/Python-programs
/Data Types/Strings/string slicing.py
368
4.53125
5
#Python program to demonstrate string slicing #Creating a string String = "PranshuPython" print("Initial String: ") print(String) #Printing 3rd to 12th character print("\nSlicing characters from 3-12: ") print(String[3:12]) #Printing characters between 3rd and 2nd last character print("\nSlicing characters between 3rd and 2nd last character: ") print(String[3:-2])
true
7c4808931b9f3a7524eee2d16e53b85d69db4a67
pranshu798/Python-programs
/Data Types/Sets/Adding elements using add() method.py
417
4.65625
5
#Python program to demonstrate Addition of elements in a Set #Creating a Set set1 = set() print("Initial blank set: ") print(set1) #Adding elements and tuple to the Set set1.add(8) set1.add(9) set1.add((6,7)) print("\nSet after Addition of Three elements: ") print(set1) #Adding elements to the Set using Iterator for i in range(1,6): set1.add(i) print("\nSet after Addition of elements from 1-5: ") print(set1)
true
673bda4cbb55311159f64da91f523a3558a430b8
pranshu798/Python-programs
/Data Types/Sets/Removing elements using pop() method.py
275
4.3125
4
#Python program to demonstrate Deletion of elements in a Set #Creating a Set set1 = set([1,2,3,4,5,6,7,8,9,10,11,12]) print("Initial Set: ") print(set1) #Removing element from the Set using the pop() method set1.pop() print("\nSet after popping an element: ") print(set1)
true
c61d200009259fbad763fe8583a8345ed949d31e
pranshu798/Python-programs
/Functions/Python classes and objects/Functions can be passed as arguments to other functions.py
358
4.3125
4
# Python program to illustrate functions # can be passed as arguments to other functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func("Hi, I am created by a function passed as an argument.") print(greeting) greet(shout) greet(whisper)
true
b6d22fe203e0abb0dc40b9a0221293729a86bf04
linafeng/Py3
/part4/function_param.py
1,193
4.3125
4
# -*- coding:utf-8 -*- """函数定义的格式""" def my_func(): print('my func') def my_func_with_param(p1, p2): print(p1, p2) my_func_with_param(1, 2) # my_func_with_param(1) # 关键字参数 my_func_with_param(p1=1, p2=2) # 默认参数 如果调用者没有传值,那么就用默认值,可以不指定名字 # 混合使用时,非默认参数必须在默认参数的前边 def my_function_with_param(name, sex, age=15): print(name + ":" + str(age)) my_function_with_param('bb', 'M') my_function_with_param('bb', 'M', age=2) # 函数返回值 def my_func_return(): return 1 p = my_func_return() print(type(p)) print(p) # 多个返回值 def func_with_return(name, age): return name, age # result xiaoming 14 n, a = func_with_return('xiaoming', 14) print(n, a) # result元组 ('xiaoming', 14) q = func_with_return('xiaoming', 14) print(q) print(type(q)) # 返回一个函数 def local_func(y): return y+1 def func_with_return_func(x): if x == 2: def inner_func(y): y * y if x == 3: def inner_func(y): return y * y * y return local_func calc = func_with_return_func(4) print(calc(4))
false
5bcbac676259b19faa8e8f5144105840ceac6c68
muftring/iu-python
/module-04/Question3.py
640
4.125
4
#!/usr/bin/env python # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 4, Question 3 # # Write a program that calculates the numeric value of a single name # provided as input. This will be accomplished by summing up the values # of the letters of the name where ’a’ is 1, ’b’ is 2, ’c’ is 3 etc., # up to ’z’ being 26. # base = ord("a")-1 def main(): print("Compute the numeric value of a word!") sum = 0 name = input("Enter any name in lower case: ") for letter in name: sum += (ord(letter) - base) print("The numeric value of entered name is", sum) main()
true
0ec8e80b01fbf1ec69a3b8afe1086415c13ecb23
muftring/iu-python
/module-03/Question2_2.py
633
4.53125
5
#!/usr/bin/env python # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 3, Question 2.2 # # Given the length of two sides of a right triangle: the hypotenuse, and adjacent; # compute and display the angle between them. # import math def main(): print("Angle between hypotenuse and adjacent side computer!") b = eval(input("Enter the length of the adjacent side: ")) c = eval(input("Enter the length of the hypotenuse: ")) radians = math.acos(b/c) degrees = radians * 180 / math.pi print("The angle in radians is", radians) print("The angle in degrees is", degrees) main()
true
932a6b227d1127dbdfa2b4517c92b0b7873a8bed
muftring/iu-python
/module-04/Question1.py
519
4.5625
5
#!/usr/bin/env python # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 4, Question 1 # # Write a program that takes an input string from the user and prints # the string in a reverse order. # def main(): print("Print a string in reverse!") forward = input("Please enter a string: ") reverse = "" for i in range(1, len(forward)+1, 1): reverse += forward[-1*i] print("You typed a string:", forward) print("The string in reverse order is:", reverse) main()
true
da8f74d891428c8fd90e7a68b7037c3cf5c8ab4c
muftring/iu-python
/module-07/Question4.py
1,647
4.28125
4
#!/usr/bin/env python3 # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 7, Question 4 # # Display the sequence of prime numbers within upper and lower bounds. # import math # """ isPrime(n): checks whether `n` is prime using trial division approach (unoptimized)""" # def isPrime(n): if n <= 1: return False sqrt = int(math.sqrt(n)) for i in range(2,sqrt+1,1): if n % i == 0: return False return True # """ printPrime(lowerLimit, upperLimit): display the sequence of prime numbers between the lower and upper limits""" # def printPrime(lowerLimit, upperLimit): print("The sequence of prime numbers in the given interval:") for n in range(lowerLimit, upperLimit+1, 1): if isPrime(n): print(n) def main(): try: lowerLimit = int(input("Enter the lower limit of the range: ")) except ValueError: print("Error - Invalid input: lower limit should be a positive integer") return if lowerLimit <= 0: print("Error - Invalid input: lower limit should be a positive integer") return try: upperLimit = int(input("Enter the upper limit of the range: ")) except ValueError: print("Error - Invalid input: lower limit should be a positive integer") return if upperLimit <= 0: print("Error - Invalid input: upper limit should be a positive integer") return if upperLimit < lowerLimit: print("Error - Invalid input: the upper limit is less than the lower limit") return printPrime(int(lowerLimit), int(upperLimit)) if __name__ == '__main__': main()
true
13e22b088fcf09564ac82f25c775564f106310d6
Dadsh/PY4E
/py4e_08.1.py
555
4.5625
5
# 8.4 Open the file romeo.txt and read it line by line. For each line, split the # line into a list of words using the split() method. The program should build a # list of words. For each word on each line check to see if the word is already # in the list and if not append it to the list. When the program completes, sort # and print the resulting words in alphabetical order. # You can download the sample data at http://www.py4e.com/code3/romeo.txt fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: print(line.rstrip())
true
620bdd6eaeea894aaaf0abc6b716309a907ae181
Dadsh/PY4E
/py4e_13.9.py
2,565
4.34375
4
# Calling a JSON API # In this assignment you will write a Python program somewhat similar to # http://www.py4e.com/code3/geojson.py. The program will prompt for a location, # contact a web service and retrieve JSON for the web service and parse that # data, and retrieve the first place_id from the JSON. A place ID is a textual # identifier that uniquely identifies a place as within Google Maps. # API End Points # To complete this assignment, you should use this API endpoint that has a # static subset of the Google Data: # http://py4e-data.dr-chuck.net/geojson? # This API uses the same parameter (address) as the Google API. This API also # has no rate limit so you can test as often as you like. If you visit the URL # with no parameters, you get a list of all of the address values which can be # used with this API. # To call the API, you need to provide address that you are requesting as the # address= parameter that is properly URL encoded using the urllib.urlencode() # fuction as shown in http://www.py4e.com/code3/geojson.py # Test Data / Sample Execution # You can test to see if your program is working with a location of # "South Federal University" which will have a place_id of # "ChIJJ8oO7_B_bIcR2AlhC8nKlok". # $ python3 solution.py # Enter location: South Federal UniversityRetrieving http://... # Retrieved 2101 characters # Place id ChIJJ8oO7_B_bIcR2AlhC8nKlok # Turn In # Please run your program to find the place_id for this location: # Zagazig University # Make sure to enter the name and case exactly as above and enter the place_id # and your Python code below. Hint: The first seven characters of the place_id # are "ChIJmW7 ..." # Make sure to retreive the data from the URL specified above and not the # normal Google API. Your program should work with the Google API - but the # place_id may not match for this assignment. import urllib.request, urllib.parse, urllib.error import json serviceurl = 'http://py4e-data.dr-chuck.net/geojson?' while True: address = input('Enter location: ') if len(address) < 1: break url = serviceurl + urllib.parse.urlencode( {'address': address}) print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read().decode() print('Retrieved', len(data), 'characters') try: js = json.loads(data) except: js = None if not js or 'status' not in js or js['status'] != 'OK': print('==== Failure To Retrieve ====') print(data) continue location = js['results'][0]['place_id'] print(location)
true
0c078d889ed24a1de6b020b99ebd2456814c2de6
RobertoGuzmanJr/PythonToolsAndExercises
/Algorithms/KthLargest.py
1,391
4.125
4
""" This is an interview question. Suppose you have a list of integers and you want to return the kth largest. That is, if k is 0, you want to return the largest element in the list. If k is the length of the list minus 1, it means that you want to return the smallest element. In this exercise, we want to do this in less than quadratic time (O(n^2)). Our first approach will sort the data and then select the index of the kth largest. This is O(n*lg(n)) since it involves a sort and that is known to done in O(n*lg(n)) time with mergeSort or QuickSort. Our second approach will solve the same problem, but will do so using a specified amount of extra space, S. """ import heapq import math def kthLargest_SortApproach(arr,k): if k >= len(arr): return None arr.sort() return arr[len(arr)-1-k] def kthLargest_FixedSpace(arr,k): if k > len(arr): return None heap = arr[0:k+1] heapq.heapify(heap) for i in range(k+1,len(arr)): if arr[i] >= heap[0]: heap[0] = arr[i] heapq.heapify(heap) return heap[0] arr = [6,3,0,3,2,7,5,6,78,12,21] print(kthLargest_FixedSpace(arr,6)) print(kthLargest_FixedSpace(arr,0)) print(kthLargest_FixedSpace(arr,10)) print(kthLargest_SortApproach(arr,6)) print(kthLargest_SortApproach(arr,0)) print(kthLargest_SortApproach(arr,10))
true
2760af375842734ef59a5ae070565cf624444ac7
viethien/misc
/add_digits.py
513
4.21875
4
#!/usr/bin/python3 def main(): print ("Hello this program will add the digits of an integer until a singular digit is obtained") print ('For example 38 -> 3+8 = 11 -> 1+1 = 2. 2 will be returned') number = input('Enter an integer value: ') print (number + ' will reduce to ' + str(addDigits(number))) def addDigits(num): sum_of_num = 0 if len(num) == 1: return num else: for n in str(num): sum_of_num += int(n) return addDigits(str(sum_of_num)) if __name__ == '__main__': main()
true
b5d527bb74efdb554058338f8ce82a1616508510
fedoseev-sv/Course_GeekBrains_Python
/lesson_2/hw_2_3.py
910
4.4375
4
''' Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. ''' numberMonth = int(input("Введите номер месяца (число от 1 до 12): ")) listMonth = ['зима', 'зима', 'весна', 'весна', 'весна', 'лето', 'лето', 'лето', 'осень', 'осень', 'осень', 'зима'] print(f"Это {listMonth[numberMonth]}") dictMonth = {1: "зима", 2: "зима", 12: "зима", 3: "весна", 4: "весна", 5: "весна", 6: "лето", 7: "лето", 8: "лето", 9: "осень", 10: "осень", 11: "осень"} print(f"Это {dictMonth[numberMonth]}")
false
94445c25ddef249f32f33e8df682506a3d12225e
fedoseev-sv/Course_GeekBrains_Python
/lesson_2/hw_2_1.py
690
4.3125
4
''' Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. ''' line = [1, 2, 4.23, True, False, "string", -3] print("Список имеет тип: ", type(line)) index = 1 for varIndex in line: print(f'Элемент {index} имеет тип: {type(varIndex)}') index += 1
false
9a2195053cd1dc6597b060e070c10db9a81f67ca
titanspeed/PDX-Code-Guild-Labs
/Python/frilab.py
2,639
4.21875
4
phonebook = { 'daniels': {'name': 'Chase Daniels', 'phone':'520.275.0004'}, 'jones': {'name': 'Chris Jones', 'phone': '503.294.7094'} } def pn(dic, name): print(phonebook[name]['name']) print(phonebook[name]['phone']) def delete(): correct_name = True while correct_name == True: delete_name = input('Enter the last name of the person you wish to delete from the phonebook: ') if delete_name in phonebook: del phonebook[delete_name] correct_name = False else: print(phonebook) print('Name not in phonebook. Try again.') def add_entry(): new_name = True while new_name == True: key_name = input('What is the last name, in lower case, of the person you wish you add?: ') full_name = input('What is the first and last name, upper case, of the person you wish to add?:') phone = input('What is the phone number of the person you wish to add?: ') if key_name not in phonebook: phonebook[key_name] = {'name': full_name, 'phone': phone} new_name = False else: print('Name is already in the phonebook: ') def edit_entry(): fix_name = True while fix_name == True: k_name = input('Last name: ') n_name = input('Replacement last name: ') f_name = input('Replacement First and Last name: ') fone = input('Replacement Phone Number: ') if k_name in phonebook: del phonebook[k_name] phonebook[n_name] = {'name': f_name, 'phone': fone} fix_name = False def lookup(): look_name = input('Enter the last name of the person you are looking for: ') if look_name in phonebook: pn('name', look_name) else: print('That name does not exist in this phonebook.') print(''' Welcome to the phonebook. You can do one of the following: -> To view the phonebook, enter "V". -> To edit an entry, enter "E". -> Look up a name in the phonebook, enter "L". -> Delete a name in the phonebook, enter "D". -> Or add a new name to the phonebook, enter "N". -> To quit the program, enter "Q".''') # print(phonebook) # lookup # delete_name() # add_entry() program_running = True while program_running == True: decision = input('What would you like to do?: ') if decision == 'V': print(phonebook) elif decision == 'L': lookup() elif decision == 'D': delete() elif decision == 'E': edit_entry( ) elif decision == 'N': add_entry() elif decision == 'Q': quit() else: print('That\'s not a valid entry. Try again, minion.')
true
19b8fc27ad30e6e45a0161f1fcbc27ce9871d51e
Tejas199818/Python
/fibonacci.py
241
4.1875
4
def fibonacci(): a=0 b=1 sum=0 x=int(input("Enter the range:")) print(a,end=" ") print(b,end=" ") for i in range(2,x): sum=a+b a=b b=sum print(sum,end=" ") print() fibonacci()
false
6692ab95a0df6ab106565a063d1f0fc9ad4806dd
MeenaShankar/python_project_aug5
/remove_item_tuple.py
241
4.1875
4
tuplex1=(1,2,3,5,6,7,9) tup2=('a','b','c','d','r') print("Before removing tuple:",tuplex1) tuplex1=tuplex1[:2]+tuplex1[3:] print(tuplex1) print("Before removing tuple:",tup2) list1=list(tup2) list1.remove('d') tup2=tuple(list1) print(tup2)
false
9c2f772a2c0188cc845f8721c62069524fbd0a5c
AsbelNgetich/python_
/fundamentals/functions/functions_Intermediate/list_iteration.py
1,088
4.46875
4
# Create a function iterateDictionary(some_list) that, given a list of dictionaries, # the function loops through each dictionary in the list and prints each key and the # associated value. For example, given the following list: students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary(some_list): for k in some_list: print(f"first_name - {k['first_name']}, last_name - {k['last_name']}") iterateDictionary(students) #3 Get Values From a List of Dictionaries old_students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary2(key_name, some_list): for k in some_list: print(k[key_name]) iterateDictionary2("last_name",old_students)
false
805efe0ecd2da5e8e225c295f2a34d0902ebcd27
thepavlop/code-me-up
/shapes.py
1,362
4.28125
4
""" This program calculates the area and perimeter of a given shape. Shapes: 'rectangle', 'triangle'. """ shape = input("Enter a shape (rectangle/triangle): ") # User input is 'rectangle': if shape == 'rectangle': # Ask user for a height and width of the rectangle i1 = input ('Enter the width of the rectangle: ') i1 = int(i1) i2 = input ('Enter the height of the rectangle: ') i2 = int (i2) # Check that the height and the width are positive while i1 < 0: i1 = int(input('Enter the width of the rectangle: ')) while i2 < 0: i2 = int(input('Enter the height of the rectangle: ')) # Calculate area and perimeter: x = i1 * i2 y = i1 + i1 + i2 + i2 print ('The area of the rectangle is:', x) print ('The perimeter of the rectangle is:', y) elif shape == 'triangle': i3 = input ("enter an int ") i3= int(i3) i4 = input ("enter an int ") i4= int (i4) i5=input ("enter an int ") i5= int (i5) while i3 < 0: i3 = int(input('enter an int ')) while i4 < 0: i4 = int(input('enter an int ')) while i5 < 0: i5 = int(input('enter an int ')) l= (i3 * i4) / 2 e= i3+ i4+ i5 print('the area is:', l) print('the perimeter is:', e)
true
ccfff65f4fb425d4fd4e5246c9f6a65e0b518d6b
nwgdegitHub/python3_learning
/12-下标.py
840
4.15625
4
str = 'abcdefg' print(str[0]) print(str[1]) # 序列[开始位置下标:结束位置下标:步长] # 步长正负数都行 默认是1 为负数表示倒着选 结尾不包含 # 不写开始 默认从0开始 # 不写结尾 默认选到最后 # 下标-1表示最后一位 -2表示倒数第二位 str1 = "0123456789" print(str1[2:5:1]) print(str1[2:5:2]) print(str1[2:5]) #默认步长1 print(str1[:5]) #默认结束下标5 print(str1[2:]) print(str1[:]) print(str1[:-1]) # 在头部开始 -1处结束 默认步长1 print("负数测试-------------") print(str1[::-1]) print(str1[-4:-1]) #倒数第4位开始 倒数第一位结束(不包含) print("步长负数测试-------------") print(str1[-4:-1:1]) print(str1[-4:-1:-1]) #步长为-1 就是说方向向左 这样的切片数据不存在 # 字符串可以认为是字符的的集合
false
a344c5d1b7a3457d5c63bf45306f8d0106031a60
hpisme/Python-Projects
/100-Days-of-Python/Day-3/notes.py
380
4.4375
4
"""Conditionals / Flow Control""" #If statement if 2 > 1: print('2 is greater than 1') #Adding an else statement if 3 < 2: print('This won\'t print') else: print('This will print!') #Adding an elif statement x = 0 if x == 1: print('This will print if x is 1.') elif x == 2: print('This will print if x is 2.') else: print('This will print if x is not 1 or 2.')
true
bd07ed2c24d4cea71914d5ff91109bd3d0c8bd7e
mohitkh7/DS-Algo
/Assignment1/1divisible.py
319
4.3125
4
# 1.WAP to check the divisibilty def isDivisible(a,b): #To check whether a is divisible by b or not if a%b==0: return True; #Divisible else: return False; #Non Divisible num=int(input("Enter Any Number : ")) div=int(input("Enter Number with which divisibilty is to check : ")) print(isDivisible(num,div));
true
29fad1f70a64fb15378c74e16b1bade6f3b12a7e
Wil10w/Beginner-Library-2
/Exam/Check Code.py
1,262
4.21875
4
#Write a function called product_code_check. product_code_check #should take as input a single string. It should return a boolean: #True if the product code is a valid code according to the rules #below, False if it is not. # #A string is a valid product code if it meets ALL the following #conditions: # # - It must be at least 8 characters long. # - It must contain at least one character from each of the # following categories: capital letters, lower-case letters, # and numbers. # - It may not contain any punctuation marks, spaces, or other # characters. #Add your code here! def product_code_check(code): count = 0 for num in code: count += 1 if count >= 8: if code.isdigit(): if code.islower(); if code.isupper(): #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: True, True, False, False, False print(product_code_check("g00dlONGproductCODE")) print(product_code_check("fRV53FwSXX663cCd")) print(product_code_check("2shOrt")) print(product_code_check("alll0wercase")) print(product_code_check("inv4l1d CH4R4CTERS~"))
true
41a221f4719dc573f0e7949b0b9b8e8d0ee7e250
Wil10w/Beginner-Library-2
/Loops/if-if-else movie ratings.py
542
4.3125
4
rating = "PG" age = 8 if rating == 'G': print('You may see that movie!') if rating == "PG": if age >= 8: print("You may see that movie!") else: print("You may not see that movie!") if rating == "PG-13": if age >= 13: print("You may see that movie!") else: print('You may not see that movie!') if rating == 'R': if age >= 17: print('You may see that movie!') else: print('You may not see that movie!') if rating == 'NC-17': if age < 18: print('You may not see that movie!') else: print('You may see that movie!')
true
2da45f99244731fc4207270d95c5ed11a7a604b3
Wil10w/Beginner-Library-2
/Practice Exam/Release Date.py
2,414
4.375
4
#Write a function called valid_release_date. The function #should have two parameters: a date and a string. The #string will represent a type of media release: "Game", #"Movie", "Album", "Show", and "Play". # #valid_release_date should check to see if the date is #a valid date to release that type of media according to #the following rules: # # - Albums should be released on Mondays. # - Games should be released on Tuesdays. # - Shows should be released on Wednesdays or Sundays. # - Movies should be released on Fridays. # - Plays should be released on Saturdays. # #valid_release_date should return True if the date is #valid, False if it's not. # #The date will be an instance of Python's date class. If #you have an instance of date called a_date, you can #access an integer representing the day of the week with #a_date.weekday(). a_date.weekday() will return 0 if the #day is Monday, 1 if it's Tuesday, 2 if it's Wednesday, #up to 6 if it's Sunday. # #If the type of release is not one of these strings, #the release date is automatically invalid, so return #False. from datetime import date #Write your function here! def valid_release_date(the_date, the_string): dayOfTheWeek = the_date.weekday() if dayOfTheWeek == 0: if the_string == 'Album': return True else: return False if dayOfTheWeek == 1: if the_string == 'Game': return True else: return False if dayOfTheWeek == 2: if the_string == 'Show': return True else: return False if dayOfTheWeek == 4: if the_string == 'Movie': return True else: return False if dayOfTheWeek == 5: if the_string == 'Play': return True else: return False if dayOfTheWeek == 6: if the_string == 'Show': return True else: return False else: return False #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: True, False, False, each on their own line. print(valid_release_date(date(2018, 7, 12), "Show")) print(valid_release_date(date(2018, 7, 11), "Movie")) print(valid_release_date(date(2018, 7, 11), "Pancake"))
true
420ea8f4d52a9be071420d6f54514a41a13a9473
kiyalab-tmu/learn-python
/2_functions/Team_top_function_caculate.py
562
4.15625
4
def Caculate(num1,num2): sum = num1 + num2 difference = num1 - num2 product = num1*num2 quotient = num1/num2 remainder = num1%num2 print(sum) print(type(sum)) print(difference) print(type(difference)) print(product) print(type(product)) print(quotient) print(type(quotient)) print(remainder) print(type(remainder)) if __name__ == "__main__": temp1=input("Please insert number1:") temp2=input("Please insert number2:") print(type(temp1)) Caculate(int(temp1),int(temp2))
false
1e284b683528ded1a80e40d9b7889999982d518d
kiyalab-tmu/learn-python
/4_sort/kinoshita_quicksort.py
1,340
4.15625
4
import copy def quicksort(list_): sorted_list = copy.copy(list_) recursive_quicksort(sorted_list, 0, len(sorted_list)) return sorted_list def recursive_quicksort(list_, start, stop): if stop - start <= 1: return med_idx = (start + stop - 1) // 2 pivot = list_[med_idx] i = start j = stop - 1 while True: while list_[i] < pivot: i += 1 while list_[j] > pivot: j -= 1 if i >= j: break list_[i], list_[j] = list_[j], list_[i] i += 1 j -= 1 recursive_quicksort(list_, start, i) recursive_quicksort(list_, j+1, stop) return if __name__ == "__main__": list1 = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] print(quicksort(list1)) print(quicksort(list1) == sorted(list1)) list1 = [1, 1, 1, 1, 0, 0, 0, 0] print(quicksort(list1)) print(quicksort(list1) == sorted(list1)) list1 = [-1, 0, 1e-10, float("inf"), -float("inf")] print(quicksort(list1)) print(quicksort(list1) == sorted(list1)) list1 = [0, 3, 2, 0, 4, 7, 5] print(quicksort(list1)) print(quicksort(list1) == sorted(list1)) list1 = [1] print(quicksort(list1)) print(quicksort(list1) == sorted(list1)) list1 = [] print(quicksort(list1)) print(quicksort(list1) == sorted(list1))
false
cf730580af6dc9754abfcb9a1e58d63ded705689
HarryBMorgan/Special_Relativity_Programmes
/gamma.py
776
4.1875
4
#Calculation of gamma factor in soecial relativity. from math import sqrt #Define a global variable. c = 299792458.0 #Define speed of light in m/s. #Define a function to calculate gamma. def gamma(v): if v < 0.1 * c: #If v is not in order of c, assume it's a decimal and * c. v *= c return 1 / sqrt(1 - (v**2.0 / c**2.0)) def gamma_inverse(gamma): #Returns beta = v/c. return sqrt(1 - (1 / gamma**2)) #__Main__ if __name__ == "__main__": #Import useful libraries. from fractions import Fraction #ask for input of velocity. v = float(input("Input the velocity as a decimal of c:")) #Call gamma fuction. gamma = gamma(v) #Print value to user. print("The gamma value =", Fraction(gamma), "=", '%.5f' %gamma)
true
b6182a34f51f0393626723f33cd60cfedfef5e5a
nagaprashanth0006/code
/python/remove_duplicate_chars_from_string.py
1,131
4.125
4
from collections import Counter str1 = "Application Development using Python" # Constraints: # Capital letters will be present only at the beginning of words. # Donot remove from start and end of any word. # Duplicate char should match across whole string. # Remove not only the duplicate char but also all of its occurances. # Remove only small case letters. # OP: "Acan Dvmt usg Pyhn" words = str1.split() # Collect the words from the given string. final = "" # Final output string will be collected here. count = Counter(str1) # Count the occurances for each char in given string str1. for word in words: uniq = [ char for char in word[1:-2] if count[char] == 1] # Skip the start and end chars of each word and collect other non repeating chars. final += word[0] + "".join(uniq) + word[-1] + " " # Join the uniq chars along with first and last chars. print final # The output. #### Same thing can also be written using list comprehensions in a single line like this: print " ".join([ word[0] + "".join([char for char in word[1:-2] if count[char] == 1]) + word[-1] for word in words])
true
88d3b4710b222d0787a96f7f4d8216f38e02f8fd
pablocorbalann/codewars-python
/5kyu/convert-pascal-to-snake.py
442
4.21875
4
# Complete the function/method so that it takes CamelCase string and returns the string in snake_case notation. # Lowercase characters can be numbers. If method gets number, it should return string. def to_underscore(string): s = '' for i, letter in enumerate(str(string)): if letter != letter.lower(): s += '{0}{1}'.format('_' if i!=0 else '', letter.lower()) else: s += letter return s
true
8fa85afc1a4b7f76c842b18c236e8b2e740b91b9
ahirwardilip/python-programme
/27feb.py
1,295
4.21875
4
#While loop(syntax):- # while <exp>: # === # === #Print 1 2 3 4 5. ''' i=1 while i<=5: print(i) i+=1 ''' #Write a program to print mathematical table of any number. ''' a=int(input("Enter Number:")) i=1 while i<=10: print(n,"*",i,"=",n*i) i+=1 ''' #Write a program to find out factorial of any number. ''' n=int(input("Enter Number:")) i=n-1 while i>0: n=n*i i-=1 print(n) ''' ''' n=int(input("Enter Number:")) f=1 while n>1: f=f*n n=n-1 print(f) ''' #Write a program to find out sum of first n numbers and also find out their average. ''' n=int(input("Enter Number:")) i=1 s=0 while i<=n: s+=i i+=1 print(s) ''' #Write a program to find sum from n1 to n2. ''' n1=int(input("Enter Number:")) n2=int(input("Enter Number:")) s=0 while n1<=n2: s+=n1 n1+=1 print(s) avg=s/(n2-n1+1) ''' ''' n1=int(input("Enter Number:")) n2=int(input("Enter Number:")) i=n1 s=0 while i<=n2: s=s+i i=i+1 print("Sum is:"+str(s)) avg=s/(n2-n1+1) print("Avg is:"+str(avg) ''' #Print 1 1 1 2 4 8 3 9 27 . . . . . . n n^2 n^3. ''' n=int(input("Enter Number:")) i=1 while i<=n: print(i," ",i*i," ",i*i*i," ",end=" ") i=i+1 '''
false
69be0a9c8b24ae5882c636d363481f7a9be43775
jonahp1/simple-bill-splitter
/Mainguy.py
1,480
4.3125
4
attendees = int(input("How many people are splitting the bill? : ")) bill_total = float(input("How much is the bill total (before tax)? (DO NOT INCLUDE $) : ")) tax_total = float(input("How much is the Tax total? (DO NOT INCLUDE $) : ")) tax_percentage = (tax_total / bill_total) # useful for math effective_tax_percentage = (tax_total / bill_total) * 100 # useful for human beings to look at print("Effective Tax percentage is " + str(effective_tax_percentage)) for person in range(attendees): person += 1 # this is done so the count does not start at 0. (ie. so nobody is referred to as "Name 0" but rather Name 1 - Name [numb(attendees)] name = input("\nName of customer " + str(person) + ": ") cost = float(input("What was " + name + "'s cost as shown on the right hand side of check? (DO NOT INCLUDE $) : ")) plus_tax = cost + (cost * tax_percentage) total_cost = plus_tax # this line is "theoretically unnecessary" but changing the variable name to "total cost" makes me feel better tipped = total_cost * .2 # some tip on tax, others do not. I usually do because worst case, you're giving more money to a person who literally just served you food. Algorithms should be grateful too tipped_total = tipped + total_cost print("\n" + name + "'s total cost after tax is $" + str(total_cost)+ "\n20% tip suggested at $" + str(tipped) + " tip. \n\nTotal for " + name + " INCLUDING tip: " + str(tipped_total) + "\n") running_total = total_cost
true
fafeba6ba874c5d7475aa7bf616d2843036d0915
lappazos/Intro_Ex_11_Backtracking
/ex11_sudoku.py
2,894
4.1875
4
################################################################## # FILE : ex11_sudoku.py # WRITERS : Lior Paz,lioraryepaz,206240996 # EXERCISE : intro2cs ex11 2017-2018 # DESCRIPTION : solves sudoku board game with general backtracking ################################################################## from math import floor from ex11_backtrack import general_backtracking def print_board(board, board_size=9): """ prints a sudoku board to the screen --- board should be implemented as a dictionary that points from a location to a number {(row,col):num} """ for row in range(board_size): if row % 3 == 0: print('-------------') toPrint = '' for col in range(board_size): if col % 3 == 0: toPrint += '|' toPrint += str(board[(row, col)]) toPrint += '|' print(toPrint) print('-------------') def load_game(sudoku_file): """ parsing input file into sudoku dict :param sudoku_file: input file location :return: dict {board coordinate: current value} """ with open(sudoku_file, 'r') as sudoku: sudoku_dict = {} sudoku = sudoku.readlines() for line in range(len(sudoku)): for index in range(0, 18, 2): sudoku_dict[(line, index / 2)] = int(sudoku[line][index]) return sudoku_dict def check_board(board, x, *args): """ legal_assignment_func :param board: dict {board coordinate: current value} :param x: item to check :param args: unused - needed for fitting other general backtracking functions :return: True if assignment is legal, False otherwise """ # row & column check for i in range(0, 9): if (board[(x[0], i)] == board[x]) and (i != x[1]): return False if (board[(i, x[1])] == board[x]) and (i != x[0]): return False # square check factor = (floor(x[0] / 3), floor(x[1] / 3)) for i in range(3): for j in range(3): index = (factor[0] * 3 + i, factor[1] * 3 + j) if (board[index] == board[x]) and (index != x): return False else: return True def run_game(sudoku_file, print_mode=False): """ :param sudoku_file: input file location :param print_mode: should we print in case of solution :return: True if there is a solution, False otherwise """ board = load_game(sudoku_file) list_of_items = [] for key in board.keys(): if board[key] == 0: list_of_items.append(key) set_of_assignments = range(1, 10) legal_assignment_func = check_board if general_backtracking(list_of_items, board, 0, set_of_assignments, legal_assignment_func): if print_mode: print_board(board) return True else: return False
true
1c2c4471e04af2ea5b94eba3ddd1d7ed884b5b0d
NeoWhiteHatA/all_my_python
/march/count_coin.py
1,356
4.125
4
print('Вам необходимо ввести небольшое количество монет') print('Цель - получить в титоге один рубль') print('имеются монеты достоинством в 5 копеекб 10 копеек и 50 копеек') nominal_one_coin = 5 nominal_two_coin = 10 nominal_three_coin = 50 coin_one = int(input('Введите количество монет достоинством 5 копеек:')) coin_two = int(input('Введите количество монет, достоинством в 10 копеек ')) coin_three = int(input('Введите количество монет, достоинством в 50 копеек ')) if nominal_one_coin * coin_one == 100: print('Вы выиграли рубль') elif nominal_one_coin * coin_two == 100: print('Вы выиграли рубль') elif nominal_three_coin * coin_three == 100: print('Вы выиграли рубль') elif (nominal_one_coin * coin_one) + (nominal_two_coin * coin_two) == 100: print('Вы выиграли рубль') elif (nominal_one_coin * coin_one) + (nominal_two_coin * coin_two) + (nominal_three_coin * coin_three) == 100: print('Вы выграли рубль') else: print('ваших монет или слишком много или слишком мало')
false
253df67cfa8bb387a919431b0ff0723e1565fbad
nomura-takahiro/study
/test/test8.py
882
4.125
4
# test8 #① tmp = "カミュ" for i in range(3): print(tmp[i]) #② """ tmp = input("What? >> ") tmp2 = input("Who? >> ") print("私は昨日{}を書いて、{}に送った!".format(tmp,tmp2)) """ #③ text = "aldous Huxley was born in 1894." print(text.capitalize()) #④ text = "どこで? だれが? いつ?" print(text) print(text.split(" ")) #⑤ text =["The","fox","jumped","over","the","fence","."] print(" ".join(text).replace(" .",".")) #⑥ text = "A screaming comes across the sky." print(text.replace("s","@")) #⑦ text = "Hemingway" print(text.index("m")) #⑧ print("何でもは知らないわよ。'知っている'ことだけ。") #⑨ text = "three" print(text + text + text) print(text * 3) #⑩ text = "四月の晴れた寒い日で、時計がどれも十三時を打っていた。" print(text) print(text[:text.index("、")+1])
false
640dbf5ad0fd5c12bc351f06cdf91bbe1555969b
Fainman/intro-python
/random_rolls.py
860
4.125
4
""" Program to simulate 6000 rolls of a die (1-6) """ import random import statistics def roll_die(num): """ Random roll of a die :param num: number of rolls :return: a list of frequencies Index 0 maps to 1 . . . Index 5 maps to 6 """ frequency = [0] * 6 # Initial values to 0 for i in range(6000): roll = random.randint(1, 6) frequency[roll - 1] += 1 return frequency def main(): """ Test function :return: """ num = int(input("How many times do you need to roll? ")) result = roll_die(num) print(result) for roll, total in enumerate(result): print(roll+1, total) mean = sum(result)/len(result) print("Average = {}".format(mean)) print("Mean = {}".format(statistics.mean(result))) if __name__ == "__main__": main() exit(0)
true
a7879e0e1d5f1946447ac1403e55bf7b3afbdae2
shivanshthapliyal/Algorithms
/day-1-sorting/merge-sort.py
924
4.1875
4
# Author => Shivansh Thapliyal # Date => 1-Jan-2020 def merge(left_arr,right_arr): output=[] #adding to output till elements are found while left_arr and right_arr: left_arr_item = left_arr[0] right_arr_item = right_arr[0] if left_arr_item < right_arr_item: output.append(left_arr_item) left_arr.pop(0) else: output.append(right_arr_item) right_arr.pop(0) while left_arr: output.append(left_arr[0]) left_arr.pop(0) while right_arr: output.append(right_arr[0]) right_arr.pop(0) return output def merge_sort(arr): arr_length = len(arr) #base case if arr_length<2: return arr left_arr = arr[:arr_length//2] right_arr = arr[arr_length//2:] # // forces division # we then sort the list recursively left_arr = merge_sort(left_arr) right_arr = merge_sort(right_arr) return merge(left_arr,right_arr) array = [34,12,2,41,53,127] sortedarray = merge_sort(array) print(sortedarray)
false
7051a6b21b2b930fb09b50df114bc9d66607c7c7
shaunakgalvankar/itStartedInGithub
/ceaserCipher.py
1,287
4.375
4
#this program is a ceaser cipher print("This is the ceaser cipher.\nDo You want to encode a message or decode a message") print("To encode your message press e to decode a messge press d") mode=raw_input() if mode=="e": #this is the ceaser cipher encoder original=raw_input("Enter the message you want to encode:") encrypted="" print("enter a number between 0 & 26 including 0 & 26 which will be the encryption key") key=input() i=0 while i<len(original): #to handle the wraping around if ord(original[i])>len(original): Ascii=ord(original[i])+key-len(original) elif ord(original[i])<0: Ascii=ord(original[i])+key+len(original) else: Ascii=ord(original[i])+key encrypted = encrypted + chr(Ascii) i=i+1 print(encrypted) elif mode=='d': #this is the ceaser cipher decoder encrypted=raw_input("Enter the message that you want to decode:") decrypted="" print("Enter the key according to which you want to decode your text") key=input() i=0 while i<len(encrypted): #to handle the wraping around if ord(encrypted[i])>len(encrypted): Ascii=ord(encrypted[i])-key-len(encrypted) elif ord(encrypted[i])<0: Ascii=ord(encrypted[i])-key+len(encrypted) else: Ascii=ord(encrypted[i])-key encrypted = encrypted + chr(Ascii) i=i+1 print(decrypted)
true
f5936be33f6ea652325db7c9b8c688b11a8e9e53
imclab/DailyProgrammer
/Python_Solutions/115_easy.py
1,220
4.40625
4
# (Easy) Guess-that-number game! # Author : Jared Smith #A "guess-that-number" game is exactly what it sounds like: a number is guessed at #random by the computer, and you must guess that number to win! The only thing the #computer tells you is if your guess is below or above the number. #Your goal is to write a program that, upon initialization, guesses a number #between 1 and 100 (inclusive), and asks you for your guess. If you type a number, #the program must either tell you if you won (you guessed the computer's number), #or if your guess was below the computer's number, or if your guess was above the #computer's number. If the user ever types "exit", the program must terminate. import random def play_game(): answer = random.randrange(1,100) print "Welcome to guess-that-numbers game! I have already picked a number in [1, 100]. Please make a guess. Type \"exit\" to quit. \n" guess = raw_input() while guess != 'exit': if int(guess) < answer: print "Guess higher..." guess = raw_input() continue elif int(guess) > answer: print "Guess lower..." guess = raw_input() continue elif int(guess) == answer: print "Correct! That is my number, you win!" break play_game()
true
2813c58d8faa2d30baa360966965b3082c4cc07a
Hirook4/Santander-Coder-Python
/2.Estruturas Avançadas/1_listas_e_tuplas.py
1,643
4.40625
4
print("Listas") # Lista vazia lista_vazia = [] # Listas podem ter diferentes tipos de valores listamista = [10, "Leonardo", 0.5, True] # Lista com valores letras = ["a", "b", "c", "d", "e"] # Acessamos cada elemento da lista através de um índice entre colchetes # Os índices começam em 0 print(letras[0]) print(letras[1]) print(letras[2]) print(letras[3]) print(letras[4]) print("\nAlterando valor de um elemento na lista") # Listas são mutáveis: podemos alterar o valor de seus itens letras[2] = "Banana" print(letras) # Um jeito inteligente de trabalhar com listas é utilizando loops indice = 0 while indice < len(letras): print(letras[indice]) indice = indice + 1 print("\nAppend") # Adiciona um elemento na lista animais = ["Cavalo", "Pato", "Macaco"] animais.append("Cobra") print(animais) print("\nRemove") print(animais) animais.remove("Cobra") print(animais) print("\nCount") # Conta quantas vezes um elemento aparece na lista jogadores = ["Ronaldo", "Rivaldo", "Ronaldo", "Adriano"] ronaldos = jogadores.count("Ronaldo") print(jogadores) print("Quantidade de Ronaldos:", ronaldos, "\n") print("Tuplas") # Tupla é uma coleção de objetos que lembra as listas, porem elas são imutáveis # As tuplas podem ser declaradas com ou sem parênteses numeros = (1, 2, 3, 5, 7, 11) # Para acessar um valor, utilizamos a mesma sintaxe das listas: print(numeros[4]) print(type(numeros)) # Podemos gerar uma tupla a partir de uma lista... lista1 = [3, 1, 4, 1, 5, 9, 2, 6, 5] tupla1 = tuple(lista1) print(tupla1) # ...ou uma lista a partir de uma tupla: tupla2 = [1, 6, 1, 8] lista2 = list(tupla2) print(lista2)
false
cddcdda3eef207d3f2911b86f4f2b767d8124669
Hirook4/Santander-Coder-Python
/2.Estruturas Avançadas/3_strings_II.py
1,641
4.34375
4
print("Strings II") # Operador de soma (+): concatena (une) 2 strings palavra1 = "Leo" palavra2 = "nardo" palavra3 = palavra1 + palavra2 print(palavra3, "\n") # Operador de multiplicação * copia uma string 'n' vezes palavra = "uma" trespalavras = 3 * palavra print(trespalavras, "\n") print(".format()") # .format() serve para preencher os campos em branco de uma string # Produto substituirá o primeiro {} e preco o segundo {} produto = "chocolate" preco = 3.50 print("O produto {} custa {}.\n".format(produto, preco)) # É possível colocar algumas opções especiais de formatação stringoriginal = "O litro da gasolina custa {:.2f}" """ : indica que passaremos opções .2 indica apenas 2 casas após o ponto decimal f indica que é um float O preço sai com apenas 2 casas após a vírgula """ preco = 5.505050 stringcompleta = stringoriginal.format(preco) print(stringcompleta, "\n") # Pode-se chamar as variávies em diferentes ordens: print("{2}, {1} and {0}\n".format("a", "b", "c")) print("{0}{1}{0}\n".format("abra", "cad")) # Podemos especificar um número de dígitos obrigatório por campo dia = 1 mes = 8 ano = 2019 data1 = "{}/{}/{}".format(dia, mes, ano) print(data1, "\n") # A opção 'd' significa que o parâmetro é um número inteiro data2 = "{:2d}/{:2d}/{:4d}".format(dia, mes, ano) print(data2, "\n") # Podemos forçar que os espaços em branco sejam preenchidos com o número 0: data3 = "{:02d}/{:02d}/{:04d}".format(dia, mes, ano) print(data3, "\n") # Um modo mais simples de utilizar o format nome = "Tulio" profissao = "Professor" escola = "Faculdade" print(f"{nome} é {profissao} da {escola}.")
false
fb21e8080bb297c30402239a1020d1815c0c18aa
bouzou/starter-kit-datascience
/raphael-vignes/Lesson1/string2.py
2,031
4.34375
4
def verbing(s): if s.__len__() >= 3: print(s[-3:]) if s[-3:] != 'ing': s+='ing' else: s+= 'ly' return s def not_bad(s): if 'not' in s and 'bad' in s: a = s.find('not') b = s.find('bad') if a < b : return s[:a] + 'good' +s[b+3:] return s # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b, return a string of the form # a-front + b-front + a-back + b-back def front_back(a, b): if len(a) % 2 == 0: middleA = int(len(a)/2) else: middleA = int(len(a)/2 +1) if len(b) % 2 == 0: middleB = int(len(b)/2) else: middleB = int(len(b)/2+1) return a[:middleA] + b[:middleB] + a[middleA:] + b[middleB:] # Simple provided test() function used in main() to print # what each function returns vs. what it's supposed to return. def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print(prefix+" Got : "+repr(got)+" Expected : " +repr(expected)) # main() calls the above functions with interesting inputs, # using the above test() to check if the result is correct or not. def main(): print('verbing') test(verbing('hail'), 'hailing') test(verbing('swiming'), 'swimingly') test(verbing('do'), 'do') print print('not_bad') test(not_bad('This movie is not so bad'), 'This movie is good') test(not_bad('This dinner is not that bad!'), 'This dinner is good!') test(not_bad('This tea is not hot'), 'This tea is not hot') test(not_bad("It's bad yet not"), "It's bad yet not") print print('front_back') test(front_back('abcd', 'xy'), 'abxcdy') test(front_back('abcde', 'xyz'), 'abcxydez') test(front_back('Kitten', 'Donut'), 'KitDontenut') if __name__ == '__main__': main()
false
3c443065b603371a6cb3733b5c2bcf52f1ab0c5a
NickAlicaya/Graphs
/projects/graph/interview.py
1,441
4.5
4
# Print out all of the strings in the following array in alphabetical order, each on a separate line. # ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] # The expected output is: # 'Cha Cha' # 'Foxtrot' # 'Jive' # 'Paso Doble' # 'Rumba' # 'Samba' # 'Tango' # 'Viennese Waltz' # 'Waltz' # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process. array = ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] # sort array # do a for loop for all items # print each item in array array.sort() for i in array: print(i) # Print out all of the strings in the following array in alphabetical order sorted by the middle letter of each string, each on a separate line. If the word has an even number of letters, choose the later letter, i.e. the one closer to the end of the string. # ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] # The expected output is: # 'Cha Cha' # 'Paso Doble' # 'Viennese Waltz' # 'Waltz' # 'Samba' # 'Rumba' # 'Tango' # 'Foxtrot' # 'Jive' # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
true
8d5e2833759970a21b7f9175aad9a3f8a9e8d345
MertTurkoglu/Python_Projects
/Python.projects/hesap_makinesi.py
664
4.125
4
print("hesap makinesi programı") print("Toplama işlemi için +\n" "çıkarma işlemi için -\n" "çarpma işlemi için *\n" "bölme işlemi için / 'e basın " ) sayi1=int(input("bir sayi gir")) sayi2=int(input("bir sayi gir")) işlem=input("işlemi girin") if(işlem=="+"): print("{} + {} = {} ".format(sayi1,sayi2,sayi1+sayi2)) elif(işlem=="-"): print("{} - {} = {} ".format(sayi1, sayi2, sayi1 - sayi2)) elif(işlem=="*"): print("{} x {} = {} ".format(sayi1, sayi2, sayi1 * sayi2)) elif(işlem=="/"): print("{} / {} = {} ".format(sayi1, sayi2, sayi1 / sayi2)) else: print("gecersiz işlem")
false
8b7bbd9cc3d0dbb4ccddab9ff8865866f5d03aa0
kochsj/python-data-structures-and-algorithms
/challenges/insertion_sort/insertion_sort.py
416
4.34375
4
def insertion_sort(list_of_ints): """Sorts a list of integers 'in-place' from least to greatest""" for i in range(1, len(list_of_ints)): # starting outer loop at index 1 j = (i - 1) int_to_insert = list_of_ints[i] while j >= 0 and int_to_insert < list_of_ints[j]: list_of_ints[j + 1] = list_of_ints[j] j -= 1 list_of_ints[j + 1] = int_to_insert
true
4e1d46b1dd5b16f5e316dfbaedc8fbf5ab674464
kochsj/python-data-structures-and-algorithms
/challenges/quick_sort/quick_sort.py
1,301
4.34375
4
def quick_sort(arr, left_index, right_index): if left_index < right_index: # Partition the array by setting the position of the pivot value position = partition(arr, left_index, right_index) # Sort the left_index quick_sort(arr, left_index, position - 1) # Sort the right_index quick_sort(arr, position + 1, right_index) def partition(arr, left_index, right_index): """ By selecting a pivot value, the partition reorganizes the array with the pivot in the middle index values to the left are lesser values to the right are greater """ # set a pivot value as a point of reference pivot = arr[right_index] # create a variable to track the largest index of numbers lower than the defined pivot low_index = left_index - 1 for i in range(left_index, right_index): if arr[i] <= pivot: low_index += 1 swap(arr, i, low_index) # place the value of the pivot location in the middle. # all numbers smaller than the pivot are on the left_index, larger on the right_index. swap(arr, right_index, low_index + 1) # return the pivot index point return low_index + 1 def swap(arr, i, low_index): temp = arr[i] arr[i] = arr[low_index] arr[low_index] = temp
true
1eda04501f801072b4c16c2f2450cbcc50765a61
sdmiller93/Summ2
/Zed/27-30/ex29studydrills.py
468
4.5625
5
# 1. The if prints the included statement if returned True. # 2. The code needs to be indented to make it known that the print statement is included with that if statement, it's a part of it. # 3. If it's not indented, it isn't included with the if statement and will print regardless of the truth of the if statement. # 4. people = 20 cats = 30 dogs = 15 if people != cats: print("People aren\'t cats") # 5. it will change the truth of the arguments.
true
de260d1be0cecc69226b792d1ff4d9bf96f5dd8b
sdmiller93/Summ2
/Zed/04-07/ex6.py
1,015
4.5625
5
# strings are pieces of text you want to export out of the program # assign variables types_of_people = 10 x = f"There are {types_of_people} types of people." # assign more variables binary = "binary" do_not = "don't" # write string with embedded variables y = f"Those who know {binary} and those who {do_not}" # printing strings/variables print(x) print(y) # produce f string print(f"I said: {x}") print(f"I also said: '{y}'") # set marker to false hilarious = False # {} at end of string allows for embedding of second variable in print further down joke_evaluation = "Isn't that joke so funny?! {}" # print statements print(joke_evaluation.format(hilarious)) # set variables w = "This is the left side of..." e = "a string with a right side." # print showing how to piece together two variables in one single string # variable + variable = longer single variable because you are adding two pieces of text together on a single line the computer views it as just x and y (or w and e here) print(w + e)
true
2b236c42e6802c261ef1c6427ef075313ace5667
maiareynolds/Unit-3
/warmUp9.py
214
4.15625
4
#Maia Reynolds #3/1/18 #warmUp8.py - capitalize vowels text=input("Enter text: ") for ch in text: if ch=="a" or ch=="e" or ch=="i" or ch=="o" or ch=="u": print(ch.upper()) else: print(ch.lower())
false
b7edfa22328e165b825e5834edf64fe96df04701
mateuszkanabrocki/LPTHW
/ex19.py
1,071
4.125
4
# defining a function with 2 arguments def cheese_and_crackers(chesse_count, boxes_of_crackers): #print(">>> START chesse_count=:", chesse_count, "boxes_of_crackers:", boxes_of_crackers) print(f"You have {chesse_count} cheeses.") print(f"You have {boxes_of_crackers} boxes of crackers.") print("Man, that's enough for a party!") print("Get a blanket.\n") #print("<<< END") print("We can just give the function numbers directly:") # function with number arguments cheese_and_crackers(20, 10) print("OR, we can use variables from our script:") # defining variables amount_of_cheese = 24 amount_of_crackers = 31 # function with given 2 arguments - variables cheese_and_crackers(amount_of_cheese, amount_of_crackers) print("We can even do math inside too") # function with given two arguments - mathematic operations cheese_and_crackers(10+20, 3+13) print("We can combine the two, variables and math:") # function with given 2 arguments - math operations on variables and numbers cheese_and_crackers(amount_of_cheese + 2, amount_of_crackers + 9)
true
a57b8ccb2942c7c26903d406f6d8343ba0db2ebe
mateuszkanabrocki/LPTHW
/ex16.py
1,071
4.25
4
# import the argv feature from the system module from sys import argv # assign the input values to the variables (strings) script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want that hit Ctrl-C (^C).") print("If you do want that hit RETURN.") input("?") print("Opening the file...") # open the file "filename" for writing (assign the file - it's coordinates in file object - "target" variable) target = open(filename, "w") print("Truncating the file. Goodbye!") # removing the contents of the file # target.truncate() # don't have to do it, already truncated the file by opening it in "w" mode print("Now I'm going to ask you for three lines.") # assign 3 input lines to 3 variables line1 = input("line1:\n") line2 = input("line2:\n") line3 = input("line3:\n") print("I'm going to write these to the file.") # write the inputs to the file target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print("And finally, we close it.") # close the file target.close()
true
e8d8bb9d41eeffc6f68266469abd9f59f790bedb
vaibhavyesalwad/Python-Bootcamp-Programs
/MathFunc.py
595
4.15625
4
import math as m def is_prime(num): if num == 1: return '1 is neither prime nor composite' else: for i in range(2, num//2+1): if num % i == 0: return False else: return True print(dir(m)) print(m.pow(2,4)) print(m.sin(m.pi/6)) print(m.cos(m.pi/3)) print(bin(100)) print(m.sqrt(3)) number= int(input('Enter number to check prime:')) if is_prime(number): if is_prime(number) == True: print(f'{number} is prime number') else: print(is_prime(number)) else: print(f'{number} is composite number')
false
921336e98aac123fae5f1760358f604ec7213112
vaibhavyesalwad/Python-Bootcamp-Programs
/TaylorsSeries.py
784
4.1875
4
import math def sin_term(x,n): return (-1)**(n-1)*(x**(2*n-1))/math.factorial(2*n-1) def cos_term(x,n): return (-1)**(n-1)*(x**(2*n-2))/math.factorial(2*n-2) def take_input(): angle = int(input('Enter angle in degrees:')) angle_radians = angle*3.14/180 # = math.radians(angle) terms = int(input('Enter number of terms(precision):')) return angle,angle_radians,terms print("Finding cos & sin using Taylor's Series") print("Let's find sin ") angle,angle_radians,terms = take_input() sin= 0 for i in range(1,terms+1): sin += sin_term(angle_radians,i) print(f'sin({angle}):{sin}') print("\nLet's find cos ") angle,angle_radians,terms = take_input() cos= 0 for i in range(1,terms+1): cos += cos_term(angle_radians,i) print(f'cos({angle}):{cos}')
false
5003672f108deea087e056411ee5a08de4cd2f54
Nakshatra-Paliwal/Shining-Star
/Area of the Triangle.py
229
4.15625
4
Base = float(input("Please enter the value of Base of the Triangle : ")) Height = float(input("Please enter the value of Height of the Triangle : ")) Area = (1/2 * Base * Height) print("Area of the Triangle is " + str(Area))
true
38df5b7ab5326cbedddc379d8d931d7ddb1c43b5
Nakshatra-Paliwal/Shining-Star
/Calculate Area of Two Triangles and Compare the Smaller One.py
849
4.25
4
""" Write a code to calculate Area of two triangles. And compare these areas, and print which triangle has the greater area Note : Take input from the user as Base and Height values for two triangles """ Base1 = float(input("Please enter the value of Base of the 1st Triangle : ")) Height1 = float(input("Please enter the value of Height of the 1st Triangle : ")) Base2 = float(input("Please enter the value of Base of the 2nd Triangle : ")) Height2 = float(input("Please enter the value of Height of the 2nd Triangle : ")) Area1 = (1/2 * Base1 * Height1) Area2 = (1/2 * Base2 * Height2) print("Area of the 1st Triangle is " + str(Area1)) print("Area of the 2nd Triangle is " + str(Area2)) if Area1<Area2: print("Area of the 1st Triangle is smaller. ") else: print("Area of the 2nd Triangle is smaller. ")
true
0a45277982cb8bdf9f34b437b34ed5c017ece3d4
Nakshatra-Paliwal/Shining-Star
/Take two Numbers as Input and Print Their Addition.py
252
4.1875
4
#Write a code to take two numbers as input and print their Addition num1 = int(input("Write a Number 1 : ")) num2 = int(input("Write a Number 2 : ")) Multiply = num1 + num2 print() print("The Addition of Both the Number is " + str(Multiply))
true
186b27c411a681ee1a704dc53d5ecc23ed2746bf
Nakshatra-Paliwal/Shining-Star
/Voice Chatbot about sports input by text.py
2,142
4.28125
4
""" Create a Voice Chatbot about sports. Ask the user to type the name of any sport. The Chatbot then speaks about interesting information about that specific sport. """ import pyttsx3 engine=pyttsx3.init() print("Welcome !! This is a Voice Chatbot about sports.") print("Please choose the Operation:") print("1. Cricket") print("2. Football") print("3. Hockey") print("4. Basketball") choice = int(input("Please Enter your choice in Numbers : ")) if choice==1: engine.setProperty("RATE",100) engine.say("Cricket is a bat-and-ball game played between two teams of eleven players on a field at the centre of which is a 22-yard (20-metre) pitch with a wicket at each end, each comprising two bails balanced on three stumps.") engine.runAndWait() if choice==2: engine.setProperty("RATE",100) engine.say("Football, also called association football or soccer, is a game involving two teams of 11 players who try to maneuver the ball into the other team's goal without using their hands or arms. The team that scores more goals wins. Football is the world's most popular ball game in numbers of participants and spectators.") engine.runAndWait() if choice==3: engine.setProperty("RATE",100) engine.say("hockey, also called Field hockey, outdoor game played by two opposing teams of 11 players each who use sticks curved at the striking end to hit a small, hard ball into their opponent's goal. It is called field hockey to distinguish it from the similar game played on ice.") engine.runAndWait() if choice==4: engine.setProperty("RATE",100) engine.say("Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court) while preventing the opposing team from shooting through their own hoop.") engine.runAndWait()
true
16dd605a3f9efc51f76e2accb45470bcfdb9f767
Nakshatra-Paliwal/Shining-Star
/Write a program for unit converter..py
1,166
4.40625
4
""" Write a program for unit converter. A menu of operations is displayed to the user as: a. Meter-Cm b. Kg-Grams c. Liter-Ml Ask the user to enter the choice about which conversion to be done. Ask user to enter the quantity to be converted and show the result after conversion. Ask user whether he wish to continue conversion or quit. Repeat the operations till the user wish to continue """ print("Display Menu of Unit Converters :-") print("a. Meter-Cm") print("b. Kg-Grams") print("c. Litre-Ml ") response = 'y' while response == 'y': choice = (input("Enter the Conversion you want to Perform: ")) Quan = int(input("Enter the Number: ")) cm = (Quan * 100) kg = (Quan * 1000) ml = (Quan * 1000) print() if choice==("a"): print("Conversion of" + str(Quan) + "m to cm is :" + str(cm)) if choice=="b": print("Conversion of" + str(Quan) + "m to cm is :" + str(kg)) if choice=="c": print("Conversion of" + str(Quan) + "m to cm is :" + str(ml)) response = input ("Do you wish to continue ? y/n : ") print() print ("Thank you for interacting with me!!")
true
3fe609269efbfddd1c814b1ab0091b868ddb73d2
Nakshatra-Paliwal/Shining-Star
/Create a 'guess the password' game (3 attempts).py
410
4.4375
4
""" Create a 'guess the password' game , the user is given 3 attempts to guess the password. Set the Password as “TechClub!!” """ attempt=1 while(attempt<=3): password=input("Enter the Password : ") if password=="TechClub!!": print("You are Authenticated!!") break else: attempt=attempt+1 if attempt > 3: print("Your Attempts are Over!!")
true
6437450be62ab8b399334915dc464a9057311eac
thuyvyng/CS160
/labs/lab4/lab4.py
242
4.15625
4
stars = int(input("How many stars do you want? ")) while (stars % 2 == 0): stars = int(input(" Enter an odd number ")) for x in range(stars +1): if x % 2 == 0: continue space = (stars-x)//2 print(" " * space + "*" * x + " " * space)
false
36de8f66b1996b5d42e96687cf91448b3fb500d2
Akshaypokley/pythonStudy
/src/Study/Strings/stringreplace.py
314
4.15625
4
s1="my name is khan" ReplaceS1=s1.replace('khan','Akshay') print(ReplaceS1) print(ReplaceS1.upper()) print (ReplaceS1.lower()) print(ReplaceS1.capitalize()) print("+".join(s1)) print("@@@@@@@Split@@@@@@@@@") print(ReplaceS1.split(" ")) print(ReplaceS1.split("a")) x = "Guru99" x = x.replace(x,"Python") print(x)
false
f48e81bf8709003a354a5e6ca37a22e172c6dbaa
astavnichiy/AIAnalystStudy
/Python_algorithm/Lesson2/les_2_task_3.py
613
4.1875
4
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. """ number2 = input('Введите натуральное число:') new_number2 = '' try: int(number2) except: print ('Хреновое число') i = len(number2)-1 while i >=0: new_number2 = new_number2 + number2[i] i -= 1 print('Новое число=', new_number2)
false
bfe2ac7fb508f2fcca6192a35c893a453f2053f4
brgyfx/Dice-Simulator
/DiceRollSimNew.py
425
4.15625
4
#DiceRollingSimulator import random import time dice = random.randint(0,9) count = 0 count_to = 10 response = input("Would you like to roll a dice? ") if response == "yes": times = int(input("How many times would you like to roll a dice? ")) count_to = times while response == "yes" and count < count_to: print("You rolled a {}!".format(random.randint(0,9))) count = count + 1 time.sleep(1)
true
7e835b8fa5ce87b359bc01a6d0be592c52efc324
javvidd/gitProject
/functions_homework.py
1,441
4.3125
4
# homework # chapter 8-1 to 8-5 def display_message(): print("im learning chapter 8 functions") display_message() def favourite_book(title): print(f"one of my favourite books is {title.title()}") favourite_book("alice in wonderland") def make_shirt(size, text): print(f"customised shirt is \"{size.upper()}\" size with printed \"{text.upper()}\" words") make_shirt("L", "Def x():") make_shirt(text="hello world", size="m") def make_shirt_2(text, size="l"): print(f"customised shirt is \"{size.upper()}\" size with printed \"{text.upper()}\" words") make_shirt_2(text="we all r in love") make_shirt_2("i luv python", "m") def describe_city(city, country="USA"): print(f"{city.title()} is in {country.capitalize()}") describe_city("baku", "azerbaijan") describe_city("boston") describe_city("london", "england") # ________________ # # chapter 8-6 def city_country(city, country): return f"\'{city}\', \'{country}\'" pair = city_country("baku", "azerbaijan") pair2 = city_country("newyork", "usa") pair3 = city_country("paris", "france") print(pair + "\n" + pair2 + "\n" + pair3) def make_album(artist, al_title, track_num=""): if track_num: return {"name": artist , "album": al_title, "number": track_num} else: return {"name": artist, "album": al_title} print(f'{make_album("uzeir", "esgerliy")}\n{make_album("madonna", "bayatishiraz", 5)}\n{make_album("namig", "garachuxurlu", 4)}')
false
39f1439582a56031c247a91b4574614555e904fb
NieMandX/Algorithms
/lesson2_task8.py
1,354
4.34375
4
# Lesson 2 Task 8 -rus- # Посчитать, сколько раз встречается определенная цифра # в введенной последовательности чисел. Количество вводимых # чисел и цифра, которую необходимо посчитать, # задаются вводом с клавиатуры. def digit_calc (dig, number): amnt = 0 for i in range(len(str(number))): amnt += int(dig == (number // 10 ** i) % 10) return amnt print(f'+{"":-^78}+') print(f'|{"Программа поиска цифр в последовательности чисел.":^78}|') print(f'|{"Подтверждайте ввод нажатием Enter.":^78}|') print(f'|{"(Для завершения работы программы, нажмите Enter в пустой строке.) ":^78}|') print(f'+{"":-^78}+') dig = input('Введите цифру, которую будем искать:') amount = 0 while True: number = input('Введите натуральное число:') if number == '': break amount += digit_calc(int(dig), int(number)) print(f'+{"":-^78}+') print (f'В веденной последовательности чисел цифра {dig} встретилась {amount} раз')
false
1738b878939eabefdeb29a0c0be498d6c2b9981a
mridulpant2010/leetcode_solution
/OOAD/ss_function_injection.py
797
4.1875
4
''' 1- creating function 2- understanding static function more on static-method: 1- static-method are more bound towards a class rather than its object. 2- they can access the properties of a class 3- it is a utility function that doesn't need access any properties of a class but makes sense that it belong to a class,we use static functions. ''' class Person: def __init__(self,name): self.name=name def __str__(self): return 'Person Object {}'.format(self.name) @staticmethod def stat_method(): a=10 print('bro, I am a static method and please don"t try to access me from an instance ') print(a) if __name__=='__main__': p =Person('mridul') print(p) p.stat_method() Person.stat_method()
true
a41a38938250fe4514ee0db952f31f953422694f
mridulpant2010/leetcode_solution
/tree/right_view_tree.py
1,102
4.125
4
''' given a tree you need to print its right view ''' from collections import deque from typing import List class TreeNode: def __init__(self, val, left=None, right=None): self.val=val self.left=left self.right=right def tree_right_view(root): res=[] q=deque() q.append(root) while q: depthsize=len(q) for i in range(depthsize): currentNode=q.popleft() if i==depthsize-1: res.append(currentNode.val) if currentNode.left: q.append(currentNode.left) if currentNode.right: q.append(currentNode.right) return res if __name__ == '__main__': root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(9) root.right.left = TreeNode(10) root.right.right = TreeNode(5) root.left.left.left = TreeNode(3) result = tree_right_view(root) print("Tree right view: ") for node in result: print(str(node) + " ", end='')
true
ce9f4fd6558c9982c815c90ce40cf53b6540405f
chandhukogila/Pattern-Package
/Alphabets/Capital_Alphabets/J.py
618
4.125
4
def for_J(): """We are creating user defined function for alphabetical pattern of capital J with "*" symbol""" row=7 col=5 for i in range(row): for j in range(col): if i==0 or (j==2 and i<6)or i-j==5: print("*",end=" ") else: print(" ",end=" ") print() def while_J(): i=0 while i<7: j=0 while j<5: if i==0 or (j==2 and i<6)or i-j==5 : print("*",end=" ") else: print(" ",end=" ") j+=1 i+=1 print()
false
7146a77b3df6dcad47002cf0701bf8f121b99f21
chandhukogila/Pattern-Package
/Numbers/zero.py
738
4.1875
4
def for_zero(): """We are creating user defined function for numerical pattern of zero with "*" symbol""" row=7 col=5 for i in range(row): for j in range(col): if ((i==0 or i==6)and j%4!=0) or ((i==1 or i==2 or i==4 or i==5 or i==3)and j%4==0) or i+j==5: print("*",end=" ") else: print(" ",end=" ") print() def while_zero(): row=0 while row<6: col=0 while col<4: if (col==0 or col==3) and (row>0 and row<5) or (row==0 or row==5) and col%3!=0 or row+col==4 : print("*",end=" ") else: print(" ",end=" ") col+=1 row+=1 print()
false
a9a2ae4248ac36eb0af0b21b924967595f412b0b
deloschang/project-euler
/005/problem5.py
782
4.125
4
#!/usr/bin/env python # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def factorize(x): # < 11 don't need to be checked because 12-20 implicitly checks them i = 380 # because 19*2, 19*3 ... 19*19 not divis by 20 # so increment by 380 as well solved = False while not solved: solved = i % 11 == 0 and i % 12 == 0 and i % 13 == 0 and \ i % 14 == 0 and i % 15 == 0 and i % 16 == 0 and \ i % 17 == 0 and i % 18 == 0 and i % 19 == 0 and \ i % 20 == 0 if not solved: i += 380 return i print factorize(20)
true
f0236977e3d6ad99197048b5dc077bbb9263d30d
ssw1991/Python-Practice
/Module 1 - Shilo Wilson/Level 1.4 - Shilo Wilson/1.4.2.py
891
4.15625
4
# coding=utf-8 """ Name: Shilo S Wilson Exercise: 1.4.2 Find the length of each list in part b of the previous exercise. Then, verify that the lengths of all three lists indeed add up to the length of the full list in part a. """ import numpy as np def Mortgages(N): """ A function that returns an unsorted list of mortgage amounts :param N: :return: """ return list(np.random.random_integers(100,1000,size = N)) def main(): print('============= Exercise 1.4.2 =============\n\n\n') mortgages = Mortgages(1000) miniMortgages = filter(lambda x: x<200,mortgages) standardMortgages = filter(lambda x: 200<=x<=467,mortgages) jumboMortgages = filter(lambda x: x>467,mortgages) full_list = len(mortgages) print full_list == (len(miniMortgages + standardMortgages + jumboMortgages)) if __name__ == '__main__': main()
true
7a156ad4ed677a8315993eb17d0d5f2ccef94f4b
ssw1991/Python-Practice
/Module 3 - Shilo Wilson/Level 3.2/3.2.1 and 3.2.2/main.py
590
4.34375
4
""" Author: Shilo Wilson Create a list of 1000 numbers. Convert the list to an iterable and iterate through it. The instructions are a bit confusing, as a list is already an iterable. Is the intention to create an iterator to iterate through the list? """ def main(): print('========== Exercise 3.2.1 and 3.2.2 ==========') mylist = range(1000) myiterator = iter(mylist) myreverse = reversed(mylist) for i in range(len(mylist)): print myiterator.next() for i in range(len(mylist)): print myreverse.next() if __name__ == '__main__': main()
true
3d617c48812fd4612ea2a082478efb76ab1b129f
ssw1991/Python-Practice
/Module 3 - Shilo Wilson/Level 3.1/3.1.3/main.py
1,542
4.65625
5
""" Author: Shilo Wilson Create a regular function (called reconcileLists) that takes two separate lists as its parameters. In this example, List 1 represents risk valuations per trade (i.e. Delta) from Risk System A and List 2 has the same from Risk System B. The purpose of this function is to reconcile the two lists and report the differences between the two systems. To this end, it should return a list of True or False values, corresponding to each value in the lists (True means they match at index, False means they don't match at index). Test the reconcileLists function with different lists of values ( lists should be of at least length ten). Note that the assumption is that both lists are the same length (report an error otherwise). """ def reconcileList(l1, l2): """ Returns a list of booleans indicating whether l1[n] = l2[n] If l1 and l2 are different lengths, raises an exception :param l1: List :param l2: List :return: List """ if len(l1) != len(l2): raise Exception('The length of the input arguments do not match!') return map(lambda (x, y): x == y, zip(l1, l2)) def main(): print('========== Exercise 3.1.3 ==========') l1 = [1, 3, 5, 6, 3, 4, 5, 7, 5, 2, 3, 5] l2 = [1, 4, 5, 6, 9, 4, 5, 7, 5, 2, 3, 5] l3 = [1, 4, 5] try: print reconcileList(l1, l2) except Exception as e: print e.args try: print reconcileList(l1, l3) except Exception as e: print e.args if __name__ == '__main__': main()
true
8abf8fd8b5e06481ed24e75fa6bcbc24cd641f0f
chi42/problems
/hackerrank/is_binary_search_tree.py
1,167
4.125
4
#!/usr/bin/python # # https://www.hackerrank.com/challenges/ctci-is-binary-search-tree?h_r=next-challenge&h_v=zen class node: def __init__(self, data): self.data = data self.left = None self.right = None def is_valid(data, max_data, min_data): if max_data and data >= max_data: return False if min_data and data <= min_data: return False return True def check_binary_search_tree_(root): stack = [(root, None, None)] while len(stack) > 0: cur, max_data, min_data = stack.pop() if not is_valid(cur.data, max_data, min_data): return False if cur.left: stack.append((cur.left, cur.data, min_data)) if cur.right: stack.append((cur.right, max_data, cur.data)) return True # if you traverse a tree inorder and the tree is sorted, you print # the sorted elements def check_binary_search_tree_2(root): is_first = True prev_value = None stack = [] cur = root while len(stack) > 0 or cur: if cur: stack.append(cur) cur = cur.left else: cur = stack.pop() if not is_first: if cur.data <= prev_value: return False else: is_first = False prev_value = cur.data cur = cur.right return True
true
205240df57c2ac6902f16b236c989bef38b7680d
K3666/githubtest
/solution-1.py
220
4.3125
4
Number = int(input("Entre Number :")) if Number % 3 == 0 and Number % 2 == 0 : print("BOTH") elif Number % 3 == 0 or Number % 2 == 0 : print("ONE") elif Number % 3 == 1 and Number % 2 == 1 : print("NEITHER")
false
72ee90d35585f110e01e929cbfdd27115f14aa49
ztwilliams197/ENGR-133
/Python/Python 2/Post Activity/Py2_PA_Task1_will2051.py
2,595
4.28125
4
#!/usr/bin/env python3 ''' =============================================================================== ENGR 133 Program Description Takes inputs for theta1 and n1 and outputs calculated values for theta2 d3 and critTheta Assignment Information Assignment: Py2_PA Task 1 Author: Zach Williams, will2051@purdue.edu Team ID: 001-01 (e.g. 001-14 for section 1 team 14) Contributor: Name, login@purdue [repeat for each] My contributor(s) helped me: [ ] understand the assignment expectations without telling me how they will approach it. [ ] understand different ways to think about a solution without helping me plan my solution. [ ] think through the meaning of a specific error or bug present in my code without looking at my code. Note that if you helped somebody else with their code, you have to list that person as a contributor here as well. =============================================================================== ''' import math as ma theta1 = float(input("Input incoming angle [degrees]: ")) n1 = float(input("Input refractive index medium 1 [unitless]: ")) n2 = 1.3 d1 = 5.3 d2 = 7.6 # Calculates leaving angle using indices of refraction and incoming angle def calcTheta2(n1, n2, theta1): return ma.degrees(ma.asin(n1 * ma.sin(ma.radians(theta1)) / n2)) # Calculates ending distance of light ray using d1, d2, and angles def calcD3(d1, theta1, d2, theta2): return d1 * ma.tan(ma.radians(theta1)) + d2 * ma.tan(ma.radians(theta2)) # Calculates critical angle using indices of refraction def calcCritTheta(n1, n2): if(n1 > n2): return ma.degrees(ma.asin(n2 / n1)) else: return ma.degrees(ma.asin(n1 / n2)) # Calls functions to calculate theta2, d3, and critTheta theta2 = calcTheta2(n1,n2,theta1) d3 = calcD3(d1,theta1,d2,theta2) critTheta = calcCritTheta(n1,n2) # Outputs theta2, d3, and critTheta print(f"There is a refraction with a leaving angle of {theta2:.1f} degrees.") print(f"The ending distance for the light ray is {d3:.1f}cm.") print(f"For these two media, the critical angle is {critTheta:.1f} degrees.") ''' =============================================================================== ACADEMIC INTEGRITY STATEMENT I have not used source code obtained from any other unauthorized source, either modified or unmodified. Neither have I provided access to my code to another. The project I am submitting is my own original work. =============================================================================== '''
true
7b56a008f94895e31074dd7fc25a5ca111e70c02
adrientalbot/lab-refactoring
/your_code/Guess_the_number.py
1,986
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import random import sys # In[100]: def condition_to_play_the_game(string="Choose any integer between 1 and 100. Your number is "): your_number = input(string) if your_number.isdigit(): your_number = int(your_number) if your_number > 100: print('Your number exceeds 100. Please play again. ') sys.exit(1) print(" Your number is an integer and we can continue! ") return your_number else: print("You have not entered an integer. Please play again. ") sys.exit(1) def guess_the_number(): Number_of_guesses_left = 8 your_number = condition_to_play_the_game() random_number = random.randint(1,100) if your_number == random_number: print("YOU WIN WITH FIRST TRY, OMG!!") while your_number != random_number: if your_number > random_number: Number_of_guesses_left -= 1 print(f' Your number of guesses left is {Number_of_guesses_left}') your_number = condition_to_play_the_game("Choose lower number. Your number is ") if Number_of_guesses_left == 0: break elif your_number < random_number: Number_of_guesses_left -= 1 print(f' Your number of guesses left is {Number_of_guesses_left}') your_number = condition_to_play_the_game("Choose higher number. Your number is ") if Number_of_guesses_left == 0: break elif your_number == random_number: print("You win!") if Number_of_guesses_left == 0: print("YOU LOOSE!") print(f' The random number was {random_number}') guess_the_number() if Number_of_guesses_left > 0: print("YOU WIN!") print(f' The random number was {random_number}') guess_the_number() # In[ ]: # add choice of range # In[ ]: # add level of difficulty
true
aa3410e31edc7ce603dbf85bff00a80195b619d1
pcmason/Automate-the-Boring-Stuff-in-Python
/Chapter 4 - Lists/charPicGrid.py
1,077
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 30 01:58:47 2021 @author: paulmason """ #print out a grid of characters with a function called charPrinter #create the that prints out every element in a 2D list def charPrinter(givenChar): #loop through the column for y in range(len(givenChar[0])): #loop through each element in each column for x in range(len(givenChar)): #print out the character at the given location print(givenChar[x][y], end = '') #print a newline so that all of the characters look like a 2D array print() #example grid to use grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] #call the charPrinter function sith the example grid charPrinter(grid)
true