blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f3a03d3e205693c0aca0145a19a6884f11216e39 | NaimChowdhury/NLTK | /Ch1/getting_started.py | 2,116 | 4.21875 | 4 | import nltk
# from NLTK's book module, load all items
from nltk.book import *
# To find out about texts, enter the text names
text1
text2
# concordance shows every occurence of a given word in a given text
text1.concordance("monstrous")
text2.concordance("affection")
text3.concordance("lived")
# 'text1 is moby dick'
# 'text2 is Sense and Sensibility'
# 'text3 is the Bible'
# 'text4 is Inaugural Address Corpus'
# 'text5 is NPS Chat Corpus, for unconvential words like im, ur, lol'
# similar will find words that are used in a similar range of contexts to the string entered as an argument
text1.similar("monstrous")
text2.similar("monstrous")
# common_contexts shows contexts that are shared by two or more words
text2.common_contexts(["monstrous", "very"])
# dispersion plots show positional information about the location of words in a text. we can use this to find patterns in word usage in a given text, or use it to find patterns of word usage over a period of history
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])
# generate will generate some random text "in the various styles" of the given texts. No argument required
text5.generate()
# len() returns the number of words and punctuation in a text (tokens)
len(text6)
# set() will return a set of all tokens in a given text
sorted(set(text3))
len(set(text3))
# calculating the "lexical richness" of a text is just number of distinct words divided by number of words
len(set(text3)) / len(text3)
# One could potentially define a function to measure the lexical diversity of a text
# The following function divides the number of unique words by number of words
def lexical_diversity(text):
return len(set(text)) / len(text)
# _2_ Lists
# Texts are nothing more than a sequence of words and punctuation.
sent1 = ['Call', 'me', 'Ishmael', '.']
sent2
sent3
# Texts can be concatenated as well
sent1+sent4
sent1.append("word")
# 2.2 Indexing lists
text4[173]
text4.index('awaken')
# This section was very simple. Won't bother typing anything up
# _3_ Computing with Language: Simple Statistics
| true |
81eb4e7e6de16dd59f92b806a3930ad4d1c0ae30 | Yuki-Sakaguchi/python_study | /challenge/part8.py | 1,168 | 4.34375 | 4 | # クラス
import math
class Apple:
"""
りんごクラス
"""
def __ini__(self, w, h, c, p):
"""コンストラクタ"""
self.width = w
self.height = h
self.color = c
self.producing_area = p
class Circle:
"""
円のクラス
"""
def __init__(self, r):
self.radius = r
def area(self):
"""
円の面積を求める
Return 半径 x 半径 x 円周率
"""
return (self.radius ** 2) * math.pi
circle = Circle(10)
print('面積は[ ' + str(circle.area()) + ' ]です')
class Triangle:
"""
三角形のクラス
"""
def __init__(self, w, h):
self.width = w
self.height = h
def area(self):
return (self.width * self.height) / 2
triangle = Triangle(10, 20)
print('面積は[ ' + str(triangle.area()) + ' ]')
class Hexagon:
"""
六角形のクラス
"""
def __init__(self, sl):
self.side_length = sl
def calculate_perimeter(self):
return self.side_length * 6
hexagon = Hexagon(10)
print('外周の長さは[ ' + str(hexagon.calculate_perimeter()) + ' ]') | false |
37457face124d49a0e26fefeb69e98a9289b92a9 | dmulholl/algorithms | /misc/shuffle.py | 1,150 | 4.34375 | 4 | #!/usr/bin/env python3
##
# This module contains an implementation of the Fisher-Yates/Durstenfeld algorithm for randomly
# shuffling an array.
##
import unittest
import random
# O(n): iterate over the array and at each index choose randomly from the remaining unshuffled
# entries. (The loop skips the final index as a minor optimization to avoid swapping the last
# element with itself.)
def shuffle(array):
for i in range(len(array) - 1):
j = random.randrange(i, len(array))
swap(array, i, j)
# This algorithm is often implemented using a backwards loop as in many languages this makes the
# math for selecting the random element more elegant. (The loop skips the zero index as a minor
# optimization to avoid swapping the first element with itself.)
def backwards_shuffle(array):
for i in range(len(array) - 1, 0, -1):
j = random.randrange(i + 1)
swap(array, i, j)
# Swap the array entries at indices `p` and `q`.
def swap(array, p, q):
array[p], array[q] = array[q], array[p]
if __name__ == '__main__':
array = [i for i in range(10)]
print(array)
shuffle(array)
print(array)
| true |
0cb6a2c3fcc488b20c3045af569b8ecfac030bde | dmulholl/algorithms | /sorting/quicksort.py | 1,638 | 4.15625 | 4 | #!/usr/bin/env python3
##
# This module contains a reference implementation of the quicksort algorithm.
##
import unittest
import random
def sort(array):
random.shuffle(array)
quicksort(array, 0, len(array) - 1)
# Sorts the slice of `array` identified by the inclusive indices `l_index` and `r_index`.
def quicksort(array, l_index, r_index):
if l_index < r_index:
p = partition(array, l_index, r_index)
quicksort(array, l_index, p - 1)
quicksort(array, p + 1, r_index)
# Partitions the slice of `array` identified by the inclusive indices `l_index` and `r_index`.
def partition(array, l_index, r_index):
l, r = l_index, r_index + 1
pivot = array[l_index]
while True:
while True:
l += 1
if array[l] >= pivot or l == r_index:
break
while True:
r -= 1
if array[r] <= pivot or r == l_index:
break
if l >= r:
break
array[l], array[r] = array[r], array[l]
array[l_index], array[r], = array[r], array[l_index]
return r
# Returns true if the input is empty, of length 1, or sorted in ascending order.
def is_sorted(array):
for index in range(1, len(array)):
if array[index] < array[index - 1]:
return False
return True
class TestSort(unittest.TestCase):
def test_sort(self):
test_array = [i for i in range(1000)]
while is_sorted(test_array):
random.shuffle(test_array)
sort(test_array)
self.assertTrue(is_sorted(test_array))
if __name__ == '__main__':
unittest.main()
| true |
ea7b05b3302d4efefb48e5c4aab9e84fb4ae33e5 | pftom/python_learning | /9/user.py | 2,250 | 4.125 | 4 | class User():
"""9-3 The user class 9-5"""
def __init__(self, first_name, last_name, login_attempts, **user_info):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = login_attempts
self.user_info = user_info
def describe_user(self):
print("The user has following info: ")
print("User's first_name is " + self.first_name)
print("User's last_name is " + self.last_name)
print("User's login_attempts is " + str(self.login_attempts))
for key, value in self.user_info.items():
print(key + ": " + value)
def greet_user(self):
print("I'm glad to meet you!")
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
def print_login_attempts(self):
print("This instance login attempts is " + str(self.login_attempts))
pftom = User('wei', 'ge', 0, address='5005')
pfmRc = User('mrc', 'mrc', 0, address='4004')
pftom.describe_user()
pftom.greet_user()
print("\n")
pfmRc.describe_user()
pfmRc.greet_user()
pftom.increment_login_attempts()
pftom.print_login_attempts()
pftom.increment_login_attempts()
pftom.print_login_attempts()
pftom.increment_login_attempts()
pftom.print_login_attempts()
pftom.increment_login_attempts()
pftom.print_login_attempts()
pftom.reset_login_attempts()
pftom.print_login_attempts()
class Privileges():
"""
A basic privilege class
"""
def __init__(self, privileges):
self.privileges = privileges
def show_privileges(self):
print("This person has following privileges: ")
privileges = self.privileges
for privilege in privileges:
print("- " + privilege)
# 9-7 extend user for child class
class Admin(User):
"""
create a admin class for special handle
"""
def __init__(self, first_name, last_name, login_attempts, privileges):
super().__init__(first_name, last_name, login_attempts)
self.privileges = Privileges(privileges)
uncle_tom = Admin('uncle', 'tom', 0, ['can add post', 'can delete', 'can ban user'])
uncle_tom.privileges.show_privileges() | true |
da39c422ee8423eb92757c01c86fcb5befb24497 | nehoraigold/battleship | /player.py | 2,476 | 4.21875 | 4 | from random import randint, choice
from coordinate import Coordinate
class Player():
def __init__(self, is_computer=False):
self.is_computer = is_computer
self.battleship_coord = None
self.guessed_coordinates = {}
self.computer_reactions = ["Rats", "Dang it", "Aw, phooey", "Curses", "Alas", "Blast", "Shoot", "Drat", "Ugh"]
def place_battleship(self, board_size):
if self.is_computer:
self.battleship_coord = self.get_random_battleship_coord(board_size)
print("Okay, I've placed my battleship.\n")
else:
battleship_coord = Coordinate.from_str(input("Where will you place your battleship? Enter the column letter and number (e.g., \"B3\") "))
while not battleship_coord or not battleship_coord.is_valid_for(board_size):
battleship_coord = Coordinate.from_str(input("That is not a valid choide. Where will you place your battleship? "))
self.battleship_coord = battleship_coord
def get_guess(self, board_size):
guess = self.get_computer_guess(board_size) if self.is_computer else self.get_player_guess(board_size)
self.guessed_coordinates[str(guess)] = True
return guess
def get_player_guess(self, board_size):
guess = Coordinate.from_str(input("Which space will you guess? "))
while not guess or not guess.is_valid_for(board_size) or self.guessed_coordinates.get(str(guess), False):
if self.guessed_coordinates.get(str(guess), False):
print("You guessed that one already.\n")
elif not guess:
print("Uh... not quite sure what that was. Let's try that again, shall we?\n")
else:
print("Oops, that's not even in the ocean.\n")
guess = Coordinate.from_str(input("Which space will you guess? "))
return guess
def get_computer_guess(self, board_size):
guess = self.get_random_battleship_coord(board_size)
while self.guessed_coordinates.get(str(guess), False):
guess = self.get_random_battleship_coord(board_size)
return guess
def get_random_battleship_coord(self, board_size):
return Coordinate.from_values(randint(1, board_size), randint(1, board_size))
def is_battleship_location(self, coordinate):
return coordinate == self.battleship_coord
def get_reaction(self):
return choice(self.computer_reactions) | true |
309eafe57d41d3f791376a9bf1736add4294ecf2 | Ksusha2626/py_algorithms | /Lesson_2/task_4.py | 558 | 4.3125 | 4 | """ Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке."""
def asc(x, y):
i = 0
for el in range(x, y + 1):
i += 1
if i % 10 == 0:
print(f'{el:3}: {chr(el)}')
else:
print(f'{el:3}: {chr(el)}', end=' ')
asc(32, 127)
| false |
f1508d93129a17c647a2bda2a851d832952db6f9 | AravindKSaravu/Dev330x_Introduction_to_Python_Unit_3 | /sort_numbers.py | 1,211 | 4.53125 | 5 |
# [ ] Write a program that reads an unspecified number of integers from the command line,
# then prints out the numbers in an ascending order
# The program should have an optional argument to save the sorted numbers as a file named `sorted_numbers.txt`
# The help message should look like:
'''
usage: sort_numbers.py [-h] [-s] [numbers [numbers ...]]
positional arguments:
numbers int to be sorted
optional arguments:
-h, --help show this help message and exit
-s, --save save the sorted numbers on a file (sorted_numbers.txt)
'''
#HINT: use nargs = '*' in an add_argument method
import argparse
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('numbers', action = 'store', nargs = '*', type = int, help = 'int to be sorted')
# Add optional arguments
parser.add_argument('-s', '--save', action = 'store', type = str, help = 'save the sorted numbers on a file (sorted_numbers.txt)')
# Parse command-line arguments
args = parser.parse_args()
# Program
arranged = sorted(args.numbers)
print(*arranged)
if args.save:
with open("sorted_numbers.txt", 'w+') as f:
for a in arranged:
f.write(str(a)+" ") | true |
b315cb6e363fe1ce5cd564ddc5282b9ec934a603 | PalashHawee/Cracking-the-Coding-Interview-by-Mcdowell-Book- | /Linked List/Palindrome.py | 964 | 4.28125 | 4 | '''Implement a function to check if a linked list is a Palindrome'''
#We can implement this using iteration to save space
def reverseLL(head):
prev=None
while head:
temp=head.next
head.next=prev
prev=head
head=temp
return prev
def palindrome(head):
#empty Linked list is a palindrome
if head is None:
return True
#finding length of the LL
length=0
cur=head
while cur:
length+=1
cur=cur.next
#finding halfway point
if length%2==0:
halfway=length/2
elif length%2==1:
halfway=length/2+1
#reversing 2nd half
cur=head
for _ in range(halfway-1):
cur=cur.next
secondHalf=cur.next
cur.next=None
secondHalf=reverseLL(secondHalf)
#ccomparing both halves
firstHalf=head
while firstHalf and secondHalf:
if firstHalf.val!=secondHalf.val
return False
firstHalf=firstHalf.next
secondHalf=secondHalf.next
return True
'''Time complexity O(n) and Space complexity O(1) | true |
16325ed77fb1ff4facc3cf5d0e66796daa2454f8 | mircica10/pythonDataStructuresAndAlgorithms | /selfCrossing.py | 996 | 4.125 | 4 | """
You are given an array x of n positive numbers.
You start at point (0,0) and moves x[0] metres to the north,
then x[1] metres to the west, x[2] metres to the south, x[3] metres to the east and so on.
In other words, after each move your direction changes counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
"""
from typing import List
"""
there are 2 posibilties for a to cross d - from left or right
from left involves 4 lines and for left 6
then is just repeating
"""
class Solution:
def isSelfCrossing(self, x: List[int]) -> bool:
b = c = d = e = f = 0
for a in x:
if d >= b > 0 and (a >= c or ( a >= c - e >= 0 and f >= d - b)):
return True
b,c,d,e,f = a,b,c,d,e
return False
def test():
sol = Solution()
input = [2,1,1,2]
correct_answer = True
answer = sol.isSelfCrossing(input)
assert (answer == correct_answer)
test()
| true |
88e1d613aadd3fcd7972ea6e15072a0fd0d3017d | MediocreCoder/Learn-Python-The-Hard-Way-Lessons | /ex25.py | 1,821 | 4.6875 | 5 | """
This exercise teaches us how to import functions from a file which we've created, like this one, and then direct it within Python.
TWO WAYS
$python
>>>import ex25
>>>sentence = "All good things come to those who wait."
>>>words = ex25.break_words(sentence)
# The . (dot, period) symbol is how you tell python,
#'Hey, inside ex25 there's a function called break_words and I want to run it."
>>>words
['All','good','things','come','to','those','who','wait.']
$
OR
$python
>>>from ex25 import * #imports everything from ex25 for native use
>>>sentence = "All good things come to those who wait."
>>>words = break_words(sentence)
# The . (dot, period) symbol is not used here because all functions have been imported to run natively
>>>words
['All','good','things','come','to','those','who','wait.']
$
"""
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
| true |
2a1c6681b0135d73c6b4aed5b377788561bf9f99 | AmnaT11/MIS | /Conditionals.py | 267 | 4.125 | 4 |
age=int(input('how old are you?')
if age >=21:
print('Your age is ', age)
print('Yes, you can.')
elif age>=6:
print('Your age is ',age)
print('You are a teenager. No you cannot.')
else:
print('Your age is ', age)
print('No, not allowed.')
| true |
1a3fab6ddf48f9ab3f4ff081e9a6ca2d0d732150 | Heroes-Academy/Intro-to-Python-Spring-2016 | /code/Week 02/string_practice.py | 1,157 | 4.5625 | 5 | """
We're going to do some practice with Strings!
In class we talked about:
- indexing Strings (getting one letter)
- slicing Strings (getting a few letters)
- making Strings uppercase (do you remember how to do this? check the slides if you forgot!)
The string we're going to work with in this assignment is "perpetual".
For each problem, I'll ask how you would print out a certain part of this string. Or, I'll give you a
print statement and ask what it will print out.
You can use the shell to check your answers. Once you've solved them, send me your answers!
I've done the first two as an example.
"""
str1 = "perpetual"
# Question 1
# how would you print "p"?
print(str1[0])
# Question 2
# what will print(str1[1]) print?
# Answer: "e"
# Question 3
# how would you print "tual"?
# Question 4
# how would you print "perperper"?
# Question 5
# how would you print "PERPETUAL"?
# Question 6
# what will print(str1[-1]) print?
# Answer:
# Question 7
# what will print(str1.capitalize()) print?
# Answer:
# Question 8
# what will print(str1[:3]) print?
# Answer:
# Question 9
# what will print(str1[3] + str1[7:]) print?
# Answer:
| true |
67efdf97e5a66ab5a697623bf3473b3bfb9accdd | kennykat/CourseWork-TTA | /Python/pythonCourse/python3EssentialTraining/exerciseFiles/01QuickStart/generator.py | 433 | 4.34375 | 4 | #!/usr/local/bin/python3
# generator function creates an iterator
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n %x == 0:
return False
else:
return True
# this is the generator function
# yield is like return. Returns a value
def primes(n = 1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
| true |
35c42ddf33bfb0412c7cf2abb3c53cdc097f81db | milger/DEVFUNDA | /movie_rental_store/src/utils/input_validation.py | 1,668 | 4.21875 | 4 | __author__ = 'JimenaSanabria'
import datetime
"""Method to validate input data from console."""
def get_date_input(item_name):
"""Verify that the input from console is a date.
Keyword arguments:
item_name -- the str with the name of item to be register as date
Return the date regiter by console
"""
while True:
try:
item = raw_input(item_name + " (dd-mm-yyyy):")
item = datetime.datetime.strptime(item, "%d-%m-%Y")
break
except:
print "Error, a " + item_name +" needs to have the format dd-mm-yyyy."
return item
def get_integer_input(item_name):
"""Verify that the input from console is an integer.
Keyword arguments:
item_name -- the str with the name of item to be register as integer
Return the integer number register by console
"""
while True:
try:
item = int(input(item_name + ":"))
break
except:
print "Error, a " + item_name +" needs to be an integer number."
return item
def get_option_input(item_name, options_list):
"""Verify that the input from console is an option of list.
Keyword arguments:
item_name -- the str with the name of item to be register as option of list
options_list -- the list of str with the the option of item_name
Return the option of options_list register by console
"""
while True:
item = raw_input(item_name + ":")
if item in options_list:
break
else:
print "Error, a " + item_name +" needs to be an option of list."
return item
| true |
63ec3e2243c8b5d58e0ebe60cf270b6fc65c4c4f | abdulmoizeng/python-baby-steps | /step5/index.py | 512 | 4.1875 | 4 | # File Handling in Python
import os
# File open in write mode
test_file = open('test.txt', 'wb')
# Printing the file mode, in this case : wb > write mode
print(test_file.mode)
# File name
print(test_file.name)
# Writing into the File
test_file.write(bytes('Some thing special\n', 'UTF-8'))
# Closing file
test_file.close()
# File open in read mode
test_file = open('test.txt', 'r+')
# Reading the text file
print(test_file.read())
# Uncomment the line below to remove the file as well.
# os.remove('test.txt')
| true |
2e738ea94883286f0fa5fd9664680a0da4fd3e9d | techakhil-me/Algo-101 | /2020/graphs/mst.py | 1,366 | 4.3125 | 4 | 1. Minimum Spanning Tree.
2. DSU
3. How to construct a MST using Kruskal Algorithm
1. MST
graph -> G
MST OF g WILL BE the tree[ aka a graph without cycle] whose sum of weight of edge is minimum.
DSU->
Graph G -> there will be certain vertices which will be completly connected to each other and there will be certain
vertices A and B which are not connected, in this scenario we end up with two connected sets in which intersection
of set A and set B is Null
These sets are disjoint sets!
Kruskal Algorithm
Agenda: Kruskal Algorithm is used to construct and MST greedily.
1. Sort all edges in increasing order ( or non -decreasing order).
2. Pick edges, and see if we can connected the edge without reaching a cycle.
3. We connect it if we are not reaching a cycle and that's it.
When we stop? When connected edges are V-1, where V is the total number of vertices.
1. Sorting
2. Where we need to figure out if there is a cycle or not ?
this leads to another problem where we need to find if there exists a cycle or not in a graph?
1. How we detect a cycle?
- we do a traversal, and we see if we are encountering any previously visited edge or not?
T, C -> O(N log M) + N*M
How to figure out how many disjoint sets exists in a graph?
a <-> b <-> c <-> d <-> e f<->g
if root is c:
- while all nodes are not visited:
dfs()
count++ | true |
12e76f987d15fb8e6b47e5e88cc6c6a9af151c4a | techakhil-me/Algo-101 | /2021/Day13/Odd Even Linked List/Odd Even Linked List.py | 2,309 | 4.28125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
odd = head # Both of them point at the first node of the target linked list
even = head.next # doesn't matter even there's only one node in the linked list (even will become None)
eHead = even # We have to keep where the even-node list starts
while even and even.next: # won't get in the loop at first if there's only one node in the linked list
# both even and even.next are necessary condition because even might point to None, which has no attribute 'next'
# AND, why these two, small discussion by myself as below
odd.next = odd.next.next
even.next = even.next.next
# After these two ops, odd/even still points at its original place
# Therefore, we move them to the next node repectively
odd = odd.next
even = even.next
odd.next = eHead # the odd pointer currently points at the last node of the odd-node list
return head # We keep the start of the odd-node list in the first of our code
#Four conditions I doubt for the while-loop:
#[A] odd and odd.next -> wrong when 1->2->3->4->None ( even nodes ) because even.next is None, which has no attribute 'next'
#[B] odd and even.next -> wrong when 1->2->3->4->5->None ( odd nodes ) because even is None, which has no attribute 'next'
#[C] even and odd.next -> wrong when 1->2->3->4->None ( even nodes ) because even.next is None, which has no attribute 'next'
#[D] even and even.next -> correct
# (1). when 1->2->3->4->5->None ( odd nodes ) even will become None first and at the same time, odd points at the last node of the linked list; therefore, breaks from the while loop.
# (2). when 1->2->3->4->None ( even nodes ) even.next will become None first and at the same time, odd points at the last-2 node of the linked list and even points at the last node of the linked list; therefore, breaks from the while loop.
| true |
f979cd9b773aa2733339d9f1aeddb6a61caf2090 | 17032/Python-Calculator- | /Component_1.py | 1,595 | 4.40625 | 4 | #Component 1
#Asks the users name and
#Print the instructions for the program
#Ask the user which shape they would like to calculate
print('*****Welcome to the area and perimeter calculator!*****')
name = input('What is your name?') #program stores name and name is a variable
print ('Hello,',name) #Then prints then welcomes the user (letters the user has entered)
print('The shape options which can be calculated are:')
print('1) Sauare')
print('2) Rectangle')
print('3) Triangle')
print('4) Circle')
print('To select a shape enter the number of the corresponding shape')
print('For example: to choose triangle enter "3"')
#The program asks the user to enter which shape to calculate only accept numbers 1-4
while True:#creates a loop for the input from the user
try:
shape = int(input("Pick a shape and enter the corresponding number:"))#input message
except ValueError:
print("Please enter a valid number")#if anything other than an integer is entered this message is printed
continue #once a number has been entered the program continues
if shape < 1:#if shape is less than one print the following user has entered invalid input
print("Your response is not valid.Please enter a valid number")
continue #once a number has been entered the program continues
elif shape > 4:
print('Please enter a valid option number')#if shape is more than 4 means the input is invalid print following
else:
#shape number was successfully entered and the number is correct
#exit the loop.
break
| true |
a9f0a0cf4558d307cd5317e3f64752d85af3c078 | danielfsousa/algorithms-solutions | /leetcode/Trees/543. Diameter of Binary Tree.py | 991 | 4.125 | 4 | # https://leetcode.com/problems/diameter-of-binary-tree/
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
"""
DFS
Time complexity: O(n)
Space complexity: O(n)
"""
diameter = 0
def height(node):
nonlocal diameter
# define the height of an empty tree to be -1.
if not node:
return -1
left_height = height(node.left)
right_height = height(node.right)
# the "2+" accounts for the edge on the left plus the edge on the right.
diameter = max(diameter, 2 + left_height + right_height)
return 1 + max(left_height, right_height)
height(root)
return diameter
| true |
e2e7235618ebe1216237598ff0a244b557d0eb97 | henriquecl/Aprendendo_Python | /Curso_Udemy_Aulas/Seção 10 - Expressões Lambdas e funções integradas/Min e Max.py | 1,889 | 4.21875 | 4 | """
Min e Max
max(*args) -> Retorna o maior valor em um iterável ou o maior de dois ou mais elementos.
# Ex 1 - Max
lista = [1, 8, 4, 99, 999, 34, 129]
print(max(lista))
tupla = (1, 8, 4, 99, 999, 34, 129)
print(max(tupla))
conjunto = {1, 8, 4, 99, 999, 34, 129}
print(max(conjunto))
dicionario = {'a': 1, 'b': 8, 'c': 4, 'd': 999, 'e': 34, 'f': 129}
print(max(dicionario.values()))
# Faça um programa que receba dois valores do usuário e mostre o maior
val1 = int(input('dale: '))
val2 = int(input('dale: '))
print(max(val1, val2)) # Recebe *args
MIN
min() -> O contrário do max, funciona exatamente igual só q com o menor valor, claro.
# Outros exemplos
nomes = ['Arya', 'Samson', 'Dora', 'Tim', 'Ollivander']
print(max(nomes)) # Letra mais ao final do alfabeto
print(min(nomes)) # Letra mais ao inicio do alfabeto
print(max(nomes, key=lambda nome: len(nome)))
print(min(nomes, key=lambda nome: len(nome)))
"""
musicas = [
{"titulo": "Thunderstruck", "tocou": 3},
{"titulo": "Fade to Black", "tocou": 2},
{"titulo": "Jah jah know", "tocou": 4},
{"titulo": "Ladrão", "tocou": 32}
]
print(max(musicas, key=lambda musica: musica["tocou"]))
print(min(musicas, key=lambda musica: musica["tocou"]))
# DESAFIO! Imprima somente o título da múscia mais e menos tocada
print(max(musicas, key=lambda musica: musica["tocou"])['titulo'])
print(min(musicas, key=lambda musica: musica["tocou"])['titulo'])
# DESAFIO! Como encontrar a música mais tocada e a menos tocada sem usar max, min e lambda
max = 0
for musica in musicas:
if musica['tocou'] > max:
max = musica['tocou']
for musica in musicas:
if musica['tocou'] == max:
print(musica['titulo'])
min = 99999
for musica in musicas:
if musica['tocou'] < min:
min = musica['tocou']
for musica in musicas:
if musica['tocou'] == min:
print(musica['titulo'])
| false |
0e78460e424db05b595694b92b8e437553fd6938 | henriquecl/Aprendendo_Python | /Curso_Udemy_Aulas/Seção 9 - Comprehensions em Python/Listas Aninhadas.py | 1,211 | 4.40625 | 4 | """
Listas aninhadas (Nested Lists)
- Algumas linguagens de programação (C/Java/Php) possuem uma estrutura de dados chamada de arrays
- Unidimensionais (Arrays/vetores);
- Multidimensionais (Matrizes);
Em Python nós temos as listas.
numeros = [1, 2, 3, 4, 5] aqui são listas, nas outras são arrays
# Exemplo
listas = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Lista de listas, ou seja, uma matriz
# LINHA0 LINHA1 LINHA2
print(listas)
print(type(listas))
# Como fazemos para acessar os dados?
# [linha] [coluna]
print(listas[0][1]) # 2
print(listas[2][1]) # 8
# Iterando com loops em uma lista aninhada
listas = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for lista in listas:
for num in lista:
print(num)
# List Comprehension
[[print(valor) for valor in lista] for lista in listas]
"""
# Outros exemplos:
# Gerando uma matrix 3x3
tabuleiro = [[numero for numero in range(1, 4)] for valor in range(1, 4)]
print(tabuleiro)
# Gerando jogadas para o jogo da velha
velha = [['X' if numero % 2 == 0 else 'O' for numero in range(1, 4)] for valor in range(1, 4)]
print(velha)
# Gerando valores iniciais
print([['*' for i in range(1, 4)] for j in range(1,4)])
| false |
b276ce8aa1814184feb238157a80cfad12647444 | henriquecl/Aprendendo_Python | /Exercícios/Lista 5 - Seção 8 - Funções em Python/Questão 3 - Função para verificar se o número é maior, igual ou menor que zero.py | 363 | 4.15625 | 4 | """
Questão 3 - Faça uma função para verificar se o número é positivo ou negativo. Sendo que o valor de retorno será 1 se
positivo, -1 se negativo e 0 se for igual a 0
"""
def numero(num):
if num == 0:
return 0
elif num > 0:
return 1
return -1
num_teste = float(input('Digite um número\n'))
print(numero(num_teste))
| false |
f9138010b86d27f6d0cd6653f160b05c9dfba770 | henriquecl/Aprendendo_Python | /Curso_Udemy_Aulas/Seção 8 - Funções em Python/Entendendo args.py | 2,031 | 4.40625 | 4 | """
Entendendo o *args
- O *args é um parâmetro como outro qualquer. Isso significa que você poderá chamar de qualquer coisa, desde que comece
com asterisco
Exemplo:
*xis
Mas por convenção, utilizamos *args para defini-lo.
O parâmetro *args utilizado em uma função, coloca os valores extras informados como uma entrada em uma tupla. Então, des
-de já, lembre-se que tuplas são imutáveis. Ou seja, podemos interpreta-lo como valores de entrada infinitos, não sendo
necessário amarrar quantas entrada nos teremos na função. Ao utilizar o *args podemos ter quantas entradas forem nece-
ssarias na função sem necessáriamente declara-las
# Ex 1
Se a cada vez fosse adicionado um novo numero na soma, iriamos ter que aumentar a função cada vez mais, ou seja, péssimo
def soma_todos_numeros(num1=1, num2=2, num3=3):
return num1 + num2 + num3
print(soma_todos_numeros(4, 6, 9))
# Entendendo o args
def soma_todos_numeros(nome, email, *args):
return sum(args)
print(soma_todos_numeros('Henrique', 'Campos'))
print(soma_todos_numeros('Henrique', 'Campos', 1))
print(soma_todos_numeros('Henrique', 'Campos', 2, 3))
print(soma_todos_numeros('Henrique', 'Campos', 2, 3, 4))
print(soma_todos_numeros('Henrique', 'Campos', 3, 4, 5, 6))
# Exemplo de utilização do *args
def verifica_info(*args):
if 'Geek' in args and 'University' in args:
return 'Bem-Vindo Geek'
return 'Eu não sei quem você é...'
print(verifica_info())
print(verifica_info(1, True, 'University', 'Geek'))
print(verifica_info(1, 'University', 3.145))
"""
def soma_todos_numeros(*args):
print(args)
return sum(args)
# print(soma_todos_numeros())
# print(soma_todos_numeros(3, 4, 5, 6))
numeros = [1, 2, 3, 4, 5, 6, 7]
# Desempacotador
print(soma_todos_numeros(*numeros))
# O asterisco serve para que informemos ao python que estamos passando como argumento uma coleção de dados. Dessa forma,
# ele saberá que precisará antes desempacotar os dados contidos. Só não funciona com dicionário
| false |
1eabf7852895d48f6d5ec0877c911f4231984983 | henriquecl/Aprendendo_Python | /Exercícios/Lista 4 - Seção 7 - Coleções/Questão 8 - Ler 16 inteiros e mostrar na tela os valores lidos na ordem inversa.py | 280 | 4.125 | 4 | # Questão 8 - Crie um programa q lê 6 valores inteiros e mostre na tela os vlaores lidos na ordem inversa
lista = []
numero = 0
for i in range(6):
print(f'Digite {6-i} valor(es)')
numero = int(input())
lista.append(numero)
print(lista)
lista.reverse()
print(lista)
| false |
b83b4646b88dddde7b635a255d0c06e999f81e87 | henriquecl/Aprendendo_Python | /Exercícios/Lista 4.1 - Seção 7 - Matrizes/Questão 3 - Criar uma matriz com os requisitos do enunciado.py | 390 | 4.125 | 4 | """
Questão 3 - Faça um programa que preenche uma matriz 4x4 com o produto do valor da linha e da coluna de cada elemento.
Em seguida, imprima a matriz
"""
matrix = [[], [], [], []]
for i in range(4):
for j in range(4):
numero = i * j
matrix[i].append(numero)
for i in range(len(matrix)):
if i == 0:
print('A matriz digitada foi:')
print(matrix[i])
| false |
a096bdb97c95ae4ecf3f0f763ffdffa9f4111c20 | henriquecl/Aprendendo_Python | /Exercícios/Lista 6 - Seção 13 - Leitura e escrita em arquivo/Questão 17 - Enunciado no código.py | 2,503 | 4.5625 | 5 | """
Questão 17 - Faça um programa que leia um arquivo que contenha as dimensões de uma matriz (linha x coluna), a quantida
de de posições que serão anuladas, e as posições a serem anuladas.
O programa lê esse arquivo, e em seguida, produz um novo arquivo com a matriz com as dimensões dadas no arquivo lido, e
todas as posições especificadas no arquivo ZERADAS e o restante recebendo valor 1.
3 3 2 / 3 tamanho de linhas, 3 tamanho de colunas, 2 posições a serem anuladas
1 0 / posição a ser anulada
1 2 / posição a ser anulada
"""
def lista_em_int(lista, lista_inteiro):
"""
:param lista: Tem uma lista como entrada
:param lista_inteiro: A lista de sáida
:return: Converte os itens que estão contidos na lista de 'str' para 'int' se forem APENAS números.
"""
for i in range(len(lista)):
lista_inteiro.append(int(lista[i]))
return lista_inteiro
def matriz_tamanho_usuário(matriz, tamanho):
"""
:param matriz : A matriz cuja você deseja criar
:param tamanho: Tamanho da matriz desejada pelo usuário
:return: Uma matriz do tamanho que o usuário desejar
"""
for i in range(tamanho):
matriz.append([])
def preenche_matriz(matriz):
"""
Essa função preenche todos os itens de uma matriz por 1
:param matriz: Matriz que deseja ser preenchida
:return: None
"""
for i in range(len(matriz)):
for j in range(len(matriz)):
matriz[i].append(1)
matriz_nova = []
with open('matrix.txt', 'r', encoding='UTF-8') as arquivo:
linha0 = arquivo.readline()
linha1 = arquivo.readline()
linha2 = arquivo.readline()
# Convertendo todas as linhas em lista, e depois em lista de inteiros
tamanho_matrix = linha0.split()
anula_1 = linha1.split()
anula_2 = linha2.split()
tamanho_matrix_inteiro = []
anula_1_inteiro = []
anula_2_inteiro = []
lista_em_int(tamanho_matrix, tamanho_matrix_inteiro)
lista_em_int(anula_1, anula_1_inteiro)
lista_em_int(anula_2, anula_2_inteiro)
# Criando uma matrix do tamanho digitado pelo usuário
matriz_tamanho_usuário(matriz_nova, tamanho_matrix_inteiro[0])
# Preenchendo a matriz com numeros 1
preenche_matriz(matriz_nova)
# Substituindo pelos valores desejados
matriz_nova[anula_1_inteiro[0]][anula_1_inteiro[1]] = 0
matriz_nova[anula_2_inteiro[0]][anula_2_inteiro[1]] = 0
a = str(matriz_nova)
# Criando um novo arquivo com a matriz_nova
with open('questao17.txt', 'w', encoding='UTF-8') as arquivo2:
arquivo2.write(a)
| false |
87255e33b288d987dc81928ff0df07c26c6f49d6 | henriquecl/Aprendendo_Python | /Exercícios/Lista 4.1 - Seção 7 - Matrizes/Questão 12 - Calcular a transposta de uma matrix 3x3.py | 314 | 4.34375 | 4 | """
Questão 12 - Imprima a transposta de uma matriz 3x3
"""
matrix = [[1, 2, 3], [789, 19, 19], [1891, 1, 1]]
matrix_transposta = [[], [], []]
for j in range(3):
for i in range(3):
numero = matrix[j][i]
matrix_transposta[i].append(numero)
for i in range(3):
print(matrix_transposta[i])
| false |
82d4d489f41466753fd05dbea76ab25c47cceab5 | ravi-sharma/datastructure | /multiThreading.py | 736 | 4.375 | 4 | from threading import *
from time import sleep
class first(Thread):
def run(self): # using run name as it require in threading
for i in range(10):
print('\n Class 1 thread: ', i)
sleep(1)
class second(Thread):
def run(self): # using run name as it require in threading
for i in range(10):
print('\n class 2 thread:', i)
sleep(1)
print('Simple example to see multi threading in python:')
# Initializing objects
object1 = first()
object2 = second()
# In order to run threading we need to call start not run
object1.start()
object2.start()
# Join will let both the threads to complete first then go to next
object1.join()
object2.join()
print('The end!')
| true |
9100f37dda1e54c5b1d6ebf1838dde0058a9bbdc | Par1Na/Twowaits | /day4-2.py | 546 | 4.375 | 4 | # Twowaits
Twowaits Problem
# Python3 code to demonstrate working of
# Sort tuple list by Nth element of tuple
# using sort() + lambda
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
# printing original list
print("The original list is : " + str(test_list))
# index according to which sort to perform
N = 1
# Sort tuple list by Nth element of tuple
# using sort() + lambda
test_list.sort(key = lambda x: x[N])
# printing result
print("List after sorting tuple by Nth index sort : " + str(test_list))
| true |
becfeb4d1fdda4695bd91031d6d7b50987555929 | Par1Na/Twowaits | /day4-3.py | 318 | 4.28125 | 4 | # Twowaits
Twowaits Problem
# Python code to find second largest
# element from a dictionary using sorted() method
# creating a new Dictionary
example_dict ={"a":13, "b":3, "c":6, "d":11}
# now directly print the second largest
# value in the dictionary
print(list(sorted(example_dict.values()))[-2])
| true |
523e45d5d2f2ec2a90a29b5b0041cc34b3cdaede | iaingblack/Python_ABSWP | /Chapter-7/p1-StrongPassword.py | 1,530 | 4.25 | 4 | # Strong Password Detection - Write a function that uses regular expressions to make sure the password
# string it is passed is strong. A strong password is defined as one that is at least eight characters long,
# contains both uppercase and lowercase characters, and has at least one digit. You may need to test the
# string against multiple regex patterns to validate its strength.
import re
# > 7 chars, 1 U, 1 l, 1 #
def TestPassword(password):
mo = numberRegex.search(password)
if mo is None:
print("No numbers in the password")
return False
mo = ucRegex.search(password)
if mo is None:
print("No UpperCase character in the password")
return False
mo = lcRegex.search(password)
if mo is None:
print("No LowerCase character in the password")
return False
mo = spacesRegex.search(password)
if mo is not None:
print("There are spaces are in the password")
return False
if len(password) > 7 :
print("Password is " + str(len(password)) + " characters long, it must be at least 8")
return False
return True
# Variables
passedRequirements = False
gotGoodPassword = False
password = ""
# regexes
numberRegex = re.compile(r'\d')
lcRegex = re.compile(r'[a-z]')
ucRegex = re.compile(r'[A-Z]')
spacesRegex = re.compile(r'[\s]')
# Main Program
while not passedRequirements:
password = input("Enter a password: ")
passedRequirements = TestPassword(password)
print("Password '" + password + "' is good!")
| true |
1ef343e496ec93339e12ef9bbbddaf4f9542f853 | btoztas/ASint | /Lab1/Ex2.py | 211 | 4.125 | 4 | print("### Example 2 ###")
print("Let's calculate the average of two numbers!")
first = float(input("First number > "))
second = float(input("Second number > "))
print("The average is %d" % ((first+second)/2))
| true |
a8a8533b75e9ab9d1705761ca3b54aa7a90daa0a | ruhita/Lets-upgrade-python | /Day 2-LU .py | 959 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
Arithmetic operators
**, *, /, %, +, -, //
# In[2]:
x = 25
y = 8
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
# In[ ]:
Comparision operators
==, <, >, <=, >=, !=
# In[3]:
x = 25
y = 8
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
# In[ ]:
Assignment operators
=, +=, -=, *=, /=, **=
forexample
x=8
x=x+8
x=x-8
# In[ ]:
Logical operators
AND, OR, NOT
# In[4]:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
# In[ ]:
Variables defination rules
variables should start with a character.
Variable can lower or upper case, numbers, underscore.
Example , a=25, A=25, -=25
here a and A are two different variables
| false |
0b9dd3404ee3bb8c63d85b12bc1759ef60915311 | coolgreenhat/Python_Practice | /Data_Structures_and_Algorithms_in_Python_GoodRich/Chapter_2_Object-Oriented_Programming/Creativity/2.26.py | 689 | 4.34375 | 4 | """
2.26 The SequenceIterator class of Section 2.3.4 provides what is known as a
forward iterator. Implement a class named ReversedSequenceIterator that
serves as a reverse iterator for any Python sequence type. The first call to
next should return the last element of the sequence, the second call to next
should return the second-to-last element, and so forth.
"""
class SequenceIterator:
def __init__(self, sequence):
self._seq = sequence
self._k = len(sequence)
def __next__(self):
self._k -=1
if self._k > 0:
return (self._seq[self._k])
else:
raise StopIteration()
def __iter__(self):
return self
| true |
eb786cb88cf258505d9f9c5f35f3e40b5c0e4f0d | ot-ke/learning | /scratches 2/z2_3.py | 730 | 4.21875 | 4 | # Написать класс для комплексного числа Complex. Принимает в конструктор целую и вещественную части, напримеp для числа a=2+3j будет написано
# a=Complex(2,3).
# Переопределить операторы сложения и вычитания.
from z2_3_classes import Complex
a=Complex(7,15)
a.display()
f1=Complex(12,36)
f2=Complex(5,35)
print("Первое складываемое число:")
f1.show()
print("Второе складываемое число:")
f2.show()
result = f1 + f2
print("Результат сложения:")
result.show()
result_minus = f1 - f2
print("")
result_minus.show_minus() | false |
0d28a1976c05fcd891f962c408721f5c2f675d70 | roxanacaraba/Learning-Python | /25-Frequently-Asked-Python-Programs/Clear_a_list.py | 460 | 4.125 | 4 | list=[6,0,4,1]
print("List before clear:", list)
#Varianta 1 folosind clear()
#list.clear()
#print("List after clear:", list)
#Varianta 2 : initializes the list with no value
#list=[]
#print("List after clear:", list)
#Varianta 3 utilizand "*=0", aceasta metoda inlatura toate elementele si o face goala
#list *=0 #deletes the list
#print("List after clear:", list)
#Varianta 4
del list[1:3] # 0 4
print(list)
del list[:] # toata lista
print(list)
| false |
b23f8325dee04647324b543a0b1557df6e99c0f9 | roxanacaraba/Learning-Python | /Regular_expressions/Regular_expression_split.py | 262 | 4.21875 | 4 | import re
s = "Today I'm having a python course"
print (re.split("[^a-z]+", s))
print (re.split("[^a-z']+", s, 2))
print (re.split("[^a-z']+", s, flags = re.IGNORECASE))
print (re.split("[^a-z']+", s, 2, flags = re.IGNORECASE))
print (re.split("[^a-z'A-Z]+", s)) | false |
0140699561fba55bf0066662b737f2f37b2efcdd | roxanacaraba/Learning-Python | /Classes/Introducere_in_classes/9-method_are_bound_to_the_self_object_of_the_class.py | 529 | 4.34375 | 4 | #Methods are bound to the self object of the class they were initialized in.
# Even if you associate a method from a different class to a new method, the self will belong to the original class.
class MyClass:
x = 10
def Test(self,value):
return ((self.x+self.y)/2 == value)
def MyFunction(self,v1,v2):
return str(v1+v2)+" - "+str(self.x)
m = MyClass()
m2 = MyClass()
m2.x = 100
m.Test = m2.MyFunction
print (m.Test(1,2)) #3 - 100 , m.Test actually refers to m2.Test
print (m.MyFunction(1,2)) #3 - 10
| true |
22a0643861c66f39a6990242873572cbaff61058 | jenniferlgunther/cmpt120GUNTHER | /Lab Assignments/guessing-game.py | 817 | 4.21875 | 4 | #Introduction to Programming
#Jennifer Gunther
#26 February 2018
animal = "cow"
def main():
print ("Guess what animal I am thinking of.")
guess = input("What animal am I thinking of?" '')
correct = False
while not correct:
if guess == 'q':
quit(0)
elif guess != 'cow':
print("Sorry! Try Again.")
guess = input("What animal am I thinking of?" '')
guess = guess.lower()
else:
print('Congradulations! Nice job!')
next_question = input("Are you a fan of cows? ('y' or 'n') ")
if next_question == "y":
print ("Awesome! Me too!")
else:
print ("Oh well. Guess I don't know you as well as I thought.")
return
main()
| true |
b265e6b30849be3c492a5ee7650e2dd902f426f7 | DAngello-Garcia/tutorialpy | /fundamentals.py | 582 | 4.21875 | 4 | # comentarios
print('Hola')
print(1+2-3*4/5) #utilizar paréntesis para jerarquía
print(2**3) #exponencial
print(20//4) #cociente
print(20%3) #residuo
# variables
entero = 2
numReal = 3.17
texto = 'texto'
otroTexto = "Hola, D'Angello"
print(texto + str(entero))
print(texto + "\n Salto de línea")
# input
nombre = str(input("Dame tu nombre: "))
print(nombre)
# booleanos
switchOn = True
switchOff = False
# operadores lógicos
# == != < > <= >=
print(7==8)
print(7!=8)
print('hola'!='hola')
# and, or, not
print('hola'!='hola' and 7==8)
print(1<2 or 2>3)
var = False
print(not var)
| false |
5b53e8ebe364b1a51af99826cc58afec2f0f824c | Hokage70/v2game.py | /paper.rock.scissors.py | 450 | 4.15625 | 4 | import random
random_number = random.randint(1, 3)
if random_number == 1:
answer = 'rock'
elif random_number == 2:
answer = 'paper'
elif random_number == 3:
answer = 'scissors'
player_choice = input('Pick either rock, paper, or scissors: ')
if player_choice == 'rock':
print(answer)
elif player_choice == 'paper':
print(answer)
elif player_choice == 'scissors':
print(answer)
else:
print('Sorry that is not a choice.')
| true |
fd4d48a8940323bb7e67700f75c1388a73a84111 | anamdey03/Python-Basics | /ListFunctions.py | 889 | 4.15625 | 4 | lucky_numbers = [42, 8, 15, 16, 23]
friends = ["Abhishek", "Rohit", "Sagar", "Prasun", "Avijit", "Sagarika", "Abhishek"]
friends.insert(1, "Anamitra") # Add the element in the index mentioned
friends.remove("Avijit") # Remove the element from the list
friends.append("Amik") # Appends an element at the end of the list
friends.extend(lucky_numbers) # Add two lists together
friends.pop() # Removes the last element of the list
print(friends)
print(friends.index("Prasun")) # Find the index of the element in the list
print(friends.count("Abhishek")) # Counts the number of times the element is present in the list
lucky_numbers.sort() # Sort the list in the ascending order
lucky_numbers.reverse() # Reverse the list
print(lucky_numbers)
friends2 = friends.copy() # Copy the content of a list into another
print(friends2)
friends.clear() # Clear the content of the whole lists
| true |
ebe7168e94719c2c6bcd065a0edfa340f49323a2 | anamdey03/Python-Basics | /Fibonacci.py | 202 | 4.28125 | 4 |
def fibonacci(num):
result = []
a, b = 0, 1
while a < num:
result.append(a)
a, b = b, a + b
return result
num = input("Enter the number: ")
print(fibonacci(int(num)))
| true |
c6fbc58219ed6d5e186f2608109d01403153ce44 | nicolas-schmitz/design-analysis-algorithms | /ordering/methods.py | 561 | 4.25 | 4 | def insertion_sort(vector: list):
"""Sort the vector utilizign insertion sort. Loops through the vector and finishes each iteration sorting the vector to position j.
Time complexity: O(n^2)
Space complexity: O(1)
Args:
vector (list): list with values
Returns:
list: list with sorted values
"""
for j in range(1, len(vector)):
key = vector[j]
i = j - 1
while i >= 0 and vector[i] > key:
vector[i + 1] = vector[i]
i -= 1
vector[i + 1] = key
return vector
| true |
254dfbdd51dccb79195a5eeb0b6e457f269ba249 | zarrock256/python | /points.py | 1,850 | 4.1875 | 4 | import math
class Point:
"""Klasa reprezentująca punkty na płaszczyźnie. Współrzędne są całkowite"""
def __init__(self, x, y): # konstruktor
self.x = x
self.y = y
def __str__(self): # zwraca string "(x, y)"
if isinstance(self.x,float) and isinstance(self.y,float): #Dla klasy Rectangle, gdzie wyliczane współrzędne
return "({0:.2f},{1:.2f})".format(self.x, self.y) # środka mogą zawierać ułamek
else:
return "({0:d},{1:d})".format(self.x, self.y)
def __repr__(self): # zwraca string "Point(x, y)"
return "Point({0:d},{1:d})".format(self.x, self.y)
def __eq__(self, other): # obsługa point1 == point2
return self.x == other.x and self.y == other.y
def __ne__(self, other): # obsługa point1 != point2
return not self == other
# Punkty jako wektory 2D.
def __add__(self, other): # v1 + v2 współrzędne wektorów będą dokładnie takie same jak współrzędne
return Point(self.x + other.x, self.y + other.y) #punktów, które są ich końcami (z uwagi na zaczepienie
#w punkcie (0,0)
def __sub__(self, other): # v1 - v2
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other): # v1 * v2, iloczyn skalarny (liczba)
return self.x*other.x + self.y*other.y
def cross(self, other): # v1 x v2, iloczyn wektorowy 2D (liczba)
return self.x * other.y - self.y * other.x
def length(self): # długość wektora
return math.sqrt(self.x*self.x + self.y*self.y)
def __hash__(self):
return hash((self.x, self.y)) # bazujemy na tuple, immutable points | false |
e0843c9cafcfa8e561f4097f0006de4b24d7e5a7 | pankaj-agrawal90/FST-M1 | /Python/Activities/activity9.py | 330 | 4.21875 | 4 | listOne = [10, 20, 23, 11, 17, 31, 34, 97]
listTwo = [13, 43, 24, 36, 12, 44, 59, 80]
third_list = []
for items in listOne:
if (items % 2 !=0):
third_list.append(items)
for item in listTwo:
if (item % 2 == 0):
third_list.append(item)
print("Items in the third list is: ", third_list) | true |
c74587c9c4da52d104106e1766237d09f0a8c290 | jasujon/Start-Python | /lession19/index.py | 2,071 | 4.46875 | 4 | #-------------------------What is list comprehension------------------------------
#List Comprehension Related With List
#List Comprehension Work Just sorted by Progranming Code
# #normal function for square
# square = []
# for i in range(1,11):
# square.append(i**2)
# print(square)
# # output : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# #List Comprehension for square
# square2 = [i**2 for i in range (1,11)]
# print(square2)
# # output : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# #Negative Number Show Like -1 to -10 Function
# #normal function
# negative = []
# for i in range(1,11):
# negative.append(-i)
# print(negative)
# #output : [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
# #List Comprehension
# new_negative = [-i for i in range(1,11)]
# print(new_negative)
# #output : [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
#---------------------------------List Comprehension with if statement-------------------------------
# numbers = list(range(1,11))
# # print(numbers)
# #output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# #normal function
# num = []
# for i in numbers :
# if i%2 == 0 :
# num.append(i)
# print(num)
#output : [2, 4, 6, 8, 10]
#List Comprehension
# even_num = [i for i in range(1,11) if i%2 == 0]
# print(even_num)
#output : [2, 4, 6, 8, 10]
#----------------------------List comprehension with if else-------------------------
# numbers = [1,2,3,4,5,6,7,8,9,10]
# #normal function
# new_num = []
# for i in numbers:
# if i%2 == 0 :
# new_num.append(i*2)
# else:
# new_num.append(-1)
# print(new_num)
# #output : [-1, 4, -1, 8, -1, 12, -1, 16, -1, 20]
# #List Comprehension
# new_list = [i*2 if(i%2 == 0) else -i for i in numbers]
# print(new_list)
#output : [-1, 4, -3, 8, -5, 12, -7, 16, -9, 20]
#-----------------------------------Nested list comprehension-----------------------------
list_number = [[1,2,3],[1,2,3],[1,2,3]]
nested_comp = [ [i for i in range(1,4)] for j in range(3)]
print(nested_comp)
#output : [[1, 2, 3], [1, 2, 3], [1, 2, 3]] | false |
c6b3977a47679f07c3bc8e0b42e4d9ca618f6b0e | kshtj24/Itsy-Bitsy-Projects | /Tic Tac Toe/TicTacToe.py | 2,210 | 4.1875 | 4 |
#create the board and print out the message to start
#ask the players to choose o or x
#while game is not over
#take input from the players
#update the board
#check if game is over (win or tie)
#printing the board
def printBoard(board):
for a,b,c in board:
print(a,b,c)
#checks for win to tie situation
def checkWinRowWise(board):
for a,b,c in board:
if a == b == c != '-':
return True
print("Row")
return False
def checkWinColumnWise(board):
board = [[row[i] for row in board] for i in range(len(board[0]))]
for a,b,c in board:
if a == b == c != '-':
return True
print("Column")
return False
def checkWinDiagonally(board):
if (board[0][0] == board[1][1] == board[2][2] != '-') or (board[0][2] == board[1][1] == board[2][0] != '-'):
return True
print("Diagonal")
return False
#validating the character inputs
def validateCharacters(*args):
if len(args) == 1:
if args[0] != 'O' or args[0] != 'X':
print("Please choose 'O' or 'X'")
return False
else:
return True
isReplay = True
while(isReplay):
#initializing the 2 dim array as board and printing the start message
board = [['-','-','-'],['-','-','-'],['-','-','-']]
print("Let's play some Tic Tac Toe:")
printBoard(board)
#taking the choice of O or X from player1
player1 = (input("Player 1, please select your mark 'O' or 'X' :")).upper()
if player1 == 'X':
player2 = 'O'
else:
player2 = 'X'
chance = 1
while(True):
location = input(f"Player {abs(chance)}, please enter the row and column to put your mark:").split(' ')
if chance == 1:
board[int(location[0]) - 1][int(location[1]) - 1] = player1
else:
board[int(location[0]) - 1][int(location[1]) - 1] = player2
printBoard(board)
if(checkWinRowWise(board) or checkWinColumnWise(board) or checkWinDiagonally(board)):
print(f"Congratulations !!! Player {abs(chance)} has won the game")
replay = input("Do you want to replay Y/N:")
if replay == 'N' or replay == 'n':
isReplay = False
break
if not any('-' in arr for arr in board):
print("It's a Tie")
replay = input("Do you want to replay Y/N:")
if replay == 'N' or replay == 'n':
isReplay = False
break
chance = ~chance
| true |
28a73b8e89ca949696cb10e1fed2d63044fa91df | lestaal/Project-Euler | /3largestPrimeFactor.py | 1,011 | 4.125 | 4 | ### Problem 3 ###
# What I referenced:
# http://stackoverflow.com/questions/23287/prime-factors
def largest_prime_factor(num):
"""
Inputs: num - positive integer to find largest prime factor of
Outputs: largest prime integer factor of num
"""
factors = [num]
while factors:
largest = factors.pop(factors.index(max(factors)))
i = 2
prime = True
while i <= int(largest/2):
if (largest%i == 0):
factors.append(i)
factors.append(largest/i)
prime = False
break
i += 1
if prime:
return largest
def test_largest_prime_factor():
""" test function largest_prime_factor
Inputs: none
Outputs: none, prints results
"""
print largest_prime_factor(9), '= 3'
print largest_prime_factor(21), '= 7'
print largest_prime_factor(38), '= 19'
print largest_prime_factor(13195), '= 29'
print largest_prime_factor(600851475143)
| true |
cad432c6eeceea1d9f9d2a4f6febdd9180eda78a | darthvedder17/data-structures | /Searching/Circular array search ( binary search variation ).py | 769 | 4.125 | 4 | def circular_array_search(arr,n,x):
low=0
high=n-1
while high>=low:
mid=int(low+(high-low/2))
if arr[mid]==x:
return mid #CASE 1 , FOUND X
elif arr[mid]<=arr[high]: #CASE 2 , RIGHT HALF IS SORTED
if x>arr[mid] and x<=arr[high]:
low=mid+1 # GO SEARCH IN RIGHT SORTED HALF
else:
high=mid-1
elif arr[mid]>=arr[low]: #CASE 3 , LEFT HALF IS SORTED
if x>=arr[low] and x<=arr[mid]:
high=mid-1 # GO SEARCH IN LEFT SORTED HALF
else:
low=mid+1
return -1
arr=[4,5,6,7,1,2,3]
search=circular_array_search(arr,7,3)
print("The index of %d is %d"%(3,search))
| false |
cb312a3b7f4c2001721c9b38e3df3e2e197414bb | darthvedder17/data-structures | /Practice Questions/factorial.py | 247 | 4.21875 | 4 | def factorial(n):
temp=n
fact=1
for i in range(1,temp+1):
fact=fact*i
return print("The factorial is %d"%fact)
while True:
sample=int(input("Enter a number:"))
factorial(sample)
| true |
16bbb8fc53087ef1e610c711ddef87917a57b00d | lizlee0225/D05 | /HW05_ex00_logics.py | 1,898 | 4.375 | 4 | #!/usr/bin/env python3
# HW05_ex00_logics.py
##############################################################################
def even_odd():
user_input = ''
while user_input == '':
try:
user_input = int(input('Enter an integer: '))
except:
print('Please enter an integer.')
if user_input % 2 == 0:
print("Even")
else:
print("Odd")
""" Print even or odd:
Takes one integer from user
accepts only non-word numerals
must validate
Determines if even or odd
Prints determination
returns None
"""
pass
def ten_by_ten():
""" Prints integers 1 through 100 sequentially in a ten by ten grid."""
inc_n = 0
for i in range(1,101):
count = range(11,101,10)
if inc_n < 9 and i == count[inc_n]:
print('\n')
inc_n += 1
print('{:5}'.format(i), end = '')
print('\n')
pass
def find_average():
""" Takes numeric input (non-word numerals) from the user, one number
at a time. Once the user types 'done', returns the average.
"""
user_input = ''
total = 0
count = 0
while True:
try:
user_input = input('Give a number to compute the average: ')
if user_input == 'done':
break
else:
total += float(user_input)
count += 1
except:
print('Please enter a number.')
return 'The average is ' + str(total/count)
pass
##############################################################################
def main():
""" Calls the following functions:
- even_odd()
- ten_by_ten()
Prints the following function:
- find_average()
"""
even_odd()
ten_by_ten()
print(find_average())
pass
if __name__ == '__main__':
main()
| true |
e09438179a8bccfc6e1e49491fbaed7579e227e4 | ozgeyurdakurban/gaih-students-repo-example | /HW_answers_eoy/answers_py/day_3.py | 461 | 4.1875 | 4 | #Day_3:
"""
User login application:
- Get Username and Password values from the user.
- Check the values in an if statement and tell the user if they were successful.
"""
users=["Ahmet","Mehmet","Ayşe"]
passwords=["qwerty"]
username=input('Please enter username? ')
password=input('Please enter password? ')
if username in users and password in passwords:
print('Succesfully login!')
else:
print('Incorrect!')
| true |
fa2d4e903d799ce95be1289af88877f968dcd5b3 | jessicaguo205/Coursera_Introduction_to_Scripting_in_Python | /PDR_note_week1.py | 1,597 | 4.1875 | 4 | """
Python Data Representatives
WEEK ONE
Course Note and Quiz
"""
name1 = "Pierre"
age1 = 7
name2 = "May"
age2 = 13
# the use of formatters
line1 = "{0:^7} {1:>3}".format(name1, age1)
line2 = "{0:^7} {1:>3}".format(name2, age2)
print(line1)
print(line2)
num = 3.283663293
output = "{0:>10.3f} {0:.2f}".format(num)
print(output)
# the demonstration of string slices
name = "𝙲𝚊𝚜𝚝𝚕𝚎 𝙰𝚗𝚝𝚑𝚛𝚊𝚡"
print(name[7:])
print(name[7:13])
# the function that required by the by the week one quiz in Python Data RePresentatives
def count_vowels(word):
"""
This function takes a string
returns the number of vowels in that string
"""
vowels = 0
for count in word:
if 'a' == count or 'e' == count or 'i' == count or 'o' == count or 'u' == count:
vowels += 1
return vowels
# the function that required by the by the week one quiz in Python Data RePresentatives
def demystify(l1_string):
"""
This function takes one string that only contains l or 1
replace a with l and b with 1
returns the new string
"""
list_string = list(l1_string)
for idx, char in enumerate(list_string):
if char == 'l':
list_string[idx] = 'a'
elif char == '1':
list_string[idx] = 'b'
else:
pass
return "".join(list_string)
print(count_vowels("aaassseefffgggiiijjjoOOkkkuuuu"))
print(count_vowels("aovvouOucvicIIOveeOIclOeuvvauouuvciOIsle"))
print(demystify("lll111l1l1l1111lll"))
print(demystify("111l1l11l11lll1lll1lll11111ll11l1ll1l111"))
word = "shrubbery"
print(word[-1])
print(word[len(word) - 1])
print(word[0])
# print(word[len(word)]
| true |
c85b70e10da8d246efba87b611ab5692ecfcb27d | mj0508/today | /calc.py | 219 | 4.15625 | 4 | # add program
def sum_function(n1, n2) : # add two number
return n1 + n2
num1 = int(input("input number 1 : "))
num2 = int(input("input number 2 : "))
sum = sum_function(num1, num2)
print(num1, "+", num2, "=", sum) | false |
c421aee281477c896c2af07bf12af842637ff6d6 | zhufengyu/Python_study | /3.5:数据类型的转化.py | 2,956 | 4.53125 | 5 | # 3.5 数据类型的转化
# 3.5.1 字符串和列表的转换
# 字符串转换成列表使用字符串函数split实现
# 列表转换成字符串使用join函数实现
# 字符串转换列表
str1 = 'Hello world'
list1 = str1.split(' ')
print(list1)
# 列表转换字符串
list1 = ['Hello', 'world']
str1 = ' '.join(list1)
print(str1)
# 其他转换函数
# 字符串转列表
str1 = '[1,2,"Hello"]'
# 字符串和列表数据格式相同,可以使用eval函数处理
list1 = eval(str1)
print(list1)
# list函数是将字符串每个元素作为列表的元素
list2 = list(str1)
print(list2)
# 列表转换字符串
# str函数直接将整个列表转换成字符串
list1 = ['Hello', 'world']
str1 = str(list1)
print(str1)
# 3.5.2 字符串与字典的转换
# 字符串转换字典使用dict函数实现,字典转换字符串使用values()函数获取字典的值,然后将其转换成字符串。
# 字符串转换字典
str1 = 'Hello'
str2 = 'Python'
dict1 = dict(a=str1,b=str2)
#输出字符串转字典{'a':'Hello','b':'Python}
print(dict1)
# 字典转字符串
dict1 = {'a': 'Hello', 'b': 'Python'}
list1 = dict1.values()
str1 = ' '.join(list1)
#输出字典转字符串:Hello Python
print(str1)
#当字符串转换字典时,dict函数需要以key=value的形式作为函数参数,该参数表示字典里的一个键值对。
#当字典转换字符串时,由value函数获取字典的所有值,以列表的形式表示。再将列表转换成字符串,从而实现字典转换为字符串。
# 特殊字符转换字典
# 方法1:eval函数实现
str3 = '{"a":"Hello","b":"Python"}'
dict2 = eval(str3)
print('方法1:', dict2)
# 方法2:json模块的loads函数
# 局限性:如果字符串里的键值对是单引号表示,则该方法无法转换
# 如将str3改为 '{'a':'Hello','b':'Python'}'
import json
dict3 = json.loads(str3)
print('方法2:', dict3)
# 方法3:ast模块的literal_eval函数
import ast
dict4 = ast.literal_eval(str3)
print('方法3:', dict4)
# 3.5.3 列表与字典的转换
# 列表转换字典可以使用dict函数实现,但是列表的元素必须以一个列表或元组的形式表示,以列表或元组的形式表示字典的键值对。
# 字典转换成列表有三种方式:values()、keys()、items()
# 例
# 列表转换字典
list1 = ['a','Hello']
list2 = ['b','Python']
dict1 = dict([list1,list2])
print(dict1)
# 字典转换列表
dict1 = {'a': 'Hello', 'b': 'Python'}
# 获取字典所有值并生成列表
list1 = dict1.values()
print('values()函数:',list(list1))
# 获取字典的所有键并生成列表
list2 = dict1.keys()
print('key()函数:',list(list2))
# 获取字典所有键值并生成列表
list3 = dict1.items()
print('items()函数:',list(list3))
| false |
33b6bde8d0ee01505058d32b2732a6e407620d6e | zhufengyu/Python_study | /3.4:字典和集合.py | 2,900 | 4.34375 | 4 | # 3.4 集合与字典
# 相同点:集合和字典在某个程度上非常相似,都以大括号来进行定义,并且元素是无序排列的
# 不同点:元素格式和数据类型有所不同,集合只支持数字、字符串和元组(Python中不可变得数据类型),字典支持全部数据类型
# 例:
# 集合:
set_1 = {'Hello','Python',123,(1,'love')}
# 字典:
dict_1 = {'name':'Python',3:4,'mylist':[1,2,3]}
# 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
# d = {key1 : value1, key2 : value2 }
# 键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。
# 字典的增删改查
# 定义空的字典
dict1 = {}
# 添加元素
dict1['name'] = 'Python'
print('添加元素:', dict1)
# 修改元素的value
dict1['name'] = 'l love Python'
print('修改元素',dict1)
# 读取元素
# 以中括号的形式读取,不存在则提示错误
name = dict1['name']
print(name)
# 使用get方法读取
# 如果不存在则将字符串‘不存在这个元素’赋值到变量age
age = dict1.get('age','不存在这个元素')
print('读取元素值:',name)
print('读取age值:',age)
# 删除字典元素
del dict1['name']
print(dict1)
# 清空字典所有元素
dict1['name'] = 'Python'
dict1.clear()
print(dict1)
# 删除整个字典对象
del dict1
# 如果字典中嵌套了多个字典或列表,可以从字典外层逐步定位,定位方法由字典元素的key实现
# 例:
# 多重嵌套字典读取方式:
dict1 = {
'a':'Hello',
'b':{
'c':'Python',
'd':['world','china']
}
}
# 读取键为c的值
# 由于键c在键b的值里面,因此先读取键b的值,再读取c的值
get_b = dict1['b']
get_c = get_b['c']
# 读取列表值China
# 由于列表是键d的值,因此先读取键b的值,再读取键d的值,最后读取列表的值
get_b = dict1['b']
get_d = get_b['d']
get_china = get_d[1]
# 其他函数与方法
#
# 内置函数
# 比较两个字典元素
cmp(dict1,dict2)
# 计算字典元素的总数。
len(dict)
# 将字典以字符串表示
str(dict)
# 内置方法
# 返回一个字典的浅拷贝
dict.copy()
# 创建一个新字典,将列表或元组的元素做字典的key,value是每个key的值
dict.fromkeys(list,value)
# 如果键在字典dict里,那么返回True,否则返回False
dict.has_key(key)
# 以列表的形式返回字典的键值对,每个键值对以元组表示
dict.items()
# 以列表返回字典所有键
dict.keys()
# 读取字典元素时,但如果键不存在于字典中,将会添加键并将值设为default
dict.setdefault(key,default=None)
# 把字典dect2的键值对更新到dict1里
dict1.update(dict2)
# 以列表返回字典中所有的值
dict.values()
| false |
85653180a06fdeb6a0ddcbf1bf5042b78df3849b | lucasmsa/python-learning | /data-types/dict.py | 678 | 4.34375 | 4 | # Work with key-value pairs
dictTest = {'name' : 'Luka Magnotta', 'age' : 32}
# Preferably use .get method, because it will return None if the item isn't in the dictionary
# Instead of dictTest['name'], you can set the default value for keys that don't exist by setting an extra parameter
print(dictTest.get('name'))
print(dictTest.get('pepper', 'NOOO'))
# Update method to add new key-value pairs
dictTest.update({'garrafa': 'pet'})
print(dictTest)
# Delete items through
# del dictTest['name']
# or
# age = dictTest.pop('age')
# Access all items
print(dictTest.items())
# Doing a normal for in the dict will only get the keys
for k, v in dictTest.items():
print(k, v)
| true |
fec1a8f78d71e8fbd49882babecf009e6b35af31 | lucasmsa/python-learning | /decorators/dec.py | 1,230 | 4.5 | 4 | # Decorators are functions that take another function as an argument, adds some kind of funcionality
# and returns another function
# Easy to add functionality, by adding that functionality inside of the wrapper
def decoratorFunction(originalFunction):
def wrapperFunction(*args, **kwargs):
print(f'wrapper exectuted: {originalFunction.__name__}')
return originalFunction(*args, **kwargs)
# return wrapperFunction that is waiting to be executed
# and when it is, it executes the originalFunction
return wrapperFunction
# It is also possible to use decorators with classes
def decoratorClass(object):
def __init__(self, originalFunction):
self.originalFunction = originalFunction
def __call__(self, *args, **kwargs):
print(f'wrapper exectuted: {self.originalFunction.__name__}')
return self.originalFunction(*args, **kwargs)
# (*)
@decoratorFunction
def display():
print('Display')
# without - (*) -> decDisplay = decoratorFunction(display)
# same as with (*)
display()
# With arguments, call in the decorator as funct(*args, **kwargs)
@decoratorFunction
def displayInfo(name, age):
print(f'Display: ({name}, {age})')
displayInfo('John', 23)
| true |
70a4ee9fcb28b8de53b3b68669baa7f9c6fb2d91 | adyadyat/pyprojects | /personal_folder/py2.py | 753 | 4.21875 | 4 | name = input("Enter your name: ")
print(name.title())
# title() - изменение регистра символов в строках
# (первые символы в словах верхним, остальные нижние)
print(name.upper())
# upper() - все символы в строках верхним регистром
print(name.lower())
# upper() - все символы в строках нижним регистром
# "\t" табуляция
# "\n" переход на новую строку
# rstrip() - удаление пробелов с правой стороны
# lstrip() - удаление пробелов с левой стороны
# strip() - удаление пробелов с обеих концов
| false |
da84d409c98acf3e568aa6934572a1987f541a4a | Jian-jobs/Leetcode-Python3 | /Python3/034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py | 1,275 | 4.21875 | 4 | #!usr/bin/env python3
# -*- coding:utf-8 -*-
'''
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
'''
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
if nums[i] == target:
left = i
break
else:
return [-1, 1]
# find the index of the rightmost appearance of `target` (by reverse
# iteration). it is guaranteed to appear.
for j in range(len(nums) - 1, -1, -1):
if nums[j] == target:
right = j
break
return [left, right]
if __name__ == "__main__":
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 5) == [0, 0]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 7) == [1, 2]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 10) == [5, 5]
| true |
239d65a5f5655a440276f5bfa5ff42c9b8f9c4ea | Jian-jobs/Leetcode-Python3 | /Python3/007_Reverse_Integer.py | 1,299 | 4.5625 | 5 | #!usr/bin/env python3
# -*- coding:utf-8 -*-
'''
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# Consider positive and negative situation
flag = 0
if x < 0:
flag = -1
if x > 0:
flag = 1
x *= flag
result = 0
while x:
result = result * 10 + x % 10
x //= 10
if result > 2 ** 32 - 1: #2的32次方
return 0
else:
return result*flag
if __name__ == "__main__":
assert Solution().reverse(654300) == 3456
assert Solution().reverse(-321) == -123
assert Solution().reverse(21474836470) == 0
| true |
7e849c32bbbedc9922d16581beae5f8e34ab3053 | sesh10/Problem-Statements | /sort_list.py | 527 | 4.1875 | 4 | # Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
# Example 1:
# Input: [3, 3, 2, 1, 3, 2, 1]
# Output: [1, 1, 2, 2, 3, 3, 3]
def sortNums(nums):
id1 = 0
id2 = len(nums)-1
i = 0
while i <= id2:
if nums[i] == 1:
nums[i], nums[id1] = nums[id1], nums[i]
i += 1
id1 += 1
elif nums[i] == 2:
i += 1
elif nums[i] == 3:
nums[i], nums[id2] = nums[id2], nums[i]
id2 -= 1
print(nums)
return nums
print(sortNums([3, 3, 2, 1, 3, 2, 1]))
# [1, 1, 2, 2, 3, 3, 3]
| true |
fbbbee5ee210a2257f1d50ef76332a9621dd9607 | OmarSadat6/GuessTheNumber | /main.py | 999 | 4.15625 | 4 |
# Mini-game
print("Guess the number \n")
number = 11
while number < 0 or number > 10:
try:
number = int(input("Choose a number between 0 and 10: "))
except ValueError:
print("Letters or decimal numbers are not accepted")
if 0 <= number <= 10:
print("The number is chose")
break
print("Now you can guess the number, you have 3 tries ! \n")
tries = 3
userChoice = 12
while userChoice != number and tries > 0:
print(tries, "tries \n")
userChoice = int(input("Take a guess: "))
if 0 <= userChoice <= 10:
if userChoice < number:
print("the number is higher")
if userChoice > number:
print("the number is lower")
if userChoice == number:
break
else:
print("The number is between 0 to 10")
tries = tries - 1
if tries > 0:
print("You guessed the right number. Congratulations !")
else:
print("You didn't manage to get the right number, better luck next time...")
| true |
0600779361f1f46e0b108140c7ebf213cb5b33ac | AndriiBoikiv/lab03repos | /Lab_03_4.py | 623 | 4.15625 | 4 | # Lab_03_4.py
# Бойків Андрій
# Лабораторна робота № 3.4
# Розгалуження, задане плоскою фігурою.
# Варіант 2
x = int(input("Enter value of x: ")) # Вхідний аргумент
y = int(input("Enter value of y: ")) # Вхідний параметр
R = int(input("Enter value of R: ")) # Вхідний параметр
# Розгалуження в повній формі:
if (x <= 0 and y >= 0 and x**2 + y**2 <= R) \
or (x >= 0 and y <= 0 and x <= R/2 and y >= -x/2) \
or (x > R/2 and y <= 0 and x <= R and y >= 2*x - 2*R):
print("yes")
else:
print("no") | false |
cf33a939113ba50e04343dea146fe5038258eddf | thiagoabreu93/ed-not-2021-2 | /listas2.py | 684 | 4.5 | 4 | # range(): gera uma faixa de números
# range() com 1 argumento: gera uma lista de números
# que vai de zero até argumento - 1
for i in range(10):
print(i)
print('------------------------')
# range() com 2 argumentos: gera uma lista de números começando pelo primeiro argumento (inclusive) até o segundo argumento (exclusive)
for j in range(5, 15):
print(j)
print('-------------------------')
# range() com três argumentos:
# 1º: limite inferior (inclusive)
# 2º: limite superior (exclusive)
# 3º: passo (de quanto em quanto a lista irá andar)
for k in range(1, 22, 3):
print(k)
print('-------------------------')
for n in range(10, 0, -1):
print(n)
| false |
bf59464787f7c5d4d297f6d770381e78af3f1b63 | aescobed/TensorFlow | /Udemy/Section 5/Neural Net Intro/Neural Net Intro/OOPRefresher.py | 517 | 4.1875 | 4 |
# executes upon creation
class SimpleClass():
def __init__(self, name):
print("hello " + name)
def yell(self):
print("YELLING")
s = "world"
type(s)
# will print hello
x = SimpleClass("andy")
#shows you what it is and where in the memory it is stored
print(x)
x.yell()
class ExtendedClass(SimpleClass):
def __init__(self):
# run the init method in the simple class
super().__init__("john")
print("EXTEND!")
y = ExtendedClass()
y.yell() | true |
00bbbc906a5162cb39ed1591e1722e71eaef7821 | Yuliya-N/MyScripts | /python-october-2016-test-Yuliya-N/duplicates.py | 1,777 | 4.28125 | 4 | def remove_duplicates(data):
"""
Removes duplicate elements from given sequence:
>>> remove_duplicates('abcdaefbg')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
If mutable argument passed, it should remain unchanged:
>>> data = [1, 2, 2, 3, 4, 2, 3, 5]
>>> remove_duplicates(data)
[1, 2, 3, 4, 5]
>>> data
[1, 2, 2, 3, 4, 2, 3, 5]
Output should preserve order of first occurence in passed argument:
>>> remove_duplicates('dcbacbd')
['d', 'c', 'b', 'a']
>>> remove_duplicates([4, 8, 3, 2, 3, 8, 6, 4, 1])
[4, 8, 3, 2, 6, 1]
Args:
data: sequence with possible duplicates
Returns:
List with all duplicates removed
"""
#unique_list = [ch for ch in data if ch not in unique_list]
unique_list = []
for ch in data:
if ch not in unique_list:
unique_list.append(ch)
return unique_list
def get_duplicates(data):
"""
Get all duplicates from given sequence along with duplicate count.
>>> dups = get_duplicates([1, 2, 2, 3, 4, 3, 5, 6, 6, 2])
>>> dups == {3: 2, 2: 3, 6: 2}
True
In case when no duplicates found, empty dict should be returned
>>> get_duplicates('abcdefg')
{}
Args:
data: sequence with possible duplicates
Returns:
Dictionary with duplicate values as keys, occurence count as values
"""
duplicates = {}
for ch in data:
if data.count(ch) > 1:
duplicates[ch] = data.count(ch)
return duplicates
# code below left for your own usage and can be deleted at will
# -------------------------------------------------------------
if __name__ == '__main__':
# tests for this module lives in tests/test_duplicates.py
import unittest
unittest.main(module='test_duplicates')
| true |
33c7fef0696c9f7dc6bca36c280c5cc09b19d8e2 | crizer03/Python | /1 - inheritance.py | 1,570 | 4.28125 | 4 | # Types of inheritance
# Single A > B
class A:
pass
class B(A):
pass
# Multi Level A > B > C
class A:
pass
class B(A):
pass
class C(B):
pass
# Hierarchical A > B, A > C
class A:
pass
class B(A):
pass
class C(A):
pass
# Multiple A > C, B > C
class A:
pass
class B:
pass
class C(A, B):
pass
# Hybrid A > B, A > C, B > D, C > D
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
# super() can be used in 3 ways.
# - To invoke parent class methods
# - To invoke parent class variables
# - To invoke parent class constructor
# globals() is the variables or method outside class
a, b = 15, 20
def method():
print('Global method {}'.format('method'))
class A:
a, b = 10, 20
def __init__(self):
print("Constructor from class A")
def method(self, a, b):
print("Method from Class A")
class B(A):
a, b = 100, 200
def __init__(self):
print("Constructor from class B")
super().__init__() # Approach 1. Calls parent class constructor
A.__init__(self) # Approach 2. Directly specify the class
def method(self, a, b):
super().method(1, 2) # Prints parent method
method() # Prints global method
print(a + b) # Local variables
print(self.a + self.b) # Child class variables
print(super().a + super().b) # Parent class variables
print(globals()['a'] + globals()['b']) # Global variables
obj = B()
obj.method(40,60)
| true |
783e2e497d5ab8b9dae69440b49874bb33cbe2b8 | pulinghao/LeetCode_Python | /283. 移动零.py | 1,307 | 4.125 | 4 | #!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 2020/4/2 12:43 下午
@Author: pulinghao
@File: 283. 移动零.py
@Software: PyCharm
"""
#
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
#
# 示例:
#
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
# 说明:
#
# 必须在原数组上操作,不能拷贝额外的数组。
# 尽量减少操作次数。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# j指针保存非0的数字, 因为j比i小,肯定不会出现覆盖的情况
# 如果j< length,那么就把剩下的位置用0补齐
# j = 0
# for i in range(len(nums)):
# if nums[i] != 0:
# nums[j] = nums[i]
# j += 1
#
# while j < len(nums):
# nums[j] = 0
# j += 1
#
# return nums
j = 0
for i in xrange(len(nums)):
if nums[i]:
nums[i],nums[j] = nums[j],nums[i]
j += 1
return nums
if __name__ == '__main__':
nums = [0,0,1]
print Solution().moveZeroes(nums) | false |
700a1a1499f66150a5d934f0a0d2cfba874425c9 | wicys-team/intro-to-python | /3_variables.py | 873 | 4.28125 | 4 | # Python has a print statement
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
# Simple way to get input data from console
input_string_var = raw_input(
"Enter some data: ") # Returns the data as a string
input_var = input("Enter some data: ") # Evaluates the data as python code
# Warning: Caution is recommended for input() method usage
# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
some_var # => 5
# Accessing a previously unassigned variable is an exception.
# See Control Flow to learn more about exception handling.
# some_other_var # Raises a name error
# if can be used as an expression
# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
| true |
b26d49a56c394ceb43cfe2323bb70304f3a31b8e | jsariasgeek/fibonacci-and-threads-exercises-with-python | /test_fibonacci.py | 1,004 | 4.3125 | 4 | """
This file is for testing the Fibonacci class
"""
import unittest
from fibonacci import Fibonacci
class FibonacciTestCase(unittest.TestCase):
def setUp(self):
self.test_cases = {0:"n has to be integer and greather than 0", 1:1, 2:1, 10:55, 25:75025, 35:9227465, 40:102334155}
def test_recursive_algorithm(self):
"""
The objective of this test is checking the fibonacci_recursive()
method returns correct values.
"""
for test in self.test_cases:
print(test)
my_fibonacci = Fibonacci(test)
self.assertEqual(self.test_cases[test], my_fibonacci.fibonacci_recursive(), f"Should be {self.test_cases[test]}")
def test_not_recursive_algorithm(self):
for test in self.test_cases:
my_fibonacci = Fibonacci(test)
self.assertEqual(self.test_cases[test], my_fibonacci.fibonacci_not_recursive(), f"Should be {self.test_cases[test]}")
if __name__ == '__main__':
unittest.main() | true |
7aad5999afa18ddb2b8542c95cb3e7661ba0067e | shivangigupta1404/pythonCodes | /sort_algo.py | 1,102 | 4.25 | 4 | def selection_sort(arr):
n=len(arr)
for i in range(0,n-1):
print arr
small=arr[i]
pos=i
for j in range(i+1,n):
if arr[j]<small:
small=arr[j]
pos=j
if pos!=i:
arr[pos]=arr[i]
arr[i]=small
print arr
def bubble_sort(arr):
n=len(arr)
for i in range(0,n-1):
print arr
swap=0
for j in range(1,n-i):
if arr[j-1]>arr[j]:
swap=1
temp=arr[j]
arr[j]=arr[j-1]
arr[j-1]=temp
#Sorting can be optimised by stopping the algorithm if inner loop does not cause any swap
if not swap:
break
print arr
def insertion_sort(arr):
n=len(arr)
for i in range(1,n):
print arr
element=arr[i]
j=i-1
while j>=0:
if arr[j]>element:
arr[j+1]=arr[j]
else:
break
j=j-1
arr[j+1]=element
print arr
| false |
d26f872e38639f7e8d6ba1facadd90fb0601c0cc | Mahnatse-rgb/LEVEL-1-PROGRAMMING-KATAS | /hello.py | 315 | 4.3125 | 4 | '''
Write a function named hello, it needs to take in a string as an argument. The function should work like this:
eg: hello("Tshepo")
should output
Hello Tshepo!
'''
def hello(name):
return "Hello" + " " + name + "!"
user_name = input("Enter user name: ")
print(hello(user_name))
| true |
2bc6fec0dc1abd49d64cc096abc238f70b862e28 | ryanhanli/Python | /crossword.py | 2,511 | 4.125 | 4 | import random
import string
board_size = 10
words = input("Enter words separated by spaces: ").split()
#Generate the board
board = [['*' for _ in range(board_size)] for _ in range(board_size)]
#Print Grid/Board Function
def print_board():
for x in range(board_size):
print('\t'*4+' '.join(board[x]))
placements = ['horizontal','vertical']
for word in words:
word_length = len(word)
placed = False
while not placed:
placement = random.choice(placements)
if placement == 'horizontal':
step_x = 1
step_y = 0
if placement == 'vertical':
step_x = 0
step_y = 1
#Generate random starting location for word
x_position = random.randint(0,board_size)
y_position = random.randint(0,board_size)
ending_x = x_position + word_length*step_x
ending_y = y_position + word_length*step_y
#Check if word will fit on the board starting at the random position
if ending_x<0 or ending_x>= board_size: continue
if ending_y<0 or ending_y>= board_size: continue
failed = False
#Try placing the word if you run into an already placed character instead of star try again
for i in range(word_length):
character = word[i]
new_position_x = x_position + i*step_x
new_position_y = y_position + i*step_y
character_at_new_position = board[new_position_x][new_position_y]
if character_at_new_position != '*':
if character_at_new_position == character:
continue
else:
failed = True
break
if failed:
continue
#Place the word onto the grid
else:
for i in range(word_length):
character = word[i]
new_position_x = x_position + i*step_x
new_position_y = y_position + i*step_y
board[new_position_x][new_position_y] = character
placed = True
#Showcase the answers
print("Board before:")
print_board()
for x in range(board_size):
for y in range(board_size):
if (board[x][y]=='*'):
board[x][y]=random.choice(string.ascii_uppercase)
print("Final board:")
print_board() | true |
c398ba1e2b42a1e06d973a6a19b4f6545dcf106b | Youngermaster/Learning-Programming-Languages | /Python/Pildoras informaticas/Tuple/tuple.py | 827 | 4.125 | 4 | myTuple = ("Juan", 23, 12, 1930, 12)
myNewList = list(myTuple) # Convert a tuple in a list
anotherList = ["Juan", 232, 1212, 1930]
anotherTuple = tuple(anotherList) # Convert a list in a tuple
print(myTuple, "And its lenght is: ", len(myTuple)) # Prints my tuple and its length
print("Juan" in myTuple) # Prints a bool if the element is or not
print(myTuple.count(12)) # Prints how many times is the parameter
print(myTuple.index("Juan")) # Print a int -> the first occurrence of the String value
# Unitary tuple
unitaryTuple = ("Juan",) # Whit the comma.
print(unitaryTuple)
# Empaneled de tuple
empaquetedTuple = "Juan", 13, 432, 132
print(empaquetedTuple)
# unpaqueted de tuple
name, age, month, year, day = myTuple
print("Name: {} Age: {} Month: {} Year: {} Day: {}"
.format(name, age, month, year, day))
| true |
b7ac40659b939ef07bf2827dffa3461cbaeef67c | sindhusha-t/Python-Programming | /ICP-2/string_alternative.py | 424 | 4.25 | 4 |
def string_alternative(input_str):
#Using List Slicing
print(input_str[::2])
#Using For Loops
output_str = [input_str[index] for index in range(0,len(input_str), 2)]
print(''.join(output_str))
def main():
print("\--------PRINT ALTERNATE CHARS IN STRINGS----------n")
input_str = input("Enter a sentence: ")
string_alternative(input_str)
if __name__ == "__main__":
main()
| false |
b664b33c05b5e2870baf6079f3d6166961e10b12 | AzizHarrington/euler | /euler09.py | 638 | 4.28125 | 4 | ##A Pythagorean triplet is a set of three natural numbers, a b c, for which,
##
##a**2 + b**2 = c**2
##For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
##
##There exists exactly one Pythagorean triplet for which a + b + c = 1000.
##Find the product abc.
def is_triplet(a, b, c):
return a**2 + b**2 == c**2
#print is_triplet(3, 4, 5)
def find_triplets(n):
for x in xrange(1, n):
for y in xrange(x + 1, n):
for z in xrange(y + 1, n):
if is_triplet(x, y, z) == True and (x + y + z) == n:
return z * y * x
return None
print find_triplets(1000)
| false |
12893abcad4c45c20442df7d0359c55e6bfcfbaf | Reatris/DeepLearing_Origin | /DeepLearning4/reshape.py | 225 | 4.34375 | 4 | #测试结果reshape不改变原来的数组,只能新复值
import numpy as np
list=[1,2,3,4,5,6]
a=np.array([1,2,3,4,5,8])
print(list)
arr=np.array(list)
print(arr)
arr.reshape(2,3)
print(arr)
d=a.reshape((2,3))
print(d)
| false |
4efbba9f922e3bea9a6f92b4522c8003c08d9a77 | NevrinO/Coding | /Python/Bday Data.py | 2,957 | 4.34375 | 4 | import datetime
print "Hello my closest, most dear and most revered friend"
print "Please, if you would be so kind, enter your birthday"
valid = False #We start with no value for 'day' at all, so that's certainly not valid
while not valid: #while we don't have a valid day:
try:
day = int(raw_input("enter the day: "))
if day < 1 or day > 31:
print "You have entered an invalid answer, please try again"
else:
valid = True
except:
print "You must enter an int"
valid = False # reset for next while loop
while not valid:
try:
month = int(raw_input("enter month ")) # retry input of valid integer
if month < 1 or month > 12:
print "You have entered an invalid answer"
else:
valid = True
except:
print "You must enter an int"
valid = False # reset for final while loop
while not valid:
try:
year = int(raw_input("enter year ")) # retry input of valid integer
if year < 1000 or year > 2013:
print "You have entered an invalid answer"
else:
valid = True
except:
print "You must enter an int"
current = datetime.date.today() # gets current date from imported datetime
print ("\nYour Birthday is: %s/%s/%s" % (day, month, year)) # prints info user entered
print ("\nThe Current date is: %s/%s/%s" % (current.day, current.month, current.year) ) # prints current date from datetime
raw_input("hit enter to continue")
weekday ={ # dictionary of days of week
0: 'Monday',
1: 'Tuesday',
2: 'Wednesday',
3: 'Thursday',
4: 'Friday',
5: 'Saturday',
6: 'Sunday',
}
bDate = datetime.date(year, month, day) # converts user data to datetime object
leapYear = int((current.year - bDate.year) / 4) # determine number of days added by leap years
deltaDays = (current - bDate) # difference in days between current date and bDate
dStrip = str(deltaDays).split() # converts days into string format and splits off unnecessary data
daysLeft = int(dStrip[0]) # gathers just the days number and convert to int from sting
mYear = daysLeft / 365 # Calculate years alive
daysLeft = daysLeft - (mYear * 365) # removes year part of days
mMonth = daysLeft / 30 # calculate months alive
mDay = daysLeft - (mMonth * 30) - 7 # Calculate days alive
if mDay < 0: # fix small discrepancy created with certain date combos
mMonth = mMonth - 1
if mMonth < 0:
mMonth = 11 # Plan on changing entire calculating section because sometimes it is still a day or two off.
mDay = mDay + 30
print "You were born on a %s: " % (weekday[bDate.weekday()])
print "you have been alive for about %s seconds" % (deltaDays.total_seconds())
print ("\nYou are %s years %s months %s days old" % (mYear, mMonth, mDay))
if mYear > 122:
print "You should call Guinness World Records cause it looks like you can give Jeanne Louise Calment a run for her money, She was born on 21 February 1875."
if year == 1875 and month == 02 and day == 21:
print "Oh never mind it looks like you are Jeanne Louise Calment."
raw_input("hit enter to continue")
| true |
df09a6da23ee50b6c84b1326ebb07db4208b155f | drewmresnick/Learning-to-code | /difference.py | 568 | 4.25 | 4 |
print("Give me two numbers to compare:")
number_one = float(input("First number > "))
number_two = float(input("Second number > "))
def difference(number_two, number_one):
diff = number_two - number_one + 1
return diff
if number_one > number_two:
print(f" {number_one} is greater than {number_two}")
elif number_one == number_two:
print(f" {number_one} is equal to {number_two}")
else:
diff = difference(number_two, number_one)
print(f" {number_one} is less than {number_two}. You must add {diff} for it to be greater.")
| true |
34e1d482e3d56f83408c6a036088c3b0b719fd3c | mcatalay/Compsci_121 | /basic_algorithms.py | 2,900 | 4.15625 | 4 |
# CS121: Analyzing Election Tweets
# Omar Elmasry and Mufitcan Atalay
# Algorithms for efficiently counting and sorting distinct
# `entities`, or unique values, are widely used in data
# analysis. Functions to implement: count_items, find_top_k,
# find_min_count, find_frequent
# DO NOT REMOVE THESE LINES OF CODE
# pylint: disable-msg=missing-docstring
from util import sort_count_pairs
def count_items(items):
'''
Counts each distinct item (entity) in a list of items
Inputs:
items: list of items (must be hashable/comparable)
Returns: list (item, number of occurrences).
'''
# YOUR CODE GOES HERE
entities = {}
for item in items:
entities[item] = entities.get(item,0) + 1
return entities.items()
def find_top_k(items, k):
'''
Find the K most frequently occurring items
Inputs:
items: list of items (must be hashable/comparable)
k: a non-negative integer
Returns: sorted list of the top K tuples
'''
# Error checking (DO NOT MODIFY)
if k < 0:
raise ValueError("In find_top_k, k must be a non-negative integer")
# Runs the helper function for you (DO NOT MODIFY)
item_counts = count_items(items)
# YOUR CODE GOES HERE
tiptop = sort_count_pairs(item_counts)
topk = tiptop[0:k]
# REPLACE RETURN VALUE WITH AN APPROPRIATE VALUE
return topk
def find_min_count(items, min_count):
'''
Find the items that occur at least min_count times
Inputs:
items: a list of items (must be hashable/comparable)
min_count: integer
Returns: sorted list of tuples
'''
# Runs the helper function for you (DO NOT MODIFY)
item_counts = count_items(items)
# YOUR CODE HERE
minc = []
tiptop = sort_count_pairs(item_counts)
for i in range(0, len(tiptop)):
if tiptop[i][1] >= min_count:
minc.append(tiptop[i])
# REPLACE RETURN VALUE WITH AN APPROPRIATE VALUE
return minc
def find_frequent(items, k):
'''
Find items where the number of times the item occurs is at least
1/k * len(items).
Input:
items: a list of items (must be hashable/comparable)
k: integer
Returns: sorted list of tuples
'''
counter = {}
for item in items:
if item in counter:
counter[item] += 1
else:
if len(counter) > k - 1:
raise ValueError(
"The number of elements stored in counter" +
" should not exceed (k-1)=" + str(k-1))
elif len(counter) < k-1:
counter[item] = counter.get(1,0) +1
elif len(counter) == k-1:
for key in counter.copy():
counter[key] -= 1
if counter[key] <= 0:
del counter[key]
return sort_count_pairs(counter.items())
| true |
8f701b7fc81a56c89615d95b16822f384a84b9f9 | snadeau/Rosalind | /INI4/oddintegersum.py | 381 | 4.15625 | 4 | #Scott Nadeau
#2013-04-26
#Rosalind
#Conditions and Loops
def sum_odd_integers(a, b):
"""
Input two positive integers such that a < b < 10000
Returns the sum of all odd integers from a through b inclusively
"""
sum = 0
while a <= b:
if (a % 2 == 1):
sum += a
a += 1
return sum
print sum_odd_integers(4939,9469)
| false |
164b6a6891b8ac0163f384545868921181a6874e | VinAVarghese/python_course | /Basic Syntax, Logic & Loops/rock_paper_scissors.py | 2,906 | 4.3125 | 4 | # Simple cli app using .input() to read user input in python
# Practices conditional logic in python
print(" |||| ROCK ||||")
print(" ||||| PAPER ||||")
print("||||| SCISSORS |||")
p1_choice = input("(enter PLAYER ONE'S choice): ").lower()
if p1_choice == "scissors":
p1_choice = "scissor"
# while (p1_choice != "rock") or (p1_choice != "paper") or (p1_choice != "scissor"):
# print("Please enter a valid selection. Check your spelling!")
# p1_choice = input("(re-enter PLAYER ONE'S choice): ").lower()
# if p1_choice == "scissors":
# p1_choice = "scissor"
# print("P1's Choice: ", p1_choice)
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
print("************ NO CHEATING **************")
p2_choice = input("(enter PLAYER TWO'S choice): ").lower()
if p2_choice == "scissors":
p2_choice = "scissor"
# while not p2_choice == "rock" or not p2_choice == "paper" or not p2_choice == "scissor":
# print("Please enter a valid selection. Check your spelling!")
# p2_choice = input("(re-enter PLAYER TWO'S choice): ").lower()
# if p2_choice == "scissors":
# p2_choice = "scissor"
# print("P2's Choice: ", p2_choice)
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("************ and ... **************")
print("SHOOT!")
print("P1's Choice: ", p1_choice)
print("P2's Choice: ", p2_choice)
if p1_choice == p2_choice:
print("It's a tie!")
elif (p1_choice == "rock") and p2_choice == "scissor":
print("PLAYER 1 WINS!")
elif p1_choice == "scissor" and p2_choice == "paper":
print("PLAYER 1 WINS!")
elif p1_choice == "paper" and p2_choice == "rock":
print("PLAYER 1 WINS!")
else:
print("PLAYER 2 WINS!") | false |
50110e637e12a573658a049b5dce53adbee2c726 | JarekCzajka/variables- | /circle.py | 311 | 4.59375 | 5 | #Jaroslaw Czajka
#24.09.2014
#Math_unit_exercises
#Calculate the circumference and area of a circle when the user enters a radius.
radius=int(input("This program will help you to calculate the circimference of a circle when the user enters a radius:"))
circumference=(radius*radius*3.14)
print(circumference)
| true |
9297d07fc385f7cbad1f84939ee8de83c45352ea | JarekCzajka/variables- | /Stretch and Challenge Exercises_Task 1.py | 617 | 4.25 | 4 | #Jaroslaw Czajka
#22.09.2014
#Stretch and Challenge Exercises_Task 1
#This program will ask the user for the measurements of users garden and calculate the perimeter and area of the gardne
print("Welcome to GardenUnit")
print("This program will help you to find the area and the perimeter of your garden")
number_one=int(input("Please enter the length of your garden:"))
#The program has asked the user for the length of the garden and dipslyed the result
print("This is the length of your garden:")
print(number_one)
#The program has displyed the result
int(input("Now please enter the width of your garden:"))
| true |
a06d5f63107d8ea4741976a835c8812311f3632b | ZhenhuiHe/Demo_Install_Python | /test1/Demo_Test1_Python.py | 982 | 4.15625 | 4 | #! -*- coding: utf-8 -*-
"""
Author: ZhenYuSha
Create Time: 2020-1-20
Info: Python打包示例1,单个文件打包
“pyinstaller -F(单个可执行文件) 程序源 -n 程序名 -w(去掉控制台窗口,这在GUI界面时非常有用) -i 图标.ico”
“pyinstaller -F test1/Demo_Test1_Python.py”
"""
def bubble_sort(arr):
"""
冒泡排序
:param arr:
:return:
"""
for i in range(1, len(arr)):
for j in range(0, len(arr)-i):
if arr[j] > arr[j+1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
if __name__ == '__main__':
test = [1, 8, 123, 18, 99, 300]
print("************************************")
print("* 冒泡排序 *")
print("************************************")
print("源列表:", test)
result = bubble_sort(test)
print("排序后:", result)
print("************************************")
input("按任意键退出...")
| false |
be5d52085165953486f1875210269082ce11c7c2 | Asynchronousx/Machine-Learning-Espresso | /1 - Preprocessing/5a_normalization.py | 2,981 | 4.28125 | 4 | import pandas as pd
# Sometimes, we can use a remote URI to access a dataset. Since this specific dataset
# is a CSV without names, we can assign them by specifying a string array into the
# function itself. We then pass another array to specify which columns of the dataset
# we need to use.
wines = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data",
names=["Class", "Alcol", "Flavonoid"],
usecols=[0,1,7])
# We then create two numpy arrays: one containing the class elements, the other
# containing the entire dataframe features except from the class. We'll use the
# values method from a dataframe to convert the dataframe itself to a nump array.
X = wines.drop("Class", axis=1)
Y = wines["Class"].values
# Let's observe the the first 10 elements and check if some values are way bigger
# than other: We suspect that values into the Alcol column are >> than flavonoid.
wines.head(10)
# We then use describe() to assure that: we see that the Min-Max range for the alcol
# is 11.03 - 14.83 and Min-Max for flavonoids are 0.34 - 5.08. A big value discrepance.
# We then need to normalize.
wines.describe()
# We can normalize using the formula: Xnorm = X - Xmin / Xmax - Xmin.
# For the sake of understanding, let's create some sub-arrays to simplify things.
# We create a copy of the wine array, that is gonna be normalized:
wines_norm = wines.copy()
# we then specify an array containing the features we want to normalize
features = ["Alcol", "Flavonoid"]
# we then create a temporary dataframe containing only those featues
to_norm = wines_norm[features]
# Now we can proceed to the normalization using the formula we stated above:
wines_norm[features] = (to_norm - to_norm.min()) / (to_norm.max() - to_norm.min())
# check for results
wines_norm.head()
# We could have done this in just one line: but it's more confusionary.
# wines[features] = (wines[features] - wines[features].min()) / (wines[features].max() - wines[features].min())
# wines.head()
# To apply normalization to a numpy array, we got an easier solution: we just use
# an already-existent method from the sklearn framework, named MinMaxScaler: as you
# could imagine, this tool use min-max values to scale the dataset to a fixed range
# values (def: 0-1), that is the normalization itself.
# Import the module and assigning it
from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler()
# Copy the X numpy array and apply the normalization on it: as usual, we use the
# fit transform method to gain infos with fit about min/max and then transforming
# the value into the array with transform applying the normalization.
# NOTE: for faster and cleaner code, let's use fit_transform that will do both
# of those process in the same function. Once the MinMaxScaler has been fitted and
# trained, we can just use transform on next dataset to normalize.
X_norm = X.copy()
X_norm = mms.fit_transform(X_norm)
X_norm[:5]
| true |
160882f13d253bc623dd00ea165606db44318e37 | romulovieira777/Aprenda_Python_3 | /Seção 02 - Aprendendo a Sintaxe/exemplo.py | 1,448 | 4.125 | 4 | # One-line comment (Comentário de uma linha)
'''
Comment from (Comentário de)
more of (mais de)
one (uma)
line (linha)
'''
# Variables and Types (Variáveis e Tipos)
# String Type Text (Tipo String Texto)
name = 'José'
phrase = 'welcome to the accelerated training of Python in 6hs.'
surname = 'Silva'
# Numbers Three Types (Números Três Tipos)
# Float Types (Tipo Float)
height = 1.80
# Integer Types (Tipo Inteiro)
age = 30
# Complex
complex_number = 1 + 2j # Used in statistical electrical engineering (Utiliado em estatística engenharia elétrica)
# Bool Types (Booleano) (Tipo Bool)
own_car = True
have_children = False
# Lists (Listas)
# Array Lists (Listas Tipo Array)
cars = ['Camaro', 'Lamborghini', 'Ferrari']
# Array Oprations (Operações com Array)
cars.append('Hilux') # Adds an object at the bottom position of the array
# Adiciona um objeto na última posição do array
cars.insert(0, 'Hilux') # Inserts an object at a specific position in the array
# Insere um objeto em uma posição específica do array
# Removes an object in the array by name (Remove um objeto no array pelo nome)
cars.remove('Hilux')
# Removes an object in the array by position (Remove um objeto no array pela posição)
cars.pop(3)
# Key Type Lists: Value (Listas Tipo Chave: Valor)
people = {'name': 'José da Silva', 'age': 30, 'height': 1.8, 'weight': 93}
| false |
5c484c683e94759a566eb8aa98fab771bcc567f7 | Vicz1010/Rock_Paper_Scissors | /main.py | 1,258 | 4.15625 | 4 | import random
options = ["Rock", "Paper", "Scissors"]
class Player():
def __init__(self,name):
self.name = name
## Introduction ##
print("Welcome to: Rock, Paper, Scissors")
## Generating Players ##
comp = Player("Computer")
name = input("What is your name? ")
player = Player(name)
## GAMEPLAY ##
print("The game is starting")
print("Rock, Paper, Scissors shoot!")
random.shuffle(options)
comp_choice = options[0]
random.shuffle(options)
player_choice = options[0]
print("The computer chose: {}".format(comp_choice))
print("{a} chose: {b}".format(a=name,b=player_choice))
## Deciding Who Wins ##
if comp_choice == "Rock" and player_choice == "Scissors":
print("Computer wins!")
else:
if comp_choice == "Scissors" and player_choice == "Rock":
print("{} wins!".format(name))
if comp_choice == "Rock" and player_choice == "Paper":
print("{} wins!".format(name))
else:
if comp_choice == "Paper" and player_choice == "Rock":
print("Computer wins!")
if comp_choice == "Scissors" and player_choice == "Paper":
print("Computer wins!")
else:
if comp_choice == "Paper" and player_choice == "Scissors":
print("{} wins!".format(name))
if comp_choice == player_choice:
print("We have a draw!") | true |
090972543f88c75d13425113e0dc9897d7cd866f | luciaj283/sturdy-sniffle | /programmingassignment33.py | 1,277 | 4.21875 | 4 | # This is my programming assignment #3 - John Paul Lucia
score1 = 0
score2 = 0
score3 = 0
sumBoris = 0
avgBoris = 0.0
sumNatasha = 0.0
avgNatasha = 0.0
teamAvg = 0.0
# Print the *'s and introduction.....
print("************************************************************************")
print(" Welcome to the Bowling application for Boris and Natasha")
print("")
# Get input from user....
score1 = int(input(" Please enter Bori's score #1: "))
score2 = int(input(" Please enter Bori's score #2: "))
score3 = int(input(" Please enter Bori's score #3: "))
sumBoris = score1 + score2 + score3
avgBoris = sumBoris / 3
print("")
score1 = int(input(" Please enter Natasha's score #1: "))
score2 = int(input(" Please enter Natasha's score #2: "))
score3 = int(input(" Please enter Natasha's score #3: "))
sumNatasha = score1 + score2 + score3
avgNatasha = sumNatasha / 3
print("")
print("...And now the averages...")
teamAvg = (avgBoris + avgNatasha) / 2
print(' Boris'' average is %2.2f' % avgBoris)
print(' Natashas'' average is %2.2f' % avgNatasha)
print(' The teams'' average is %2.2f' % teamAvg)
print("*****************************************************************")
print("Thank you") | false |
f20943fc1381226b554e65e4c80c51f9a36a412b | StephonBrown/AlgorithmicPractice | /Sorting.py | 1,133 | 4.125 | 4 | #%%
def HeapSort(arr):
n = len(arr)
array = [3,7,2,1,4]
HeapSort(array)
# %%
def Partition(arr, low, high):
#The element being pivoted around
pivot = arr[high]
#This is the element after the element being focused on in the loop
i = low - 1
for j in range(low, high):
#if the current element is less than the pivot, move it to the lefy
if(arr[j] < pivot):
i = i+1
#Make this swap more pythonic like this arr[j], arr[i] = arr[i], arr[j]
swap = arr[i]
arr[i] = arr[j]
arr[j] = swap
##This swap is done to make sure the pivot is placed between number
# less than and numbers greater than the pivot after going through all numbers
swap = arr[i + 1]
arr[i+1] = arr[high]
arr[high] = swap
return i + 1
def QuickSort(arr, low, high):
if(low < high):
par = Partition(arr, low, high)
QuickSort(arr, low, par - 1)
QuickSort(arr, par + 1, high)
# Driver code to test above
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
QuickSort(arr,0,n-1)
print ("Sorted array is:")
print(arr)
# %%
| true |
ecdd37aa767c53096db304df0a8ce891b865a614 | jdlambright/Intermediate-Python | /1 Previous Notes/27 TKinter/grid_practice.py | 1,264 | 4.46875 | 4 | from tkinter import *
window = Tk()
window.title("GUI")
window.minsize(width=500, height = 300)
window.config(padx=20, pady=20)
#button
def button_clicked():
#to capture what is typed lines 23-24
new_text= entry.get()
my_label.config(text= new_text)
print("i got clicked")
#label- create it and say how it will be laid out
my_label = Label(text="label", font=("Arial", 22, "bold"))
my_label.config(text="new text")
my_label.grid(column=0, row=0)
my_label.config(padx=15, pady=15)
#button
button1 = Button(text="button 1", command=button_clicked)
button1.grid(column=1, row=1)
button2 = Button(text="button 2", command=button_clicked)
button2.grid(column=2, row=0)
#Entries
input = Entry(text="type something", width=30)
print(input.get())
input.grid(column=3, row=2)
#pack() is going to put widgets on the screen in a logical manner but hard to customize
#place() uses x and y starting top left corner as 0,0 (100, 0) would move widget over 100 px and keep at top
#the downside of place() is you have to work and play with every single widget to get it where you want
#grid() system puts everything into columns and rows. it is relative to other widgets
# you cannot put grid() and pack() in the same program
window.mainloop() | true |
2bb365071a9bb048502191a2c3eac98a5f391d4d | yasol123/Python_Practice | /Merge_Sorted_List.py | 739 | 4.21875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
input:
l1=[1,2,4]
l2=[1,3,4]
Output: [1,1,2,3,4,4]
Approach: Linked List with Recursion
"""
if l1 and l2: #if l1 and l2 are not null
if l1.val>l2.val: #if n1 node value is bigger than l2 node.
l1,l2=l2,l1 #swap for sorting
l1.next = self.mergeTwoLists(l1.next,l2) #recursion function
return l1 or l2 #if either l1 or l2 has no more node to traverse, it will return the sorted merge linked lists
| true |
d6115094249fab8a43ac96473e1c748624738cbf | VarTony/Playground | /Python/Just Python/LevelUp/Level_1/exercise12.py | 531 | 4.3125 | 4 | # Реализуйте функцию reverse, которая переворачивает строку.
# reverse('hello, world!'); // !dlrow ,olleh
def reverse(str):
result = ''
i = len(str) - 1
palindrome = ' palindrome'
while i >= 0:
result += str[i]
i -= 1
i = len(result) - 1
while i >= 0:
if (str[i] != result[i]):
palindrome = ' not' + palindrome
break
i -= 1
result += ' is' + palindrome
return result
print(reverse('strange')) | false |
6c6183cb4d50877b76a81dd2e8daf942eb078263 | VarTony/Playground | /Python/Just Python/LevelUp/Level_1/exercise2.py | 779 | 4.1875 | 4 | # Реализуйте функцию squareOfSum, которая находит квадрат суммы двух чисел по формуле: a² + 2 * a * b + b².
# squareOfSum(2, 3) // 25
# squareOfSum(1, 10) // 121
import unittest
import random
def squareOfSum(value1, value2):
result = (value1 * value1) + 2 * value1 * value2 + (value2 ** 2)
# print(result)
return result
class TestUM(unittest.TestCase):
def test_squareOfSum(self, a, b):
self.assertEqual(squareOfSum(a, b), ((a + b) ** 2))
test = TestUM()
j = 0
i = 0
result = True
while (i <= 10000):
j = random.randint(1, i if (i > 10) else 25)
if test.test_squareOfSum(2, 2) == False: result = False
i += 1
if result:
print('successful')
else:
print('Error')
| false |
58e0ccc372a42652ef27b5261605b6cc67667fbf | NishKoder/Python-Repo | /Chapter 6/tuple_intro.py | 671 | 4.53125 | 5 | # is same as list but its imutable and use ()
# No(pop , append , insert, remove)
# its faster rather than list
name = (23, 34, "34") # when u not want to change ur data means WeekDays, Months etc
# Tuple Methods
# Count
# index
# len
# slice - [:3]
# More About Tuple
# For Loop in tuple
mixed = (2, 4, 5, 2.3)
for i in mixed:
print(i, end=" ")
# tuple with one element
# num = (1)# Not a tuple need to put comma
num = (1,)
print(type(num))
# tuple without paranthesis
num1 = 2, 3, 5
print(type(num1))
# tuple unpacking
unpack = (3, 4)
a, b = unpack
print(a, end=" ")
print(b)
# final tuple
numss = tuple(range(1, 10))
print(list(numss)) # tuple to list
| true |
c02e4622c1cd6f0de52533ea5cc646fd01d88762 | Eduardo211/EG | /Challenge_Exercises/collatz_sequence.py | 1,525 | 4.5625 | 5 | # The Collatz Conjecture is named after Lothar Collatz, who introduced the idea in 1937, two years
# after receiving his doctorate
# State of the problem
# Considering the following operation on an arbitrary positive integer:
# if the number is even, divide it by two
# if the number is odd, triple it and add one
# Now form a sequence by performing this operation repeatedly, beginning with any positive
# integer, and taking the result at each step as the input at the next
# The Collatz conjecture is: This process will eventually reach the number 1, regardless
# of which positive integer is chosen initially
# Write a program to prompt user to enter a positive integer
# then print out the Collatz sequence for the positive integer
# Prompt user for the input (don't forget to validate the input)
def user_input():
while True:
try:
n = int(input("Please enter a positive integer: "))
if n <= 0:
print("The number must be positive. ")
else:
return n
except ValueError:
print("It's not a valid number. ")
# if we reach here, it means the number is valid
print(n)
def collatz(num):
print(num, end=' ')
while num != 1:
if num % 2 == 0: # an even number
num = num // 2
else:
num = num * 3 + 1
print(num, end=' ')
print()
# What type of loop should we use?
number = user_input()
collatz(number)
# The sequence should start with the number user chose
# and end with 1
| true |
1f5fa3892cc64b57c68d9014a409989a08d1dab6 | Eduardo211/EG | /Final_Projects/tic_tac_toe.py | 871 | 4.40625 | 4 | # Write a program that uses the "turtle" module
# to allow two players to play Tic Tac Toe
# RULES:
# 1. Players alternate turns
# 2. Players can only place a mark on an empty slot
# 3. Players can win only if:
# 1). They have won horizontally, or
# 2). They have won vertically, or
# 3). They have won diagonally
# 4. Players tie if there are no empty slots and on one has won
# Instructions:
# 1. Use the turtle module to draw the game board and
# the game pieces
# 2. Use two different colors to represent the two players
# Topics that will be covered in this project:
# 1. How to use the turtle module to draw a square (3x3)
# 2. How to change the default image of a turtle object
# 3. How to use turtle module to write text on the screen
# 4. How to find the coordinates of the turtle (xcor, ycor)
# This program is worth 100 points
# import turtle | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.