blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3f9247d1c7d9538a20aa26e1dae4736284fc6b4c | mgoldstein32/python-the-hard-way-jupyer-notebooks | /ex15.py | 483 | 4.375 | 4 | #importing arguments
#assigning variables to said arguments
print "Type the filename:"
#assigning a variable called "txt" as the file being opened
txt = raw_input("> ")
#printing out the file
print "Here's your file %r" %txt
filename = open(txt)
print filename.read()
#doing it again with a different variable
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
filename.close()
txt_again.close()
| true |
9407a8304b4a4236ddc45934aea4b91bbe7da0d4 | cloudmesh-community/sp19-222-89 | /project-code/scripts/read_data.py | 1,003 | 4.21875 | 4 | #this function is meant to read in the data from the .csv file and return
#a list containing all the data. It also filters out any rows in the
#data which include NaN as either a feature or a label
"""Important note: when the data is read using the csv.DictReader,
the order of the features is changed from the original. In the
list of dictionaries, the order of features is as follows:
ISOS_Size_x, ISOS_Size_y, COST_Size_y, COST_Size_x, Coord_y, Coord_x,
ISOS_z, COST_z, Cone_Type"""
import csv
import math
def read(fpath):
#make file object
with open(fpath) as f_obj:
#make reader object
reader = csv.DictReader(f_obj, delimiter=',')
#make data list
data = []
#boolean nan to store if there's a non value or not
for row in reader:
nan = 0
for i in row.items():
if(i[1] == "NaN"):
nan = 1
if(nan == 0):
data.append(row)
return data
| true |
78ee951a2cd1745691f28bc36e674c358792a8b2 | jurentie/python_crash_course | /chapter_3/3.8_seeing_the_world.py | 420 | 4.40625 | 4 | places_to_visit = ["Seattle", "Paris", "Africa", "San Francisco", "Peru"]
print(places_to_visit)
# Print in alphabetical order
print(sorted(places_to_visit))
# Show that list hasn't actually been modified
print(places_to_visit)
# Print list in reverse actually changing the list
places_to_visit.reverse()
print(places_to_visit)
# Sort list and actually change the list
places_to_visit.sort()
print(places_to_visit)
| true |
3a69957eac67a12c16cf6e5bb2c28eb7dc87a950 | HaoMood/algorithm-data-structures | /algds/ds/deque.py | 1,541 | 4.28125 | 4 | """Implementation of a deque.
Queue is an ordered collection of items. It has two ends, a front and a rear.
New items can be added at either the front or the rear. Likewise, existing items
can be removed from either end. It provides all the capabilities of stacks and
queues in a single data structure.
"""
from __future__ import division, print_function
__all__ = ['Deque']
__author__ = 'Hao Zhang'
__copyright__ = 'Copyright @2017'
__date__ = '2017-07-26'
__email__ = 'zhangh0214@gmail.com'
__license__ = 'CC BY-SA 3.0'
__status__ = 'Development'
__updated__ = '2017-07-26'
__version__ = '1.0'
class Deque(object):
"""Implementation of a deque.
We will use list to build the internal representation of the deque.
Attributes:
_items (list)
>>> d = Deque()
>>> d.isEmpty()
True
>>> d.addRear(4)
>>> d.addRear('dog')
>>> d.addFront('cat')
>>> d.addFront(True)
>>> d.size()
4
>>> d.isEmpty()
False
>>> d.addRear(8.4)
>>> d.removeRear()
8.4
>>> d.removeFront()
True
"""
def __init__(self):
self._items = []
def isEmpty(self):
return self._items == []
def size(self):
return len(self._items)
def addRear(self, x):
self._items.insert(0, x)
def addFront(self, x):
self._items.append(x)
def removeRear(self):
return self._items.pop(0)
def removeFront(self):
return self._items.pop()
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
test()
| true |
bca0941d748df7a79930774c1e57287ddbfdc8e9 | sylwiam/ctci-python | /Chapter_4_Trees_Graphs/4.2-Minimal-Tree.py | 883 | 4.125 | 4 | """
Given a sorted (increasing order) array with unique integer elements, write
an algorithm to create a binary search tree with minimal height.
"""
from binary_tree import BinaryTree
# @param li a list of sorted integers in ascending order
# @param start starting index of list
# @param end ending index of list
def create_minimal_bst(li, start, end):
if end < start:
return None
# get the middle element of the list
middle = (start + end) / 2
n = BinaryTree(li[middle])
n.left = create_minimal_bst(li, start, middle-1)
n.right = create_minimal_bst(li, middle+1, end)
# root = BinaryTree(li[middle], create_minimal_bst(li, start, middle-1), create_minimal_bst(li, middle+1, end))
return n
if __name__ == '__main__':
binary_search_tree = create_minimal_bst([2,4,6,7,92,101,333,334,888], 0, 8)
print binary_search_tree
| true |
6767de31ed8eea4e1c0489ed5a1a7ad3b0f9bca7 | sylwiam/ctci-python | /Chapter_2_Linked_Lists/2.7_Intersection.py | 2,760 | 4.15625 | 4 | """
2.7 Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the inresecting node.
Note that the intersection is defined based on reference, not value.
That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the
second list, then they are intersecting.
For example, the following two linked lists:
A: a1 -> a2 -> c1 -> c2 -> c3
B: b1 -> b2 -> b3 -> c1 -> c2 -> c3
begin to intersect at node c1.
Notes:
* If two linked lists have no intersection at all, return None.
* The linked lists must retain their original structure after the function returns
* You may assume there are no cycles anywhere in the entire linked structure
* Your code should preferably run in O(n) time and use only O(1) memory.
"""
from MyLinkedList import LinkedList, Node
def get_intersection_node(headA, headB):
# figure out the difference in length of the two linked lists
# then use that information to traverse the two lists in sync looking out
# for when there is an intersection
# O(n)
listA_length = 0
listB_length = 0
current_node = headA
while current_node: # get size/length of list A
listA_length = listA_length + 1
tailA = current_node
current_node = current_node.next
print "list A tail: ", tailA.data
current_node = headB
while current_node: # get size/length of list B
listB_length = listB_length + 1
tailB = current_node
current_node = current_node.next
print "list B tail: ", tailB.data
if tailA.data != tailB.data:
return None
if listA_length > listB_length:
longest = headA
shorter = headB
else:
longest = headB
shorter = headA
difference = abs(listA_length - listB_length)
print "difference: ", difference
listA_index = 0
listB_index = 0
current_node = longest
while listA_index < difference:
current_node = current_node.next
listA_index = listA_index + 1
intersection = None
current_other_node = shorter
while current_other_node:
if current_other_node == current_node:
intersection = current_other_node
break
current_other_node = current_other_node.next
current_node = current_node.next
return intersection
if __name__ == '__main__':
lA = LinkedList()
lA.insert('c3')
lA.insert('c2')
lA.insert('c1')
lA.insert('a2')
lA.insert('a1')
lB = LinkedList()
lB.insert('c3')
lB.insert('c2')
lB.insert('c1')
lB.insert('b4')
lB.insert('b3')
lB.insert('b2')
lB.insert('b1')
print "list A size: ", lA.get_size()
print "list A head: ", lA.head.data
lA.print_list2(lA.head)
print "list A size: ", lB.get_size()
print "list A head: ", lB.head.data
lA.print_list2(lB.head)
print get_intersection_node(lA.head, lB.head)
# print 'middle', lA.find_middle(lA.head) | true |
76375c4530dc177c5587eeace5e53a23df692f1e | ghj3/lpie | /untitled14.py | 691 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 22:13:36 2018
@author: k3sekido
"""
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for c in list(secretWord):
if c not in lettersGuessed:
return False
return True
secretWord = 'durian'
lettersGuessed = ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u']
print(isWordGuessed(secretWord, lettersGuessed))
| true |
dbf9328fd348044e9dda97a75e7a0ca4312ef1e4 | augustoscher/python-excercises | /hacking/picking-numbers.py | 619 | 4.25 | 4 | #
# Given an array of integers, find and print the maximum number of integers you can select
# from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1
#
# Ex:
# a = [1,1,2,2,4,4,5,5,5] -> r1 = [1,1,2,2] and r2 = [4, 4, 5, 5, 5]
# result would be 5 (length of second array)
#
# Complete the 'pickingNumbers' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#
def pickingNumbers(a):
return max([sum((a.count(i), a.count(i+1))) for i in set(a)])
print(pickingNumbers([4, 6, 5, 3, 3, 1])) | true |
b79bcd4bc7ae9fc8fc1c6d38e0ddc20a55e33ff6 | piwan/PyTemperature | /temperature.py | 2,082 | 4.1875 | 4 | class Temperature:
"""Temperature conversion and presentation class"""
def __init__(self, celsius=0):
"""
Construct new Temperature
:param celsius: temperature value in Celsius
"""
self.celsius = celsius
@property
def celsius(self):
"""Temperature value in Celsius degrees"""
return self._value
@celsius.setter
def celsius(self, value):
if (value < -273):
raise AbsoluteZeroError(value)
else:
self._value = value
@property
def fahrenheit(self):
"""Temperature value in Fahrenheit degrees"""
return (self.celsius * 9 / 5) + 32
@fahrenheit.setter
def fahrenheit(self, value):
self.celsius = (value - 32) * 5 / 9
@property
def kelvin(self):
return self.celsius + 273.15
@kelvin.setter
def kelvin(self, value):
self.celsius = value - 273.15
def __eq__(self, other):
return self.celsius == other.celsius
def __lt__(self, other):
return self.celsius < other.celsius
def __le__(self, other):
return self.celsius <= other.celsius
def __add__(self, other):
return Temperature(self.celsius + other.celsius)
def __sub__(self, other):
return Temperature(self.celsius - other.celsius)
def __mul__(self, other):
return Temperature(self.celsius * int(other))
def __truediv__(self, other):
return Temperature(self.celsius / int(other))
def __abs__(self):
return Temperature(abs(self.celsius))
def __int__(self):
return self.celsius
def __repr__(self):
return f'{self.celsius}°C = {self.fahrenheit}°F = {self.kelvin}K'
class AbsoluteZeroError(Exception):
"""An exception thrown when the value is below absolute zero (-273 Celsius)"""
def __init__(self, value):
"""
Create new exception
:param value the value that is lower than absolute zero point
"""
super().__init__(f'Value {value} is below absolute zero point')
| false |
ac73357099eec0d42992610677661f1ee21cea38 | pokemonball34/PyGame | /quiz.py | 1,378 | 4.59375 | 5 | # A Function that asks for the initial temperature type and converts it from Celsius to Fahrenheit or vice versa
def temperature_type_def(temperature_type):
# Conditional to check if user typed in C or c to convert from C -> F
if temperature_type == 'C' or temperature_type == 'c':
# Asks the user for the temperature value
temperature = float(input('Please input the temperature value: '))
# Returns the converted value
return print(str(temperature) + "C is " + str(temperature * 1.8 + 32) + "F.")
# Conditional to check if user typed in F or f to convert from F -> C
elif temperature_type == "F" or temperature_type == "f":
# Asks the user for the temperature value
temperature = float(input('Please input the temperature value: '))
# Returns the converted value
return print(str(temperature) + "F is " + str((temperature - 32) / 1.8) + "C.")
# Recursion to reset the program if the user written an error
else:
# Prints the console that an error has occured
print('ERROR, Please try again')
# Restarts the function
return temperature_type_def(input('Please input the temperature type you are converting from (Type C or F): '))
# Calls the function
temperature_type_def(input('Please input the temperature type you are converting from (Type C or F): ')) | true |
9b5504ebd01228f23fbb55d87c0c29eb942ab25b | bwayvs/bwayvs.github.io | /Ch5_milestone.py | 2,589 | 4.15625 | 4 | print()
print("You wake up to find yourself trapped in a deep hole. How will you get out?")
print()
look = input("Type LOOK UP or LOOK DOWN for more details: ")
print()
if look.upper() == "LOOK UP":
print()
print("You see a pull string attached to the ceiling.")
pull_string = input("Maybe you should PULL STRING to find out what happen: ")
if pull_string.upper() == "PULL STRING":
print()
print("You pull the string and you hear a **CLICK*")
print()
print("A trap door opens under you and you fall down a slide.")
print(".")
print(".")
print(".")
print(".")
print("It is a long slide!")
print(".")
print(".")
print(".")
print(".")
print("You land comfortably in your own bed.")
print()
print("Was that all just a bizarre dream?")
print()
else:
print()
print("You can't do that here.")
elif look.upper() == "LOOK DOWN":
print()
print("You see a trap door on the ground.")
print()
open_trap = input("Maybe your should OPEN TRAP to see what happens: ")
if open_trap.upper() == "OPEN TRAP":
print()
print("You try to open the trap door, but it won't budge.")
look_up4 = input("Maybe LOOK UP to see if there is anything to help you: ")
if look_up4.upper() == "LOOK UP":
print()
print("You see a pull string attached to the ceiling.")
pull_string = input("Maybe you should PULL STRING to find out what happen: ")
if pull_string.upper() == "PULL STRING":
print()
print("You pull the string and you hear a **CLICK*")
print()
print("A trap door opens under you and you fall down a slide.")
print(".")
print(".")
print(".")
print(".")
print("It is a long slide!")
print(".")
print(".")
print(".")
print(".")
print("You land comfortably in your own bed.")
print()
print("Was that all just a bizarre dream?")
else:
print()
print("You can't do that here.")
else:
print()
print("You can't do that here.")
else:
print()
print("You can't do that here.")
else:
print()
print("You can't do that here.") | true |
3fa2cc87a45bc022d7f44fcf173dcc8b028d950e | FarnazO/Simplified-Black-Jack-Game | /python_code/main_package/chips.py | 900 | 4.1875 | 4 | '''
This module contains the Chips class
'''
class Chips():
'''
This class sets the chips with an initial chip of 100 for each chip object
It contains the following properties:
- "total" wich is the total number of chips, initially it is set to 100
It also contains the following methods:
- "win_bet" which adds the won chips to the total existing chips
- "lose_bet" which removes the lost chips from the total existing chips
'''
def __init__(self):
'''
Inititalises the chip object
'''
self.total = 100
def win_bet(self, bet):
'''
Adds the beted chips to the total chips
'''
self.total += bet
return self.total
def lose_bet(self, bet):
'''
Takes away the beted chips from the total chips
'''
self.total -= bet
return self.total
| true |
efd5e6e4fdaa571aea4b16c99e84e6fc3046a544 | N-SreeLatha/operations-on-matrices | /append.py | 371 | 4.375 | 4 | #appending elements into an array
import numpy as np
a=np.array(input("enter the elements for the first array:"))
b=np.array(input("enter the elements for the second array:"))
print("the first array is:",a)
print ("the second array is:",b)
l=len(b)
for i in range(0,l):
a=np.append(a,b[i])
print("the new array formed by appending the terms in array b into array a:",a)
| true |
cc1ca54cd720e9403f2bdf20ccde569838a37ffb | siddharth952/DS-Algo-Prep | /Pep/LinkedList/basic.py | 856 | 4.34375 | 4 |
# single unit in a linked list
class Element(object):
def __init__(self,value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
# If we establish a new LinkedList without a head, it will default to None
self.head = head
def append(self, new_element):
current = self.head
if self.head:
# LinkedList already has a head, iterate through the next reference in every Element until you reach the end of the list
while current.next:
current = current.next
# Set next for the end of the list to be the new_element
current.next = new_element
else:
# there is no head already, you should just assign new_element to it and do nothing else
self.head = new_element | true |
89a86ec738390178a218821719f3959213d0f1ad | R-Tomas-Gonzalez/python-basics | /list_intro_actions_methods.py | 2,863 | 4.53125 | 5 | #lists are pretty much arrays with some differences
#collections of items
#lists are Data Structures
li = [1,2,3,4,5]
li2 = ['a', 'b', 'c']
li3 = [1,2,'a',True]
# Data Structures - A way for us to organize info and data
#Shopping Cart Example
shopping_cart = [
'notebooks',
'sunglasses',
'toys',
'grapes'
]
#Accessing Cart
#prints the entire shopping_cart
print(shopping_cart)
#prints the first index of the shopping_cart
print(shopping_cart[0])
#prints the last index of the shopping_cart
print(shopping_cart[len(shopping_cart)-1])
#changing the original arrays
# shopping_cart[0] = 'laptop'
print(shopping_cart)
#list slicing creates a copy of the original list
new_cart = shopping_cart[:]
new_cart[0] = 'laptop'
print(new_cart)
##################################################
#Actions
#finding the length of a list
basket = [1,2,3,4,5]
# print(len(basket)) #5
#METHODS
#ADDING to lists
#append method
#adds to the end of the list
basket.append(100)
# print(basket)
#insert method
#inserts into list where you specify, in this case, inserts 100 into index 1
# basket.insert(1, 100)
# print(basket)
#extending a list
#takes an iterable(another list) and appends it to the end
# basket.extend([100,101])
# print(basket)
#REMOVING from lists
#pop method
#removes the last index of the list and returns the value
# basket.pop()
# #you can specify an index to remove in the index
# basket.pop(0)
# print(basket)
#remove method
#you specify what value you'd like to remove
# basket.remove(1)
# print(basket)
#clear method
#clears out the list
basket.clear()
print(basket)
##################################################
#Methods
basket = ['a','b','c','d','e']
#index method
#provides the index of the value you specify
#you can also specify which indexes to search(start and stop) within the list
# print(basket.index('c',0,4))
#in keyword
# print('b' in basket) #true
# print('x' in basket) #false
#count method
#counts how many times a value occurs in a list
# print(basket.count('d'))
#sort method
#sorts the list from a-z and modifies the original array
# basket = ['x', 'b', 'a', 'c', 'd', 'e', 'd']
# basket.sort()
# print(basket)
#sorted method
#sorts the list from a-z but makes a copy and doesn't modify the original
# basket = ['x', 'b', 'a', 'c', 'd', 'e', 'd']
# new_basket = sorted(basket)
# print('the new basket:', new_basket)
# print('the original basket:', basket)
#reverse method
#reverses the list without sorting
# basket.reverse()
# print(basket)
#join method
#joins the values in a list to make a string
# new_sentence = ' '.join(['hello', 'my', 'age', 'is', str(28)])
# print(new_sentence)
#list unpacking
#this allows you to assign a variable to individual values in a list. you can also section off certain groups of values
a,b,c,*other,d,e = [1,2,3,4,5,6,7,8,9]
print(a,b,c,other,d,e)
| true |
3884eb54e7e03a3ef48250ac38e73501f51b3ad0 | bommankondapraveenkumar/PYWORK | /code47.py | 1,282 | 4.125 | 4 | def horoscope():
M=input("enter the month and date :\n")
S=M.split()
month=S[0]
day=int(S[1])
print("YOUR ZODIAC SIGN IS:")
if(month=="december"):
if(day>21):
print("Capricorn")
else:
print("sagittarius")
elif(month=="january"):
if(day>19):
print("aquarius")
else:
print("capricorn")
elif(month=="february"):
if(day>19):
print("Pisces")
else:
print("aquarius")
elif(month=="march"):
if(day>20):
print("Aries")
else:
print("Pisces")
elif(month=="april"):
if(day>19):
print("Taurus")
else:
print("Aries")
elif(month=="may"):
if(day>20):
print("Gemini")
else:
print("Taurus")
elif(month=="june"):
if(day>20):
print("cancer")
else:
print("Gemini")
elif(month=="july"):
if(day>22):
print("Leo")
else:
print("cancer")
elif(month=="august"):
if(day>22):
print("Virgo")
else:
print("Leo")
elif(month=="september"):
if(day>22):
print("Libra")
else:
print("Virgo")
elif(month=="october"):
if(day>22):
print("Scorpio")
else:
print("Lobra")
elif(month=="november"):
if(day>21):
print("Sagittarius")
else:
print("Scorpio")
else:
print("please enter a valid month and date")
horoscope() | false |
a71b77d255c9db65dc6e6bd7dffb6683494eb31d | bommankondapraveenkumar/PYWORK | /code45.py | 510 | 4.21875 | 4 | def squarecolor():
letter=input("enter the letter")
number=int(input("enter the number"))
evencolum=['b','f','d','h']
oddcolum=['a','c','e','g']
evenrow=[2,4,6,8]
oddrow=[1,3,5,7]
if(letter in evencolum and number in evenrow or letter in oddcolum and number in oddrow):
print("square is black")
elif(letter in evencolum and number in oddrow or letter in oddcolum and number in evenrow):
print("square is white")
else:
print("enter a letter first then a number")
squarecolor() | true |
b6be82f0a96114542689840b501cae39305b284f | bommankondapraveenkumar/PYWORK | /code38.py | 445 | 4.34375 | 4 | def monthname():
E=input("enter the month name:\n")
if(E=="january" or E=="march" or E=="may" or E=="july" or E=="august" or E=="october" or E=="December"):
print(f"31 days in {E} month")
elif(E=="february"):
print("if leap year 29 otherwise 28")
elif(E=="april" or E=="june" or E=="september" or E=="november"):
print(f"30 days in {E} month")
else:
print("check the spelling buddy, type name of months only")
monthname() | true |
bbe61dbdac5acdbd4baa422c303664481b308763 | mdeora/codeeval | /sum_of_digits.py | 422 | 4.15625 | 4 | """
Given a positive integer, find the sum of its constituent digits.
Input sample:
The first argument will be a text file containing positive integers, one per line. e.g.
23
496
Output sample:
Print to stdout, the sum of the numbers that make up the integer, one per line.
e.g.
5
19
"""
import sys
with open(sys.argv[1]) as f:
for str_num in f:
print sum(int(i) for i in str_num if i != '\n')
| true |
a7bcd098bef75d2226097d4d11f0a6ce957fd43c | sidduGIT/linked_list | /single_linked_list1.py | 734 | 4.1875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def printlist(self):
temp=self.head
while(temp):
print(temp.data)
temp=temp.next
first=LinkedList()
first.head=Node(10)
print('after iniliazing first node')
first.printlist()
print('after adding second node')
second=Node(20)
first.head.next=second
first.printlist()
print('after adding third node')
third=Node(30)
second.next=third
first.printlist()
print('after adding third node')
fourth=Node(40)
third.next=fourth
first.printlist()
print('after adding fifth node')
fifth=Node(50)
fourth.next=fifth
first.printlist()
| true |
7f9c06979dd778bf0313bffacd4b954fe55498aa | sidduGIT/linked_list | /linked_list_all_operations.py | 1,336 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert_at_end(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
return
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=new_node
def count_nodes(self):
count=0
cur=self.head
while cur.next!=None:
count+=1
cur=cur.next
print('number of nodes',count)
def insert_after(self,data,after):
new_node=Node(data)
cur=self.head
while cur.next!=None:
save=cur.next
if cur.data==after:
cur.next=new_node
new_node=save
else:
print(after,'node not found in a list')
def display(self):
cur=self.head
while cur.next!=None:
print(cur.data)
cur=cur.next
print(cur.data)
llist=LinkedList()
print('initial linked list')
llist.insert_at_end(10)
llist.insert_at_end(20)
llist.insert_at_end(30)
llist.insert_at_end(40)
llist.insert_at_end(50)
llist.insert_at_end(60)
llist.display()
print('linked list after adding item')
llist.insert_after(500,30)
llist.display()
| true |
06966d4ff9727c6eb910497e92654ad6eec68810 | sidduGIT/linked_list | /doubly_linkedlist_delete_at_first.py | 1,619 | 4.25 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class Doubly_linkedlist:
def __init__(self):
self.head=None
def insert_at_end(self,data):
if self.head==None:
new_node=Node(data)
self.head=new_node
return
else:
cur=self.head
new_node=Node(data)
while(cur.next!=None):
cur=cur.next
cur.next=new_node
new_node.prev=cur
def display(self):
if self.head==None:
print('list is empty')
return
cur=self.head
while(cur.next!=None):
print(cur.data)
cur=cur.next
print(cur.data)
def delete_at_first(self):
if self.head==None:
print('list is empty nothing to delete')
return
else:
self.head=self.head.next
self.prev=None
llist=Doubly_linkedlist()
llist.insert_at_end(10)
llist.insert_at_end(20)
llist.insert_at_end(30)
llist.insert_at_end(40)
llist.insert_at_end(50)
llist.insert_at_end(60)
llist.insert_at_end(70)
llist.insert_at_end(80)
print('linked list after inserting elements')
llist.display()
print('linked list after deleting first element')
llist.delete_at_first()
llist.display()
print('linked list after deleting second element')
llist.delete_at_first()
llist.display()
print('linked list after deleting third element')
llist.delete_at_first()
llist.display()
print('linked list after deleting fourth element')
llist.delete_at_first()
llist.display()
| true |
1e1b603ef227a61948ea220bbb0bf261f73ad3b9 | DarkEyestheBaker/python | /ProgramFlow/guessinggame.py | 1,290 | 4.15625 | 4 | answer = 5
print("Please guess a number between 1 and 10: ")
guess = int(input())
if guess == answer:
print("You got it on the first try!")
else:
if guess < answer:
print("Please guess higher.")
else: # guess must be greater than answer
print("Please guess lower.")
guess = int(input())
if guess == answer:
print("Well, done! You guessed it!")
else:
print("Sorry, you have not guessed correctly.")
# if guess < answer:
# print("Please guess higher.")
# guess = int(input())
# if guess == answer:
# print("Well done! You guessed it!")
# else:
# print("Sorry, you have not guessed correctly.")
# elif guess > answer:
# print("Please guess lower.")
# guess = int(input())
# if guess == answer:
# print("Well done! You guessed it!")
# else:
# print("Sorry, you have not guessed correctly.")
# else:
# print("Well done! You got it first time!")
# You can have one or more elif print blocks
# You don't have to include elif.
# If you have any elif lines, they come after the if.
# Elif also has to come before else if there is an else.
# You don't have to use else, but if you do, it must come after the if.
# It must also come after any elifs if there are any. | true |
d08f70e1711874ed57fbdc089835155e4d98bd57 | beechundmoan/python | /caesar_8.py | 1,359 | 4.3125 | 4 | """
All of our previous examples have a hard-coded offset -
which is fine, but not very flexible. What if we wanted to
be able to encode a bunch of different strings with different
offsets?
Functions have a great feature for exactly this purpose, called
"Arguments."
Arguments are specific parameters that we can set when we
call a function, and they're super versatile.
"""
def encode_string(character_offset):
string_to_encode = input("Please enter a message to encode! [ PRESS ENTER TO ENCODE ] :")
string_to_encode = string_to_encode.upper()
output_string = ""
no_translate = "., ?!"
# We don't need the following line, because we've defined it as an argument.
#character_offset = 6
for character in string_to_encode:
if character in no_translate:
new_character = character
else:
ascii_code = ord(character)
new_ascii_code = ascii_code + character_offset
if new_ascii_code > 90:
new_ascii_code -= 25
new_character = chr(new_ascii_code)
output_string += new_character
print(output_string)
print("Welcome to our second Caesar Cipher script")
print("Let's call our first argumented function!")
# Those parentheses might make a little more sense now...
encode_string(3)
encode_string(18)
encode_string(1)
# Notice that we can now specify an offset of zero, which doesn't encode at all!
encode_string(0)
| true |
fbcd09f15d85456e86ac136af36b7797f730ca94 | bhushankorpe/Fizz_Buzz_Fibonacci | /Fizz_Buzz_Fibonacci.py | 1,727 | 4.3125 | 4 | #In the programming language of your choice, write a program generating the first n Fibonacci numbers F(n), printing
#"Buzz" when F(n) is divisible by 3.
#"Fizz" when F(n) is divisible by 5.
#"FizzBuzz" when F(n) is divisible by 15.
#"BuzzFizz" when F(n) is prime.
#the value F(n) otherwise.
#We encourage you to compose your code for this question in a way that represents the quality of
#code you produce in the workplace - e.g. tests, documentation, linting, dependency management
#(though there's no need to go this far).
# >>>>>> SOLUTION <<<<<<
# Method checks if the given number is a Prime number
def checkPrime(N):
flag = False
# Try finding a factor of the number other than itself
if N > 1:
for x in range(2,N):
if (N % x) == 0:
return flag
flag = True
return flag
# This is our function F(n) described in the problem statement
def F(num):
buff = []
# Condition checks if given number is divisible by 3,5, 15 or prime.
#If not calculates Fibonacci series which reduces computations
if num%3 == 0 or num%5 == 0 or num%15 == 0 or checkPrime(num):
if num%3 == 0:
buff.append("Buzz")
if num%5 == 0:
buff.append("Fizz")
if num%15 == 0:
buff.append("FizzBuzz")
if checkPrime(num):
buff.append("BuzzFizz")
for i in buff:
print i
else:
fibo = []
a = 0
b = 1
for i in range(0,num):
if i == 0:
fibo.append(a)
if i == 1:
fibo.append(b)
if i > 1:
c = a+b
fibo.append(c)
a=b
b=c
print fibo
# Main() function
if __name__ == '__main__':
# The program takes input from the user
print "How many fibonacci numbers do you want to see? "
n = input()
F(n) | true |
fd0c0d40b181c03d4a0e3d1adcbe37ee69e31bbf | Polinq/InfopulsePolina | /HW_3_Task_6.2.py | 382 | 4.3125 | 4 | def is_a_triangle(a, b, c):
''' Shows if the triangle exsists or not. If it exsisrs, it will show "yes" and if it does not exsit it will show "no". (num, num, num) -> yes or (num, num, num) -> no.'''
if (a + c < b or a + b < c or b + c < a):
print('NO')
else:
print('YES')
# пример использования функции:
is_a_triangle(7, 9, 4) | true |
5a4f54078e1a341c9107f9efec5726b869a0fc27 | Polinq/InfopulsePolina | /HW_3_Task_6.1.py | 313 | 4.40625 | 4 | def is_year_leap(a):
'''The function works with one argument (num) and shows if the year is leap. If the year is leap it shows "True", if the year is not leap it shows "False"'''
if ((a % 4 == 0 and a % 100 != 0) or (a % 400 == 0)):
print('True')
else:
print('False')
is_year_leap(4)
| true |
df1af2c50ba4f110e76c4609518c6e9e166a1fe4 | kavyan92/code-challenges | /rev-string/revstring.py | 610 | 4.15625 | 4 | """Reverse a string.
For example::
>>> rev_string("")
''
>>> rev_string("a")
'a'
>>> rev_string("porcupine")
'enipucrop'
"""
def rev_string(astring):
"""Return reverse of string.
You may NOT use the reversed() function!
"""
# new_string = []
# for char in range((len(astring)-1), -1, -1): #[c, b, a] #[2, 1, 0]
# new_string.append(astring[char])
# return "".join(new_string)
return astring[::-1]
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. !KROW DOOG\n")
| true |
c2b7982dc8b822a17f9d60634888c0b3ae151884 | alvas-education-foundation/spoorti_daroji | /coding_solutions/StringKeyRemove.py | 377 | 4.28125 | 4 | '''
Example
If the original string is "Welcome to AIET" and the user inputs string to remove "co" then the it should print "Welme to AIET" as output .
Input
First line read a string
Second line read key character to be removed.
Output
String which doesn't contain key character
'''
s = input('Enter The Main String: ')
a=input('Enter The Sub String: ')
print(s.replace(a, '')) | true |
0607f73a1d10f718b4dea2d28c7a6a64b73233af | SpiffiKay/CS344-OS-py | /mypython.py | 1,078 | 4.15625 | 4 | ###########################################################################
#Title: Program Py
#Name: Tiffani Auer
#Due: Feb 28, 2019
#note: written to be run on Python3 :)
###########################################################################
import random
import string
#generate random string
#adapted from tutorial on https://pynative.com/python-generate-random-string/
def myString(strLength=10):
return ''.join(random.choice(string.ascii_lowercase) for i in range(strLength))
#create strings
str1 = myString();
str2 = myString();
str3 = myString();
#print strings to screen
print(str1)
print(str2)
print(str3)
#add newline
str1+='\n'
str2+='\n'
str3+='\n'
#create files
file1 = open("file1", "w+")
file2 = open("file2", "w+")
file3 = open("file3", "w+")
#write string to files
file1.write(str1)
file2.write(str2)
file3.write(str3)
#close files
file1.close()
file2.close()
file3.close()
#generate random numbers
num1 = random.randint(1, 42)
num2 = random.randint(1, 42)
#multiply numbers
total = num1 * num2
#print numbers
print(num1)
print(num2)
print(total)
| true |
bb797f115f513f5210013037f1cda1a86aefe6df | Phazon85/codewars | /odd_sorting.py | 673 | 4.1875 | 4 | '''
codewars.com practice problem
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
'''
def sort_array(source_array):
temp = sorted([i for i in source_array if i%2 != 0])
odd_int = 0
if source_array == []:
return source_array
else:
for i in range(len(source_array)):
if source_array[i] % 2 != 0:
source_array[i] = temp[odd_int]
odd_int += 1
return source_array
test = [5, 3, 2, 8, 1, 4]
print(sort_array(test)) | true |
91092e769d5b1258414d8cac0b3009a9f59b4ef3 | jk555/Python | /if.py | 1,503 | 4.25 | 4 | number = 5
if number == 5:
print("Number is defined and truthy")
text = "Python"
if text:
print("text is defined and truthy")
#Boolean and None
#python_course = True
#if python_course:
# print("This will execute")
#aliens_found = None
#if aliens_found:
# print("This will not execute")
#! operator
# number = 5
# if number != 5:
# print("This will not execute")
#
#python_course = True
#if not python_course:
# print("This will not execute")
#Multiple if conditions
#number=3
#python_course=True
#if number ==3 and python_course:
# print("This will execute")
#
#if number==17 or python_course:
# print("This will also execute")
#ternery If Statements
#a=1
#b=2
#"b is bigger than a" if a > b else "a is smallet than b"
student_names = ["Mark","Katerina","Jessica"]
print(student_names[1])
#last is -1 index
print(student_names[-1])
print(student_names[-2])
#Adding to the list: Add at the end
#student_names.append("Homer")
print(student_names)
print("Mark" in student_names)
#How many elements do we have in list
print(len(student_names))
#list can include multiple types items in the list. But try to avoid that.
#how to delete the item from the list.
#del(student_names[2])
print(student_names)
#List slicing: [1: means ignore first one and print the rest
print(student_names[1:])
#ignore first and last and print the rest of the list
print(student_names[1:-1])
| true |
137af1c6366d00b78500c8b111ad5e6b3bc6121e | rameshroy83/Learning | /Lab014.py | 227 | 4.15625 | 4 | #!/usr/bin/python2
'''
In this code we will talk about escape sequecnce \n is for a new line, \t for a tab.
\'' to print quote \\ to print backslash.
'''
a = input("Enter the string")
print("You entered the string as \n",a)
| true |
bffbe1b30baf3a918462905e96e3a853b96388a6 | for-wd/django-action-framework | /corelib/tools/group_array.py | 449 | 4.21875 | 4 | def groupArray(array, num):
"""
To group an array by `num`.
:array An iterable object.
:num How many items a sub-group may contained.
Returns an generator to generate a list contains `num` of items for each iterable calls.
"""
tmp = []
count = 0
for i in array:
count += 1
tmp.append(i)
if count >= num:
yield tmp
tmp = []
count = 0
yield tmp
| true |
0927f0c0882096fec39a956385abe8509ccabb38 | nashj/Algorithms | /Sorting/mergesort.py | 1,197 | 4.25 | 4 | #!/usr/bin/env python
from sorting_tests import test
def merge(left_list, right_list):
# left_list and right_list must be sorted
sorted_list = []
while (len(left_list) > 0) or (len(right_list) > 0):
if (len(left_list) > 0) and (len(right_list) > 0):
if left_list[0] < right_list[0]:
sorted_list.append(left_list[0])
left_list = left_list[1:]
else:
sorted_list.append(right_list[0])
right_list = right_list[1:]
elif len(left_list) > 0:
sorted_list.append(left_list[0])
left_list = left_list[1:]
else: # right_list nonempty
sorted_list.append(right_list[0])
right_list = right_list[1:]
return sorted_list
def mergesort(list):
# Lists of length <= 1 are trivially sorted
if len(list) <= 1:
return list
# Split the list in half and sort each side
left_list = mergesort( list[0:len(list)/2] )
right_list = mergesort( list[len(list)/2:] )
# Merge the newly sorted lists
return merge(left_list, right_list)
if __name__ == "__main__":
test(mergesort)
| true |
428ae6aee6bf3d0a604320a2cabe06cb0757bf42 | nashj/Algorithms | /Sorting/quicksort.py | 588 | 4.1875 | 4 | #!/usr/bin/env python
from sorting_tests import test
def quicksort(list):
# Lists of length 1 or 0 are trivially sorted
if len(list) <= 1:
return list
# Break the list into two smaller lists by comparing each value with the first element in the list, called the pivot.
pivot = list[0]
lteq_list = []
gt_list = []
for i in list[1:]:
if i <= pivot:
lteq_list.append(i)
else:
gt_list.append(i)
return quicksort(lteq_list) + [pivot] + quicksort(gt_list)
if __name__ == "__main__":
test(quicksort)
| true |
0109651e4e3977981ff67b5d226589f2763225d6 | TimDN/education-python | /functions/function.py | 1,033 | 4.15625 | 4 | def say_hello(name):
print("Hello {}!".format(name))
def combine_name(fname, sname, mname = ""):
return "{} {} {}".format(fname, mname, sname)
def read_number():
number = input("Give number: ")
if is_special_operator(number):
handle_special_operator(number)
else:
return float(number)
def read_operator():
operator = input("Give operator: ")
if is_special_operator(operator):
handle_special_operator(operator)
else:
return operator
def handle_special_operator(operator):
pass
def is_special_operator(operator):
if operator == "c" or operator == "x":
return True
return False
number_1 = read_number()
operator = read_operator()
number_2 = read_number()
say_hello("World") # prints Hello World
say_hello("Foo") # prints Hello Foo
full_name = combine_name("Tim", "Nielsen", "Daldorph")
print(full_name) # prints Tim Daldorph Nielsen
full_name = combine_name(sname="Nielsen", fname="Tim")
print(full_name) # prints Tim Nielsen | false |
b04548acb91ff5e1a6d32b547ed68480db462f7c | TimDN/education-python | /class/basic.py | 491 | 4.34375 | 4 | class Person: # create a class with name person
first_name = "Foo" # class variable
foo = Person() # Create a Person object and assign it to the foo variable
bar = Person() # Create a Person object and assign it to the bar variable
print(foo.first_name) #prints Foo
print(bar.first_name) #prints Foo
bar.first_name = "Bar" # changing first_name of this Person instance
print(foo.first_name) #prints Foo (no change)
print(bar.first_name) #prints Bar (changed)
test = Person()
| true |
7b824c269e031a2b621ee9c69f571970ccfc5ec9 | usmannA/practice-code | /Odd or Even.py | 508 | 4.3125 | 4 | '''Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.'''
entered_number= int(input("Please enter any number:"))
if entered_number % 2 == 0:
print ("Thats an even number")
if entered_number % 4 == 0:
print("that's also a multiple of four")
else:
print ("That's an odd number")
| true |
5def7924086f2dcfd0121f7a6979fb5cbbf47e6d | standrewscollege2018/2021-year-11-classwork-padams73 | /zoo.py | 273 | 4.25 | 4 | # Zoo program
# Start by setting a constant
# This is the age limit for a child
CHILD_AGE = 13
# Get the age of the user
age = int(input("What is your age?"))
# Check if they are a child
if age < CHILD_AGE:
print("You pay the child price")
print("Welcome to the zoo") | true |
2681d86a929e491d1bc7774d9ce8f346ab5c8161 | standrewscollege2018/2021-year-11-classwork-padams73 | /madlib.py | 333 | 4.25 | 4 | # This program is a Madlib, getting the user to enter details
# then it prints out a story
print("Welcome to my Madlib program!")
# Get their details
body_part = input("Enter a body part:")
name = input("Enter a name:")
# Print the story
print("Hello {}, you have the strangest looking {} I have ever seen".format(name, body_part)) | true |
aafa7894fa867811e663cf65282ece2445fe700e | standrewscollege2018/2021-year-11-classwork-padams73 | /for_user_input.py | 316 | 4.1875 | 4 | # In this program the user enters a starting
# value, stopping value, and step
# The program then counts up
# Get inputs from user
start_num = int(input("Start?"))
stop_num = int(input("Stop?"))
step = int(input("Change each time?"))
# Print the numbers
for num in range(start_num, stop_num+1, step):
print(num) | true |
5fd1994db19c724283342c9c6a08671949bdc0db | VictorB1996/GAD-Python | /GAD-05/oop.py | 2,542 | 4.40625 | 4 | from abc import abstractmethod
class Animal:
number_of_legs = 4
def __init__(self, name, breed=None):
self._name = name
self.breed = breed
# def set_name(self, name):
# self._name = name
#
# def get_name(self):
# return self._name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@name.deleter
def name(self):
del self._name
@staticmethod
@abstractmethod
def speak():
pass
class Dog(Animal):
@staticmethod
def speak():
print("Ham, ham!")
@classmethod
def create_instance(cls):
return cls("Ben")
# Used for converting object to string
def __str__(self):
return "<%s - Name = %s" % (type(self).__name__, self._name)
# Used for representation inside a list or any other data structure
def __repr__(self):
return "%s(name = %s, breed = %s)" % (type(self).__name__, self._name, self.breed)
def __len__(self):
return len(self._name)
class CustomClass:
number_of_legs = 2
class Cat(Animal, CustomClass):
@staticmethod
def speak():
print("Miau, miau!")
def __len__(self):
return 20
# rex = Dog("Rex", "Bulldog")
# rex.name = "New Rex"
# print(f"Dog name is {rex.name} - {rex.breed} - {rex.number_of_legs} legs.")
# # del rex.name
# # print(f"Dog name is {rex.name} - {rex.breed} - {rex.number_of_legs} legs.")
# rex.speak()
# Dog.speak()
#
# new_dog = Dog.create_instance()
# print(new_dog)
#
# l = [new_dog]
# print(l)
#
# print(len(new_dog))
#
# julie = Cat("Julie")
# # julie.legs_number
#
# data_1 = [1, 2, 3, 4, 5]
# data_2 = "abcdefg"
# data_3 = julie
#
# my_list = [data_1, data_2, data_3]
# for i in my_list:
# print(len(i))
# Iterators and iterables
class FibonacciIterator:
def __init__(self, n):
self.n = n
def __iter__(self):
self.value = 1
self.next_value = 1
self.iteration = 0
return self
def __next__(self):
if self.iteration < self.n:
self.iteration += 1
aux_value = self.value
if self.next_value == 1:
self.next_value += 1
else:
self.value = self.next_value
self.next_value = aux_value + self.next_value
return aux_value
raise StopIteration
x = iter(FibonacciIterator(10))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
| false |
c1c77ddd5cb6b430281603fcb29680c0181898be | VictorB1996/GAD-Python | /GAD-02/Homework.py | 432 | 4.28125 | 4 | initial_list = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6]
ascending_list = sorted(initial_list)
print("Ascending order: ")
print(ascending_list)
descending_list = sorted(initial_list, reverse = True)
print("\nDescending order: ")
print(descending_list)
print("\nEven numbers using slice: ")
print(ascending_list[1::2])
print("\nOdd numbers using slice: ")
print(ascending_list[::2])
print("\nMultiples of 3: ")
print(ascending_list[2::3]) | true |
f9411bce9690b08a947a99ef66cd0423949a7ec4 | lukew2251/Scripting | /Mod01Tutorial.py | 1,309 | 4.375 | 4 | 'Luke Willis'
'Tutorial #1'
print('Task 1')
print('Hello World')
input()
print('Task 2')
user_guess = input('Please enter an integer: ')
print (user_guess)
input()
print('Task 3')
user_guess = int(user_guess)
converted_user_guess = int(user_guess)
print(user_guess * 3)
print(converted_user_guess * 3)
user_guess = str(user_guess)
print(user_guess * 3)
print('I entered ' + user_guess)
##print('I entered ' + converted_user_guess)
print('Task 4')
for i in range (1,21,1):
if i == 7:
print('Snowflake')
elif (i % 2) == 0:
print('Even')
else:
print('Odd')
print('Task 5')
for i in range(1,int(input('Enter a number greater than 13: '))+1,1):
if(i) == 7:
print('Lucky')
elif(i) == 13:
print('Unlucky')
elif (i % 2) == 0:
print('Even')
else:
print('Odd')
print('Task 6')
while True:
user_name = input('Please enter a last name(Willis): ')
if user_name == 'Willis':
break
print('Task 7')
counter = 0
while counter < 10:
print (counter)
counter += 1
break
print('Task 8')
import random
for i in range (0,5):
random_value = random.randint(-10,10)
print (random_value, end="")
print('Press enter to end')
print()
input()
| false |
d8cf3b2cb04b117c5ed1478384723b1df83290e8 | Jangchezo/python-code-FREE-SIMPLE- | /readReverse.py | 736 | 4.125 | 4 | # readReverse.py
#test code
"""
reverseRead(file)
->print from the end of the file
"""
file = open('c:/Users/JHLee/Desktop/test.txt', 'r')
lines = file.readlines()
for i in range(0, len(lines)):
print(lines[len(lines)-i-1][0:-1])
# Real code 1
file = open('c:/Users/JHLee/Desktop/test.txt', 'r')
def reverseRead(file):
lines = file.readlines()
for i in range(0, len(lines)):
seeLine = lines[len(lines)-i-1][0:-1]
print(seeLine)
# Real code 2
file = open('c:/Users/JHLee/Desktop/test.txt', 'r')
def reverseRead(file):
lines = file.readlines()
lines = lines.reverse() # WOW! It's simple.
for seeLine in lines:
print(seeLine)
| true |
3b00e1478f40be5570bea24005279ba4f673c38e | grohj17/comp110-21ss1-workspace | /exercises/ex02/vaccine_calc.py | 1,290 | 4.15625 | 4 | """A vaccination calculator."""
__author__ = "730201179"
from datetime import datetime, timedelta
population: str = input("How large is the population? ")
doses_given: str = input("How many doses of the vaccine have already been administered? ")
doses_per_day: str = input("How mainy doses are being given daily? ")
tgt_pct: str = input("What percent of the population are we hoping to vaccinate? ")
target_percent_vaccinated: int = int(tgt_pct)
necessary_vaccinated: float = int(population) * target_percent_vaccinated * .01
already_vaccinated: float = int(doses_given) / 2
remaining_target_unvaccinated: int = round(necessary_vaccinated) - round(already_vaccinated)
vaccinated_daily: float = int(doses_per_day) / 2
tgt_day: float = round(remaining_target_unvaccinated / vaccinated_daily)
today: datetime = datetime.today()
one_day: timedelta = timedelta(int(tgt_day))
tomorrow: datetime = today + one_day
fnl_stmt: str = "We will reach "
fnl_stmt_2: str = "% vaccination in "
fnt_stmt_3: str = " days, which falls on "
print("Population: " + population)
print("Doses administered: " + doses_given)
print("Doses per day: " + doses_per_day)
print("Target percent vaccinated: " + tgt_pct)
print(fnl_stmt + tgt_pct + fnl_stmt_2 + str(tgt_day) + fnt_stmt_3 + tomorrow.strftime("%B %d, %Y")) | false |
7f48cdb6cbd455fcf38fbb1a0c4f6819e3f6b8a0 | Elvolox/ExerciciosPythonCurso | /Desafio28.py | 361 | 4.125 | 4 | import random
numero = int(input('Digite um numero de 0 a 5: '))
numeroc = random.randint(0,5)
if numero == numeroc:
print('Voce acertou o número que a maquina pensou, sou número foi {} e o da maquina foi {}'.format(numero, numeroc))
else:
print('Que pena , você errou, seu número {} não é igual da maquina {}'.format(numero, numeroc)) | false |
4b4f24d14742b12f8c806f7c911976105bdd6d35 | lukeblanco/python_b | /luke/desafio1.py | 314 | 4.21875 | 4 | ##Diseñar un programa en el cual el usuario ingrese tres números, uno a la vez, y se muestre a la salida el promedio de los tres números.
num = int( input("Ingrese Primer Numero: ") )
num = num+int( input("Ingrese Segundo Numero: ") )
num = num+int( input("Ingrese Tercero Numero: ") )
num = num/3
print(num)
| false |
727a3fadc945279790ace65b0810de18791f0c2a | jeancarlov/python | /decisionB.py | 2,913 | 4.46875 | 4 | # ----- Design Tool - PseudoCode ---------
# Create main function and inside the main function enter the variables codes for input and output
# Display Menu options and request user to make a selection
# Enter variables with input request to the use
# print user input result
# Create if statements to check if variable number match choice selection
# Create def functions and add to each if statement
# Print result from new variables
# call main function main() for inside code to display
# ------ Comment Header -----------
# Name: Jean Carlo Valderrama
# Date : June 13, 2021
# Purpose : Decision B homework
from datetime import date
def main():
print('1. Get name then display name')
print('2. Get Age then display statement')
print("3. Today's date ")
print('4. Quit')
choice = input('Enter selection:')
if choice == '1':
displayName()
if choice == '2':
ageDisplay()
if choice == '3':
displayDate()
if choice == '4':
print('Thanks for trying program ended.')
def displayName():
userName = input('What is your name: ')
print('hello', userName, ", have a good day.")
def ageDisplay():
userAge = input('What is your age: ')
if float(userAge) <= 10:
print(' You are only', userAge, 'go to bed')
if 10 <= float(userAge) <= 20:
print(' This age would display no output')
if 21 <= float(userAge) <= 60:
print("Since you are", userAge, "let's go have a drink.")
elif float(userAge) >= 61:
print( 'Wow,', userAge, ' is really old.')
def displayDate():
today = date.today()
today = today.strftime(" %m/%d/%y")
print(" Today's date:", today)
# main()
main()
userNumberLines = input('Hi please type a number from 1 - 50: ')
print('hello', userNumberLines, ", have a good day.")
if int(userNumberLines) <= 50:
print(' Thanks your number is with in 1 - 50')
else:
print('please try again ')
userKeyword = input('Enter a character from the keyboard: ')
print('your keyboard character is :', userKeyword, )
# newResult = ''.join([char * userNumber for char in userKeyword])
# print(newResult)
for userNumberLine in userNumberLines:
print(str(userKeyword) * userNumberLine)
# print(x.replace(userNumber, userKeyword, 50))
userNumberLines = input('Hi please type a number from 1 - 50: ')
print('hello', userNumberLines, ", have a good day.")
print("Twice the number you give: {number}".format(number=userNumberLines * 2))
if int(userNumberLines) <= 50:
print(' Thanks your number is with in 1 - 50')
else:
print('please try again ')
userKeyword = input('Enter a character from the keyboard: ')
print('your keyboard character is :', userKeyword, )
# newResult = ''.join([char * userNumber for char in userKeyword])
# print(newResult)
for userNumberLine in userNumberLines:
print(str(userKeyword) * userNumberLine) | true |
cb56d6e59567c3713f2b9fff7efea89ed5d29c77 | atbohara/basic-ds-algo | /linkedlist/rearrange_pairs.py | 1,420 | 4.25 | 4 | """Rearrange node-pairs in a given linked list.
Demonstration of 'runner' technique.
"""
from linked_list import Node
from linked_list import LinkedList
def rearrange_pairs(orig_list):
"""Modifies the input list in-place.
O(N).
"""
slow_ptr = orig_list.head
fast_ptr = orig_list.head
while fast_ptr:
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next.next # jumps two nodes every time
# When the fast_ptr reaches end, put it back at head.
# slow_ptr would be at (N/2)+1 element.
fast_ptr = orig_list.head
# Start 'weaving' the pairs.
while slow_ptr:
# Store the original next nodes in temp variables.
next1 = slow_ptr.next
next2 = fast_ptr.next
# Rearrange pointers.
fast_ptr.next = slow_ptr
if not next1: # p1 reached the last node
# Cleanup: remove unneccessary links (optional).
slow_ptr = None
fast_ptr = None
next2 = None
break
slow_ptr.next = next2
slow_ptr = next1
fast_ptr = next2
def main():
orig_items = [1, 2, 3, 4, 'a', 'b', 'c', 'd']
orig_list = LinkedList()
for item in orig_items:
orig_list.insert_at_tail(item)
print("Original list:")
orig_list.print()
rearrange_pairs(orig_list)
print("After rearranging:")
orig_list.print()
if __name__ == '__main__':
main()
| true |
b106c568098b8d4db825de07a3f6d869f4a0fc0e | abokumah/Lab_Python_02 | /solutions/extra_credit_solutions/Lab03_2.py | 828 | 4.71875 | 5 | """
Lab_Python_02
Extra Credit
Solutions for Extra Credit Question 1
"""
# getting input from the user
unencrypted = int(raw_input("Enter a number to encrypt: "))
encrypted = 0
encrypted_old = 0
while unencrypted > 0:
# multiplying both the encrypted numbers by 10
encrypted *= 10
encrypted_old *= 10
#getting the last digit of what is left of the unencrypted number
new_digit = unencrypted % 10
#adding the new digit to the old encryption method before we transform it
encrypted_old += new_digit
#transforming the new digit
new_digit = (new_digit + 7) % 10
#adding the new digit
encrypted += new_digit
# shortening the unencrypted number
unencrypted //= 10
print "Using the old method, the encrypted number is %d" % encrypted_old
print "Using the new method, the encrypted number is %d" % encrypted
| true |
1e3b15e3576fa57b0af51d37cf91cbf158d0a4a2 | cnluzon/advent2016 | /scripts/03_triangles.py | 2,969 | 4.15625 | 4 | import argparse
"""
--- Day 3: Squares With Three Sides ---
Now that you can think clearly, you move deeper into the labyrinth of hallways
and office furniture that makes up this part of Easter Bunny HQ. This must be a
graphic design department; the walls are covered in specifications for
triangles.
Or are they?
The design document gives the side lengths of each triangle it describes,
but... 5 10 25? Some of these aren't triangles. You can't help but mark the
impossible ones.
In a valid triangle, the sum of any two sides must be larger than the remaining
side. For example, the "triangle" given above is impossible, because 5 + 10 is
not larger than 25.
In your puzzle input, how many of the listed triangles are possible?
"""
class TriangleValidator:
def validate_side_list(self, sides):
result = True
if sides[0] + sides[1] <= sides[2]:
result = False
elif sides[1] + sides[2] <= sides[0]:
result = False
elif sides[0] + sides[2] <= sides[1]:
result = False
return result
def count_good_triangles(self, triangle_list):
good_triangle_count = 0
for triangle in triangle_list:
if self.validate_side_list(triangle):
good_triangle_count += 1
return good_triangle_count
def parse_input_horizontal(fi):
lines = fi.readlines()
triangles_list = []
for line in lines:
values = line.rstrip().split()
values = [int(v) for v in values]
triangles_list.append(values)
return triangles_list
def parse_input_vertical(fi):
triangle_list = []
transposed_matrix = []
lines = fi.readlines()
for line in lines:
line = line.rstrip()
values = line.split()
values = [int(v) for v in values]
transposed_matrix.append(values)
for j in range(0, len(transposed_matrix[0])):
value_list = [transposed_matrix[i][j] for i in range(len(transposed_matrix))]
for i in range(0, len(value_list), 3):
triangle_list.append(value_list[i:i+3])
return triangle_list
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Solve Advent of Code 2016 problem 03: Squares with three sides')
parser.add_argument('in_file', help='Input triangles file')
args = parser.parse_args()
validator = TriangleValidator()
fi = open(args.in_file)
triangle_list_horizontal = parse_input_horizontal(fi)
fi.close()
fi = open(args.in_file)
triangle_list_vertical = parse_input_vertical(fi)
fi.close()
good_triangles_horizontal = validator.count_good_triangles(triangle_list_horizontal)
good_triangles_vertical = validator.count_good_triangles(triangle_list_vertical)
print "In the list, there are {} good triangles".format(good_triangles_horizontal)
print "In the list (vertically), there are {} good triangles".format(good_triangles_vertical)
| true |
147db49069181bfd366e2975da98f704e3a7ca89 | Jetroid/l2c | /solutions/l2s_solution14.py | 674 | 4.4375 | 4 | #Write a program that will print out the contents of a multiplication table from 1x1 to 12x12.
# ie. The multiplication table from 1x1 to 3x3 is as follows:
# 1 2 3
# 2 4 6
# 3 6 9
#Hint: You'll probably want to use two for loops for each number.
#Reminder: To print something without putting a newline on the end, you can use print(..., end="\t").
# You might also want to use tabs so double/triple digit numbers are formatted in a nice table.
#Bonus: See if you can figure out how to print the column headers.
#Write your code below:
upperLimit = 13
for i in range(1, upperLimit):
for j in range(1, upperLimit):
print(str(i * j), end="\t")
print() | true |
a2dcded762980962a583a58af292352dcb1185b9 | Jetroid/l2c | /solutions/l2c_solution11.py | 650 | 4.4375 | 4 | #Finish the if/elif/else statement below to evaluate if myInt is divisible by 4, else evaluate if it is divisible by 3.
#Try out myInt for several different values!
#Reminder: We can use the modulo operator to get the remainder. eg: 7 % 3 is equal to 1. (because 2*3 + 1 is equal to 7)
#Hint: If a modulo result is zero, then the left hand operator is wholly divisible by the right hand operator.
#Example Solution:
myInt = 12
if myInt % 4 == 0:
print("myInt was divisible by four.")
elif myInt % 3 == 0:
print("myInt was divisible by three but not four.")
else:
print("myInt was divisible by neither three nor four.")
| true |
77166e51f2facbc44dd6e1763ea5111f45276e69 | Vampirskiy/helloworld | /venv/Scripts/Урок1/if_simple.py | 310 | 4.125 | 4 | age=int(input('Введите свой возраст'))
#Если возраст меньше 18 лет
#Вывести на экран "Доступ запрещен"
if age<18:
print('Пошел на хуй!')
elif age==18:
print('Вам точно 18?')
else:
print('Доступ открыт') | false |
3383c4a85f5db4d89293ff8e43183a4e3832be83 | wa57/info108 | /Chapter8/Chapter8Ex1.py | 1,069 | 4.25 | 4 | """a) _____ Assume “choice” is a variable that references a string.
The following if statement determines whether choice is equal to ‘Y’ or ‘y’.:
if choice == ‘Y’ or choice == ‘y’:
Rewrite this statement so it only makes one comparison and does not use the or operator.
b) _____ Write a loop that counts the number of space characters that appear in
the string referenced by “myString”. myString = “The best things in life are free.”
c) _____ Write a function that accepts a string as an argument and returns
true if the argument ends with the substring “.com”. Otherwise, the function
should return false.
"""
choice = 'Y'
if choice.lower() == 'y':
print(True)
myString = 'The best things in life are free.'
emptySpaces = 0
for char in myString:
if(char == ' '):
emptySpaces += 1
print(emptySpaces)
def isURI(string):
#WA - starts at the end of the string and slices the last 4 characters (the domain)
if(string[-4:] == '.com'):
return True
return False
uri = input('URI: ')
print(isURI(uri))
| true |
98bdd82a126a576d54c51b03d9201ee1ffa22b46 | wa57/info108 | /Chapter7/AshmanLab4Problem1.py | 2,300 | 4.15625 | 4 | #Project Name: Lab 4 Homework
#Date: 4/28/16
#Programmer Name: Will Ashman
#Project Description: Lab 4 Homework
#Resource used for table formatting: http://knowledgestockpile.blogspot.com/2011/01/string-formatting-in-python_09.html
#WA - Import the math module to perform calculations
import math
def main():
#WA - Get and validate user input
loanAmount = getInput('\nEnter the amount of the loan (number greater than 0): ')
loanYears = getInput('\nEnter the number of years as an integer: ')
#WA - Pass input into calculateLoanPayments to be calculated
calculateLoanPayments(loanAmount, loanYears)
#WA - Asks user if they want another table to be created. If y is entered, main is rerun
createAnotherTable = input('\nDo you want to create another table? (y/n): ')
if(createAnotherTable == 'y'):
main()
def calculateLoanPayments(loanAmount, loanYears):
#WA - Uses replacement fields to set a maximum column width and left align column headers
print('\n{0:<8} {1:<18} {2:<16}'.format('Rate', 'Monthly Payment', 'Total Payment'))
print('-'*46)
#WA - Iterates through specified range starting with 4 and running until 8, incremented by 1 each cycle
for rate in range(4, 9, 1):
#WA - Divides annual rate by months in 1 year (12) to get percentage.
# Result is divided by 100 to obtain decimal value usable in the following formulas
monthlyRate = (rate / 12) / 100
#WA - Uses provided formulas to calculate monthlyPayment and the totalPayment for the provided rate
monthlyPayment = loanAmount * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), loanYears * 12))
totalPayment = monthlyPayment * loanYears * 12
#WA - Uses replacement fields to set a maximum column width and left align data set rows.
# Will also truncate result to 2 decimal places
print('{0:<8} {1:<18} {2:<16}'.format(str(rate) + '%', '$%.2f' % monthlyPayment, '$%.2f' % totalPayment))
#WA - Accepts a message and performs check to verify input is not a negative number,
# uses a while loop to prompt user until valid input is given
def getInput(message):
userInput = float(input(message))
while userInput < 0:
userInput = float(input(message))
return userInput
main()
| true |
cc2e5541bc5a57ca67de5109dae3f5cc976d560d | wa57/info108 | /Lab2/TestFunctions.py | 843 | 4.21875 | 4 | #WA - Gathers a positive, negative, and inclusive number between 48-122
#WA - As well as a string from the user
posInteger = float(input('Positive integer: '))
negInteger = float(input('Negative integer: '))
myChar = int(input('Integer between 48 and 122 inclusive: '))
myString = input('String: ')
#WA - outputs absolute value of postInteger and negInteger
print('Absolute value of', str(posInteger) + ':', abs(posInteger))
print('Absolute value of', str(negInteger) + ':', abs(negInteger))
#WA - output Unicode character associated with integer
print('Unicode translation of', str(myChar) + ':', chr(myChar))
#WA - output length of myString
print('Length of string', '"' + myString + '"' + ':', len(myString))
#WA - output posInteger to the power of 4
myPower = posInteger ** 4
print('Number', posInteger, 'to the power of 4:', myPower)
| true |
730667d8c9bfd1f0883a35d85468609387b33ca7 | chenhuang/leetcode | /maxSubArray.py | 1,575 | 4.1875 | 4 | #! /usr/bin/env python
'''
Maximum Subarray
Given an array of integers, find a contiguous subarray which has the largest sum.
Note
The subarray should contain at least one number
Example
For example, given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Maximum Subarray II
Fair Maximum Subarray II
18% Accepted
Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
Note
The subarray should contain at least one number
Example
For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, -2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.
'''
import os
import re
import sys
class solution:
def max_subarray(self, nums):
# Naive solution: O(n^2): iterate through all possible sub arraies.
# Better: many subproblems: sum[i][j] = sum[i][j-1]+num[j]
# sum[0][n]: max sum from 0 to n = max(sum[0][n-1]+num[n-1], sum[0][n-1])
# pre-processing: a[i] = sum(num[0] to num[i])
# then the problem would become: find max(a[j]-a[i]): stock market price problem.
def max_subarray_ii(self, nums):
# Based on solution of max_subarray, preprocessing nums such that:
# a[i] = sum(sum[0] to sum[i])
# b[i]: max (a[i]-a[0])
# c[i]: max (a[n]-a[i])
def max_subarray_iii(self, nums):
# DP:
# A[n][k]: max sum from nums[0] to nums[i]
# A[n][k] = max(A[i][k-1], max_subarray(i,n))
| true |
9ca5bf3b0e75a993f519289bbc5b50ca7e8f5b68 | chenhuang/leetcode | /insert.py | 2,143 | 4.15625 | 4 | #! /usr/bin/env python
'''
Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
https://oj.leetcode.com/problems/insert-interval/
'''
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert_1(self, intervals, newInterval):
stack = []
for i in intervals:
if i.start > newInterval.end:
stack.append(newInterval)
newInterval = i
elif (newInterval.start >= i.start and newInterval.start <= i.end) or (i.start >= newInterval.start and i.start <= newInterval.end):
newInterval.start = min(newInterval.start, i.start)
newInterval.end = max(newInterval.end, i.end)
else:
stack.append(i)
stack.append(newInterval)
return stack
def insert(self, intervals, newInterval):
stack = []
for i in intervals:
if i[0] > newInterval[1]:
stack.append(newInterval)
newInterval = i
elif (newInterval[0] > i[0] and newInterval[0] < i[1]) or (i[0] > newInterval[0] and i[0]< newInterval[1]):
newInterval[0] = min(newInterval[0], i[0])
newInterval[1] = max(newInterval[1], i[1])
else:
stack.append(i)
stack.append(newInterval)
return stack
if __name__ == "__main__":
s = Solution()
print s.insert([[1,2],[3,5],[6,7],[8,10],[12,16]],[4,9])
print s.insert([[1,3],[6,9]],[2,5])
| true |
896c390f0835370f76156d3c3de4e2997a7d7522 | sauravrana1983/Python | /Challenge/Introductory/7_Print.py | 261 | 4.1875 | 4 | # Read an integer .
# Without using any string methods, try to print the following:
# Note that "" represents the values in between.
# Input Format
# The first line contains an integer .
def printAll(value):
print(*range(1,value + 1), sep='')
printAll(10) | true |
372d7c1cfb442b51ee13d70fe0a7f56bcde4184e | King-Of-Game/Python | /Example/list/翻转列表.py | 695 | 4.1875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# __author__ : YiXuan
# __date__ : 12/31/2020 2:50 PM
# __software__ : PyCharm
'''
翻转列表
方法一:使用内置函数 reversed()
方法二:使用列表的内置方法 list.sort()
方法二:使用列表的第三个参数
'''
def reversed_list1():
list1 = [1,2,3]
new_list = [i for i in reversed(list1)]
print(new_list)
def reversed_list2():
list1 = [1,2,3]
list1.sort(reverse=True)
# list1.reverse()
print(list1)
def reversed_list3():
list1 = [1,2,3]
new_list = list1[::-1]
print(new_list)
if __name__ == '__main__':
reversed_list1()
reversed_list2()
reversed_list3()
| false |
db0c042f6507dc4c8bacf40b15fdf12d0dfff57c | King-Of-Game/Python | /Algorithm/插入排序.py | 1,159 | 4.21875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# __author__ : YiXuan
# __date__ : 1/23/2021 8:23 PM
# __software__ : PyCharm
'''
插入排序(英语:Insertion Sort)是一种简单直观的排序算法。
它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
'''
# 从小到大排列
def insertionSort(lst):
for i in range(1, len(lst)):
key = lst[i]
j = i
while j > 0 and key < lst[j-1]:
lst[j] = lst[j-1]
j -= 1
lst[j] = key
print(f'从小到大插入排序后: {lst}')
# 从大到小
def insertionSort1(lst):
# 从第二个元素开始遍历,此时第一个元素自然就是有序序列
for i in range(1, len(lst)):
key = lst[i]
j = i
while j > 0 and key > lst[j-1]:
lst[j] = lst[j-1]
j -= 1
lst[j] = key
print(f'从大到小插入排序后: {lst}')
if __name__ == '__main__':
lst = [0, 6, 1, 7, 8, 3, 9, 4, 5, 2]
print(f'原始列表: {lst}')
insertionSort(lst)
insertionSort1(lst)
| false |
a795f444b9265560800773b2cbd980ba6eb989e6 | Abinash-giri/mypractise | /AgeCalculator.py | 761 | 4.21875 | 4 | #Program to calculate age of a person
import datetime
def calculateAge(dob):
'''Calulate's a person age'''
today = datetime.date.today()
age = today.year - dob.year
return age
def checkDate(dob):
'''Checks if date is valid or not'''
day,month,year = dob.split('/')
isvaliddate = True
try:
datetime.datetime(int(year),int(month),int(day))
except ValueError:
isvaliddate = False
return isvaliddate
if __name__ == "__main__":
dob = input('Enter Date of birth in dd/mm/yyyy format:')
isdatevalid = checkDate(dob)
if isdatevalid:
dt = datetime.datetime.strptime(dob,"%d/%m/%Y")
print('Age={} years'.format(calculateAge(dt)))
else:
print('Invalid date entered')
| true |
f57eebb51e5cf1fa20b4b2fbdecf21ecc555e5dc | HoangQuy266/nguyenhoangquy-fundamental-c4t4 | /Session04/sheep.py | 580 | 4.21875 | 4 | print ("Hello, my name is Hiepand these are my sheep size: ")
sheep = [5, 7, 300, 90, 24, 50 ,75]
print (sheep)
for i in range (3):
print("MONTH", i+1)
print ("Now one month has passed and this is my flock: ")
new_sheep = [x+50 for x in sheep]
print (new_sheep)
max_sheep = max(new_sheep)
print ("Now my biggest sheep has size", max(new_sheep), "let's shear it")
print ("After shearing, here is my flock: ")
index = new_sheep.index(max(new_sheep))
new_sheep[index] = 8
print (new_sheep)
sheep = list(new_sheep) | true |
9839709ad5c1b281e13e9cd0cbe3e3eeb736513d | ashutoshkmrsingh/Library-Management-System-Console-based- | /faculty.py | 1,334 | 4.375 | 4 | """
faculty module contains FacultyClass and faculty_list data structure.
FacultyClass used to create faculty objects.
And, faculty_list is a list data structure which stores the faculty objects,
and used for modifying faculty data and storing it in a pickle file named as "faculty_data.pkl"
"""
class FacultyClass:
"""
The FacultyClass contains information of the faculties.
FacultyClass have following attributes:
1. e_name = Contains name of the faculty.
2. e_id = Contains id of the faculty.
3. book_issued = A list data structure, stores book objects issued to the faculty.
"""
def __init__(self, e_name=None, e_id=None, book_issued=[]):
"""Initialises FacultyClass object variables with given arguments. Default arguments are None"""
self.e_name, self.e_id, self.book_issued = e_name, e_id, book_issued
def set(self, e_name=None, e_id=None, book_issued=[]):
"""Set or modify FacultyClass object variables with given arguments. Default arguments are None"""
self.e_name, self.e_id, self.book_issued = e_name, e_id, book_issued
def __str__(self):
return f'Faculty name is {self.e_name}, id is {self.e_id} and book issued are {self.book_issued}'
faculty_list = [] | true |
c2af48a092afd6f5ea2e2080b38ebc4eb099045f | symonk/python-solid-data-structures-and-algorithms | /algorithms/searching/binary_search.py | 884 | 4.25 | 4 | import random
import typing
def binary_search(arr: typing.List[int], target: int) -> int:
"""
Performs a binary search through arr. Divide and conquer the list to achieve
o(log n) performance. Pre requisites are that `arr` must be already sorted.
:param arr: The (sorted) sequence of integers.
:param target: The target number to retrieve the index of.
:return: the index of target; or -1 if target is not `in` arr.
"""
left, right = 0, len(arr) - 1
while left <= right:
pivot = (right + left) // 2
value = arr[pivot]
if value == target:
return pivot
elif value < target:
left = pivot + 1
else:
right = pivot - 1
return -1
if __name__ == "__main__":
seq, find = list(range(0, 250_000, 3)), random.choice(range(250_000))
print(binary_search(seq, find))
| true |
a8ad59d9cdb2baf7d7b33188f42bdf3af7a7d0ed | GeorgeDiNicola/blackjack-game | /application/utils.py | 790 | 4.25 | 4 | from os import system, name
def get_valid_input(prompt, possible_input, error_message):
"""Retrieve valid input from the user. Repeat the prompt if the user gives invalid input.
Keyword Arguments:
prompt (string) -- the question/input prompt for the user.
possible_input (list) -- the allowable input for the prompt.
error_message (string) -- the message to output to the user when his or her input is not in the list allowable inputs.
"""
valid = False
while not valid:
choice = input(prompt)
if choice.lower() in possible_input:
valid = True
else:
print(error_message)
return choice.lower()
def clear_window():
"""Clear all output in the console window."""
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux
else:
_ = system('clear') | true |
91f35e9fcb6f5aaaf03d1e34353a33c405c0e581 | skurtis/Python_Pandas | /Question3.py | 1,578 | 4.125 | 4 | #!/usr/bin/env python3
datafile = open("CO-OPS__8729108__wl.csv") # open the CSV file as the variable "datafile"
diffmax = 0 # starts the max difference between final and initial mean as 0
for i in datafile:
if i.startswith('Date'): # skips the first line (header) but makes sure the previous line is designated as "prevline"
prevline = i
# the previous line needs to be called as the current line before the loop begins again
continue
if prevline.startswith('Date'): # skips the first line of data since there is no preceding data to subtract
prevline = i
continue
if i[17:22].startswith(','): continue # this skips the line with missing data
date_curr = i[:10] # these positions in the line represent the date
time_curr = i[11:16] # these positions in the line represent the time
diff_curr = float(i[17:22]) - float(prevline[17:22]) # these positions in the line represent the water level
# The float command is used to convert the strings to numbers.
# The difference between the previous and current water level is calculated
if diff_curr > diffmax:
# If the difference (increase) in water level is greater than before, then update the water level difference, time, and date
diffmax = diff_curr
datemax = date_curr
timemax = time_curr
prevline = i
print("The maximum increase in water level was", round(diffmax,3), "that was observed on", datemax, "at", timemax)
# the round function is used to round the water level to three decimal points
# the max water level increase and its time and date are inputted into the print function
| true |
6f9357e25c29399021993de2c12c3edb1581c6da | Sablier/Sorts | /Structure/Dequeue.py | 924 | 4.1875 | 4 | class Dequeue(object):
"""构造一个双端队列"""
def __init__(self):
self.data = []
def add_front(self, content):
"""添加一个元素到头部"""
self.data.insert(0, content)
def add_rear(self, content):
"""添加一个元素到队尾"""
self.data.append(content)
def remove_front(self):
"""从队首取出元素"""
return self.data.pop(0)
def remove_rear(self):
"""从队尾取出元素"""
return self.data.pop()
def is_empty(self):
"""判断队列是否为空"""
return self.data == []
def size(self):
"""返回队列的元素个数"""
return len(self.data)
if __name__ == '__main__':
queue = Dequeue()
queue.add_front(1)
queue.add_front(2)
queue.add_front(3)
print(queue.remove_front())
print(queue.remove_rear())
print(queue.remove_rear())
| false |
1364cf38e545880dc0694b9400f227e9bef16438 | PIfagor/ApplicationProgramming-15 | /SecondLabor/Point.py | 1,376 | 4.21875 | 4 | __author__ = 'Wise'
from math import sqrt
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
return
def equals(self, another_point):
return self._x == another_point._x and self._y == another_point._y
def distanse(self, another_point):
assert isinstance(another_point, Point), "%r is not a Point" % another_point
return sqrt((self._x - another_point._x)*(self._x - another_point._x) + (self._y - another_point._y)*(self._y - another_point._y) )
class Point3D:
def __init__(self, x, y,z):
self._x = x
self._y = y
self._z = z
return
def equals(self, another_point):
assert isinstance(another_point, Point3D), "%r is not a Point" % another_point
return self._x == another_point._x and self._y == another_point._y and self._z == another_point._z
def distanse(self, another_point):
assert isinstance(another_point, Point3D), "%r is not a Point" % another_point
return sqrt((self._x - another_point._x)*(self._x - another_point._x) + (self._y - another_point._y)*(self._y - another_point._y) + (self._z - another_point._z)*(self._z - another_point._z))
def showing(self, name):
print("\nPoint: " + name)
print("X: " + str (self._x))
print("Y: " + str(self._y))
print("Z: " + str(self._z))
| false |
e48c040f638eda0e83d01e812c34386af253b29b | cspyb/Graph-Algorithms | /BFS - Breadth First Search (Iterative).py | 897 | 4.21875 | 4 | """
BFS Algorithm - Iterative
"""
#graph to be explored, implemented using dictionary
g = {'A':['B','C','E'], 'B':['D','E'], 'E':['A','B','D'], 'D':['B','E'], 'C':['A','F','G'], 'F':['C'], 'G':['C']}
#function that visits all nodes of a graph using BFS (Iterative) approach
def BFS(graph,start):
queue = [start] #add nodes yet to be checked
explored = [] #add nodes already checked
while queue: #execute while loop until the list "queue" is empty
node=queue.pop(0) #gets first element of the list "queue"
if node not in explored:
explored.append(node) #add node to the list "explored"
neighbours = graph[node] #assign neighbours of the node
for n in neighbours:
queue.append(n) #adds neighbours of the node to the list "queue"
return explored
print(BFS(g,'A'))
| true |
eb415e333c7e0db6ef2e5542b7daaf6b07813c1c | ElliotFriend/bin | /fibonacci.py | 436 | 4.15625 | 4 | #!/usr/bin/env python3
import sys
# Start the sequence. It always starts with [0, 1]
f_seq = [ 0, 1 ]
# Until the length of our list reaches the limit that
# the user has specified, continue to add to the sequence
while len(f_seq) <= int(sys.argv[1]):
# Add the last two numbers in the list, and stick
# that onto the end of the list
f_seq.append(f_seq[-1] + f_seq[-2])
# Print the list out for all to see.
print(f_seq)
| true |
040c39b646a03fb71fbae182b336d1367ffe8d8c | agermain/Leetcode | /solutions/1287-distance-between-bus-stops/distance-between-bus-stops.py | 1,298 | 4.125 | 4 | # A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
#
# The bus goes along both directions i.e. clockwise and counterclockwise.
#
# Return the shortest distance between the given start and destination stops.
#
#
# Example 1:
#
#
#
#
# Input: distance = [1,2,3,4], start = 0, destination = 1
# Output: 1
# Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
#
#
#
# Example 2:
#
#
#
#
# Input: distance = [1,2,3,4], start = 0, destination = 2
# Output: 3
# Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
#
#
#
#
# Example 3:
#
#
#
#
# Input: distance = [1,2,3,4], start = 0, destination = 3
# Output: 4
# Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
#
#
#
# Constraints:
#
#
# 1 <= n <= 10^4
# distance.length == n
# 0 <= start, destination < n
# 0 <= distance[i] <= 10^4
#
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
total = sum(distance)
cw = sum(distance[min(start, destination):max(start, destination)])
acw = total-cw
return min(cw, acw)
| true |
486023ab94e7e490a5ca39bfa2224c26c469f617 | beth2005-cmis/beth2005-cmis-cs2 | /cs2quiz3.py | 1,645 | 4.75 | 5 | # 1) What is a recursive function?
# A function calls itself, meaning it will repeat itself when a certain line or a code is called.
# 2) What happens if there is no base case defined in a recursive function?
#It will recurse infinitely and maybe you will get an error that says your maximum recursion is reached.
# 3) What is the first thing to consider when designing a recursive function?
# You have to consider what the base case(s) are going to be because that is when and how your function will end and return something.
# 4) How do we put data into a function call?
# We put data into a function call by using parameters.
# 5) How do we get data out of a function call?
# We get data out of a function call by using parameters.
#a1 = 8
#a2 = 8
#a3 = -1
#b1 = 2
#b2 = 2
#b3 = 4
#c1 = -2
#c2 = 4
#c3 = 45
#d1 = 6
#d2 = 8
#d3 = 4
#Programming
#Write a script that asks the user to enter a series of numbers.
#When the user types in nothing, it should return the average of all the odd numbers that were typed in.
#In your code for the script, add a comment labeling the base case on the line BEFORE the base case.
#Also add a comment label BEFORE the recursive case.
#It is NOT NECESSARY to print out a running total with each user input.
def avg_odd_numbers(sum_n=0, odd_n=0):
n = raw_input("Next number: ")
#Base Case
if n == "":
return "The average of all the odd numbers are {}".format(sum_n/odd_n)
#Recursive Case
else:
if float(n) % 2 == 1:
return avg_odd_numbers(sum_n + float(n), odd_n + 1)
else:
return avg_odd_numbers(sum_n, odd_n)
print avg_odd_numbers()
| true |
31f900dde317cc4b7d78cbedca4c6beb09aa5229 | swheatley/LPTHW | /ex5.2.py | 763 | 4.34375 | 4 | print "LPTHW Lesson 5.2 \n \t Python format characters"
print '% :', "This character marks the start of the specifier"
print 'd :', "Integer/decimal"
print 'i :', "Integer/decimal"
print 'o :', "Octal value"
print 'u :', "Obsolete type- identical to 'd' "
print 'x :', "Hexadecimal(uppercase)"
print 'e :', "Floating point exponential format(lowercase)"
print 'E :', "Floating point exponential format(uppercase)"
print 'f :', "Floating point decimal format"
print 'g :', "Floating point format(lowercase)"
print 'G :', "Floating point format(uppercse)"
print 'c :', "Single character ( accepts integer or single character string)"
print 'r :', "String (converts any Python object using repr())."
print 's :', "String (converts any Python object using str())." | true |
c4259a587814ff544af950d1383199fc40daf12e | swheatley/LPTHW | /ex40.1.py | 888 | 4.15625 | 4 | # Exercise 40: Modules, Classes, and Objects
mystuff ={'apple', "I AM APPLES!"}
print mystuff['apple']
#this goes in mystuff.py
def apple():
print "I AM APPLES!"
import mystuff
mystuff.apple()
def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
import mystuff
mystuff.apple()
print mystuff.tangerine
mystuff['apple'] # get apple from dict
mystuff.apple() # get apple from the module
mystuff.tangerine # same thing, it's just a variable
class MyStuff(object):
def _init_(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I AM CLASSY APPLES!"
# Instaniates the class MyStuff
thing = MyStuff()
thing.apple()
print thing.tangerine
# dict style
mystuff['apples']
#module style
mystuff.apples()
print mystuff.tangerine
#class style
thing = MyStuff()
thing.apples()
print thing.tangerine
| false |
5d93d04b10b4b45fa27233a37798dd6948feebd5 | chengbaobao630/practies | /07-19/Student.py | 706 | 4.125 | 4 | from datetime import datetime
class Person(object):
def __init__(self):
print("person init")
self.__birth = datetime.now()
def birth(self):
return self.__birth
class Man(object):
def __init__(self):
print(r"i'm a man")
class Student(Man, Person):
def __init__(self, name="default"):
Man.__init__(self)
Person.__init__(self)
print("student init")
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
s = Student()
s.name = "cc"
print(s.name)
s.age = 99
print(s.age)
p = Person()
print(p.birth())
print(s.birth())
| false |
2a0a967462c5958e31e20cbe1cfce34be2a05a93 | pjain4161/HW08 | /fun2.py | 1,139 | 4.25 | 4 | # Borrowed from https://realpython.com/learn/python-first-steps/
##############################################################################
#### Modify the variables so that all of the statements evaluate to True. ####
##############################################################################
var1 = -588
var2 = "pi banana a string"
var3 = ['hi', 'hello', "salut", 'salaam', 'namaste']
var4 = ("pooja", "says", "Hello, Python!")
var5 = {'happy': 1, 'tuna':7, 'egg':'salad'}
var6 = 11.0
###############################################
#### Don't edit anything below this comment ###
###############################################
# integers
print(type(var1) is int)
print(type(var6) is float)
print(var1 < 35)
print(var1 <= var6)
# strings
print(type(var2) is str)
print(var2[5] == 'n' and var2[0] == "p")
# lists
print(type(var3) is list)
print(len(var3) == 5)
# tuples
print(type(var4) is tuple)
print(var4[2] == "Hello, Python!")
# dictionaries
print(type(var5) is dict)
print("happy" in var5)
print(7 in var5.values())
print(var5.get("egg") == "salad")
print(len(var5) == 3)
var5["tuna"] = "fish"
print(len(var5) == 3) | true |
546ee390dfe4711bab61a6648daae43389ec8b4d | irsol/hacker-rank-30-days-of-code | /Day 9: Recursion.py | 446 | 4.3125 | 4 | """
Task
Write a factorial function that takes a positive integer,N as a parameter and prints the result
of N!(N factorial).
Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial,
you will get a score of 0.
Input Format
A single integer,N (the argument to pass to factorial).
"""
def factorial(n):
if n == 1:
return 1
else:
return(n * factorial(n - 1))
print(factorial(10)) | true |
e07b328b02a76c8cc243bcf7002b07cf96f8b8fc | infractus/my_code | /RPG Dice Roller/rpg_dice_roller.py | 2,336 | 4.4375 | 4 | #Dice roller
import random
roll = True #this allows to loop to play again
while roll:
def choose_sides(): #this allows player to choose which sided die to roll
print('Hello!')
while True:
sides=(input('How many sides are the dice you would you like to roll?' ))
if sides.isdigit(): break
print('Choose a proper number of sides.')
return sides
def choose_dice_number(): #choose how many dice to roll
while True:
num_dice=input('How many of these dice would you like to roll?')
if num_dice.isdigit(): break
print('No, you must enter a whole number.')
num_dice=int(num_dice)
while num_dice <=0:
print('Enter a valid number: ')
num_dice=int(input())
return num_dice
sides=choose_sides()
num_dice=choose_dice_number()
subtotal=0
for n in range(num_dice):
result=random.randint(1, int(sides))
result=int(result)
print (result)
subtotal=result+subtotal
#choose a modifier
while True:
print('What is the modifier?')
modifier=input()
if modifier.lstrip('-').isdigit(): break # lstrip for neg number
if modifier.lstrip('+').isdigit(): break
print('No, you must enter a whole number.')
modifier=int(modifier)
resultmod=subtotal+modifier
#creates plus_or_minus variable to properly display the modifier in the results
if modifier >= 0:
plus_or_minus='+'
else:
plus_or_minus='-'
#show results
modifier=str(abs(modifier)) #sets modifier string with an absolute value (no negative)
result=str(result)
resultmod=str(resultmod)
num_dice=str(num_dice)
sides=str(sides)
subtotal=str(subtotal)
#explain what user has rolled
print('You rolled ' + num_dice + 'd' + sides + plus_or_minus + modifier +'.')
print('You rolled ' + subtotal + ' with a ' + plus_or_minus + modifier + ' modifier resulting in a ' + resultmod + '.')
while True:
again=str(input('Do you want to play again? y/n? ')).lower()
if again.startswith('n'):
roll = False
break
elif again.startswith('y'):
roll = True
break
else:
print('Enter "y" or "n".')
| true |
5bd8b16f9adeb479b29a0970406cf62d5e4a7477 | paigeweber13/exercism-progress | /python/clock/clock.py | 1,145 | 4.125 | 4 | """
contains only the clock object
"""
class Clock():
"""
represents a time without a date
"""
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
self.fix_time()
def __repr__(self):
# return str(self.hour) + ':' + "{:2d}".format(self.minute)
return str(self.hour).zfill(2) + ':' + str(self.minute).zfill(2)
def __eq__(self, other):
return bool(self.hour == other.hour
and self.minute == other.minute)
def __add__(self, minutes):
self.minute += minutes
self.fix_time()
return self
def __sub__(self, minutes):
self.minute -= minutes
self.fix_time()
return self
def fix_time(self):
"""
checks if self is a valid time and fixes it in place if not
"""
while self.minute >= 60:
self.minute -= 60
self.hour += 1
while self.hour >= 24:
self.hour -= 24
while self.minute < 0:
self.minute += 60
self.hour -= 1
while self.hour < 0:
self.hour += 24
| true |
1ac9e7c54261c2c15c3856ccba743791d2e3cd41 | amacharla/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,343 | 4.3125 | 4 | #!/usr/bin/python3
class Square:
def __init__(self, size=0, position=(0, 0)):
"""
Calls respective setter funciton
Args:
size: must be int and greater than 0
position: must be tuple and args of it must be int
"""
self.size = size
self.position = position
# SIZE------------------------------------------------------------------------
@property
def size(self):
"""
Getter method
Returns: size
"""
return self.__size
@size.setter
def size(self, value):
""" setter method
Args:
value: must be int and greater than 0
Raises:
TypeError: if size is not int
ValueError: size is less than 0
"""
if type(value) != int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
# Position--------------------------------------------------------------------
@property
def position(self):
""" Getter method
Returns: position """
return self.__position
@position.setter
def position(self, position):
""" setter method
Args:
position: tuple must be 2 positive int
Raises:
TypeError: position must be a tuple of 2 positive integers
"""
if type(position) != tuple or len(position) != 2 \
or type(position[0]) != int or type(position[1]) != int:
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = position
# Special--------------------------------------------------------------------
def area(self):
""" Returns: current square area """
return self.__size ** 2
def my_print(self):
""" prints square visually with # at position(x, y) """
if self.__size == 0:
print()
else:
x, y = self.__position[0], self.__position[1]
[print() for i in range(y)] # goes down
for j in range(self.__size):
print(" " * x, end='') # goes right set position
print("#" * self.__size) # prints square horozantally then \n
| true |
217c17718277bd9eebc936314da74581bf1c5d07 | Kevin-Rush/CodingInterviewPrep | /Python/findMissingNumInSeries.py | 617 | 4.21875 | 4 | '''
1. Find the missing number in the array
You are given an array of positive numbers from 1 to n, such that all numbers from 1 to n are
present except one number x. You have to find x. The input array is not sorted. Look at the below array
and give it a try before checking the solution.
'''
def find_missing(input):
# calculate sum of all elements
# in input list
sum_of_elements = sum(input)
# There is exactly 1 number missing
n = len(input) + 1
actual_sum = (n * ( n + 1 ) ) / 2
return actual_sum - sum_of_elements
if __name__ == "__main__":
print(find_missing([3, 7, 1, 2, 8, 4, 5]))
| true |
958e8293912a6df866ea3b8821948db8dc3540e4 | Kevin-Rush/CodingInterviewPrep | /Python/TreeORBST.py | 712 | 4.25 | 4 | '''
6. Determine if a binary tree is a binary search tree
Given a Binary Tree, figure out whether it’s a Binary Search Tree. In a binary search tree, each
node’s key value is smaller than the key value of all nodes in the right subtree, and is greater than
the key values of all nodes in the left subtree. Below is an example of a binary tree that is a valid BST.
'''
def is_bst_rec(root, min_val, max_val):
if root == None:
return True
if root.data < min_val or root.data > max_val:
return False
return is_bst_rec(root.left, min_val, root.data) and is_bst_rec (root.right, root.data, max_val)
def is_bst(root):
return is_bst_rec(root, -sys.maxsize-1, sys.maxsize)
#tested in browser | true |
e1fa4cc48342e31acfbfc03bb7dba9addb12711a | subashreeashok/python_solution | /python_set1/q1_1.py | 1,325 | 4.21875 | 4 | '''
Name : Subahree
Setno: 1
Question_no:1
Description:Finding the largest odd numbers
'''
x=raw_input("enter X: ")
y=raw_input("enter Y: ")
z=raw_input("enter Z: ")
a=int(x)
b=int(y)
c=int(z)
if(a%2!=0 and b%2!=0 and c%2!=0):#all are odd numbers
if(a>b and a>c):
print("a is large")
elif(b>a and b>c):
print("b is large")
else:
print("c is large")
elif(a%2!=0 and b%2!=0 and c%2==0):#when a and b are odd numbers
#print "c is not odd number"
if(a>b):
print("a is largest odd number")
else:
print("b is largest odd number")
elif(a%2==0 and b%2!=0 and c%2!=0):#when b and c are odd numbers
if(b>c):
print("b is largest odd num")
else:
print("c is largest odd num")
elif(a%2!=0 and b%2==0 and c%2!=0):#when a and c are odd numbers
if(a>c):
print("a is largest odd num")
else:
print("cis largest odd number")
elif(a%2==0 and b%2==0 and c%2!=0):#when c alone is an odd number
print("c is largest odd num")
elif(a%2!=0 and b%2==0 and c%2==0):#when a alone is an odd number
print("a is largest odd num")
elif(a%2==0 and b%2!=0 and c%2==0):#when b alone is an odd number
print("c is largest odd num")
else:#all are even numbers
print("not odd number") | false |
5f815d28e7ed7d3a54819698c3446cdfc6b146c8 | subashreeashok/python_solution | /python_set1/q1_3.py | 486 | 4.15625 | 4 | '''
Name : Subahree
Setno: 1
Question_no:3
Description:get 10 numbers and find the largest odd number
'''
try:
print "enter the numbers: "
max=0
#getting 10 numbers
for i in range(0,10):
num=int(raw_input())
#print(num)
#checking odd or not
for j in range(0,10):
if(num%2!=0):
if(num>max):
max=num
if(max==0):
print "numbers are not odd"
print "largest odd number: "+str(max)
except Exception as e:
print e | true |
7042390201ce8b3fc1a3d34d8ef24599dc947445 | realrlgus/Python_Practice | /20200203/DataType/String.py | 2,309 | 4.25 | 4 | # 파이썬에서 문자열 만드는 방법
# 큰 따옴표
double_quotes = "Hello Python"
# 작은따옴표
single_qoutes = 'Hello Python'
# 삼중 큰 따옴표
triple_double_quotes = """Hello Python"""
# 삼중 작은따옴표
triple_single_quotes = '''Hello Python'''
# 삼중 큰, 작은 따옴표를 사용 시 다수의 라인이 포함된 문자열 작성 가능
# 문자열 연산 string = Python is fun!
head = "Python"
tail = " is fun!"
string = head + tail
print(string)
# 문자열 곱하기 =이 50번 출력
print("=" * 50)
# 문자열 인덱싱 twelve = s, back = n 마이너스 일경우 뒤에서부터 시작
phrase = "Life is too short, You need Python"
twelve = phrase[12]
back = phrase[-1]
print(twelve, back)
# 문자열 슬라이싱 one_three = Lif 끝번호에 해당되는것은 포함되지 않음 0:4 ==> 0 <= a < 3
one_three = phrase[0:4]
after_nineteen = phrase[19:]
before_seventeen = phrase[:17]
all_string = phrase[:]
print(one_three, after_nineteen, before_seventeen, all_string)
# 문자열 포매팅 문자열 내에 값을 삽입함
formmating_number = "I eat %d apples." % 3
formmating_string = "I eat %s apples." % "three"
num = 3
formmating_variable = "I eat %d apples." % num
day = "three"
formmating_many = "I ate %d apples. so i was sick for %s days." % (num, day)
# 고급 문자열 포매팅
advance_formmating = "I eat {0} apples.".format(num)
print(formmating_number, formmating_string,
formmating_variable, formmating_many, advance_formmating)
# 문자열 관련 함수
# 문자 개수 세기(count) a.count("b") = 2
a = "hobby"
print(a.count("b"))
# 문자 위치 알려주기(find) a.find('a') = -1 해당하는 문자의 인덱스 값 반환 없을경우 -1반환
# 문자 위치 알려주기(index) 해당하는 문자열을 찾지 못할경우 에러 발생
a = "Python!"
print(a.find('a'))
# 문자열을 대문자로 변경(upper) 소문자로 변경(lower) HI
a = "hi"
b = "HI"
print(a.upper())
print(b.lower())
# 문자열 공백 제거 lstrip rstrip strip 왼쪽 오른쪽 양쪽
a = " hi"
b = "hi "
c = " hi "
print(a.lstrip())
print(b.rstrip())
print(c.strip())
# 문자열 왼쪽 오른쪽 가운데 정렬
right = "{0:<10}".format("hi")
left = "{0:>10}".format("hi")
center = "{0:^10}".format("hi")
print(right, left, center)
| false |
4cbba297236116927584453cab7e9d579b93f3a1 | DeltaEcho192/Python_test | /pos_neg_0_test.py | 267 | 4.1875 | 4 | test1=1;
while test1 != 0:
test1=int(input("Please enter a number or to terminate enter 0 "))
if test1 > 1:
print("This number is positve")
elif test1 < 0:
print("This number is negative")
else:
print("This number is zero")
| true |
59588a208d398b0c0f0621d99e188318d771646f | esther4599/Python01_Starting_Python | /15.클래스와객체지향프로그래밍/02.인스턴스이해.py | 766 | 4.125 | 4 | #클래스와 인스턴스?
print(type(5)) # <class 'int'>
print(isinstance(5, int))
num1 = []
print(type(num1))
num2 = list(range(10))
print(num2)
chr = list('Hello')
print(chr)
print(type(num1), type(num2), type(chr)) # 모두 <class 'list'>
print(isinstance(num1, list)) # True
print(num1 == list) # False
'''
위와 같은 결과? class = 분류 (사람 = 강사, 학생 / 강사 != 학생)
사람 = class
강사, 학생 = instance
'''
#실습추가
# + is = 변수의 포인터를 비교하는 연산자. 파이썬의 변수는 모두 포인터를 가리킨다.
str1 = 'Hello'
str2 = 'Hello'
print(str1 == str2) # True
print(str1 is str2) # True. 왜...?
str1 = list('Hello')
str2 = list('Hello')
print(str1 == str2) # True
print(str1 is str2) # False
| false |
32d0350eead71df434bd5a6cf065c18d5007ff46 | Kify7/Python_string_data | /manipular_strings.py | 1,588 | 4.3125 | 4 | #CONCATENATIG STRINGS
a = "hello"
b = a + "There"
c = a + ' ' + 'There'
print(b)
print(c)
#USING IN AS A LOGICAL OPERATOR
fruit = 'banana'
print('n' in fruit)
print('t' in fruit)
if 'a' in fruit :
print('Found it!')
#STRING COMPARISON
word = input("enter word: ")
if word == 'banana' :
print('Al right, bananas!')
if word < 'banana' :
print('Your word,' + word + ',comes before banana.')
elif word > 'banana' :
print('Your word,' + word + ',comes after banana.')
else :
print('Al right')
#STRING FUNCTIONS IN STRING LIBRARY
# lower() object method
greet = "Hello Kify"
zap = greet.lower()
print(zap)
print(greet)
print('Hi There'.lower())
#Type method / dir method
stuff = "cats"
print(type(stuff))
print(dir(stuff)) #prints out the method of the type of data
#str.capitalize
#str.enter
#str.endswith()
#str.find()
#str.lstrip()
#str.replace()
#str.lower()
#str.rstrip()
#str.strip()
#str.upper()
#SEARCHING IN A STRING
fruta = 'pomelo'
pos = fruta.find('me')
print(pos)
aa = fruta.find('z')
print(aa)
#REPLACE
saludo = ('Hola Nina')
saludito =saludo.replace('Nina', 'Kify')
print(saludito)
#SPACES
hello = ' Nina Danonina '
hi2 = hello.lstrip()
hi3 = hello.rstrip()
hi4 = hello.strip()
print(hi2)
print(hi3)
print(hi4)
#PREFIXES
line = 'Please, have a nice day'
print(line.startswith('Please'))
print(line.startswith('p'))
#PARSING AND EXTRACTING
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
atpos = data.find('@')
print(atpos)
sppos = data.find(' ',atpos)
print(sppos)
host = data[atpos+1 : sppos]
print(host)
| false |
9728556ef7629be2b859b6482bcb2ebe2fc690ae | ultra-programmer/Complete_Python3_Bootcamp_Final_Captsone_Projects | /text/pig_latin.py | 558 | 4.125 | 4 | """
Pig Latin!
"""
while True:
try:
STRING = input('Please enter the word to be translated into pig latin: ')
if len(STRING.split()) > 1:
raise RuntimeError
elif len(STRING.split()) < 1:
raise RuntimeError
except RuntimeError:
print('Please enter a word to be reversed\n')
continue
else:
break
if STRING[0].lower() in ['a', 'e', 'i', 'o', 'u']:
print(f'Your word in pig latin is: {STRING}-ay')
else:
print(f'Your word in pig latin is: {STRING[1::]}-{STRING[0]}ay')
| false |
a956e9f48c66200f088ac091faac027169e43040 | Roy-Wells/Python-Code | /算法第四版(python)/第一章 基础/03Queue.py | 1,030 | 4.21875 | 4 | """
P78.队列
class Queue.Queue(maxsize=0)
FIFO即First in First Out,先进先出。Queue提供了一个基本的FIFO容器,使用方法很简单,maxsize是个整数,指明了队列中能存放的数据个数的上限。
一旦达到上限,插入会导致阻塞,直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。
常用基本方法:
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.get([block[, timeout]]) 读队列,timeout等待时间
Queue.put(item, [block[, timeout]]) 写队列,timeout等待时间
Queue.queue.clear() 清空队列
"""
#注意这里在python3中的导入队列为queue。
#而在python2中导入队列因为Queue
import queue
q = queue.Queue()
for i in range(5):
if (~q.full()):
q.put(i)
while not q.empty():
print(q.get())
| false |
e744e1dc6f4ee7b3a9917cb05c9a9cfc82de8b09 | SushanthPS/Python | /0primeNumber.py | 287 | 4.15625 | 4 |
def isprime(n):
if n==1:
return False
elif n==2 or n==3:
return True
elif n%2==0:
return False
else:
for i in range(3,n//2,2):
if n%i==0:
return False
return True
print(isprime(13)) | false |
91cb2e4f2e111bee836829551d4da8b8d59366a1 | kinghaoYPGE/career | /python/20190117/Code/c2.py | 1,010 | 4.125 | 4 | """
python常用高阶函数
map, reduce, filter, sorted
"""
# map reduce 是一个算法模型--hadoop(map/reduce:映射,规约),并行计算
# map 映射
list_a = [1, 2, 3, 4, 5]
def my_square(x):
return x**2
r = map(my_square, list_a)
print(list(r))
# reduce
# reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
# 从序列头计算到尾
from functools import reduce
def minus(x, y):
return x - y
r = reduce(minus, list_a)
# [1, 2, 3, 4, 5] -->12345
# def my_fn(x, y):
# return x*10 + y
# r = reduce(my_fn, list_a)
# def char2num(s):
# list_a = list(range(10))
# list_b = list(map(chr, list(range(48, 58))))
# return dict(zip(list_b, list_a))[s]
# r = reduce(my_fn, map(char2num, '123579'))
def str2int(s):
def my_fn(x, y):
return x*10 + y
def char2num(s):
list_a = list(range(10))
list_b = list(map(chr, list(range(48, 58))))
return dict(zip(list_b, list_a))[s]
return reduce(my_fn, map(char2num, s))
r = str2int('134314234')
print(r)
| false |
acb25112304c3b8e372806b92a8294be764da0c8 | kinghaoYPGE/career | /python/20190124/Code/c2.py | 1,267 | 4.125 | 4 | """
collections模块:就是对'组'数据结构的补充
"""
# tuple->namedtuple(命名元组)
from collections import *
point = (1, 2) # 坐标点
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2) # 结构化
print('x: %s, y: %s' % (p.x, p.y))
print(isinstance(p, Point))
print(isinstance(p, tuple))
# list(线性存储:查询元素快,插入删除效率低)->deque(双向列表如 队列、栈): 首尾插入删除效率高)
dq = deque(['a', 'b', 'c', 1, 2, 3])
dq.append('x')
print(dq)
dq.appendleft('y')
print(dq)
dq.pop()
print(dq)
dq.popleft()
print(dq)
# dict->defaultdict(初始化一个默认值)
d_d = defaultdict(lambda: 'NIL')
d_d['a'] = 1
print(d_d['a'])
print(d_d['b'])
# dict->OrderedDict
d1 = dict([(1, 'a'), (5, 'e'), (2, 'b'), (3, 'c'), (4, 'd')])
d1[9] = '9'
print(d1.keys()) # 字典的key是无序的、不重复的、不可变的
od = OrderedDict([(1, 'a'), (5, 'e'), (2, 'b'), (3, 'c'), (4, 'd')])
print(od)
# dict->ChainMap:把一组dict串成一个ChainMap对象
cm = ChainMap({1:'1', 2: '2'}, {3: 'a', 4: 'b'})
for k, v in cm.items():
print(k, v)
# dict->Counter(计数器): 统计字符
c = Counter('life is short, i use python!')
# str_target = 'life is short, i use python!'
c = Counter([1, 1, 2, 3, 'a', 2])
print(c)
| false |
97f02f7148f3afc7bd4b190a20d0b87d30a210f2 | fmarculino/CursoEmVideo | /ExMundo2/Ex041.py | 812 | 4.15625 | 4 | """
A confederaçã nacional de natação precisa de um programa que
leia o ano de nascimento de um atleta e mostre sua categoria, de
acordo com a idade:
- Até 9 anos: MIRIM
- Até 14 anos: INVFANTIL
- Até 19 anos: JUNIOR
- Até 24 anos: SENIOR
- Acima: MASTER
"""
from datetime import date
dtnascimento = int(input('Digite o ano de nascimento:'))
idade = date.today().year - dtnascimento
if 0 < idade <= 9:
print(f'O atleta tem {idade} anos e é da categoria MIRIM')
elif 9 < idade <= 14:
print(f'O atleta tem {idade} anos e é da categoria INFANTIL')
elif 14 < idade <= 19:
print(f'O atleta tem {idade} anos e é da categoria JUNIOR')
elif 19 < idade <= 24:
print(f'O atleta tem {idade} anos e é da categoria SENIOR')
else:
print(f'O atleta tem {idade} anos e é da categoria MASTER')
| false |
37e26a32544446f0780d2a902598e23bf84f578d | fmarculino/CursoEmVideo | /ExMundo2/Ex059.py | 1,239 | 4.4375 | 4 | """
Crie um programa que leia dois valores e mostre um menu como o ao lado
da tele:
Seu programa deveŕa realizar a operação solicitada em cada casoself.
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos números
[5] Sair do programa
"""
valor1 = float(input('Digite o primeiro valor: '))
valor2 = float(input('Digite o segundo valor: '))
opcao = str('0')
while opcao != 5:
print('[1] Soma')
print('[2] Multiplica')
print('[3] Maior')
print('[4] Novo número')
print('[5] Sair do programa')
opcao = str(input('Digite sua opção: '))
if opcao == str('1'):
print(f'A soma do {valor1} + {valor2} = {valor1 + valor2}')
elif opcao == str('2'):
print(f'A multiplicação do {valor1} x {valor2} = {valor1 * valor2}')
elif opcao == str('3'):
if valor1 > valor2:
maior = valor1
else:
maior = valor2
print(f'entre os valores digitados o maior valor é {maior}')
elif opcao == str('4'):
valor1 = float(input('Digite o primeiro valor: '))
valor2 = float(input('Digite o segundo valor: '))
elif opcao == str('5'):
break
else:
print('O valor digitado é invállido tente novamente.')
print('Fim do programa!')
| false |
0c63157083ee466ff665870a7d70c3e0c09c62f6 | 15AshwiniI/PythonPractice | /Calculator.py | 570 | 4.1875 | 4 | #this is how you comment in python
print "Welcome to Calculator!"
print "Enter your first number"
a = input()
print "Enter your second number"
b = input()
print "What calculation whould you like to do?"
print "Addition, Subtraction, Multiplication, Division"
p = raw_input()
if p == "Addition":
print "Answer: "+ str(a + b)
elif p == "Subtraction":
print "Answer: "+ str(a - b)
elif p == "Multiplication":
print "Answer: "+ str(a * b)
elif p == "Division":
print "Answer: "+ str(a / b)
else:
print "Not a valid calculation"
print "goodbye!"
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.