blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1da282a3db3a9b690c69d8b9a7261d8685ad6d5a | piyushPathak309/100-Days-of-Python-Coding | /Challenge Solve Quadratic Equations.py | 1,300 | 4.375 | 4 | # Write a Python program that prints the positive and negative solutions (roots) for a quadratic equation.
#
# If the equation only has one solution, print the solution as the output.
#
# If it has two solutions, print the negative one first and the positive one second on the same line.
#
# If the equation has no real solutions, print "Complex Roots".
#
# You can determine the number of solutions with the discriminant (the result of b^2 - 4ac in the formula below).
#
# - If it's negative, the equation has no real solutions (only complex roots).
#
# - If it's 0, there is only one solution.
#
# - If it's positive, there are two real solutions.
#
# A quadratic equation has this form:
#
#
#
# For example:
#
#
# To solve this equation, we use the quadratic formula:
#
#
# We find the result by replacing the values of a, b, and c in the formula.
import math as m
a = int(input("Enter First Number :"))
b = int(input("Enter Second Number :"))
c = int(input("Enter Third Number :"))
d = (b ** 2 - 4 * a * c)
if (d < 0):
print("No Real Solution , Complex Roots")
if (d > 0):
x1 = (-b + (m.sqrt(b ** 2 -4 * a * c))) / (2 * a)
x2 = (-b - (m.sqrt(b ** 2 -4 * a * c))) / (2 * a)
print(x1, x2)
if (d == 0):
p = -b // (2 * a)
print(p)
| true |
4e56f040e15f71067bf725fa1c6368fe9600ef62 | piyushPathak309/100-Days-of-Python-Coding | /Check String Contain Numbers or not.py | 217 | 4.21875 | 4 | # Write a Python program that check if a string only contains numbers.
#
# If it does, print True. Else, print False.
text = input("Enter a text: ")
if (text.isdigit()):
print(True)
else:
print(False)
| true |
5b646ffd8354cebd9e929ecf336550b31792e52d | amiskov/real-python | /part1/02. Fundamentals: Working with Strings/notes.py | 1,390 | 4.5625 | 5 | """
Fundamentals: Working with Strings
"""
# "Addition" and "multiplication" of strings
print('hello' * 3)
print('hello' + 'world')
# Convert strings to numbers
print(int('22') + float(1.35))
# We can't convert floating point strings to integers
# int('22.3') # error
# Convert numbers to strings
print(str(22.3) + 'hello') # when we need to combine strings and numbers together
"""
Streamline Your Print Statements
================================
"""
# String interpolation is just a fancy way of saying that you want to insert some 'stuff' - i.e., variables - into a string.
name = 'Zaphod'
num_heads = 2
num_arms = 3
print('{} has {} heads and {} hands'.format(name, num_heads, num_arms)) # sequence
print('{2} has {1} heads and {0} hands'.format(name, num_heads, num_arms)) # indexes
print('{0} has {1} heads and {0} hands'.format(name, num_heads)) # repeating indexes
# assign objects right inside format, any order
print('{name} has {heads} heads and {hands} hands'.format(heads=2, name='Zaphod', hands=3))
"""
Find a String in a String
=========================
"""
phrase = "the surprise is in here somewhere"
print(phrase.find('surprise')) # 4, zero based, case sensitive starting symbol position (first appearence)
print(phrase.find('ololo')) # -1, not found
print(phrase.replace('surprise', 'ololo')) # don't change string, returns new string. Strings are immutable
| true |
5997e47a7d55ef99daf50d986493eeca7a7245a4 | zecookiez/CanadianComputingCompetition | /2018/Senior/sunflowers.py | 1,424 | 4.15625 | 4 | """Barbara plants N different sunflowers, each with a unique height, ordered from smallest to largest, and records their heights for N consecutive days. Each day, all of her flowers grow taller than they were the day before.
She records each of these measurements in a table, with one row for each plant, with the first row recording the shortest sunflower's growth and the last row recording the tallest sunflower's growth.
The leftmost column is the first measurement for each sunflower, and the rightmost column is the last measurement for each sunflower.
If a sunflower was smaller than another when initially planted, it remains smaller for every measurement.
Unfortunately, her children may have altered her measurements by rotating her table by a multiple of 90 degrees.
Your job is to help Barbara determine her original data.
[Input Specification]
The first line of input contains the number N (2≤N≤100). The next N lines each contain N positive integers, each of which is at most 109 . It is guaranteed that the input grid represents a rotated version of Barbara's grid.
[Output Specification]
Output Barbara's original data, consisting of N lines, each of which contain N positive integers."""
grid = [[*map(int, input().split())] for i in range(int(input()))]
lowest = min(map(min, grid))
while lowest != grid[0][0]:
grid = [*zip(*grid[::-1])]
for i in grid:
print(" ".join(map(str, i)))
| true |
abd86de13f0ee03be189915181c1bb753ef1d88c | UnknownAbyss/CTF-Write-ups | /HSCTF 7/Miscellaneous/My First Calculator/calculator.py | 805 | 4.21875 | 4 | #!/usr/bin/env python2.7
try:
print("Welcome to my calculator!")
print("You can add, subtract, multiply and divide some numbers")
print("")
first = int(input("First number: "))
second = int(input("Second number: "))
operation = str(raw_input("Operation (+ - * /): "))
if first != 1 or second != 1:
print("")
print("Sorry, only the number 1 is supported")
if first == 1 and second == 1 and operation == "+":
print("1 + 1 = 2")
if first == 1 and second == 1 and operation == "-":
print("1 - 1 = 0")
if first == 1 and second == 1 and operation == "*":
print("1 * 1 = 1")
if first == 1 and second == 1 and operation == "/":
print("1 / 1 = 1")
else:
print(first + second)
except ValueError:
pass
| true |
899c8b3843aef975c187c0eee14bd7fbf333c0b8 | dingning8768/aaa | /raw_input | 299 | 4.21875 | 4 | #!/usr/bin/env python
this_year = 2013
name = raw_input("please input your name:")
#age = raw_input("how old are you?")
#age = input("how old are you?")
age = int(raw_input("how old are you?"))
print "hello",name,'\n'
print "you are",age,'years old!'
print "so you were born in: ",this_year - age
| false |
87bc943b81db33c06442b07dfc3a342473670801 | gbrs/EGE_files | /strings.py | 1,683 | 4.25 | 4 | string1 = ' абраКАДАБРА'
string2 = 'АБРАкадабра '
string3 = '13579'
string4 = '02468'
print('конкатенация:')
print(string1 + string2)
print(string3 + string4)
print('-=-'.join([string1, string3, string2, string4]))
print()
print('методы строк:')
print(string1)
print(string1.strip())
print(string1.lower() + '<->' + string2.upper())
print(string1.strip().lower() + '<->' + string2.strip().upper())
string5 = 'торторт, вкусный торт.'
print(string5)
print('количество непересекающихся совпадений для слова торт:')
print(string5.count('торт'))
print('замена торт на ТАРТ и удаление знаков препинания:')
string5 = string5.replace('торт', 'ТАРТ') # метод делает копию
string5 = string5.replace('.', '')
string5 = string5.replace(',', '')
print(string5)
print()
print('обращение к элементам строк:')
print(string3[2])
print('вывод строки задом наперёд:')
for i in range(len(string4)-1, -1, -1):
print(string4[i], end='')
print()
print('но срезом проще:')
print(string4[::-1])
print()
print('есть ли в строке string5 вк?')
print('вк' in string5)
print()
string34 = ''
for i in range(5):
string34 += string4[i] + string3[i]
print(string34)
print()
number = 564687954231548789746513453421655487897987
print('В числе', len(str(number)), 'разряда')
print()
print('преобразование списка в строку:')
lst = [1, 35, 7, 9]
lst = list(map(str, lst))
str_ = ' :-) '.join(lst)
print(str_)
| false |
aaeb75bbd4423f7c148e61da5bef5232589ab5a7 | skybrim/practice_leetcode_python | /everyday/349.py | 576 | 4.125 | 4 | """
349. 两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
"""
def intersection(nums1, nums2):
set1 = set(nums1)
set2 = set(nums2)
if len(set1) < len(set2):
return [num for num in set1 if num in set2]
else:
return [num for num in set2 if num in set1]
| false |
14d781f18c86c4e48e0237da097831651a6b49c3 | skybrim/practice_leetcode_python | /everyday/941.py | 1,003 | 4.15625 | 4 | """
941. 有效的山脉数组
给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。
让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:
A.length >= 3
在 0 < i < A.length - 1 条件下,存在 i 使得:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]
提示:
0 <= A.length <= 10000
0 <= A[i] <= 10000
示例 1:
输入:[2,1]
输出:false
示例 2:
输入:[3,5,5]
输出:false
示例 3:
输入:[0,3,2,1]
输出:true
"""
def valid_mountain_array(A):
length = len(A)
if length < 3:
return False
i = 0
# 判断递增
while i + 1 < length and A[i] < A[i + 1]:
i += 1
if i == 0 or i == length - 1:
return False
# 判断递减
while i + 1 < length and A[i] > A[i + 1]:
i += 1
return i == length - 1
if __name__ == "__main__":
print(valid_mountain_array([1, 7, 9, 5, 4, 1, 2]))
| false |
9f709bddfc95ddef6e0b1e4c074924cc2fe8278f | mikesorsibin/PythonHero | /Generators/Example_three.py | 285 | 4.15625 | 4 | def myfunc():
for x in range(3):
yield x
x = myfunc()
#using next to call the values of x one by one
print(next(x))
#iter keyword
s="hello"
for x in s:
print(x)
#here we cannot directly call next method, we need to iter s.
iter_s = iter(s)
print(next(iter_s))
| true |
89cd5390e210dda72dc45ea5bf2f0f81e8ffa4b8 | mikesorsibin/PythonHero | /Inbuilt and Third Party Modules/datetime.py | 833 | 4.1875 | 4 | >>> import datetime
>>> t = datetime.time(5,34,5)
>>> t
datetime.time(5, 34, 5)
>>> t.min
datetime.time(0, 0)
>>> datetime.time
<class 'datetime.time'>
>>> datetime.time.min
datetime.time(0, 0)
>>> print(datetime.time.min)
00:00:00
>>> today = datetime.date.today()
>>> today
datetime.date(2020, 4, 7)
>>> print(today)
2020-04-07
>>> print(today.timetuple())
time.struct_time(tm_year=2020, tm_mon=4, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=98, tm_isdst=-1)
>>> today.year
2020
>>> datetime.date.min
datetime.date(1, 1, 1)
>>> datetime.date.max
datetime.date(9999, 12, 31)
>>> datetime.date.resolution
datetime.timedelta(1)
>>> d1=datetime.date(2020,4,7)
>>> d1
datetime.date(2020, 4, 7)
>>> d2=d1.replace(2021)
>>> d2
datetime.date(2021, 4, 7)
>>> d1
datetime.date(2020, 4, 7)
>>> d1-d2
datetime.timedelta(-365)
| false |
3f7235eccddf88ef10b556af01ffbe1a8c0cf44f | mikesorsibin/PythonHero | /Inbuilt and Third Party Modules/re_one.py | 585 | 4.1875 | 4 | import re
# List of patterns to search for
patterns = ['term1', 'term2']
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'
for pattern in patterns:
print('Searching for "%s" in:\n "%s"\n' %(pattern,text))
#Check for match
if re.search(pattern,text):
print('Match was found. \n')
else:
print('No Match was found.\n')
'''
words= 'i am michael cor sibin and my id is michaelcorsbin@gmail.com'
>>> re.split('@',words)
['i am michael cor sibin and my id is michaelcorsbin', 'gmail.com']
>>> re.findall('michael',words)
['michael', 'michael']
'''
| true |
550001146f8a243c64d6d3649d907af7b715730b | Hafsa25/Assignment | /marksheet.py | 1,145 | 4.21875 | 4 | print(" ******* 9TH MARKSHEET*******")
print("CODED BY HAFSA BHATTI")
print("Enter your Roll number")
roll_no=int(input())
print("What did you chose in 9th? Biology or Computer?")
choice=input()
if choice=="Biology":
final=choice
elif choice=="Chemistry":
final=choice
print("Enter your Sindhi marks out of 75:")
sindhi=int(input())
print("Enter your Pakistan Studies marks out of 75:")
pst=int(input())
print("Enter your English marks out of 75:")
eng=int(input())
print("Enter your Chemistry marks out of 100:")
chem=int(input())
print("Enter your ",final," marks out of 100:")
fin=int(input())
percent=((sindhi+pst+eng+chem+fin)/425)*100
if percent>=80:
print("Congratulations Roll no ",roll_no," you got A+ grade with ",percent,"%")
elif percent<=79 & percent>=70:
print("Good! Roll no ",roll_no,"you got A grade with ",percent,"%")
elif percent<=69 & percent>=60:
print("Roll no ",roll_no,"you got B grade with ",percent,"%")
elif percent<=59 & percent>=50:
print("Roll no ",roll_no," you got C grade with ",percent,"%")
else:
print("Roll no ",roll_no,"You are fail with ",percent,"%")
| false |
0906f368808b375ed77eb7fd946b3c2ea78d073f | danrihe/Fractals | /TriangleFractal.py | 2,413 | 4.40625 | 4 | import turtle #input the turtle module
wn = turtle.Screen() #create the screen
wn.bgcolor("black")
hippo = turtle.Turtle() #create 4 turtles
fishy = turtle.Turtle()
horse = turtle.Turtle()
sheeha = turtle.Turtle()
print("What color would you like **hippo** to be? (Not black)") #allows user to define the color for the hippo turtle
hippoColor = input()
hippo.color(hippoColor) #sets the color to the user selected color
print("What color would you like **fishy** to be? (Not black)") #allows user to define the color for the fishy turtle
fishyColor = input()
fishy.color(fishyColor) #sets the color to the user selected color
print("What color would you like **horse** to be? (Not black)") #allows user to define the color for the horse turtle
horseColor = input()
horse.color(horseColor) #sets the color to the user selected color
print("What color would you like **sheeha** to be? (Not black)") #allows user to define the color for sheeha turtle.
sheehaColor = input()
sheeha.color(sheehaColor)#sets the color to the user selected color
print("How fast would you like the turtles to run?") #allows user to choose the run speed.
turtleSpeed = int(input())
hippo.speed(turtleSpeed) #sets all the turtles to be the selected speed
fishy.speed(turtleSpeed)
horse.speed(turtleSpeed)
sheeha.speed(turtleSpeed)
coord=300 #variable used for the size of the circle
horse.left(90) #sets all the turtles in the right direction so that they can properly execute the circle(s)
fishy.right(180)
sheeha.right(90)
hippo.up() #left the turtle up
hippo.goto (0,-300) #moves the turtle to the correct spot without making a line
hippo.down() #enables the turtle to draw
hippo.circle(coord) #defines the size of the circle
for level in range(5):
hippo.circle(coord/2) #draws the bottom circle
fishy.up()
fishy.goto (0, 300) #moves fishy to the correct position
fishy.down()
fishy.circle(coord/2) #draws the top circle
horse.up()
horse.goto (300,0) #moves horse to the correct position
horse.down()
horse.circle(coord/2) #draws the right circle
sheeha.up()
sheeha.goto (-300,0) #moves sheeha to the correct position
sheeha.down()
sheeha.circle(coord/2) #draws the left circle
coord = coord/2 #redefines the variable coord
| true |
7c6a81e88ffb8eb0dc9c3b67fe9552bdbfcaa2af | momentum-cohort-2019-09/examples | /w5d2--word-frequency/word_frequency.py | 2,753 | 4.125 | 4 | import string
STOP_WORDS = [
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were',
'will', 'with'
]
def remove_stop_words(words):
"""Given a list of words, remove all words found in STOP_WORDS."""
filtered_words = []
for word in words:
if word not in STOP_WORDS:
filtered_words.append(word)
return filtered_words
def clean_word(word):
"""Given one word:
- clean the word (remove punctuation from the beginning and end of the string)
- normalize it (lowercase, remove possessives)
and return the string."""
word = word.strip(string.punctuation)
word = word.lower()
if word[-2:] == "'s":
word = word[:-2]
return word
def clean_words(words):
"""Takes a list of words and cleans each one, returning a new list."""
cleaned_words = []
for word in words:
cleaned_words.append(clean_word(word))
return cleaned_words
def calculate_word_freqs(words):
"""
Given a list of words, return a dictionary of words to the number of
times each word is found in the list.
"""
freqs = {}
for word in words:
# if word in freqs:
# freqs[word] += 1
# else:
# freqs[word] = 1
freqs[word] = freqs.get(word, 0) + 1
return freqs
def get_longest_word(words):
"""Given a list of words, return the longest."""
return sorted(words, key=len, reverse=True)[0]
def print_word_freq(filename):
"""Read in `filename` and print out the frequency of words in that file."""
# read in the file
with open(filename) as file:
text = file.read()
# split the file in words
words = text.split()
# clean each word
words = clean_words(words)
# remove stop words
words = remove_stop_words(words)
# calculate the frequency of each word -- needs a dictionary
freqs = calculate_word_freqs(words)
# Print out the frequencies for the top 10 most frequent words
sorted_freqs = sorted(freqs.items(), key=lambda pair: pair[1], reverse=True)
longest_word_len = len(get_longest_word(words))
for word, freq in sorted_freqs[:10]:
print(word.rjust(longest_word_len), "|", str(freq).ljust(3), "*" * freq)
if __name__ == "__main__":
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(
description='Get the word frequency in a text file.')
parser.add_argument('file', help='file to read')
args = parser.parse_args()
file = Path(args.file)
if file.is_file():
print_word_freq(file)
else:
print(f"{file} does not exist!")
exit(1)
| true |
14c0855e08dca33dedd9b2a619b6aad79373f892 | harkbot/beginners_python | /whos_yo_daddy.py | 1,898 | 4.34375 | 4 | #Who's yo daddy?
#Self-coded
#create dictionary of sons and fathers
#key = son, value = father
#make options to exit, enter name of son to get father, add, replace, and delete son-father pairs
daddy = {"Bill": "Tedd", "Jack": "Jill?", "Rory": "Kyle", "Kevin": "Adam", "Dylan": "Jeremy"}
choice = None
print()
while choice != "0":
print("""
Who's yo daddy?
0 - Quit Program
1 - Get daddy for Bill, Tedd, Jack, Rory, Kevin, or Dylan
2 - add son/father pairing
3 - replace son/father pairing
4 - delete son/father pairing
""")
choice = input("Choice: ")
print()
# exit program
if choice == "0":
print("Good-bye.")
# get son/father pairing
elif choice == "1":
son = input("Please one of the aforementioned sons: ")
if son in daddy:
print (daddy[son])
# add son/father pairing
elif choice == "2":
son = input("What son would you like to add?: ")
if son not in daddy:
dad = input("What father would you like me to add?: ")
daddy[son] = dad
print("\n", son, "and", dad, "have been added.")
else:
print("Son/father pairing already exists.")
# replace existing son/father pairing with new father
elif choice == "3":
son = input("Which son's father would you like to replace?: ")
if son in daddy:
dad = input("Who's his new daddy?")
daddy[son] = dad
print("\n", son,"'s father has been replaced by", dad)
else:
print("Son/father does not exist.")
# delete father/son pairing
elif choice == "4":
son = input("Which son/father pairing would you like to delete?: ")
if son in daddy:
del daddy[son]
print("\n", son, "and his father have been deleted.")
input("\n\nPress enter to exit.") | true |
ffb8b75b6d47da30a53c358148b0e64012a95495 | khaloodi/graphs_codecademy | /graph_search/bfs.py | 1,282 | 4.28125 | 4 | '''
Breadth-First Search: Take My Breadth Away
Unlike DFS, BFS is primarily concerned with the shortest path that exists between two points, so that’s what we’ll be thinking about as we build out our breadth-first search function.
Using a queue will help us keep track of the current vertex and its corresponding path. Unlike with DFS, with BFS we may have to expand on paths in several directions to find the path we’re looking for. Because of this, our path is not the same as our visited vertices.
For visited we don’t care about the order of visitation; we only care about whether a vertex is visited or not, so we’ll use a Python set. Our breadth-first search logic should begin something like this:
def bfs(graph, start_vertex, target_value):
set path to a list containing the start_vertex
create a queue to hold vertices and their corresponding paths
define an empty visited set
'''
# def bfs(graph, start_vertex, target_value):
def bfs(graph, start_vertex, target_value):
# set path to a list containing the start_vertex
path = [start_vertex]
# create a queue to hold vertices and their corresponding paths
vertex_and_path = [start_vertex, path]
bfs_queue = [vertex_and_path]
# define an empty visited set
visited = set()
| true |
0ed42ee0ca150237661494c4ceadc36d4db9c4af | toeysp130/Lab-Py | /lab3-2.py | 338 | 4.21875 | 4 | #watcharakorn#
num1 = int( input("Enter value number 1 :"))
num2 = int( input("Enter value number 2 :"))
num3 = int( input("Enter value number 3 :"))
MinValue = min(num1, num2, num3)
MaxValue = max(num1, num2, num3)
print()
print("Your Enter Number :",num1, num2, num3)
print("maxvalue : " , MaxValue)
print("minvalue : " , MinValue)
| false |
7530c19e94561d02d5f4f26a0d3a6a3d25018949 | nahTiQ/poker_bot | /table.py | 2,815 | 4.15625 | 4 | '''Table object'''
from random import randint
from players import Player
import console as c
class Table:
def __init__(self):
self.players = 0
self.cards = []
self.pot_round = 0
self.pot = 0
def ask_for_players(self):
'''Ask for a number, convert to int, then return that number to pass
to the create_players() function.'''
while self.players == 0 or self.players > 7:
number_of_players = input('How many players would you like to play with? (1-7) ')
try:
number_of_players = int(number_of_players)
except ValueError:
print("You must enter a number between 1 and 7.")
else:
if number_of_players > 7:
print("You must enter a number between 1 and 7.")
continue
else:
return number_of_players
break
def accept_cards(self, cards_to_table):
''' Accept cards from another function to be added to the table'''
for card in cards_to_table:
self.cards.append(card)
def print_table(self):
'''Prints the table cards to the console'''
print('+----- TABLE -----+')
for card in self.cards:
print(card)
print('+-----------------+\n')
def print_pot(self, players, player_bet):
'''Take all bets and print pot to console
----- TO DO -----
Build seperate function that gets passed bot hand strength and bets
based on "confidence in your hand" '''
bot_bet = 0
self.pot_round = 0
print('\n+----- PLAYER BETS -----+')
for player in players:
if player == players[0]:
bot_bet = 0
else:
bot_bet = randint(1,5)
if player == players[0]:
print(f" {player.name} bet ${player_bet}")
else:
print(f' {player.name.title()} bet ${bot_bet}')
self.pot_round += bot_bet
self.pot += player_bet + self.pot_round
print(f"The current table pot is ${self.pot}")
print('+----- END BETS -----+\n')
def reset_table(self):
self.pot = 0
self.cards = []
def play_again(play_bool):
keep_playing = ''
while keep_playing != 'y' and keep_playing != 'n':
keep_playing = input("Whould you like to play again? (y/n)")
if keep_playing.lower() == 'y':
return True
elif keep_playing.lower() == 'n':
return False
elif keep_playing != 'y' and keep_playing != 'n':
print("You must select (Y) or (N)o")
continue
def who_wins(self, handstrengths):
'''Give a dictionary of hand strengths?'''
# def players_at_table(self, number):
'''Check if user is trying to add more than 7 players to the table'''
'''try:
number = int(number)
except ValueError:
print("You must enter a number!")
else:
while number > 7:
number = int(number)
print("You can not play with more than 7 other people.")
number = int(input("How many people would you like to play with? (1-7)"))'''
| true |
4d819770c12674b97b385227107fb104c15f975f | Queru78/programacion1 | /practica2/probandoH.py | 213 | 4.1875 | 4 |
#!/usr/bin/python
numero =input("ingrese numero ")
el6= numero % 6
if (el6==0):
print("el numero %s es divisible por 6"% (numero))
else:
print("el numero %s no es divisible por 6" % (numero))
| false |
91b6c2dbe6ff6c2d2c4ff492c6a4e872a5da5d22 | pwatson1/python | /exampleCode/inheritance_ex1.py | 896 | 4.125 | 4 | # Object oriented programing based around classes and
# instances of those classes (aka Objects)
# How do classes interact and Directly effect one another?
# Inheritence - when one class gains all the attributes of
# another class
# BaseClass is the parent class
# Must use object so the child class can refer to its attributes
class BaseClass(object):
# passing in self makes BaseClass the owner of the function
def printHam(self):
print 'Ham'
# passing in BaseClass makes InheritingClass the child class
# of BaseClass and allows InheritingClass to inherit BaseClasses
# attributes
class InheritingClass(BaseClass):
pass
# creating an instance of InheritingClass
# InheritingClass has all the attributes of BaseClass
x = InheritingClass()
# so even though it doesn't have a printHam function you can
# still call the function
x.printHam()
| true |
db3d42f5b60b5478fe2081a5f564f48bca96c71c | pwatson1/python | /exampleCode/nesting_functions_decorators.py | 2,138 | 4.625 | 5 | # what are nesting functions? Functions that are
# declared within other Functions
'''
def outside():
def printHam():
print "ham"
return printHam
myFunc = outside()
myFunc()
'''
'''
# why nest a function within a function?
def outside():
# this acts like a class for the subfunctions
# you can think of each function as an object
# x is created in local space for the outside()
# function. After it executes the printHam() function
# it no longer exists.
x = 5
def printHam():
print x
return printHam
myFunc = outside()
myFunc()
# reasons for using nested functions
# less code than classes
# do not have to know what function you are calling just
# add () like myFunc
# can use if, Else, Elif to CHOOSE which function is returned
'''
'''
# passing x through the outside() function works the same as
# the global
def outside(x = 5):
def printHam():
print x
return printHam
# you can also override the passed in variable as well
myFunc = outside(7)
myFunc()
'''
'''
# passing a function into another function
# a decorator for oldFunc
def addOne(myFunc):
def addOneInside():
return myFunc() +1
return addOneInside
def oldFunc():
return 3
newFunc = addOne(oldFunc)
print oldFunc(), newFunc()
'''
'''
# we can have the results of the old function be replaced
# by the results of the new function whenever we call oldFunc
def addOne(myFunc):
def addOneInside():
return myFunc() +1
return addOneInside
def oldFunc():
return 3
oldFunc = addOne(oldFunc)
print oldFunc()
'''
def addOne(myFunc):
# by adding *arhs and **kwargs you can handle most
# functions passed in
def addOneInside(*args, **kwargs):
return myFunc(*args, **kwargs) +1
return addOneInside
# by using the @addOne declaration we no longer need
# the oldFunc = addOne(oldFunc) line from below and the
# decorator still works.
@addOne
def oldFunc(x=3):
return x
# values can always be overridden at output
print oldFunc(654)
| true |
c97bb7b63b95d8e4004876c4fcc9ec45afdacb85 | pwatson1/python | /exampleCode/singletonMetaClass.py | 1,215 | 4.375 | 4 | # Chapter 17
class Singleton(type):
# _instance is just a container name for the dictionary
# but it makes it easier to foloow what's happening
_instances = {}
# this function uses cls instead of self . Unlike self which refers
# to the parent class, cls refers to any class
def __call__(cls, *args, **kwargs):
# this says. "if the class does not exist...
if cls not in cls._instances:
# use the parent singleton class to make it
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
# create an instance with a value of 5
cls.x = 5
# Output that instance
return cls._instances[cls]
class MyClass(object):
# when this class is defined, we want python to search for a
# __metaclass__ definition which prevents other classes from
# inheriting its attributes. Therefore there can only be one of
# this class which satisfies the singleton definition.
# when the class is created it will be created based on the
# singleton method
__metaclass__ = Singleton
# By creating m and v instances we can test to see if they are
# actually the same block of memory
m = MyClass()
v = MyClass()
print m.x
m.x = 9
print v.x
| true |
5d5adcde16694ecb2dcf02af9af1264f972c823a | crazcalm/PyTN_talk_proposal | /recipies/recipe1/recipe1.py | 701 | 4.3125 | 4 | """
Source: Python Cookbook, 3rd edition, number 4.14
Problem:
--------
You have a nested sequence that you want to flatten into a single list of
values
Solution:
---------
This is easily solved by writing a recursive generator function involving a
yield from statement
Notes:
------
1. Python 2 does not have yield from (check)
"""
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
if __name__ == "__main__":
items = [1, 2, [3, 4, [5 ,6], 7], 8]
for x in flatten(items):
print(x)
| true |
89dfe9e4aef4b838180e5e36928a4bb1bfde8b19 | nnanchari/CodingBat | /Warmup-1/front3.py | 313 | 4.15625 | 4 | #Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3,
#the front is whatever is there. Return a new string which is 3 copies of the front.
def front3(str):
front=str[:3]
if len(str)<3:
return str+str+str
else:
return front+front+front
| true |
ef733ebbf670d6d41b80406a57c09b261e029856 | pcolonna/coding-exercises | /Chapter_2/2.3_delete_mid_node.py | 1,226 | 4.34375 | 4 | # Question 2.3: delete_middle_node.
"""
Algo to delete a node in the middle of a singly linked list.
Not necessarily the middle, just any node that is not the first or last one.
"""
from LinkedList import LinkedList
"""
To delete a node in a linked list, you can just skip it. Jump or ignore it.
So if you want to delete node n, change its value to the value of node n+1 ,
and change the ref from n to n+2. We just shift everythong.
1 -> 2 -> 3 -> 4 -> 5 -> 7 -> 8 -> 9
copy |
v
1 -> 2 -> 3 -> 4 -> 7 -> 7 -> 8 -> 9
then skip
1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 9
"""
def delete_mid_node(node):
node.value = node.next.value # Change/copy value from the next node.
node.next = node.next.next # Point two nodes ahead, which delete a node in practice.
"""
We should also deal with the case where the node is the last one in the list.
Our algo doesn't work in that situation yet.
"""
if __name__ == "__main__":
ll = LinkedList()
ll.add_multiple([1, 2, 3, 4])
middle_node = ll.add(5)
ll.add_multiple([7, 8, 9])
print(ll)
delete_mid_node(middle_node)
print(ll) | true |
c1e9d0096130246882886fecb3dd52106bb4f657 | pcolonna/coding-exercises | /Chapter_3/3.5_Sort_Stack.py | 1,182 | 4.125 | 4 | # Question 3.5: Sort Stack
#
# Sort a stack such as the smallest item is on top.
# Use only one additional temporary stack.
from random import randrange
class Stack(list):
def peak(self):
return self[-1]
def push(self, item):
self.append(item)
def empty(self):
return len(self) == 0
def sort_stack(unsorted_stack):
sorted_stack = Stack()
while not unsorted_stack.empty():
tmp = unsorted_stack.pop()
while not sorted_stack.empty() and sorted_stack.peak() > tmp:
unsorted_stack.push(sorted_stack.pop())
sorted_stack.push(tmp)
while not unsorted_stack.empty() and unsorted_stack.peak() >= sorted_stack.peak():
sorted_stack.push(unsorted_stack.pop())
return sorted_stack
if __name__ == '__main__':
test_items = [randrange(20) for x in range(20)]
print(test_items)
S = Stack()
for item in test_items:
S.push(item)
S = Stack.sort_stack(S)
for i, item in enumerate(sorted(test_items)):
print("item", item, S[i]) | true |
a50dac74db197f2e63675b1bf0bbcaaa53c3eaa1 | heenashree/pyTutorialsforAnalytics | /Lists/listOperations.py | 2,292 | 4.34375 | 4 | #!/bin/python
import sys
mega_list = [2,3,4,5.5,6,'hi']
list1 = ["hi", "1", 1, 3.4, "there", True]
def add_an_item(item):
print("Your list before append", list1)
print("Adding/appending an item at the end of the list\n")
list1.append(item)
print("Item is appended\n")
print(list1)
def update_to_list_by_index(ind, item):
print("Your list before insert", list1)
print("Pass index and the object. Format insert(index, object)")
list1.insert(ind, item)
print(list1)
def remove_item(item):
print("Removes the item described. Format list.remove(item)")
print("My list looks like this for now", list1)
list1.remove(item)
print("Item has been removed")
print(list1)
def del_an_item_by_index(ind):
print("This will take index to delete the object\n")
print("Our list looks like this before pop", mega_list)
mega_list.pop(ind)
print("The element on this index is removed\n")
print(mega_list)
print("pop method witout an index removes the last element")
mega_list.pop()
print(mega_list)
def extend_list(item):
print("Make sure that you pass a list to extend\n")
mega_list.extend(item)
print("List is extended\n")
print(mega_list)
def del_list():
print("List before clearing elements", mega_list)
mega_list.clear()
print(mega_list)
def replace_item(ind, item):
print("Before replacing, your list looks like ", list1)
list1[ind] = item
print("Now list looks like", list1)
if __name__ == "__main__":
if sys.argv[1] == 'add':
add_an_item(sys.argv[2])
elif sys.argv[1] == 'update_index':
update_to_list_by_index(int(sys.argv[2]), sys.argv[3])
elif sys.argv[1] == 'remove_item':
remove_item(sys.argv[2])
elif sys.argv[1]=='del':
del_an_item_by_index(int(sys.argv[2]))
elif sys.argv[1] == 'extend':
input_str= input("Enter the numbers seperated by space\n")
print("Your input string looks like this ", input_str)
user_list = input_str.split()
print(user_list)
extend_list(user_list)
elif sys.argv[1] == 'DEL':
del_list()
elif sys.argv[1] == 'replace':
replace_item(int(sys.argv[2]), sys.argv[3])
else:
print("chose an operation to perform")
| true |
cea53adb50f9ccf3498e4ff272e45ed0186e4536 | AhmedZahid098/tests_and_side_projects | /Book learning python/sqlite_python/mydatabase.py | 1,178 | 4.15625 | 4 | import sqlite3
from database import Employee
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""create table employees(
first text,
last text,
pay integer
)""")
def insert_emp(emp):
with conn:
c.execute("insert into employees values (:first, :last, :pay) ", {
'first': emp.first, 'last': emp.last, 'pay': emp.pay})
def get_emp_by_name(lastname):
c.execute("select * from employees where last=:last", {'last': lastname, })
return c.fetchall()
def update_pay(emp, pay):
with conn:
c.execute("""update employees set pay=:pay where first=:first AND last=:last""", {
'first': emp.first, 'last': emp.last, 'pay': pay})
def remove_emp(emp):
c.execute("""delete from employees where first = :first and last = :last""", {
'first': emp.first, 'last': emp.last})
emp_1 = Employee('ahmed', 'zahid', 500)
emp_2 = Employee('ali', 'zahid', 600)
insert_emp(emp_1)
insert_emp(emp_2)
emps = get_emp_by_name('zahid')
print(emps)
payed = update_pay(emp_2, 100000)
print(payed)
emps = get_emp_by_name('zahid')
print(emps)
remove_emp(emp_2)
conn.close()
| false |
b01ea9552782249f526040b1621b4218adb68a7a | jaewon4067/Codes_with_Python | /Object-oriented programming/Creating a simple blog.py | 1,576 | 4.5 | 4 | """
As I'm learning OOP, I'm going to make a mini blog where people can post with me.
I'm going to create a 'Post' class and a BlogUser' class to print out the full contents of the blog.
"""
class Post:
def __init__(self, date, content):
# The post class has date and content as attributes.
self.date = date
self.content = content
def __str__(self):
# a method that returns the infomation of the post.
return "Date: {}\n Content: {}".format(self.date, self.content)
class BlogUser:
def __init__(self, name):
# Users from a blog have name and posts as attributes.
self.name = name
self.posts = []
def add_post(self, date, content):
# Append a new post.
new_post = Post(date, content)
self.posts.append(new_post)
def show_all_posts(self):
# Print all the posts
for post in self.posts:
print(post)
def __str__(self):
# Return a simple sentence with the name.
return("Hello, I am {}.\n".format(self.name))
# Create a blog user instance.
blog_user_1 = BlogUser("Jaewon")
# Print a blog user instance(hello, name)
print(blog_user_1)
# Write two posts
blog_user_1.add_post("1th March 2021", """
It's already march, time flies.
Let's be a better person!
""")
blog_user_1.add_post("28th Feb 2021", """
I love coding, I don't have to think about anything else.
I like problem solving, I want to live my life happy like this with Python!
""")
# Print all the post
blog_user_1.show_all_posts()
| true |
08208fe3612826d96129e5fcf3e87131e11f3a24 | namaslay33/Python | /Day1.py | 1,368 | 4.375 | 4 | # Write a Python program to print the following string in a specific format (see the output). Go to the editor
# Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
# Output :
# Twinkle, twinkle, little star,
# How I wonder what you are!
# Up above the world so high,
# Like a diamond in the sky.
# Twinkle, twinkle, little star,
# How I wonder what you are
print("Twinkle, twinkle, litte star,\n\tHow I wonder what you are!\n\t\tUp above the world so high,\n\t\tLike a diamon in the sky.\nTwinkle, twinkle, little star,\n\tHow I wonder what you are")
# Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
name = input("What is your name?")
age = input("How old are you?")
num = 100 - age
year100 = 2018 + num
print("Hello, " + name + ". You will turn 100 in " + str(year100) + ".")
# Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. Go to the editor
# Sample value of n is 5
# Expected Result : 615
n = int(input("Enter in a number: "))
n1 = int( "%s" % n )
n2 = int( "%s%s" % (n,n) )
n3 = int( "%s%s%s" % (n,n,n) )
print(n1 + n2 + n3)
| true |
c945a40c704f1620193151da431a184542c957ad | namaslay33/Python | /FunctionExercises/FunctionExercise4.py | 435 | 4.15625 | 4 | # 4. Odd or Even
# Write a function f(x) that returns 1 if x is odd and -1 if x is even. Plot it for x values of -5 to 5 in increments of 1. This time, instead of using plot.plot, use plot.bar instead to make a bar graph.
import matplotlib.pyplot as plot
def f(x):
if x % 2 != 0:
return 1
else:
return -1
xs = list(range(-5, 6))
ys = []
for x in xs:
ys.append(f(x))
plot.bar(xs, ys)
plot.show() | true |
3f020df6813f72453e9ee31b3cf272b0ecb93c8b | MintuKrishnan/subrahmanyam-batch | /python_lectures/22. Merge Sort/merge_sort.py | 893 | 4.15625 | 4 | def merge(A, start1, end1, start2, end2):
p1 = start1
p2 = start2
temp = list()
while p1 <= end1 and p2 <= end2:
if A[p1] < A[p2]:
temp.append(A[p1])
p1 += 1
else:
temp.append(A[p2])
p2 += 1
while p1 <= end1:
temp.append(A[p1])
p1 += 1
while p2 <= end2:
temp.append(A[p2])
p2 += 1
idx = 0
while idx < len(temp):
A[start1 + idx] = temp[idx]
idx += 1
def mergeSort(A, left, right):
if left >= right:
return
mid = (left + right) >> 1
mergeSort(A, left, mid)
mergeSort(A, mid + 1, right)
merge(A, left, mid, mid + 1, right)
if __name__ == '__main__':
#yypA = [5, 6, 2, 3, 66, 7, 1, 2,2, 34, 5]
A = [5,4,3,2,1]
print("Unsorted Array is ", A)
mergeSort(A, 0, len(A) - 1)
print("Sorted Array is ", A)
| false |
e09253f9a7610a88e51bb69920829a69ad5fb3a1 | spettigrew/cs2-guided-project-ram-basics | /src/lower_case_demo1.py | 1,660 | 4.59375 | 5 | """
Given a string, implement a function that returns the string with all lowercase
characters.
Example 1:
Input: "LambdaSchool"
Output: "lambdaschool"
Example 2:
Input: "austen"
Output: "austen"
Example 3:
Input: "LLAMA"
Output: "llama"
*Note: You must implement the function without using the built-in method on
string objects in Python. Think about how character encoding works and explore
if there is a mathematical approach that you can take.*
"""
def to_lower_case(string):
# Your code here
# U - convert char to ascii 'a' = 97, 'b' = 98, so on.
# Plan - how to tell if it's lowercase. ascii 97-122, all lowercase a-z. All uppercase is ascii 65-90. from a-z 77 + 32 = 109
# create empty answer_string
answer_string = ""
# loop through each char of input_string
for char in string:
# for each char convert to ascii
ascii_char = ord(char)
# check if number is between 65 and 90
if 65 <= ascii_char <= 90:
# the letter is uppercase, so lets convert to lower
lower_char_num = ascii_char + 32
# convert the new ascii num back to character
lower_char = chr(lower_char_num)
# add lower_char to our answer_string
answer_string += lower_char
else:
# add the character to answer_string
answer_string += char
return answer_string
print(to_lower_case('LambdaSchool'))
print(to_lower_case('LLAMA'))
# if ascii < 90 .add(32)
# return ascii
# ans = ""
# for char >= 65 and char <= 90:
# newChar = ord(char) + 32
# ans += newChar
# return ans
| true |
fa9f821dd75ab2d98c2f8fdc7a62b275f905d5c7 | Gcriste/Python | /listAppendInsertExtend.py | 1,579 | 4.3125 | 4 | # Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
instructors.append("Colt")
instructors.append("Blue")
instructors.append("Lisa")
# Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
# Use any of the list methods we've seen to accomplish this:
instructors.extend(["Colt", "Blue", "Lisa"])
## Deleting things from a list
# Clear - removes everything from the list
# Pop - removes last item, if you provide an index it removes that item from where it is in the index
# Remove - removes the first instance of the item that you specify to remove, throws an error if not found
#index - returns the index of the specified item in the list
#count - returns the number of times x appears in the list
#reverse - reverses the elements of the list (in-place)
#sort - sorts the items of the list (in-place)
#join - technically a string method that takes an interable argument and concatenates(combines) a copy of the base string between each item of the list
# Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
instructors.extend(["Colt", "Blue", "Lisa"])
# Remove the last value in the list
instructors.pop()
# Remove the first value in the list
instructors.pop(0)
# Add the string "Done" to the beginning of the list
instructors.insert(0, 'Done') | true |
1d89205fbd188befd987f7be0bb108c3559d66ad | yandryvilla06/python | /funciones/var_global.py | 1,367 | 4.28125 | 4 | """
Un ámbito define los límites de un programa en los que un espacio de nombres puede ser accedido sin utilizar un prefijo.
Como te he mostrado en el apartado anterior, en principio existen, como mínimo, tres ámbitos. Uno por cada espacio de nombres:
Ámbito de la función actual, que tiene los nombres locales a la función.
Ámbito a nivel de módulo, que tiene los nombres globales, los que se definen en el propio módulo.
Ámbito incorporado, el más externo, que tiene los nombres que define Python.
Cuando desde dentro de una función se hace referencia a un nombre, este se busca en primer lugar en el espacio de nombres local, luego en el espacio de nombres global y finalmente en el espacio de nombres incorporado.
Si hay una función dentro de otra función, se anida un nuevo ámbito dentro del ámbito local.
"""
#nombre="MArio" aqui esta definida globalmente
# def funcion():
# nombre="Pepe" # esto seria una variable local
#print(nombre) no podemos hacer un print de esto debido a que nombre es local a la funcion
"Si la queremos modificar fuera de la funcion lo que debemos de hacer es hacerla global"
def funcion():
global nombre
nombre="Pepe"
# funcion() Ojo: si no invocamos la funcion es normal que no la tengamos definida
funcion()
nombre="Yandry wp"
print(nombre) #aqui modificamos la funcion , bueno arriba
| false |
bc91aa916a3de2e1347840f80d4348dc06e706b6 | sat5297/AlgoExperts.io | /Easy/InsertionSort.py | 295 | 4.1875 | 4 | def insertionSort(array):
for i in range(1, len(array)):
j = i
while j>0 and array[j] < array[j-1]:
swap(j, j-1, array)
j-=1
return array
def swap(m, n, arr):
arr[m], arr[n] = arr[n], arr[m]
#Time Complexity: O(n^2)
#Space Complexity: O(1)
| false |
f525573e903ced3083429eab40cb5e20af07ea70 | Ivaylo-Atanasov93/The-Learning-Process | /Python Advanced/Lists_as_Stacks_and_Queues-Exercise/Balanced Paretheses.py | 874 | 4.125 | 4 | sequence = input()
open_brackets = ['(', '{', '[']
closing_brackets = [')', '}', ']']
def balanced(sequence):
stack = []
for bracket in sequence:
if bracket in open_brackets:
stack.append(bracket)
elif bracket in closing_brackets:
index = closing_brackets.index(bracket)
if len(sequence) > 0 and open_brackets[index] == stack[len(stack) - 1]:
stack.pop()
else:
return 'NO'
if len(stack) == 0:
return 'YES'
else:
return 'NO'
print(balanced(sequence))
# def check(my_string):
# brackets = ['()', '{}', '[]']
# while any(x in my_string for x in brackets):
# for br in brackets:
# my_string = my_string.replace(br, '')
# return not my_string
#
#
# string = input()
# print("YES"
# if check(string) else "NO")
| true |
d79154371342cce5e8aa5986ab62d94f01d9ce78 | Ivaylo-Atanasov93/The-Learning-Process | /Python Advanced/Functions_Advanced-Exercise/Odd or Even.py | 346 | 4.28125 | 4 | def odd(numbers):
return sum([num for num in numbers if num % 2 != 0])
def even(numbers):
return sum([num for num in numbers if num % 2 == 0])
command = input()
numbers = [int(num) for num in input().split()]
if command == 'Odd':
print(odd(numbers) * len(numbers))
elif command == 'Even':
print(even(numbers) * len(numbers))
| false |
376a1185f116eebf1b94ecaa5669cfc799a7dacb | santhosh790/competitions | /DailyCodingProblem/D130a_MaxProfitStockList.py | 1,447 | 4.1875 | 4 | '''
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in
those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by
buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in
decreasing order, then profit cannot be earned at all.
Follow up Problem similar to this:
https://www.geeksforgeeks.org/maximum-difference-between-two-elements/
'''
def maxProfitBuySell(prices):
'''
:param prices:
:return:
This approach is working by finding the local minima and local maxima in the list.
Run time complexity is O(n)
'''
if len(prices) == 1: ## Cannot have a buy sell pair
return
lSize = len(prices)
buySellPair = []
i = 0
while i<lSize-1:
while i < (lSize-1) and prices[i] > prices[i+1]:
## Buying when cost is lesser than next day
i+=1
if i == lSize - 1:
print("Prices are descending order - cannot make profit")
break
buy = i+1
i+=1
while i < lSize-1 and prices[i] < prices[i+1]:
## Selling when reaching highest profit, Keep as long as money increasing
i+=1
sell = i+1
buySellPair.append((buy,sell))
print(buySellPair)
maxProfitBuySell([100, 180, 260, 310, 40, 535, 695])
| true |
9172b5f15b2faef2f93a79417f72647832ebdaf9 | mr-vaibh/python-payroll | /PRACTICAL-FILES/string/string2.py | 371 | 4.34375 | 4 | # This function prints a pyramid
def make_pyramid(n):
k = n - 1 # for spaces
# loop for number of rows
for i in range(0, n):
# loop for number spaces
for j in range(0, k):
print(end=" ")
k -= 1
# loop for number of columns
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = int(input("Enter pyramid size in numeric: "))
make_pyramid(n) | true |
4d32a642c347bed483aa859d9b499485e2818265 | mr-vaibh/python-payroll | /PRACTICAL-FILES/string/string1.py | 293 | 4.25 | 4 | # this program simply prints a string in vertical reverse order
string = str(input("Enter a string: "))
length = len(string)
initial = 0
# the range in the loop below basically deals with length
for i in range(-1, -(length + 1), -1):
print(string[initial] + "\t" + string[i])
initial += 1 | true |
ba973167bfcc7d3842194a2e1d190c276ec5b74e | mr-vaibh/python-payroll | /PRACTICAL-FILES/others/3-stack.py | 609 | 4.28125 | 4 | # implementation of stack using list
stack = []
choice = 'y'
print('1. Push\n2. Pop\n3. Display elements of stack')
while True:
choice = int(input("Enter your choice: "))
if choice == 1:
elem = input("Enter your element which you want to push: ")
stack.append(elem)
elif choice == 2:
if stack == []:
print("Stack is empty... cannot delete element")
else:
print("Deleted element is: " + stack.pop())
elif choice == 3:
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
else:
print("Wrong input !!")
| true |
8fef69e5d705f817e78315d18611a2c3a77f09b4 | love-adela/algorithm-ps | /acmicpc/4504/4504.py | 215 | 4.15625 | 4 | n = int(input())
number = int(input())
while number:
if number % n == 0:
print(f'{number} is a multiple of {n}.')
else:
print(f'{number} is NOT a multiple of {n}.')
number = int(input())
| true |
3785c2340cc205f09c94f5d1753ff221f53aa041 | wmichalak/algorithms_and_datastructures | /Session 1/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py | 1,337 | 4.125 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
"""Find the maximal value of items that fit into the backpack
:param capacity:
:param weights:
:param values:
:return maximum price of items that fit into the backpack of given capacity"""
# Get price per weight list sorted from most to least valueable
items = sorted([(p/w, p, w) for p, w in zip(values, weights)], reverse=True)
total_weight = 0
total_value = 0
# try full unit items
for item in items:
item_ppw = item[0]
item_value = item[1]
item_weight = item[2]
if total_weight <= capacity:
if (item_weight + total_weight) <= capacity:
total_weight += item_weight
total_value += item_value
# If discrete items don't fill, add fraction of item until full
else:
total_value += (capacity - total_weight) * item_ppw
total_weight += (capacity - total_weight)
return total_value
if __name__ == "__main__":
input = sys.stdin.read()
data = list(map(int, input.split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.4f}".format(opt_value))
| true |
44cb4188e6949960326659bdd6ee4db10f9d8046 | cesarramos95/Algotitmo-Shannon-Fano | /encode.py | 1,043 | 4.15625 | 4 | #!/usr/bin/env python3
from calculations import calculate_codes
def encode(symbol_sequence, codes):
encoded = []
codes_dict = dict(codes)
for symbol in symbol_sequence:
code = codes_dict.get(symbol)
if code is None:
raise Exception(f"Invalid symbol: {symbol}")
encoded.append(code)
encoded = ' '.join(encoded)
return encoded
def main():
raw_symbols = input("Enter symbols that should be encoded: ")
symbols = raw_symbols.split()
raw_probs = input("Enter their probabilities: ")
probs = [float(prob) for prob in raw_probs.split()]
if len(symbols) != len(probs):
raise Exception("Amount of probabilities should be equal"
"to amount of symbols")
message = input("Enter the message to encode (e.g. 'A B C D'): ")
symbol_sequence = message.split()
codes = calculate_codes(zip(symbols, probs))
encoded = encode(symbol_sequence, codes)
print("Encoded message:", encoded)
if __name__ == '__main__':
main()
| true |
367216a1c5906e1f53f70f5425f533800f52222d | rubaalibrahim/100DaysOfCode | /week 02.py | 2,226 | 4.25 | 4 | >>> # Day 6
>>> x = int(4)
>>> y = int(6.2)
>>> z = int('9')
>>> print(x)
4
>>> print(y)
6
>>> print(z)
9
>>> x = float(4)
>>> y = float(6.2)
>>> z = float('9')
>>> print(x)
4.0
>>> print(y)
6.2
>>> print(z)
9.0
>>> x = str('r3')
>>> y = str(66)
>>> z = str(7.3)
>>> print(x)
r3
>>> print(y)
66
>>> print(z)
7.3
>>> # Day 7
>>> print('hello')
hello
>>> print("how are you?")
how are you?
>>> r = 'ruba'
>>> print(r)
ruba
>>> a = ''' my name's ruba i'm 21 i'm a CS student and i love learning a new programming language '''
>>> print(a)
my name's ruba i'm 21 i'm a CS student and i love learning a new programming language
>>> print(a[5])
a
>>> print(a[3:12])
name's r
>>> # Day 8
>>> i = "hello world"
>>> n = " hello world "
>>> print(n.strip())
hello world
>>> print(len(n))
19
>>> s = 'RUBA'
>>> print(s.lower())
ruba
>>> print(n.upper())
HELLO WORLD
>>> print(n.replace('h','J'))
Jello world
>>> print(n.split('ll'))
[' he', 'o world ']
>>> x = 'hello, world'
>>> print(x.split(','))
['hello', ' world']
>>> # Day 9
>>> age = 21
>>> text = " i'm {} "
>>> print(text.format(age))
i'm 21
>>> quantity = 4
>>> price = 27.45
>>> order = "can i get {} drinks for {} "
>>> print(order.format(quantity , price))
can i get 4 drinks for 27.45
>>> MyOrder = "i'm gonna pay {1} for {0} drinks "
>>> print(MyOrder.format(quantity , price))
i'm gonna pay 27.45 for 4 drinks
>>> # Day 10
>>> x = 3
>>> y = 2
>>> print(x*y)
6
>>> a = 4
>>> a += 6
>>> print(a)
10
>>> x = 5
>>> x /= 3
>>> print(x)
1.6666666666666667
>>> x = 7
>>> y = 9
>>> print(x > y)
False
>>> print(x < Y)
>>> print(x==y)
False
>>> print(y>x)
True
>>> # Day 11
>>> x = 7
>>> print(x > 3 or x < 2)
True
>>> s = 'car'
>>> p = 'train'
>>> v = p
>>> print(s is not p)
True
>>> print(s is p)
False
>>> print(v is p)
True
>>> o = ['cat','dog']
>>> print('cat' in o)
True
>>> print('puppy' in o)
False
>>> # Day 12
>>> a = 'please I want {} sandwiches and {} donuts'
>>> b = a.replace('I','we')
>>> print(b)
please we want {} sandwiches and {} donuts
>>> c = b.format(5,7)
>>> print(c)
please we want 5 sandwiches and 7 donuts
>>> d = c.replace('a','A')
>>> print(d)
pleAse we wAnt 5 sAndwiches And 7 donuts
>>>
| false |
f115ae3b67a11c1b83b04bc014190f4716a04516 | rubaalibrahim/100DaysOfCode | /week 05 (part 2).py | 1,703 | 4.15625 | 4 |
>>> # Day 29
>>> numbers = ['1','2','3']
>>> for x in numbers:
print(x)
1
2
3
>>> for x in'python':
print(x)
p
y
t
h
o
n
>>> fruits = ['apple','strawberry','orange']
>>> for x in fruits:
print(x)
if x == 'strawberry':
break
apple
strawberry
>>> for x in fruits:
if x == 'strawberry':
break
print(x)
apple
>>> for x in fruits:
if x =='strawberry':
continue
print(x)
apple
orange
>>> # Day 30
>>> for x in range(7):
print(x)
0
1
2
3
4
5
6
>>> for x in range(3,9):
print(x)
3
4
5
6
7
8
>>> for x in range(3,13,2):
print(x)
3
5
7
9
11
>>> for x in range(4):
print(x)
else:
print('done')
0
1
2
3
done
>>> clothes = ['t-shirt','pants','shoes']
>>> color = ['white','red','black']
>>> for x in color:
for y in clothes:
print(x,y)
white t-shirt
white pants
white shoes
red t-shirt
red pants
red shoes
black t-shirt
black pants
black shoes
>>> # Day 31
>>> def new_func():
print('hello')
>>> new_func()
hello
>>> def my_func(Fname):
print(Fname + " refsnes")
>>> my_func('emil')
emil refsnes
>>> my_func('tobias')
tobias refsnes
>>> my_func('linus')
linus refsnes
>>> def Func(country = 'norway'):
print("i'm from " + country)
>>> Func('sweden')
i'm from sweden
>>> Func('india')
i'm from india
>>> Func()
i'm from norway
>>> # Day 32,33
>>> for x in range(3,18,2):
for y in range(2,17,2):
print(x,y)
3 2
3 4
3 6
3 8
3 10
3 12
3 14
3 16
5 2
5 4
5 6
5 8
5 10
5 12
5 14
5 16
7 2
7 4
7 6
7 8
7 10
7 12
7 14
7 16
9 2
9 4
9 6
9 8
9 10
9 12
9 14
9 16
11 2
11 4
11 6
11 8
11 10
11 12
11 14
11 16
13 2
13 4
13 6
13 8
13 10
13 12
13 14
13 16
15 2
15 4
15 6
15 8
15 10
15 12
15 14
15 16
17 2
17 4
17 6
17 8
17 10
17 12
17 14
17 16
>>>
| false |
515e1f803403b0da28345dab126a0c43ee26c855 | EshSubP/Advent-of-code2020 | /Day 5/Solution/Day5_1.py | 274 | 4.125 | 4 | fname = input("Enter file name: ")
fh = open(fname)
s = ""
largest = 0
for line in fh:
s = line.replace('F','0').replace('B','1').replace('L','0').replace('R','1')
decimal = int(s,2)
if decimal>largest:
largest = decimal
print(largest)
| true |
74496e40f3712ea5a0a66e12f6bc8379319be36a | ag220502/Python | /Programs/ForLoops/nDiffInputsSumAndAverage.py | 297 | 4.15625 | 4 | #Take N different inputs and print their sum and average
n = int(input("Enter the Number Of Values : "))
sum1 = 0
for i in range(1,n+1):
inp = int(input("Enter Value",i," : "))
sum1 = sum1 + inp
print("The Sum Of Inputs are : ",sum1)
avg = sum1/n
print("The Average Of Inputs are : ",avg)
| true |
e5f3ee04a995d38082ce69037f2093b8732110f8 | ag220502/Python | /Programs/Swapping/25.SwappingUsingSecMethod.py | 257 | 4.21875 | 4 | #Swap Variables Using First Method
a = int(input("Enter Value Of A : "))
b = int(input("Enter Value Of B : "))
print("Valus Of A :",a)
print("Valus Of B :",b)
a,b=b,a
print("Values after Swapping are : ")
print("Valus Of A :",a)
print("Valus Of B :",b)
| false |
3d51fc9dc33632d4b7716a77322f25c4c60087d4 | ag220502/Python | /PythonWorbook/IntroductionToProgramming/ex1.py | 602 | 4.5625 | 5 | '''
Exercise 1: Mailing Address
Create a program that displays your name and complete mailing address.
The address should be printed in the format that is normally used in the
area where you live.Your program does not need to read any input from the user.
'''
name = "Narendra Aliani"
comp = "Pragati Computers"
street = "Ambawadi Circle"
area = "Sardarnagar"
pincode = "382475"
print("="*40)
print(" Mailing Address ")
print("="*40)
print("Name :",name)
print("Company Name :",comp)
print("Street Name :",street)
print("Area Name :",area)
print("Pincode :",pincode)
print("="*40)
| true |
536ee6d0932a23527435bf198a2ad25b7a67b846 | hwulfmeyer/NaiveBayesClassifier | /filehandling.py | 2,133 | 4.15625 | 4 | """
This file is for the methods concerning everything from file reading to file writing
"""
import re
import random
def read_data_names(filepath: str):
"""
function to read class names & attributes
:param filepath: the relative path to the file containing the specifications of the attribute_values
:return: a tuple of lists
classes: is a one-dimensional list containing the class names
attributes: is a one-dimensional list containing the attribute names
attribute_values: is a two-dimensional list where each row respresents
one attribute(in the order of 'attributes') and the possible values
"""
with open(filepath, "r") as f:
lines = f.read().splitlines()
classes = re.sub(r'^' + re.escape("class values: "), '', lines.pop(0))
classes = classes.split(", ")
attributes = re.sub(r'^' + re.escape("attributes: "), '', lines.pop(0))
attributes = attributes.split(", ")
attribute_values = []
for i in range(0, len(attributes)):
values = re.sub(r'^' + re.escape(attributes[i] + ": "), '', lines.pop(0))
attribute_values.append(values.split(", "))
return classes, attributes, attribute_values
def read_data(filepath: str):
"""
function to read the actual data
:param filepath: the relative path to the file containing the specifications of the data
:return: the data in filepath as a two-dimensional list where each row represents one instance and
its values
"""
with open(filepath, "r") as f:
lines = f.read().splitlines()
data = []
for line in lines:
data.append(line.split(","))
return data
def separation(instances):
size_train = int((len(instances)) * 2 / 3)
train_dataset = []
test_set = list(instances) # copy the full list
while len(train_dataset) < size_train:
index = random.randrange(len(test_set)) # find the random index to append in train data set
train_dataset.append(test_set.pop(index)) # reduce the size of test set and increase and add the inctances in trainset
return train_dataset, test_set
| true |
1c6666ec14512ddee9fc74a1c5c5384e3a0865ec | cleversongoulart/fatec_20211_ids_introducao_calculadora | /calculadora.py | 517 | 4.125 | 4 | a=int(input("Digite o primeiro inteiro: "))
b=int(input("Digite o segundo inteiro: "))
operacao=input("Escolha a operação:\n (+) soma\n (-) subtração\n (*) multiplicação\n (/) divisão\n (**) exponenciação \n Digite o símbolo da operação escolhida: ")
if(operacao=='+'):
resultado=a+b
elif(operacao=='-'):
resultado=a-b
elif(operacao=='*'):
resultado=a*b
elif(operacao=='/'):
resultado=a//b
elif(operacao=='**'):
resultado=a**b
else:
print("Operação inválida")
print(resultado) | false |
40d611aa7b3363cc767033f6b75ccec10c449c07 | Lem0049/less0n3 | /Lesson4/mnozhestvo.py | 464 | 4.125 | 4 | mnozhestvo1 = {'red','green','blue','yellow'}
mnozhestvo2 = {'green', 'blue', 'brown'}
mnozhestvo1.add('orange')
print(mnozhestvo1)
mnozhestvo2.remove('blue')
print(mnozhestvo2)
a = 5
mnozhestvo3 = mnozhestvo1.copy()
mnozhestvo3.add('cyan')
print(mnozhestvo3)
print(mnozhestvo1 | mnozhestvo3) #объединение множеств
print(mnozhestvo1 & mnozhestvo3) # пересечение
print(mnozhestvo1 - mnozhestvo2) # разность множеств
| false |
902324145120c755d622786b53aac55ecd666314 | medvedodesa/Lesson_Python_Hillel | /My_algorithms/Fibonacci_Nums/fibonacci_recursion_ method.py | 582 | 4.28125 | 4 | # ЧИСЛА ФИБОНАЧЧИ С ПОМОШЬЮ РЕКУРСИИ
# Последовательность: 1, 1, 2, 3, 5, 8, 13, 21, 34, 34, 55, 89, ...
def fibonacci_1(number):
if 0 <= number <= 1:
return number
else:
return fibonacci_1(number - 1) + fibonacci_1(number - 2)
def fibonacci_2(number):
return number if 0 <= number <= 1 else fibonacci_2(number - 1) + fibonacci_2(number - 2)
# Проверяем, что оно работает
num = int(input('Введите любое число: '))
print(fibonacci_1(num))
print(fibonacci_2(num))
| false |
1e477ac3ab739fbb9c3459473a9546f6629ce711 | medvedodesa/Lesson_Python_Hillel | /Lesson_1/task_lesson_1/task_1.py | 1,380 | 4.59375 | 5 | # Задача №1 ("Hello World")
"""
- Скачать и установить Python (Не забываем про установку галочки "Add python to PATH")
- Проверить правильность установки и доступность python.Для этого в консоли (терминале)
вводим комманду: python -V (в ответ должны увидеть соббщение Python 3.x.x - где х.х будут цифры указывающие на версию установленного интерпретатора)
- Скачать и установить среду разработки (IDE) PyCharm
- Создать первый проект.
- Добавить в него новый python файл
- Набрать в этом файле первую программу: print('Hello World!')
- Запустить программу на исполнение
- Убедиться что программа выполнилась без ошибок
"""
print('Hello World')
# Advanced calculator
num1 = float(input('Please, enter first number: '))
num2 = float(input('Please, enter second number: '))
num3 = float(input('Please, enter third number: '))
# We perform operation of adding numbers:
num = num1 + num2 + num3
# Output on display
print("Result is amounts number: " + str(num))
| false |
ccd2ad36f3775d3697aa5b95913cb371047aa272 | vaishalicooner/Practice-Linked-list | /practice_linkedlist/llist_palindrome.py | 484 | 4.15625 | 4 | # Implement a function to check if a linked list is a palindrome.
def is_palindrome(self):
head = self
prev = None
while self.next:
self.prev = prev
prev = self
self= self.next
tail = self
tail.prev = prev
while head is not tail and head.data == tail.data:
head = head.next
tail = tail.prev
if head is tail:
return True
elif head.data == tail.data:
return True
else:
return False | true |
1bf5b7b938d506f0b446fa6b37d74ae6f2d0fbb3 | Maruthees/Python-learning | /For-elif-break-enumerate.py | 965 | 4.1875 | 4 |
#break is for for-loop where it comes out of loop immediately
x="Dhoni is captain"
for i in x:
if i=='i':
print("Sucess")
break
else:
print("Fail")
#To check more conditions use elif
for i in x:
if i=='i':
print("Success we got i")
elif i=='a':
print("Sucess we got a")
else:
print("Fail")
#logical operators use instead of elif
print("Logical operators")
for i in x:
if i=='i' or i=='a':
print("Success we got i OR a")
else:
print("Fail")
#Enumerate provides index & values
#check enumerate
for i in enumerate(x):
print(i)
#Checking enumerate
for i in enumerate(x):
if i=='i':
print('sucess')
else:
print('Fail')
#Since enumerate return index & values we need to use two values for index & values
for i,j in enumerate(x):
print(i ,j)
| false |
8ec1024e7c5c2eb0cce0f7eeef0c8c0fdc572b12 | caitp222/algorithms | /circular_moves.py | 1,022 | 4.15625 | 4 | # http://www.techiedelight.com/check-given-set-moves-circular-not/
# check if a given set of moves is circular or not
def is_circular(str):
possible_directions = ["north", "east", "south", "west"]
current_direction = "north"
co_ords = { "x": 0, "y": 0 }
for char in str:
if char == "M":
if current_direction == "north":
co_ords["y"] += 1
elif current_direction == "east":
co_ords["x"] += 1
elif current_direction == "south":
co_ords["y"] -= 1
elif current_direction == "west":
co_ords["x"] -= 1
elif char == "R":
current_direction = possible_directions[possible_directions.index(current_direction) + 1]
elif char == "L":
current_direction = possible_directions[possible_directions.index(current_direction) - 1]
return co_ords == { "x": 0, "y": 0 }
# both should return true:
print is_circular("MRMRMRM")
print is_circular("MRMLMRMRMMRMM")
| false |
d2637b319939be641a6c2a7c41e65e4aa0c09087 | caitp222/algorithms | /quicksort.py | 396 | 4.125 | 4 | def quicksort(lst):
if len(lst) <= 1:
return lst
else:
pivot = lst[-1]
less = []
more = []
for x in lst:
if x < pivot:
less.append(x)
elif x > pivot:
more.append(x)
return quicksort(less) + [pivot] + quicksort(more)
list_to_sort = [9,-3,5,2,6,8,-6,1,3]
print quicksort(list_to_sort)
| true |
125983d80ed08e174a0b4fa12298dea058c6dbff | tiagoColli/tcc | /oam/preprocess/__init__.py | 1,066 | 4.28125 | 4 | import pandas as pd
def normalize(df: pd.DataFrame, min: int, max: int, weights: dict = None) -> pd.DataFrame:
''' A min-max normalization to all the columns in the dataframe.
If desired you can change the scale of a given column using the 'weights'
param. The weight will be multiplied by every value in the column, given it
more or less importance in the model to be used.
Args:
**df** (pandas.DataFrame): The dataframe to be transformed.
**min** (int): The lower limit of the feature' new range.
**max** (int): The upper limit of the feature's new range.
**weights** (dict): Key should be the column name and value
should be the weight that will multiply it's values.
Returns:
(pd.Dataframe): Transformed dataframe.'''
normalized_df = (df-df.min())/(df.max()-df.min())
X_scaled = normalized_df * (max - min) + min
if weights:
for column, weight in weights.items():
df[column] = df[column] * weight
return X_scaled
| true |
81907a9c79fd38a1eaf3f0f3ca3bcfad2822eed7 | Environmental-Informatics/building-more-complex-programs-with-python-walcekhannah | /program_6.5.py | 553 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Due January 31, 2020
Created on Tue Jan 28 14:49:13 2020
by Hannah Walcek
ThinkPython Exercise 6.5
This program creates the function gcd which finds the greatest common divisor
between two values, a and b.
"""
def gcd(a,b):
"""
This function takes two integers, a and b, and finds their greatest
common divisor.
"""
#when b is 0, the greatest common divisor is a
if b == 0:
return a
#using the remainder (a%b) as the next input for b
else:
return gcd(b, a%b)
| true |
db80e754a496e9bbfe46e4bc6221f88db2881867 | nimesh-p/python | /Programs/prime.py | 368 | 4.25 | 4 | def check_prime_number():
num = int(input("Enter the number to check prime or not: "))
if (num == 1):
return "1 is neither prime nor composite"
elif (num <= 0):
return "Enter valid number"
else:
for number in range(2, num):
if(num % number == 0):
return "Number is not prime"
break
else:
return "Number is prime"
| true |
dde3119b0326f82c7fc6a841a65c743996761905 | EmilyM1/IteratorAndGenerator | /iterateGenerate.py | 2,325 | 4.21875 | 4 | #!/usr/bin/python 3
#counts letters in words
words = """When we speak we are afraid our words will not be heard or welcomed.
But when we are silent, we are still afraid. So it is better to speak.""".split()
print(words)
numberoflettersineachword = [len(word) for word in words]
print(numberoflettersineachword)
#FOR EACH VALUE ON THE RIGHT, EVALUATE ITEMS ON LEFT
numbers = [1,2,4,8]
squares = [number**2 for number in numbers]
print(squares)
#dictionry comp
capitals = {"UK": "London", "Brazil": "Brasilia", "France": "Paris", "Sweden": "Stockholm"}
printcap = [capitals for k,v in capitals.items()]
print(printcap)
printval = [capitals for v in capitals.values()]
print(printval)
listofnumb = [1,2,34]
iterator = iter(listofnumb)
print(next(iterator))
print(next(iterator))
def iterator(listt):
iterate = iter(listt)
try:
return next(iterate)
except StopIteration:
raise ValueError("no more to iterate")
print(iterator([1,2,3]))
print(iterator([1,2,3]))
print(iterator([1,2,3]))
print(iterator([1,2,3]))
#Generators next value on command, need yield, at least once or return with no arg
def generator123():
yield 1
yield 2
yield 3
#returns interable object
g = generator123()
print(g)
print(next(g))
print(next(g))
print(next(g))
for v in generator123():
print(v)
#generator function that counts and teminates at a count
def take(count, iterable):
counter = 0
for item in iterable:
if counter == count:
return
counter +=1
yield item
def runtake():
iterable = [2,4,6,8,10,12]
for iterable in take(2, iterable):
for v in iterable:
print(v)
print(runtake)
print(runtake)
print(runtake)
def fib():
a, b = 0,1
while b < 25:
yield a
a, b, = b, a + b
print(fib())
it = [b for b in fib()]
print(it)
#or use list to print fib
print("list form {}" .format(list(fib())))
adict = dict(a=1, b=2, c=3)
print(adict)
dictcomp = [a for a in adict.items()]
print(dictcomp)
monday = [1,8,15]
tuesday = [2,9,16]
print([temp for temp in zip(monday, tuesday)])
a,b,c = [temp for temp in zip(monday, tuesday)]
print(a,c,b) #unpacking
#count words and show words and count of words in input string
def count_words_in_dictionary(d):
frequency = {}
for word in d.split():
frequency[word] = frequency.get(word, 0) +1
return frequency
print(count_words_in_dictionary("will it work")) | true |
5f4bbef7e4d835b91cd01c0b40820d3ce2b33fb1 | masonbot/Wave-1 | /volumeofcylinder.py | 223 | 4.125 | 4 | import math
pi = math.pi
Height = input("Height of cylinder in metres: ")
Radius = input("Radius of cylinder in metres: ")
r2 = float(Radius) * float(Radius)
area = float(pi) * (r2) * float(Height)
print(round(area,1)) | true |
93aecb1e3e72c0bf869e318fc8bd42a087f4df2f | MTGTsunami/LeetPython | /src/leetcode/graph/union_find/1202. Smallest String With Swaps.py | 1,848 | 4.25 | 4 | """
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.
"""
from collections import defaultdict
class Solution(object):
def smallestStringWithSwaps(self, s, pairs):
"""
:type s: str
:type pairs: List[List[int]]
:rtype: str
"""
class UF:
def __init__(self, n): self.p = list(range(n))
def union(self, x, y): self.p[self.find(x)] = self.find(y)
def find(self, x):
if x != self.p[x]: self.p[x] = self.find(self.p[x])
return self.p[x]
uf, res, m = UF(len(s)), [], defaultdict(list)
for x, y in pairs:
uf.union(x, y)
for i in range(len(s)):
m[uf.find(i)].append(s[i])
for comp_id in m.keys():
m[comp_id].sort(reverse=True)
for i in range(len(s)):
res.append(m[uf.find(i)].pop())
return ''.join(res)
| true |
722ce61e45de006519ae80918965d818eb1a749a | MTGTsunami/LeetPython | /src/leetcode/graph/union_find/547. Friend Circles.py | 1,882 | 4.25 | 4 | """
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.
"""
class UF:
def __init__(self, n):
self.p = list(range(n))
def find(self, x):
if x != self.p[x]:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, x, y):
self.p[self.find(x)] = self.find(y)
class MySolution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
N = len(M)
uf = UF(N)
for i in range(N):
for j in range(i, N):
if M[i][j] == 1:
uf.union(i, j)
group = set()
for i in uf.p:
if uf.find(i) not in group:
group.add(uf.find(i))
return len(group)
| true |
60d9cea1e813483eb57a4383766a61fc3b8d85d8 | selivanovzhukov/Homework1 | /lesson_7/les7_task2.py | 863 | 4.25 | 4 | temp_value = int(float(input('Please enter the value:\n')))
temp_unit = input('Please enter the type:\n')
def temp_calc(temp_value, temp_unit):
if temp_unit == 'K':
k = temp_value
c = temp_value + 273.15
f = int(float((temp_value + 459.67) / 1.8))
print(f'The temperature in Kelvins is {k}, in Celsius is {c}, in Fahrenheits is {f}.')
if temp_unit == 'C':
c = temp_value
k = temp_value - 273.15
f = int(float(temp_value - 32)) / 1.8
print(f'The temperature in Celsius is {c}, in Kelvins is {k}, in Fahrenheits is {f}.')
if temp_unit == 'F':
f = temp_value
k = int(float(temp_value + 459.67) / 1.8)
c = int((temp_value - 32) / 1.8)
print(f'The temperature in Fahrenheits is {f}, in Kelvins is {k}, in Celsius is {c}.')
temp_calc(temp_value, temp_unit)
| false |
29c910f3e2c4c5f71d547c819d2b52cf33c1d6fb | TamishaRutledge/LearningPython | /learning_strings.py | 554 | 4.59375 | 5 | #Learning about strings and string manipulation
strings = "The language of 'Python' is named for Monty Python"
print(strings)
"""
The title method changes each word to title case
Where each word begins with a capital letter
The upper method converts the string to all uppercase
The lower method converts the string to all lowercase
"""
name = "cheddar the dog"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "kevin"
last_name = "holt"
full_name = f"{first_name} {last_name}"
greeting = f"Hello, {full_name.title()}!"
print(greeting)
| true |
b69b7875b640001a743e3d51961b81e6ccf64299 | Whit3bear/yogurt | /katas/5kky_The_Clockwise_Spiral.py | 1,031 | 4.8125 | 5 | """ Do you know how to make a spiral? Let's test it!
Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away as it revolves around the point.
Your objective is to complete a function createSpiral(N) that receives an integer N and returns an NxN two-dimensional array with numbers 1 through NxN represented as a clockwise spiral.
Return an empty array if N < 1 or N is not int / number
Examples:
N = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
1 2 3
8 9 4
7 6 5
N = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
N = 5 Output: [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9 """
def create_spiral(n):
res = []
for i in range(1, n+1):
res.append(i)
return res
print(create_spiral(3))
'[1, 2, 3][8, 9, 4][7, 6, 5]' | true |
e4719f01ead333588f33677263df9745019bbc4c | Whit3bear/yogurt | /katas/6kky_Build_Tower.py | 989 | 4.1875 | 4 | """ Build Tower
Build Tower by the following given argument:
number of floors (integer and always greater than 0).
Tower block is represented as *
Python: return a list;
JavaScript: returns an Array;
C#: returns a string[];
PHP: returns an array;
C++: returns a vector<string>;
Haskell: returns a [String];
Ruby: returns an Array;
Have fun!
for example, a tower of 3 floors looks like below
[
' * ',
' *** ',
'*****'
]
and a tower of 6 floors looks like below
[
' * ',
' *** ',
' ***** ',
' ******* ',
' ********* ',
'***********'
]
Go challenge Build Tower Advanced once you have finished this :)
"""
def tower_builder(n_floors):
result = []
for i in range(1, n_floors+1):
result.append(' '*(n_floors-i) + '*'*(i*2-1) + ' '*(n_floors-i))
return result
print(tower_builder(1))
#['*', ]
print(tower_builder(2))
#[' * ', '***']
print(tower_builder(3))
#[' * ', ' *** ', '*****']
| true |
9c04455fc47972869896529685f7887bb5f79458 | Lcarpio69/Interactive-Python-Temperature-Converter | /myController.py | 1,623 | 4.34375 | 4 | import tkinter
import myView # the VIEW
import myModel # the MODEL
# this is controller class that binds the View and Model classes
class Controller:
"""
The Controller for an app that follows the Model/View/Controller architecture.
When the user presses a Button on the View, this Controller calls the appropriate
methods in the Model. The Controller handles all communication between the Model
and the View.
"""
def __init__(self):
"""
This starts the Tk framework up, instantiates the Model (a Converter object),
instantiates the View (a MyFrame object), and starts the event loop that waits
for the user to press a Button on the View.
"""
root = tkinter.Tk()
self.model = myModel.Converter()
self.view = myView.MyFrame(self)
self.view.mainloop()
root.destroy()
def btnFahrenheitToCelsiusClicked(self):
"""
Python calls this method when the user presses the Fahrenheit To Celsius button in the View.
"""
self.view.txtCelsius.delete(0, 'end')
self.view.txtCelsius.insert(0, self.model.fahrenheitToCelsius(float(self.view.txtFahrenheit.get())))
def btnCelsiusToFarenheightClicked(self):
"""
Python calls this method when the user presses the Celsius To Fahrenheit button in the View.
"""
self.view.txtFahrenheit.delete(0, 'end')
self.view.txtFahrenheit.insert(0, self.model.celsiusTofahrenheit(float(self.view.txtCelsius.get())))
if __name__ == "__main__":
c = Controller()
| true |
f905cfcc20b56b5c3e5c089e878869aa4422b80a | AngelVasquez20/APCSP | /Angel Vasquez - Magic 8 Ball.py | 982 | 4.125 | 4 | import time
import random
answers = ["maybe", "not sure", "could be", "positive", "ask again", "Yes", "no", "Possibly", "Ask later", "I'm tired",
"I don't know", "YESSS", "I think you are"]
name = input("What is your name:")
print("Welcome to Magic 8 Ball %s where you ask a question and the magic ball will answer it for you." % name)
def eight_ball():
track = 0
while True:
time.sleep(1)
print("")
print("%s To end the game you can enter q or quit" % name)
question = input("Type a question to shake the magic 8 ball")
track += 1
print("")
if question == "q" or question == "quit":
print("you have shake the magic ball %d times. Thanks for playing" % track)
return
for i in range(0, 11):
print('Shaking...')
print("")
time.sleep(1)
print(random.choice(answers))
time.sleep(1)
break
eight_ball()
| true |
ead07a51b9790967e90c5cd0e81dffeddd863046 | AngelVasquez20/APCSP | /Challenge 5.py | 212 | 4.15625 | 4 | def rectangle():
length = int(input("Please enter the following length of a rectangle: "))
width = int(input("Please enter the following width of the rectangle: "))
print(length * width)
rectangle() | true |
ea4e20dda65d32fdadcdcaa8035abf5eb452e4b2 | Vakicherla-Sudheethi/Python-practice | /count.py | 215 | 4.21875 | 4 | o=input('Enter a string as input:')
p={}#{} are used to define a dictionary.
for i in set(o):
p[i]=o.count(i)#count() function returns the number of occurrences of a substring in the given string.
print(p)
| true |
00a987fc4606e2298bc57b2286f28353e75e0c0d | Vakicherla-Sudheethi/Python-practice | /lists2.py | 341 | 4.4375 | 4 | colleges=["aec","jntuk","iit",1,2,3,"kkd","surampalem","kharagpur"]
print(colleges)
#data type of colleges
print("data type of colleges",type(colleges))
#modification or change the list name is possible
colleges[1]="pragathi"
print(colleges)
#access list elements by element by using for loop
for i in colleges:
print(i)
| false |
879aa63a51fa2cc436e14df1ecd21f94bd8c3faf | FaDrYL/From0ToPython | /src/Fundamental/Variables_Data_Types/Variables_Data_Types_sample.py | 1,034 | 4.25 | 4 | """
Author: FaDr_YL (_YL_)
"""
print("---int---")
a_int = 10
print(type(a_int))
print("---string---")
a_string = "string"
print(type(a_string))
print(a_string.upper())
print(a_string.index("s"))
# you can try other functions by your own.
print("---format string---")
string_2 = "price: {0}, desc: {1}"
print(string_2.format(10, "Description"))
print("---boolean---")
a_bool = True
print(type(a_bool))
print("---tuple---")
a_tuple = (1, 2)
print(type(a_tuple))
print("---list---")
a_list = [1, 2, 3, 4, 5]
print(type(a_list))
print("---set---")
a_set = {"item1", "item2", "item3", "item1"}
print(type(a_set))
print(a_set)
print("---list to set---")
set_2 = set(a_list)
print(type(set_2))
print("---dictionary---")
a_dict = {'name': "the_item", 'price': 9.95, 'stock': 10}
print(type(a_dict))
print(a_dict["name"])
a_dict["desc"] = "just an item"
a_dict['price'] = 8.5
print(a_dict)
print(a_dict.keys())
print(a_dict.values())
print("---dictionary creation 2---")
dict_2 = {x: x+2 for x in range(3)}
print(dict_2)
| false |
186e12c1d208a7637635ef204bdccf4bd79d0a8b | Iandavidk/Web-development-2021 | /Numerical_grade_to_letter_grade.py | 333 | 4.3125 | 4 | #get user input of a numerical grade
grade = input("Enter your grade: ")
#cast to an int
grade = int(grade)
#test the range of the number and print the appropriate letter grade
if grade >= 90:
print('A')
elif grade >= 80:
print('B')
elif grade >= 70:
print('C')
elif grade >= 60:
print('D')
else:
print('F')
| true |
ccf306f58c97d71600d74907fe1552c2d23aedbb | Iandavidk/Web-development-2021 | /Iterate_over_name.py | 210 | 4.1875 | 4 | name = input("What is your first name?")
letter_count = 0
print(name, "is spelled:")
for x in name:
print(x, end = '')
letter_count += 1
print("")
print(letter_count, "letters in the name", name)
| true |
6af7c1099fabb4e8f14d29224113a35fd252f95d | vivek-x-jha/practiceML | /LogisticRegression/LogisticRegression.py | 1,497 | 4.15625 | 4 | # Implement Logistic Regression from scratch
# Performs Linear Regression (from scratch) using randomized data
# Optimizes weights by using Gradient Descent Algorithm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(0)
features = 3
trainingSize = 10 ** 1
trainingSteps = 10 ** 3
learningRate = 10 ** -2
randFeatures = np.random.rand(trainingSize, features)
flags = np.random.randint(2, size=(trainingSize, 1))
randData = np.concatenate((randFeatures, flags), axis=1)
colNames = [f'f{i}' for i in range(1, features + 1)]
colNames.append('labels')
dummy_column = pd.Series(np.ones(trainingSize), name='f0')
df = pd.DataFrame(randData, columns=colNames)
X = pd.concat([dummy_column, df.drop(columns='labels')], axis=1)
y = df['labels']
thetas = np.random.rand(features + 1)
# cost = lambda thetas: np.mean((np.matmul(X, thetas) - y) ** 2) / 2
# dJdtheta = lambda thetas, k: np.mean((np.matmul(X, thetas) - y) * X.iloc[:, k])
# gradient = lambda thetas: np.array([dJdtheta(thetas, k) for k in range(X.shape[1])])
# # J(theta) before gradient descent
# print(cost(thetas))
# # Perform gradient descent
# errors = np.zeros(trainingSteps)
# for step in range(trainingSteps):
# thetas -= learningRate * gradient(thetas)
# errors[step] = cost(thetas)
# # J(theta) after gradient descent
# print(cost(thetas))
# # Plots Cost function as gradient descent runs
# plt.plot(errors)
# plt.xlabel('Training Steps')
# plt.ylabel('Cost Function')
plt.show()
| true |
9b1d5204cb8a3a1b5aa66d58323feda831bef1da | jackson097/Exam_Calculator | /functions.py | 2,121 | 4.34375 | 4 | """
Determines if the number is a floating point number or not
Parameters: number - the value entered by the user
"""
def is_float(number):
try:
float(number)
return True
except:
return False
"""
Determines if the number provided is a valid float
Parameters: number - the value entered by the user
"""
def is_valid(number):
# Check if the number is a digit
if is_float(number) != False:
if float(number) <= 100 and float(number) >= 0:
return True
return False
"""
Calculate the mark needed on final exam
Parameters: current_mark - the student's current mark (float)
desired_mark - the overall course mark desired by the student (float)
exam_weight - the weight of the exam
"""
def calculate_mark_needed(current_mark, desired_mark, exam_weight):
current_mark = (current_mark * (1-exam_weight))
return (desired_mark - current_mark) / exam_weight
"""
Print human readable results from the calculation
Parameters: mark_needed - the mark needed on exam to achieve desired mark
desired_mark - the overall course mark desired by the student
"""
def print_results(mark_needed, desired_mark):
print_statement = "\nYou will need a {:.2f}% on the final exam to achieve a final mark of {:.2f}%. ".format(float(mark_needed), float(desired_mark))
if mark_needed > 100:
print(print_statement + "You're screwed.")
elif mark_needed >= 90 and mark_needed <= 100:
print(print_statement + "Anything's possible.")
elif mark_needed >= 80 and mark_needed < 90:
print(print_statement + "You can do it!")
elif mark_needed >= 70 and mark_needed < 80:
print(print_statement + "Not too bad.")
elif mark_needed >= 60 and mark_needed < 70:
print(print_statement + "Shouldn't be too hard.")
elif mark_needed >= 50 and mark_needed < 60:
print(print_statement + "Should be a breeze.")
elif mark_needed < 50 and mark_needed > 0:
print(print_statement + "Just show up and you're good.")
elif mark_needed <= 0:
print(print_statement + "Don't even bother...")
else:
print("Error.")
| true |
2ac0e3f7d5bab58c67a46c92d533bd298f1b73e0 | geshkocker/python_hw | /hw5_task1.py | 203 | 4.375 | 4 | for x in range(1,10):
if x % 2 == 0:
print(f'{x} is even')
elif x % 3 == 0:
print(f'{x} is odd')
elif x % 2 != 0 or x % 3 != 0:
print(f'{x} in not divisible')
| false |
2152125ba808c6e177a2dbaf26ed313490f4809b | BrianArb/CodeJam | /Qualification_Round_Africa_2010/t9_spelling.py | 2,859 | 4.1875 | 4 | #!/usr/bin/env python
"""
Problem
The Latin alphabet contains 26 characters and telephones only have ten digits on
the keypad. We would like to make it easier to write a message to your friend
using a sequence of keypresses to indicate the desired characters. The letters
are mapped onto the digits as shown below. To insert the character B for
instance, the program would press 22. In order to insert two characters in
sequence from the same key, the user must pause before pressing the key a second
time. The space character ' ' should be printed to indicate a pause. For
example, 2 2 indicates AA whereas 22 indicates B.
+------+-----+------+
| 1 | 2 | 3 |
| | ABC | DEF |
+------+-----+------+
| 4 | 5 | 6 |
| GHI | JKL | MNO |
+------+-----+------+
| 7 | 8 | 9 |
| PQRS | TUV | WXYZ |
+------+-----+------+
| * | 0 | # |
+------+-----+------+
Input
The first line of input gives the number of cases, N. N test cases follow. Each
case is a line of text formatted as
desired_message Each message will consist of only lowercase characters a-z and
space characters ' '. Pressing zero emits a space.
Output
For each test case, output one line containing "Case #x: " followed by the
message translated into the sequence of keypresses.
Limits
1 < N < 100.
Small dataset
1 < length of message in characters < 15.
Large dataset
1 < length of message in characters < 1000.
Sample
Input
4
hi
yes
foo bar
hello world
Output
Case #1: 44 444
Case #2: 999337777
Case #3: 333666 6660 022 2777
Case #4: 4433555 555666096667775553
"""
import sys
import os
MAP_LETTER = {
' ': '0',
'A': '2', 'B': '22', 'C': '222',
'D': '3', 'E': '33', 'F': '333',
'G': '4', 'H': '44', 'I': '444',
'J': '5', 'K': '55', 'L': '555',
'M': '6', 'N': '66', 'O': '666',
'P': '7', 'Q': '77', 'R': '777', 'S': '7777',
'T': '8', 'U': '88', 'V': '888',
'W': '9', 'X': '99', 'Y': '999', 'Z': '9999'}
TEMPLATE = 'Case #{0}: {1}'
def key_presses(string):
return_value = ''
for c in string.upper():
digits = MAP_LETTER.get(c, None)
if digits is None:
continue
if return_value.endswith(digits[0]):
return_value += ' ' + digits
else:
return_value += digits
return return_value
def tests():
assert key_presses('hi') == '44 444'
assert key_presses('yes') == '999337777'
assert key_presses('foo bar') == '333666 6660 022 2777'
assert key_presses('hello world\n') == '4433555 555666096667775553'
def main(fileobj):
with open(fileobj) as fd:
_number_of_cases = fd.readline()
case_number = 0
for line in fd.readlines():
case_number += 1
string = key_presses(line)
print TEMPLATE.format(case_number, string)
if __name__ == '__main__':
tests()
fileobj = ' '.join(sys.argv[1:])
if os.path.isfile(fileobj):
main(fileobj)
| true |
1aab08b258a9cf37d22bcbd707142377720b906c | mosestembula/andela-day4 | /find_missing.py | 661 | 4.21875 | 4 |
# ============================================================================
# missing number function implementation
# ============================================================================
def find_missing(list_one, list_two):
"""find_missing function
find the missing number between two lists
"""
# check if both lists are empty
if len(list_one) == len(list_two) == 0:
return 0
# check if both lists are similar
if not set(list_one).symmetric_difference(set(list_two)):
return 0
else:
result= list(set(list_one).symmetric_difference(set(list_two)))
for i in result:
return i | true |
501d3a53838105543f4e3ca884061d84096045cb | kkarczewski/Private-Secure-Shell | /tools/fibo/fibo.py | 541 | 4.125 | 4 | #! /usr/bin/env python3.5
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a=0
b=1
while b < n:
print(b)
a,b=b,a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
if __name__ == "__main__":
import sys
if len(sys.argv) <=1 or '-h' in sys.argv:
help_info = 'Fibbonacci numbers'
print("Help message: "+help_info)
else:
fib(int(sys.argv[1]))
| false |
c2f4ea87cbf17bb311b550b701f52e3292e8d910 | MadeleineNyhagen-zz/coursework | /Python/Lynda-Python-Courses/Python GUI Development with tkinter/Ch06_01_pack.py | 1,918 | 4.15625 | 4 | #!/usr/bin/python3
# template.py by Barron Stone
# This is an exercise file from Python GUI Development with Tkinter on lynda.com
from tkinter import *
from tkinter import ttk
root = Tk()
### Using fill and expand properties:
##ttk.Label(root, text = 'Hello, Tkinter!',
## background = 'yellow').pack(fill = BOTH, expand = True) # fill can be X for horizontal, Y for vertical, or BOTH for both
## # expand tells the pack manager to expand it to fill the entire space
##ttk.Label(root, text = 'Hello, Tkinter!',
## background = 'blue').pack(fill = BOTH)
##ttk.Label(root, text = 'Hello, Tkinter!',
## background = 'green').pack(fill = BOTH, expand = True)
# Using side, anchor, pad, and ipad properties: widgets should usually be packed against the same side when using the pack manager
# (If packing against multiple sides, the grid manager is more appropriate)
# anchor uses cardinal directions to anchor a widget
ttk.Label(root, text = 'Hello, Tkinter!',
background = 'yellow').pack(side = LEFT, anchor = 'nw')
ttk.Label(root, text = 'Hello, Tkinter!',
background = 'blue').pack(side = LEFT, padx = 10, pady = 10) # padx & pady add external padding
ttk.Label(root, text = 'Hello, Tkinter!',
background = 'green').pack(side = LEFT, ipadx = 10, ipady = 10) # ipadx & ipady add internal padding
# to create a label that is saved in a variable, it's necessary to create and pack it separately, like this:
label = ttk.Label(root, text = 'Hello, Tkinter!', background = 'red')
label.pack()
print(label) # testing that the label variable actually refers to something
label.pack_forget() # to forget the label, but not destroy it
for widget in root.pack_slaves(): # a loop to apply a style to all widgets that are children of the parent window
widget.pack_configure(fill = BOTH, expand = True)
print(widget.pack_info())
root.mainloop()
| true |
0a987c5193de317a08bd3e0092c28a8129085cef | MadeleineNyhagen-zz/coursework | /Python/Lynda-Python-Courses/Python GUI Development with tkinter/Ch05_05_scrollbar.py | 1,386 | 4.3125 | 4 | #!/usr/bin/python3
# scrollbar.py by Barron Stone
# This is an exercise file from Python GUI Development with Tkinter on lynda.com
from tkinter import *
from tkinter import ttk
root = Tk()
### text with scrollbar:
##text = Text(root, width = 40, height = 10, wrap = 'word')
##text.grid(row = 0, column = 0)
##scrollbar = ttk.Scrollbar(root, orient = VERTICAL, command = text.yview)
##scrollbar.grid(row = 0, column = 1, sticky = 'ns')
##text.config(yscrollcommand = scrollbar.set) # to adjust the scrollbar so that it displays a bar that is proportional to the amount of text being scrolled through
# canvas with scrollbar:
canvas = Canvas(root, scrollregion = (0, 0, 640, 480), bg = 'white')
xscroll = ttk.Scrollbar(root, orient = HORIZONTAL, command = canvas.xview)
yscroll = ttk.Scrollbar(root, orient = VERTICAL, command = canvas.yview)
canvas.config(xscrollcommand = xscroll.set, yscrollcommand = yscroll.set)
canvas.grid(row = 1, column = 0)
xscroll.grid(row = 2, column = 0, sticky = 'ew')
yscroll.grid(row = 1, column = 1, sticky = 'ns')
def canvas_click(event):
x = canvas.canvasx(event.x) # canvasx method translates this event to the correct location on the canvas, despite scrolling
y = canvas.canvasy(event.y) # canvasy method does the same
canvas.create_oval((x-5, y-5, x+5, y+5), fill = 'green')
canvas.bind('<1>', canvas_click)
root.mainloop()
| true |
94cfee2114c031675bad9a6c4a598268c8b65f4a | MadeleineNyhagen-zz/coursework | /Python/Python-in-a-Day/simple_script9.py | 1,943 | 4.34375 | 4 | epic_programmer_dict = {'ada lovelace' : ['lordbyronsdaughter@gmail.com', 111],
'margaret hamilton' : ['asynchronous.apollo@mit.edu', 222],
'grace hopper' : ['commodore.debug@vassar.edu', 333],
'jean jennings bartik' : ['bartik@eniac.mil', 444],
'adele goldstine' : ['goldstine@eniac.mil', 555]}
##print epic_programmer_dict['ada lovelace'][1]
##
### to make a variable that uses a dictionary key/value pair
##programmer = epic_programmer_dict['ada lovelace']
##print programmer[1]
##
### use raw input to have user input a name
##personsName = raw_input('Please enter a name: ').lower()
##
### to take name inputted and compare it to dictionary
##personsInfo = epic_programmer_dict[personsName]
def searchPeople(personsName):
# looks up the name in the epic dictionary
try:
# tries the following lines of texts and if there are no errors then it runs
personsInfo = epic_programmer_dict[personsName]
print 'Name: ' + personsName.title()
print 'Email: ' + personsInfo[0]
print 'Number: ' + str(personsInfo[1])
except:
# if there are errors, then this code gets run
print 'No information found for that name'
userWantsMore = True
while userWantsMore == True:
# asks user to input persons name
personsName = raw_input('Please enter a name: ').lower()
# run our new function searchPeople with what was typed in searchPeople(personsName)
searchPeople(personsName)
# see if user wants to search again
searchAgain = raw_input('Search again? (y/n) ')
# look at what they reply and act accordingly
if searchAgain == 'y':
# userWantsMore stays as true so loop repeats
userWantsMore = True
elif searchAgain == 'n':
# userWantsMore turns to false to stop loop
userWantsMore = False
else:
# user inputs an invalid response so we quit anyway
print "I don't understand what you mean, quitting"
userWantsMore = False
| true |
fa8119fbd9a657952ef79880744cdcfad6a0f758 | HugoSantiago/Quickest-Way-Up | /Dijkstra/dijkstra.py | 2,313 | 4.1875 | 4 | # Python3 implementation to find the
# shortest path in a directed
# graph from source vertex to
# the destination vertex
infi = 1000000000
# Function to find the distance of
# the node from the given source
# vertex to the destination vertex
def dijkstraDist(g, s, path):
# Stores distance of each
# vertex from source vertex
dist = [infi for i in range(len(g))]
# bool array that shows
# whether the vertex 'i'
# is visited or not
visited = [False for i in range(len(g))]
for i in range(len(g)):
path[i] = -1
dist[s] = 0
path[s] = -1
current = s
# Set of vertices that has
# a parent (one or more)
# marked as visited
sett = set()
while (True):
# Mark current as visited
visited[current] = True
for i in range(len(g[current].children)):
v = g[current].children[i].first;
if (visited[v]):
continue
# Inserting into the
# visited vertex
sett.add(v)
alt = dist[current] + g[current].children[i].second
# Condition to check the distance
# is correct and update it
# if it is minimum from the previous
# computed distance
if (alt < dist[v]):
dist[v] = alt
path[v] = current;
if current in sett:
sett.remove(current);
if (len(sett) == 0):
break
# The new current
minDist = infi
index = 0
# Loop to update the distance
# of the vertices of the graph
for a in sett:
if (dist[a] < minDist):
minDist = dist[a]
index = a;
current = index;
return dist
# Function to print the path
# from the source vertex to
# the destination vertex
def printPath(path, i, s):
if (i != s):
# Condition to check if
# there is no path between
# the vertices
if (path[i] == -1):
print("Path not found!!")
return;
printPath(path, path[i], s)
print(path[i] + " ")
| true |
b9b20a0d8fb550b18852a1b063e8e006f6c50833 | jpragasa/Learn_Python | /Basics/3_Variables.py | 385 | 4.28125 | 4 | greeting = "This is stored in greeting"
#Basic data types
#Integer: numbers with no decimals
#Float: numbers with decimals
a = 5
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b) #The 2 slashes mean the number is returned as an integer
print(a % b)
for i in range(1, a // b):
print(i)
c = a + b
d = c / 3
e = d - 4
print(e * 12) | true |
c5f658bb8e497c1563f0bbaf249c2f978c2d33ab | micaswyers/Advent | /Advent2015/16/day16.py | 2,311 | 4.15625 | 4 | from collections import defaultdict
TARGET_SUE = {
'children': 3,
'cats': 7,
'samoyeds': 2,
'pomeranians': 3,
'akitas': 0,
'vizslas': 0,
'goldfish': 5,
'trees': 3,
'cars': 2,
'perfumes': 1,
}
# Part 1
def parse_input():
"""Returns dict mapping Sue # to item & counts dict
ex) {500: {'cats': 2, 'goldfish': 9, 'children': 8}}
"""
sues = defaultdict(lambda: {})
with open('input.txt') as f:
for line in f:
words = line.split()
words = [word.strip(':,') for word in words]
num_sue = int(words[1])
items_counts = [word.strip(':,') for word in words[2:]]
sues[num_sue][items_counts[0]] = int(items_counts[1])
sues[num_sue][items_counts[2]] = int(items_counts[3])
sues[num_sue][items_counts[4]] = int(items_counts[5])
return sues
def find_sue(sues_dict):
"""Returns list containing numbers of possible Aunt Sues
Args:
sues_dict: dict mapping number to dict of known possessions & counts
Returns:
int representing possible Aunt Sue match
"""
possible_sue = None
for num_sue, items in sues_dict.iteritems():
possible_match = []
for item, number in items.iteritems():
if number == TARGET_SUE[item]:
possible_match.append(True)
if len(possible_match) == 3:
return num_sue
# Part 2
def find_sue2(sues_dict):
"""Returns list containing numbers of possible Aunt Sues
Args:
sues_dict: dict mapping number to dict of known possessions & counts
Returns:
int representing possible Aunt Sue match
"""
for num_sue, items in sues_dict.iteritems():
possible_match = []
for item, number in items.iteritems():
if item not in ['cats', 'trees', 'pomeranians', 'goldfish'] and number == TARGET_SUE[item]:
possible_match.append(True)
elif item in ['cats', 'trees'] and number > TARGET_SUE[item]:
possible_match.append(True)
elif item in ['pomeranians', 'goldfish'] and number < TARGET_SUE[item]:
possible_match.append(True)
if len(possible_match) == 3:
return num_sue
| false |
c0e7ca6c23d2cfd041c3e1d5663ef9724bd3af54 | SharmaSwapnil/Py_Stats_Scripts | /HR_StringUpdate.py | 375 | 4.15625 | 4 | def count_substring(string, sub_string):
counter = []
for i in range(len(string)):
ss = string.count(sub_string,i,i+len(sub_string))
counter.append(ss)
return sum(counter)
if __name__ == '__main__':
string = input("Enter string ").strip()
sub_string = input("Enter substring ").strip()
count = count_substring(string, sub_string)
print(count) | true |
032f6f4b8860955361d854b7134fd13ca3670691 | inbalalo/Python | /hw1_question1.py | 541 | 4.25 | 4 | def trifeca(word):
"""
Checks whether word contains three consecutive double-letter pairs.
word: string
returns: bool
"""
for i in range(0, len(word)):
if (len(word)-i) >= 6:
if word[i] == word[i+1] and word[i+2] == word[i+3] and word[i+4] == word[i+5]:
return True
else:
return False
if __name__ == '__main__':
# Question 1
param1 = 'hjjkaabbccgh'
return_value = trifeca(param1)
print(f"Question 1 solution: {return_value}") | true |
cb1688a038336a2725b06870130b2d5d5754fc10 | Shopzilla-Ops/python-coding-challenge | /calculator/mjones/calculator.py | 1,477 | 4.25 | 4 | #!/usr/bin/python2.7
'''A simple interactive calculator'''
import sys
def add(num1, num2):
'''Add two numbers'''
res = num1 + num2
return res
def sub(num1, num2):
'''Subtract one number from another'''
res = num1 - num2
return res
def mult(num1, num2):
'''Multiply two numbers'''
res = num1 * num2
return res
def div(num1, num2):
'''Divide one number by another'''
res = num1 / num2
return res
def calculate(calc_buffer):
'''Do the math'''
num1 = float(calc_buffer[0])
num2 = float(calc_buffer[2])
oper = calc_buffer[1]
if oper == '+':
res = add(num1, num2)
elif oper == '-':
res = sub(num1, num2)
elif oper == '*':
res = mult(num1, num2)
elif oper == '/':
res = div(num1, num2)
else:
print "Invalid operator: %s" % oper
sys.exit(2)
return str(res)
if __name__ == "__main__":
'''Main loop'''
last = ''
calc_buffer = []
print "Let's start!"
while True:
try:
input_var = str(raw_input("{%s} " % last))
if input_var == '=':
break
calc_buffer.append(input_var)
if len(calc_buffer) == 3:
res = calculate(calc_buffer)
calc_buffer = [res, ]
last = res
else:
last = input_var
except KeyboardInterrupt:
break
print "\nFinal Result: %s\n" % last
| false |
0b2f4e73efe111b9e87707f5c9a81c62f6f8db20 | lipanlp/Python-crawler-learning | /class learning.py | 1,791 | 4.25 | 4 | class student():
def speak(self):
print('%s 说我是一个%s岁的%s生' % (self.name,self.age,self.gender))
lipan=student()
lipan.name="帅哥"
lipan.age="15"
lipan.gender="男"
lipan.speak()
#>>>帅哥 说我是一个15岁的男生
#学习类(class)相关实践
#2020年2月18日15:16:19
class teacher():
def __init__(self,name,age,height):
self.name=name
self.age=age
self.height=height
def introduce(self):
print('%s是一名%s岁%sM高的老师' % (self.name,self.age,self.height))
Zhouxiaowu=teacher('傻逼','50','1.6')
Zhouxiaowu.introduce()
#>>>傻逼是一名50岁1.6M高的老师
#学习类class中init的应用,用于方便地自己对类的属性进行定义
#其中下划线开头的函数是声明该属性为私有,不能在类的外部被使用或访问
#2020年2月18日15:21:59
class boy(object):
def __init__(self, n, a):
# 设置属性
self.name = n
self.age = a
# 输出一个字符串(追踪对象属性信息变化)
def __str__(self): # __str__(self)不可以添加参数(形参)
return "名字:%s 年龄:%d" % (self.name, self.age)
# 实例化一个对象john
john = boy("约翰", 19)
# 当使用print输出对象时,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
print(john)
# >>>名字:约翰 年龄:19
class test():
def __init__(self,n):
self.name=n
def say(self):
print('名字是%s' % self.name)
def __del__(self):
print("实例%s已销毁"% self.name)
sb=test('sb')
sb.say()
print('---------------------')
del sb
sb.say()
#print()
#有关__del__的应用和用法试验 | false |
e458a1e97a36eb70d0d602bc920f58d16cca0b9a | Dsgra/python_examples | /ExamplesWordCount.py | 945 | 4.125 | 4 | #!/usr/bin/python
#The code used below will return the content of a file from the directory
# in fact it will do with any file.
f = open("example.txt", "r")
data = f.read()
f.close()
print(data)
# Another example below will show a more complex data readed structure
f = open("New_File_Reading.txt", "r")
data = f.read()
f.close()
# In my case the data.split("") should include , as delimiter since it is used in the file
words = data.split(",") # This \n will return number of lines by new lines
print("The words in the text are:")
print(words)
num_words = len(words)
print("The number of words is:", num_words)
lines = data.split("\n")
print("The lines in the text are:")
print(lines)
print("The number of lines is", len(lines))
#Display a list containing the number from 0 to 4 in a range of 5
#for i in range(5):
#print(i)
for l in lines:
if not l:
lines.remove(l)
if not 1:
lines.remove(1)
| true |
47b16887879d2f6631c7e47b10f4ba87a02606d8 | practicerkim/lpthw | /ex33a.py | 940 | 4.4375 | 4 | # -*- coding: utf-8 -*-
def make_array(array_length, incre):
i = 0
numbers = []
print '\nfunction using while statement'
while i < array_length:
numbers.append(i)
i = i + incre
print numbers
print "\n"
def make_array_using_for(array_length, incre):
i = 0
numbers = []
print '\nfunction using for statement'
for i in range(0,array_length):
numbers.append(i)
print numbers
i = i + incre
print '\n'
a = int(raw_input('length of array: '))
b = int(raw_input('increment option: '))
make_array(a,b)
make_array_using_for(a,b)
#"""
#while i < 6:
# print "at the top i is %d" % i
# i+=1
# numbers.append(i)
# print "list: numbers[] %s" % numbers
# print '???n'
# print "at the bottom i is %d" % i
#print "the numbers"
#for a in numbers:
# print a
#print '???n'
#print numbers
#"""
| false |
b0ad65d0f6dfc06546385afa9a7f69bfe3cc017d | vineeta786/geeksForGeeks_python | /String/Stng functions - II.py | 315 | 4.3125 | 4 | #User function Template for python3
# Function to check if string
# starts and ends with 'gfg'
def gfg(a):
b = a.lower()
if((b.startswith('gfg') or b.startswith('GFG')) and b.endswith('gfg') or b.endswith('GFG')): # use b.startswith() and b.endswith()
print ("Yes")
else:
print ("No") | true |
fcdae2fbe26fdc25a813d3e14e72d358903c78aa | super-aardvark/project-euler | /problem-001-100/problem-011-020/problem-015.py | 951 | 4.1875 | 4 | '''
Created on Jan 10, 2017
@author: jfinn
'''
def paths_through_lattice(grid_size):
# Problem defines the grid size as the number of squares. Add one to get the number of intersections.
grid_size += 1
# We'll track the number of different paths that may be taken to get to each node
nodes = [ [ 0 for col in range(grid_size) ] for row in range(grid_size) ]
# Always 1 path to the first node (we start there)
nodes[0][0] = 1
# For each path to a given node, that many paths are added to any node reachable from there
for row in range(grid_size):
for col in range(grid_size):
if row < grid_size - 1:
nodes[row+1][col] += nodes[row][col]
if col < grid_size - 1:
nodes[row][col+1] += nodes[row][col]
return nodes[-1][-1]
print(paths_through_lattice(1))
print(paths_through_lattice(2))
print(paths_through_lattice(20)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.