blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
33f5c2d803562730098d3b4393d5843d9d2f9d4a
|
luthraG/ds-algo-war
|
/general-practice/14_09_2019/p18.py
| 1,586
| 4.34375
| 4
|
'''
https://leetcode.com/problems/unique-email-addresses/
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)
If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?
'''
import re
def unique_emails_count(emails):
unique_emails = []
for email in emails:
email_split = email.split('@')
email = re.sub(r'\.', '', email_split[0])
email = email + '@' + email_split[1]
email = re.sub(r'\+(.*?)(?=@)', '', email)
unique_emails.append(email)
return len(set(unique_emails))
emails = str(input('Enter list of emails : ')).split(',')
emails = list(map(str, emails))
print('Total unique emails count is {}'.format(unique_emails_count(emails)))
| true
|
2016817647c32c5e148437225c826b39f2ce8ee4
|
luthraG/ds-algo-war
|
/general-practice/10_09_2019/p3.py
| 2,228
| 4.125
| 4
|
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.start_node = Node()
def add_to_start(self, data):
node = Node(data)
node.next = self.start_node.next
self.start_node.next = node
def add_to_end(self, data):
node = Node(data)
n = self.start_node
while n.next is not None:
n = n.next
n.next = node
def remove_from_begining(self):
node = self.start_node.next
if node is None:
print('List is empty. Nothing to delete')
else:
self.start_node.next = node.next
node = None
def remove_from_end(self):
node = self.start_node
if node.next is None:
print('List is empty. Nothing to delete')
else:
while node.next.next is not None:
node = node.next
node.next = None
def traverse_list(self):
node = self.start_node
while node is not None:
if node.data is not None:
print(node.data)
node = node.next
def count(self):
c = 0
node = self.start_node
while node is not None:
if node.data is not None:
c += 1
node = node.next
return c
if __name__ == '__main__':
linkedList = LinkedList()
number = int(input('Enter number of items to add in list :: '))
for i in range(number):
data = int(input('Enter data :: '))
# If i is even then add to start, else add to end
if i & 1 == 1:
linkedList.add_to_end(data)
else:
linkedList.add_to_start(data)
count = linkedList.count()
print('Total items in the list :: {}'.format(count))
MAX_ALLOWED = 2
diff = count - MAX_ALLOWED
if diff > 0:
print('Going to remove {} items from end'.format(diff))
for i in range(diff):
linkedList.remove_from_end()
print('List items are')
linkedList.traverse_list()
print('Total items in the list :: {}'.format(linkedList.count()))
| true
|
b3aaf2652c1cfda99a9c3b3c8e1d7d47b358abb4
|
luthraG/ds-algo-war
|
/general-practice/18_09_2019/p12.py
| 1,035
| 4.15625
| 4
|
'''
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
'''
def longest_common_prefix(str1, str2):
length1 = len(str1)
length2 = len(str2)
if length1 == 0 or length2 == 0:
return ''
else:
i = 0
while i < length1 and i < length2:
if str1[i] != str2[i]:
break
i += 1
return str1[0:i] if i > 0 else ''
def longest_common_prefix_solution(items):
length = len(items)
common_prefix = items[0] if length > 0 else ''
i = 1
while i < length:
common_prefix = longest_common_prefix(common_prefix, items[i])
i += 1
return common_prefix
| true
|
6d53601a7fc6a0c2fb2e35f5685770bd5e771798
|
stollcode/GameDev
|
/game_dev_oop_ex1.py
| 2,829
| 4.34375
| 4
|
"""
Game_dev_oop_ex1
Attributes: Each class below, has at least one attribute defined. They hold
data for each object created from the class.
The self keyword: The first parameter of each method created in a Python program
must be "self". Self specifies the current instance of the class.
Python Directions: Create a Python module on your Z:\GameDev folder named oop_ex1.py.
Add the following code to the module. Do not forget to test!!!
*** Teacher Class ***
1. Define a class named Teacher containing the following attributes:
a. Attributes:
i. name
ii. gender
iii. date_of_birth
iv. phone_number
b. Set all attributes to default as empty strings (also called null strings).
Write the code below the triple quotes below.
"""
# Your code goes here.
"""
*** Monkey Class ****
2. Define a class named Monkey containing the following attributes:
a. Attributes:
i. age
ii. species
iii. is_rain_forest
b. Set the default age to zero, species to an empty string and is_rain_forest to False.
Write the code below the triple quotes below.
"""
# Your code goes here
"""
*** Fish Class ***
3. Define a class named Fish with the following attributes:
a. Attributes:
i. is_fresh_water
ii. weight
iii. age
iv. gender
b. Set the following defaults for the attributes:
is_fresh_water to False, weight to 0.0, age to 0 and gender to an empty string.
c. Define a breathe() method that returns the following string: The fish breathes
Do not forget to include self as the first parameter of the method.
Example:
def breathe(self):
Write the code below the triple quotes below.
"""
# Your code goes here
"""
*** Enemy Class ***
4. Create a class named Enemy with the following attributes:
a. Attributes:
i. Name = "Goblin"
ii. health = 100
Write the code below the triple quotes below.
"""
# Your code goes here
"""
*** Testing ***
5. For each class:
a. Print a message describing the class being tested (ie. "Testing the Fish Class:")
b. Create an object instance.
c. Set all attribute values. (be creative, unless otherwise specified)
d. Modify the attribute values.
e. Print the attribute values using descriptive headings
f. Call methods for the class where appropriate.
g. Print any values returned by the methods, with descriptive headings.
Write the tests below the triple quotes below.
"""
# Test the Teacher class here
# Test the Monkey class here
# Test the Fish class here (Don't forget to call the breathe() method)
# Test the Enemy class below.
| true
|
0f227ae102e644024608c93a33dac90b39f2dcb9
|
greenblues1190/Python-Algorithm
|
/LeetCode/14. 비트 조작/393-utf-8-validation.py
| 1,893
| 4.15625
| 4
|
# https://leetcode.com/problems/utf-8-validation/
# Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.
# A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
# For a 1-byte character, the first bit is a 0, followed by its Unicode code.
# For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0,
# followed by n - 1 bytes with the most significant 2 bits being 10.
# This is how the UTF-8 encoding would work:
# Char. number range | UTF-8 octet sequence
# (hexadecimal) | (binary)
# --------------------+---------------------------------------------
# 0000 0000-0000 007F | 0xxxxxxx
# 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
# 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
# 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
# Note: The input is an array of integers.
# Only the least significant 8 bits of each integer is used to store the data.
# This means each integer represents only 1 byte of data.
from typing import List
class Solution:
def validUtf8(self, data: List[int]) -> bool:
def check(bytes: int, start: int) -> bool:
for i in range(start + 1, start + bytes):
if i >= len(data) or (data[i] >> 6) != 0b10:
return False
return True
start = bytes = 0
while start < len(data):
code = data[start]
if code >> 3 == 0b11110:
bytes = 4
elif code >> 4 == 0b1110:
bytes = 3
elif code >> 5 == 0b110:
bytes = 2
elif code >> 7 == 0b0:
bytes = 1
else:
return False
if not check(bytes, start):
return False
start += bytes
return True
| true
|
bf67b98e1c8d67e03db25488893518e5fd2e3a36
|
GaiBaDan/GBD-GoodMan
|
/demo1.py
| 599
| 4.5625
| 5
|
#1.注释:代码中不会被编译执行的部分(不会起到任何程序作用,用来备注用的)
#在说明性文字前加#键可以单行注释
'''
'''
"""
A.对程序进行说明备注 B.关闭程序中的某项功能
"""
#建议:写程序多写注释
print("HELLO world") ;print("hello python") #每条语句结束后可以没有分号r如果一行要写多条语句,那么每条语句之间用分号隔开
# print("hello world")
print("hello world")
# print("hello world")
print('dandan')
# print('hahahahahaha')\
list1 = [2,4,6]
num = [3*x for x in list1]
print(num)
| false
|
02bd64d1871d08a5ef5354e4962074dc01363b8e
|
darrenthiores/PythonTutor
|
/Learning Python/level_guessing.py
| 2,170
| 4.125
| 4
|
# membuat app number guessing dengan level berbeda
import random
def low_level() :
number = random.randint(1,10)
chances = 3
while (chances > 0) :
guess = int(input('Your guess : '))
if (guess == number) :
print ('Congratss you win the game!!')
break
elif (guess > number) :
print ('your guess is too high, go with a lower number')
elif (guess < number) :
print ('your guess is too low, go with a bigger number')
if (chances <= 0) :
print ('you lose the game!!')
def med_level() :
number = random.randint(1,25)
chances = 5
while (chances > 0) :
guess = int(input('Your guess : '))
if (guess == number) :
print ('Congratss you win the game!!')
break
elif (guess > number) :
print ('your guess is too high, go with a lower number')
elif (guess < number) :
print ('your guess is too low, go with a bigger number')
if (chances <= 0) :
print ('you lose the game!!')
def high_level() :
number = random.randint(1,50)
chances = 8
while (chances > 0) :
guess = int(input('Your guess : '))
if (guess == number) :
print ('Congratss you win the game!!')
break
elif (guess > number) :
print ('your guess is too high, go with a lower number')
elif (guess < number) :
print ('your guess is too low, go with a bigger number')
if (chances <= 0) :
print ('you lose the game!!')
def pick_level() :
print ('='*10,'Number Guessing Game','='*10)
print ('[1] Low Level (1 - 10, 3 chances)')
print ('[2] Medium Level (1 - 25, 5 chances)')
print ('[3] High Level (1 - 50, 8 chances)')
print ('[4] EXIT')
menu = int(input('Pick level (index) : '))
if (menu == 1) :
low_level()
elif (menu == 2) :
med_level()
elif (menu == 3) :
high_level()
elif (menu == 4) :
exit()
else :
print ('Which level did you picked?')
if __name__ == "__main__":
while (True) :
pick_level()
| true
|
9b39f95066e6bf5919683302f61adc5f40300a60
|
younism1/Checkio
|
/Password.py
| 1,673
| 4.15625
| 4
|
# Develop a password security check module.
# The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least
# one digit, as well as containing one uppercase letter and one lowercase letter in it.
# The password contains only ASCII latin letters or digits.
# Input: A password as a string.
# Output: Is the password safe or not as a boolean or any data type that can be converted and processed as a boolean.
# In the results you will see the converted results.
# checkio('A1213pokl') == False
# checkio('bAse730onE') == True
# checkio('asasasasasasasaas') == False
# checkio('QWERTYqwerty') == False
# checkio('123456123456') == False
# checkio('QwErTy911poqqqq') == True
def checkio(data: str) -> bool:
upper = False
lower = False
digit = False
if not len(data) >= 10:
# print("Your password needs to be 10 characters long or more")
return False
for i in data:
if i.isdigit():
digit = True
if i.isupper():
upper = True
if i.islower():
lower = True
return upper and digit and lower
if __name__ == '__main__':
#self-checking and not necessary for auto-testing
assert checkio('A1213pokl') == False, "1st example"
assert checkio('bAse730onE4') == True, "2nd example"
assert checkio('asasasasasasasaas') == False, "3rd example"
assert checkio('QWERTYqwerty') == False, "4th example"
assert checkio('123456123456') == False, "5th example"
assert checkio('QwErTy911poqqqq') == True, "6th example"
print("Passed all test lines ? Click 'Check' to review your tests and earn cool rewards!")
| true
|
66b8c6815a588d9c9c1bfac47ce0e22d3ebb20f0
|
cytoly/data_structures
|
/implementations/LinkedList.py
| 2,755
| 4.125
| 4
|
from typing import Union
class Node:
def __init__(self, data=None):
self.data = data
self.next: Union[Node, ()] = None
def has_next(self) -> bool:
return self.next is not None
class LinkedList:
def __init__(self):
self.head: Union[Node, ()] = None
self.length = 0
def __len__(self) -> int:
# current_node = self.head
# count = 0
# while current_node is not None:
# count += 1
# current_node = current_node.next
# return count
return self.length
def prepend(self, data) -> ():
new_node = Node(data)
if self.length == 0:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
self.length += 1
def append(self, data) -> ():
current_node = self.head
while current_node.has_next():
current_node = current_node.next
new_node = Node(data)
current_node.next = new_node
self.length += 1
def all(self) -> Union[list, str]:
if self.length == 0:
return "empty"
current_node = self.head
output = []
while current_node:
output.append(current_node.data)
current_node = current_node.next
return output
def pop_start(self):
if self.length == 0:
return print("empty")
self.head = self.head.next
self.length -= 1
def pop(self):
current_node = self.head
if self.length <= 1:
self.pop_start()
return
while current_node.next.has_next():
current_node = current_node.next
current_node.next = None
self.length -= 1
def insret(self, index: int, data) -> ():
if self.length < index or index < 0:
return print("are you dumb?")
if index == 0:
self.prepend(data)
return
if index == self.length:
self.append(data)
return
new_node = Node(data)
count = 0
current = self.head
while count < index-1:
count += 1
current = current.next
new_node.next = current.next
current.next = new_node
self.length += 1
def clear(self):
self.head = None
self.length = 0
class test(LinkedList):
def pop(self): ...
if __name__ == "__main__":
ll = LinkedList()
ll.prepend(69)
ll.append(420)
print(len(ll))
print(ll.all())
ll.pop()
ll.pop_start()
print(ll.all())
ll.insret(0, "hello world")
ll.insret(1, "testing")
ll.insret(2, "nerd")
print(ll.all())
ll.clear()
print(ll.all())
| false
|
522385d08ccd855e401d141f9f4e8ccf1535f926
|
purwokang/learn-python-the-hard-way
|
/ex6.py
| 971
| 4.15625
| 4
|
# creating variable x that contains format character
x = "There are %d types of people." % 10
# creating variable binary
binary = "binary"
# creating variable do_not
do_not = "don't"
# creating variable y, contains format character
y = "Those who know %s and those who %s." % (binary, do_not)
# printing content of variable x
print(x)
# printing content of variable y
print(y)
# printing the content of variable x
print("I said: %r." % x)
# printing the content of variable y
print("I also said: '%s'." % y)
# creating variable with boolean content
hilarious = True
# creating variable, contains format character
joke_evaluation = "Isn't that joke so funny?! %r"
# printing combination of two variables
print(joke_evaluation % hilarious)
# creating variable w with string content
w = "This is the left side of..."
# variable e, the content is string as well
e = "a string with a right side."
# printing both variable w and e, consist of strings
print(w + e)
| true
|
ea1e981b9a899e15fddce5b28d20ea97c05b5ccd
|
lovingstudy/Molecule-process
|
/point2Plane.py
| 1,296
| 4.15625
| 4
|
#---------------------------------------------------------------------------------------------------
# Name: point2Plane.py
# Author: Yolanda
# Instruction: To calculate the distance of a point to a plane, which is defined by 3 other points,
# user should input the coordinates of 3 points in the plane into (x1,y1,z1)(x2,y2,z2)(x3,y3,z3),
# also input the coordinates of the point out of the plane into (x0,y0,z0). This program will
# print the distance.
# Application: Measure the distance of a atom to a benzene ring.
#---------------------------------------------------------------------------------------------------
import numpy as np
from scipy import linalg
# 3 points to define a plane. For example, 3 atoms in a benzene ring.
x1, y1, z1 = 0.421, 9.340, 10.017
x2, y2, z2 = -0.042, 8.673, 8.866
x3, y3, z3 = 0.785, 8.316, 7.853
# Train the equation of the plane. Equation: Ax + By + Cz + 1 = 0
A = np.array([[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]])
b = np.array([[-1],[-1],[-1]])
pr = list(linalg.inv(A).dot(b).flat) + [1] # pr == [A, B, C, 1]
# The point out of the plane.
x0, y0, z0 = 2.691, 11.980, 9.187
# Calculte the distance of the point to the plane.
d = np.abs(sum([p*x for p,x in zip(pr, [x0,y0,z0,1])])) / np.sqrt(sum([a**2 for a in pr[:3]]))
print "Distance: ", d
| true
|
8f06c97a2061ed6cdd62c6230d8bf5857210ea84
|
liu-yuxin98/Python
|
/chapter7/shape.py
| 1,033
| 4.125
| 4
|
#-*- coding=utf-8-*-
import math
class Circle:
def __init__(self,radius=1):
self.radius=radius
def getPerimeter(self):
return self.radius*2*math.pi
def getArea(self):
return self.radius*self.radius*math.pi
def setRadius(self,radius):
self.radius=radius
class Rectangular:
def __init__(self,length=2,width=1):
self.width=width
self.length=length
def setLength(self, length):
self.length=length
def setWidth(self, width):
self.width=width
def getArea(self):
return self.width*self.length
def getPerimeter(self):
return 2*(self.width+self.length)
class Coordinate:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def setVaule(self,x,y):
self.x=x
self.y=y
def getX(self):
return self.x
def getY(self):
return self.y
'''
c1=Circle()# c1.radius=1
print(c1.radius)
r1=Rectangular(5,3)
print(r1.getArea())
p1=Coordinate(5,6)
print(p1.x)
print(p1.getX())
'''
| false
|
3c1219e7c7c57db39fc61e7551c9e3e8808fadb7
|
league-python-student/level1-module2-ezgi-b
|
/_01_writing_classes/_b_intro_to_writing_classes.py
| 2,725
| 4.3125
| 4
|
"""
Introduction to writing classes
"""
import unittest
# TODO Create a class called student with the member variables and
# methods used in the test class below to make all the tests pass
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
self.homework_done = False
def do_homework(self):
self.homework_done = True
def go_to_school(self, start = "7 am"):
return self.name + " is leaving for school at " + start
# ================== DO NOT MODIFY THE CODE BELOW ============================
class WriteClassesTests(unittest.TestCase):
student_1 = Student(name='Zeeshan', grade=7)
student_2 = Student(name='Amelia', grade=8)
student_3 = Student(name='Penelope', grade=9)
def test_student_objects_created(self):
self.assertIsNotNone(WriteClassesTests.student_1, msg='student 1 not created!')
self.assertIsNotNone(WriteClassesTests.student_2, msg='student 2 not created!')
self.assertIsNotNone(WriteClassesTests.student_3, msg='student 3 not created!')
def test_names(self):
self.assertTrue(WriteClassesTests.student_1.name == 'Zeeshan')
self.assertTrue(WriteClassesTests.student_2.name == 'Amelia')
self.assertTrue(WriteClassesTests.student_3.name == 'Penelope')
def test_grades(self):
self.assertTrue(WriteClassesTests.student_1.grade == 7)
self.assertTrue(WriteClassesTests.student_2.grade == 8)
self.assertTrue(WriteClassesTests.student_3.grade == 9)
def test_student_methods(self):
self.assertEquals(False, WriteClassesTests.student_1.homework_done)
self.assertEquals(False, WriteClassesTests.student_2.homework_done)
self.assertEquals(False, WriteClassesTests.student_3.homework_done)
WriteClassesTests.student_1.do_homework()
WriteClassesTests.student_2.do_homework()
WriteClassesTests.student_3.do_homework()
self.assertEquals(True, WriteClassesTests.student_1.homework_done)
self.assertEquals(True, WriteClassesTests.student_2.homework_done)
self.assertEquals(True, WriteClassesTests.student_3.homework_done)
def test_going_to_school(self):
leave_str = WriteClassesTests.student_1.go_to_school(start='6 am')
self.assertEqual('Zeeshan is leaving for school at 6 am', leave_str)
leave_str = WriteClassesTests.student_2.go_to_school(start='6:30 am')
self.assertEqual('Amelia is leaving for school at 6:30 am', leave_str)
leave_str = WriteClassesTests.student_3.go_to_school()
self.assertEqual('Penelope is leaving for school at 7 am', leave_str)
if __name__ == '__main__':
unittest.main()
| true
|
10b98f23aed7717f9648ea95aa78e7ab2790cb52
|
0t3b2017/CursoemVideo1
|
/aula06b.py
| 477
| 4.3125
| 4
|
"""
Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
"""
x=input("Digite algo: ")
print("O tipo do valor é {}".format(type(x)))
print("O valor digitado é decimal? ",x.isdecimal())
print("O valor digitado é alfanum? ",x.isalnum())
print("O valor digitado é alfa? ",x.isalpha())
print("O valor digitado é printable? ",x.isprintable())
print("O valor digitado é maiuculo? ",x.isupper())
| false
|
4bfba7c91923794a62b17e796ea043d8f8afa543
|
0t3b2017/CursoemVideo1
|
/desafio #037.py
| 2,039
| 4.125
| 4
|
"""
desafio #037
Escreva um programa que leia um número inteiro (em decimal) e peça para o usuário escolher qual será a base de conversão:
1 para binário
2 para octal
3 para hexadecimal
"""
"""
num = int(input("Digite um número: "))
opc = int(input(\"""Selecione uma das base de conversão desejada:
1 => binário
2 => octal
3 => hexadecimal
digite: \"""))
if opc == 1:
base = 2
rest = []
divisor = num
while divisor >= 1:
rest.append(divisor % base)
divisor = divisor // base
rest.reverse()
print("\nO valor {} em binário é ".format(num), *rest, sep='')
elif opc == 2:
base = 8
rest = []
divisor = num
while divisor >= 1:
rest.append(divisor % base)
divisor = divisor // base
rest.reverse()
print("\nO valor {} em binário é ".format(num), *rest, sep='')
elif opc == 3:
base = 16
rest = []
divisor = num
while divisor >= 1:
rest.append(divisor % base)
divisor = divisor // base
rest.reverse()
print("\nO valor {} em binário é ".format(num), *rest, sep='')
else:
print("\n\033[31mOpção inválida\033[m")
"""
## Guanabara
num = int(input("Digite um número inteiro: "))
while True:
print('''Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL''')
opcao = int(input('\nSua opção: '))
print('')
if opcao == 1:
print('{} convertido para binário é igual a \033[34m{}\033[m'.format(num, bin(num)[2:]))
break
elif opcao == 2:
print('{} convertido para octal é igual a \033[34m{}\033[m'.format(num, oct(num)[2:]))
break
elif opcao == 3:
print('{} convertido para hexadecimal é igual a \033[34m{}\033[m'.format(num, hex(num)[2:]))
break
else:
print('\033[31mOpção inválida. Favor selecionar uma das opções disponíveis.\033[m\n')
| false
|
1866eaa566cf7da42fad880204300044ed994fa4
|
0t3b2017/CursoemVideo1
|
/desafio #022.py
| 1,004
| 4.375
| 4
|
"""
Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas
- O nome com todas as letras minusculas
- Quantas letras ao todo (sem considerar espaços)
- Quantas letras tem o primeiro nome.
"""
name = str(input("Type your name: ")).strip()
print("Seu nome em letras maiúsculas é {}.".format(name.upper()))
print("Seu nome em letras minúsculas é {}.".format(name.lower()))
# print(name.strip())
# print(name.capitalize())
# print(name.title())
# Minha ideia
print("Seu nome ao todo tem {} letras.".format(len(''.join(name.split()))))
# Guanabara ideia
print("Seu nome ao todo tem {} letras.".format(len(name) - name.count(' ')))
# Minha ideia # Split the name in a list and then verify the lenght of the first name.
print("Seu primeiro nome tem {} letras.".format(len(name.split()[0])))
# Guanabara ideia # Find de first space position. As the index starts with 0, the count matches.
print("Seu primeiro nome tem {} letras.".format(name.find(' ')))
| false
|
e897af19e5fdf1f6ab3568b14ae124c5971a2a57
|
Prabhjyot2/workshop-python
|
/L2/P2.py
| 235
| 4.40625
| 4
|
#wapp to read radius of circle & find the area & circumference
r = float(input("Enter the radius "))
pi = 3.14
area = pi * r** 2
print("area=%.2f" %area)
cir = 2 * pi * r
print("cir=%.4f" %cir)
print("area=", area, "cir=", cir )
| true
|
44f9c71e161a2fddd66975520ca4b0444be0fefa
|
alexcarlos06/CEV_Python
|
/Mundo 2/Desafio 069.py
| 2,095
| 4.15625
| 4
|
'''Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou nao continuar. No final, mostre:
a) Quantas pessoas tem mais de 18 anos. b) Qantos homens foram cadastrados. c)Quantas mulheres tem mais de 20 anos .'''
print('\n{:^100}\n'.format(' \033[1;4mCadastro de Pessoas \033[m'))
c = ''
maior = homens = mulheres = 0
while c != 'N':
print('{}\n'.format('-' * 100))
s = str(input('Informe o sexo [M / F]: ')).upper().strip()[0]
while s not in 'F,M':
s = str(input('Informe "M" para Masculino e "F" para Feminino: ')).upper().strip()[0]
i = int(input('Informe a idade: '))
while i not in range(1, 1000):
i = int(input('Informe a idade entre 1 e 999: '))
if i > 18:
maior += 1
if s == 'M':
homens +=1
if s == 'F' and i > 20:
mulheres += 1
c = str(input('Deseja cadastrar mais [S / N]: ')).upper().strip()[0]
while c not in 'S,N':
c = str(input('Deseja cadastrar mais [S / N]: ')).upper().strip()[0]
if c == 'N':
print('~' * 100, '\033[1;32m')
break
if maior == 0:
print('\nNão foi Cadastrado nenhuma pessoa com idade superior a 18 anos.')
elif maior == 1:
print('\nFoi cadastrada uma pessoa com idade superior a 18 anos.')
else:
print(f'\nforam cadastradas {maior} pesoas com idade superior a 18 anos.')
if homens == 0:
print('Não foi cadastrado nenhuma pessoa do sexo masculino.')
elif homens == 1:
print('Foi cadastro uma pessoa do sexo masculo.')
else:
print(f'Foram cadastradas {homens} pessoas do sexo masculino.')
if mulheres == 0:
print('Não foi cadastrada nenhuma pessoa do sexo femino com idade superior a 20 anos.')
elif mulheres == 1:
print('Foi cadastrada uma pessoa do sexo feminino com idade superior a 20.')
else:
print(f'Foram cadastradas {mulheres} pessoas com sexo feminino e idade superior a 20 anos.')
print('\n\n\n\033[m{:=^110}'.format(' \033[1;4mObrigado por utilizar o sistema de cadastro ACSistemas\033[m '))
# Desafio Concluído.
| false
|
337341d300ebe5397368e6ca19dcf2ae8c895d3e
|
alexcarlos06/CEV_Python
|
/Mundo 2/Desafio 071.py
| 2,201
| 4.15625
| 4
|
'''Crie um programa que simule o funcionamento de um caixa eletônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro)
e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: Considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1'''
print('\n{}{:^^100}{}\n'.format('\033[1;4;34m', '\033[1;31m Caixa Eletrônico ACSistemas \033[1;4;34m', '\033[m'))
import os
saque = int(input('Informe o valor do saque: '))
print('')
c = 100
valor = saque
cont = 0
while True:
if valor >= c:
while valor >= c:
valor -= c
cont += 1
total = cont * c
print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f} \n')
if valor >= 50:
c = 50
cont = 0
while valor >= c:
valor -= c
cont += 1
total = cont * c
print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f} \n')
elif valor >= 20:
c = 20
cont = 0
while valor >= c:
valor -= c
cont += 1
total = cont * c
print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f}\n')
elif valor >= 10:
c = 10
cont = 0
while valor >= c:
valor -= c
cont += 1
total = cont * c
print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f}\n')
elif valor >= 1:
c = 1
cont = 0
while valor >= c:
valor -= c
cont += 1
total = cont * c
print(f'Serão {cont} notas de R${c:.2f} ==> O total das notas de {c} será R${total: .2f}\n')
else:
print('-' * 85)
print('')
if saque == 0:
break
else:
saque = int(input('Informe um novo valor do saque ou 0 para sair: '))
print('')
c = 100
valor = saque
cont = 0
print('\033[1;33m{:~^100}'.format(' \033[1;4;34mObrigado por utilizar o nosso sistema de Caixa eletrônico\033[1;33m '))
# Desafio Concluído
| false
|
7adc48dd7da8cea5d02cbdc83ea6524f924fc037
|
alexcarlos06/CEV_Python
|
/Mundo 1/desafio 008.py
| 341
| 4.21875
| 4
|
#Escreva um programa que leia um valor em metros e o exiba convertido em centimentros e milimetros
m=int(input('Informe a quantidade de metros que desja converter: '))
mm=int(1000)
cm=int(100)
mmconverte=m*mm
cmconverte=m*cm
print(' Em {} metros existem {} centimetros e {} milimetros.'.format(m, cmconverte, mmconverte))
#Desafio concluído
| false
|
532793eb6901f35e2184ab5b510aea233c5a484b
|
Sher-Chowdhury/CentOS7-Python
|
/files/python_by_examples/loops/iterations/p02_generator.py
| 845
| 4.34375
| 4
|
# functions can return multiple values by using the:
# return var1,var2....etc
# syntax.
# you can also do a similar thing using the 'yield' keyword.
fruits = ['apple', 'oranges', 'banana', 'plum']
fruits_iterator = iter(fruits)
# we now use the 'next' builtin function
# https://docs.python.org/3.3/library/functions.html
# a genarotor is simply a functions that contains one or more 'yield' lines.
def fruits():
print("about to print apple")
yield 'apple'
print("about to print oranges")
yield 'oranges'
print("about to print banana")
yield 'banana'
print("about to print plum")
yield 'plum'
fruit = fruits()
print(type(fruit))
print(next(fruit))
print(next(fruit))
print(next(fruit))
print(next(fruit))
# the yield command effectively pauses the function until the next 'next' command is executed.
| true
|
8ee8bfee53f3b666a3cddd35bb85ddae2c52e6b8
|
tntterri615/Pdx-Code-Guild
|
/Python/lab10unitconverter.py
| 587
| 4.125
| 4
|
'''
convert feet to meters
'''
x = int(input('What distance do you want to convert?'))
y = input('What are the input units?')
z = input('What are the output units?')
if y == 'ft':
output = x * 0.3048
elif y == 'km':
output = x * 1000
elif y == 'mi':
output = x * 1609.34
elif y == 'yd':
output = x * 0.9144
elif y == 'in':
output = x * 0.0254
if z == 'ft':
output /= 0.3048
elif z == 'km':
output /= 1000
elif z == 'mi':
output /= 1609.34
elif z == 'yd':
output /= 0.9144
elif z == 'in':
output /= 0.0254
print(f'{x} {y} is {output} {z}')
| false
|
f1497ee3c556984b0c9034b07687c2353046edb5
|
tntterri615/Pdx-Code-Guild
|
/Python/lab31atm.py
| 1,398
| 4.125
| 4
|
'''
atm lab
'''
class Atm:
transaction_list = []
def __init__(self, balance = 0, interest_rate = 0.1):
self.balance = balance
self.interest_rate = interest_rate
def check_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
self.transaction_list.append(f'You deposited ${amount}')
return self.balance
def check_withdrawl(self, amount):
return (self.balance - amount) > 0
def withdraw(self, amount):
self.balance -= amount
self.transaction_list.append(f'You withdrew ${amount}')
return self.balance
def calc_interest(self, interest):
self.balance *= interest
return self.balance
def print_transactions(self):
for i in self.transaction_list:
print(i)
account = Atm(0, 0)
while True:
command = input('What would you like to do (deposit, withdraw, check balance, history)? ').strip()
if command == 'deposit':
deposit_amount = input('Enter amount to deposit: ')
account.deposit(int(deposit_amount))
elif command == 'withdraw':
withdraw_amount = input('Enter amount to withdraw: ')
account.withdraw(int(withdraw_amount))
elif command == 'check balance':
print(account.check_balance())
elif command == 'history':
account.print_transactions()
| false
|
9cae7dd953a102a146fe23105b85c64746c2f834
|
YEJINLONGxy/shiyanlou-code
|
/matrixmul.py
| 1,735
| 4.25
| 4
|
#!/usr/bin/env python3
#这个例子里我们计算两个矩阵的 Hadamard 乘积。
#要求输入矩阵的行/列数(在这里假设我们使用的是 n × n 的矩阵)。
n = int(input("Enter the value of n: "))
print("Enter value for the Matrix A")
a = []
for i in range(n):
a.append([int(x) for x in input().split()])
#print(a)
print("Enter value for the Matrix B")
b = []
for i in range(n):
b.append([int(x) for x in input().split()])
#print(b)
c = []
for i in range(n):
c.append([a[i][j] * b[i][j] for j in range(n)])
#print(c)
print("after matrix multiplication")
print("-" * 7 * n)
for x in c:
for y in x:
print(str(y).rjust(5), end=" ")
print()
print("-" * 7 * n)
#+++++++++++++++++++++++++++++++++++++++++++++++++++
#运行如下
#[root@dev1 python_code]# ./matrixmul.py
#Enter the value of n: 4
#Enter value for the Matrix A
#1 2 3 4
#5 6 7 8
#9 10 11 12
#13 14 15 16
#[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
#Enter value for the Matrix B
#16 15 14 13
#12 11 10 9
#8 7 6 5
#4 3 2 1
#[[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]]
#[[16, 30, 42, 52], [60, 66, 70, 72], [72, 70, 66, 60], [52, 42, 30, 16]]
#after matrix multiplication
#----------------------------
# 16 30 42 52
# 60 66 70 72
# 72 70 66 60
# 52 42 30 16
#----------------------------
#这里我们使用了几次列表推导式:
#[int(x) for x in input().split()] 首先通过 input() 获得用户输入的字符串
#再使用 split() 分割字符串得到一系列的数字字符串,然后用 int() 从每个数字字符串创建对应的整数值
#我们也使用了 [a[i][j] * b[i][j] for j in range(n)] 来得到矩阵乘积的每一行数据
| false
|
f6cf5dd18f276acb2e83a3f7b2fb701a3b4528f3
|
YEJINLONGxy/shiyanlou-code
|
/palindrome_check.py
| 668
| 4.25
| 4
|
#!/usr/bin/env python3
#回文检查
#回文是一种无论从左还是从右读都一样的字符序列。比如 “madam”
#在这个例子中,我们检查用户输入的字符串是否是回文,并输出结果
s = input("Please enter a string: ")
z = s[::-1] #把输入的字符串 s 进行倒叙处理形成新的字符串 z
if s == z:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
#运行程序
#[root@dev1 python_code]# ./palindrome_check.py
#Please enter a string: madam1
#The string is not a palindrome
#[root@dev1 python_code]# ./palindrome_check.py
#Please enter a string: madam
#The string is a palindrome
| false
|
f9886344b8c61878d322680525f4f4afe8220042
|
abbi163/MachineLearning_Classification
|
/KNN Algorithms/CustomerCategory/teleCust_plots.py
| 873
| 4.125
| 4
|
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('E:\Pythoncode\Coursera\Classification_Algorithms\KNN Algorithms\CustomerCategory/teleCust1000t.csv')
# print(df.head())
# value_counts() function is used to count different value separately in column custcat
# eg.
# 3 281
# 1 266
# 4 236
# 2 217
# count() function counts the number of value in column custcat, or sum of all value_counts(), here 1000
print(df['custcat'].value_counts())
# if sample is from 1 is to 100 , then bin size of 50 implies 50 range of histgram, from [0,2) to [98,100], Last bin include 100
# basically bins are number of class size.
df.hist(column = 'income', bins = 50)
plt.show()
print(df.count())
plt.scatter(df.custcat, df.income, color = 'blue')
plt.xlabel('custcat')
plt.ylabel('income')
plt.show()
| true
|
491ffe454bdd5161ea332eb5114561b1a56b8e36
|
sacheenanand/pythondatastructures
|
/ReverseLinkedList.py
| 557
| 4.1875
| 4
|
__author__ = 'sanand'
# To implement reverse Linked we need 3 nodes(curr, prev and next) we are changing only the pointers here.
class node:
def __init__(self, value, nextNode=None):
self.value = value
self.nextNode = nextNode
class LinkedList:
def __init__(self, head):
self.head = head
def reverse(self):
current = head
prev = None
while True:
next = current.nextNode
current.nextNode = prev
prev = current
current = next
return prev
| true
|
04dce36f9f552216ea548da767dbf306fc2de8e9
|
mrvbrn/HB_challenges
|
/medium/code.py
| 1,162
| 4.1875
| 4
|
"""TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work.
You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
"""
class Codec:
def __init__(self):
self.url_to_code={}
self.code_to_url={}
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
letters = string.ascii_letters+string.digits
while longUrl not in self.url_to_code:
code = "".join([random.choice(letters) for _ in range(6)])
if code not in self.code_to_url:
self.url_to_code[longUrl]=code
self.code_to_url[code]=longUrl
return self.url_to_code[longUrl]
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.code_to_url[shortUrl[-6:]]
| true
|
289820dd78f4cf13538bde92149ae03d3e93784c
|
mrvbrn/HB_challenges
|
/hard/patternmatch.py
| 2,712
| 4.59375
| 5
|
"""Check if pattern matches.
Given a "pattern string" starting with "a" and including only "a" and "b"
characters, check to see if a provided string matches that pattern.
For example, the pattern "aaba" matches the string "foofoogofoo" but not
"foofoofoodog".
Patterns can only contain a and b and must start with a:
>>> pattern_match("b", "foo")
Traceback (most recent call last):
...
AssertionError: invalid pattern
>>> pattern_match("A", "foo")
Traceback (most recent call last):
...
AssertionError: invalid pattern
>>> pattern_match("abc", "foo")
Traceback (most recent call last):
...
AssertionError: invalid pattern
The pattern can contain only a's:
>>> pattern_match("a", "foo")
True
>>> pattern_match("aa", "foofoo")
True
>>> pattern_match("aa", "foobar")
False
It's possible for a to be zero-length (a='', b='hi'):
>>> pattern_match("abbab", "hihihi")
True
Or b to be zero-length (a='foo', b=''):
>>> pattern_match("aaba", "foofoofoo")
True
Or even for a and b both to be zero-length (a='', b=''):
>>> pattern_match("abab", "")
True
But, more typically, both are non-zero length:
>>> pattern_match("aa", "foodog")
False
>>> pattern_match("aaba" ,"foofoobarfoo")
True
>>> pattern_match("ababab", "foobarfoobarfoobar")
True
Tricky: (a='foo', b='foobar'):
>>> pattern_match("aba" ,"foofoobarfoo")
True
"""
def pattern_match(pattern, astring):
"""Can we make this pattern match this string?"""
# Q&D sanity check on pattern
assert (pattern.replace("a", "").replace("b", "") == ""
and pattern.startswith("a")), "invalid pattern"
count_a = pattern.count("a")
count_b = pattern.count("b")
first_b = pattern.find("b")
for a_length in range(0, len(astring) // count_a + 1):
if count_b:
b_length = (len(astring) - (a_length*count_a)) / float(count_b)
else:
b_length = 0
if int(b_length) != b_length or b_length < 0:
continue
b_start = a_length * first_b
if matches(pattern=pattern,
a=astring[0:a_length],
b=astring[b_start:b_start+int(b_length)],
astring=astring):
return True
return False
def matches(pattern, a, b, astring):
test_string = ""
for p in pattern:
if p == "a":
test_string += a
else:
test_string += b
return test_string == astring
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. WE'RE WELL-MATCHED!\n")
| true
|
560459ddf49384a758c3bcfde15517ba99e44077
|
shaikharshiya/python_demo
|
/fizzbuzzD3.py
| 278
| 4.15625
| 4
|
number=int(input("Enter number"))
for fizzbuzz in range(1,number+1):
if fizzbuzz % 3==0 and fizzbuzz%5==0:
print("Fizz-Buzz")
elif fizzbuzz % 3==0:
print("Fizz")
elif fizzbuzz % 5==0:
print("Buzz")
else:
print(fizzbuzz)
| true
|
814d9846600316450e097ef7ce0cb8f40d45efd1
|
2371406255/PythonLearn
|
/24_访问限制.py
| 1,728
| 4.125
| 4
|
#!/usr/bin/env python3
#coding:utf-8
#如果要让内部属性不被外部访问,可以在属性名称前加上两个下划线,这样就变成了私有变量,只能内部访问
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s : %s' % (self.__name, self.__score))
stu = Student('BOBO', 90)
stu.print_score()#BOBO : 90
#此时,已经无法使用stu.__name去访问变量
# print(stu.__name)会报错
#如果外部需要获取name,score,则需要增加get_name和get_score方法
#如果需要外部修改name,score,则需要增加set_name和set_score方法
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_name(self, name):
self.__name = name
def set_score(self, score):
self.__score = score
stu = Student('Angle', 99)
print(stu.get_name())#Angle
print(stu.get_score())#99
stu.set_name('Baby')
stu.set_score(98)
print(stu.get_name())#Baby
print(stu.get_score())#98
#特殊变量是__xx__,特殊变量可以直接访问,不是私有的,所以不能这样命名
#有的私有变量是_name,此时,我们应该按照规定,视为私有变量,不要使用
#__name私有变量实际上是,解释器把__name改成_Student_name,所以可以通过_Student_name来访问
#注意的地方:
stu.__name = 'New Name'
print(stu.__name)#New Name 此时是动态添加__name变量,而不是设置了__name变量
print(stu.get_name())#Baby 本身的私有变量还是没有被改变的
| false
|
c21f73253780164661997fa29d873dec5a4803ce
|
A7xSV/Algorithms-and-DS
|
/Codes/Py Docs/Zip.py
| 424
| 4.4375
| 4
|
""" zip()
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
The returned list is truncated in length to the length of the shortest argument sequence. """
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
print x
print y
zipped = zip(x, y)
print zipped
# Unzip
x2, y2 = zip(*zipped)
print x2
print y2
print (x == list(x2)) and (y == list(y2))
| true
|
3edc817a68cc1bbf028c1594a2b9b9c78bb4a879
|
BruceHi/leetcode
|
/month1/MaxQueue.py
| 1,378
| 4.1875
| 4
|
# 剑指 offer 59-2:队列的最大值
from collections import deque
# class MaxQueue:
#
# def __init__(self):
# self.queue = deque()
#
# def max_value(self) -> int:
# if not self.queue:
# return -1
# return max(self.queue)
#
# def push_back(self, value: int) -> None:
# self.queue.append(value)
#
# def pop_front(self) -> int:
# if not self.queue:
# return -1
# return self.queue.popleft()
class MaxQueue:
# 辅助队列,从左到右,非递增数列
def __init__(self):
self.queue = deque()
self.min_queue = deque()
def max_value(self) -> int:
if not self.queue:
return -1
return self.min_queue[0]
def push_back(self, value: int) -> None:
self.queue.append(value)
while self.min_queue and value > self.min_queue[-1]:
self.min_queue.pop()
self.min_queue.append(value)
def pop_front(self) -> int:
if not self.queue:
return -1
val = self.queue.popleft()
if val == self.min_queue[0]:
self.min_queue.popleft()
return val
queue = MaxQueue()
queue.push_back(1)
queue.push_back(2)
print(queue.max_value())
print(queue.pop_front())
print(queue.max_value())
queue = MaxQueue()
print(queue.pop_front())
print(queue.max_value())
| false
|
44471df9935c1a87147214d0650e534373ed391d
|
arun-me/copy
|
/100DaysOfPython/test_bmi.py
| 424
| 4.375
| 4
|
#bmi calculator
height = float(input('enter your height (cms)\n'))
weight = float( input('enter your weight (kg)\n'))
bmi = round(weight/(height/100)**2,2)
if bmi < 18.5:
bmi_type="Under Weight"
elif bmi < 25 :
bmi_type="Normal"
elif bmi < 30 :
bmi_type="Over Weight"
elif bmi< 35 :
bmi_type="Obesity"
else:
bmi_type="Clinical Obesity"
print(f'yout bmi is {bmi}, which is {bmi_type}')
| false
|
a194787f8f7e817bf3b7166bcb3b9bce96e024ef
|
ataylor1184/cse231
|
/Proj01/Project01.py
| 1,221
| 4.46875
| 4
|
#######################################################
# Computer Project #1
#
# Unit Converter
# prompt for distance in rods
# converts rods to different units as floats
# Outputs the distance in multiple units
# calculates time spent walking that distance
########################################################
Rods = input("Input rods: ")
Rods = float(Rods)
print("You input " + str(Rods) + " rods.")
print("Conversions")
Furlongs = round(float(Rods / 40) ,3) # Converts Rods to Furlongs
Meters = round(float(Rods * 5.0292) , 3) # Converts Rods to Meters
Feet = round(float(Meters / .3048) ,3) # Converts Meters to Feet
Miles = round(float(Meters / 1609.34) , 3) # Converts Meters to Miles
SpeedInRods = float(3.1 *320)/60 # Converts MpH to Rods per minute
Time = round(float(Rods / SpeedInRods) ,3) # Divides distance by speed
print("Meters: " + str(Meters))
print("Feet: " + str(Feet))
print("Miles: " + str(Miles))
print("Furlongs: " + str(Furlongs))
print("Minutes to walk " + str(Rods) + " rods: " + str(Time))
#print("Minutes to walk " + str(Rods) + " Rods:" + )
| true
|
793b5d06a3a64bcc3eeefca9fee2e4785ab7295c
|
Damianpon/damianpondel96-gmail.com
|
/zjazd I/zadania domowe/zad_domowe_1.py
| 1,458
| 4.15625
| 4
|
print("Gdzie znajduje się gracz na planszy?")
position_of_X = int(input("Podaj pozycję gracza X: "))
position_of_Y = int(input("Podaj pozycję gracza Y: "))
if position_of_X <= 0 or position_of_Y <= 0:
print("Gracz znajduje się poza planszą")
elif position_of_X <= 40:
if position_of_Y <= 40:
print("Gracz znajduje się w lewym dolnym rogu")
elif position_of_Y > 40 and position_of_Y < 60:
print("Gracz znajduje się w lewym centralnym rogu")
elif position_of_Y >= 60 and position_of_Y <= 100:
print("Gracz znajduje się w lewym górnym rogu")
elif position_of_X > 40 and position_of_X < 60:
if position_of_Y <= 40:
print("Gracz znajduje się w środkowej części na dole planszy")
elif position_of_Y > 40 and position_of_Y < 60:
print("Gracz znajduje się w środkowej części na środku planszy")
elif position_of_Y >= 60 and position_of_Y <= 100:
print("Gracz znajduje się w środkowej części na górze planszy")
elif position_of_X >= 60 and position_of_X <= 100:
if position_of_Y <= 40:
print("Gracz znajduje się w prawej dolnej części planszy")
elif position_of_Y > 40 and position_of_Y < 60:
print("Gracz znajduje się w prawej środkowej części planszy")
elif position_of_Y >= 60 and position_of_Y <= 100:
print("Gracz znajduje się w prawej górnej części planszy")
else:
print("Gracz znajduje się poza planszą")
| false
|
7f3dc6666df5dbc8b2144dd22a4c175a299aa599
|
Princess-Katen/hello-Python
|
/13:10:2020_Rock_Paper_Scissors + Loop _v.4.py
| 1,696
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 13:18:18 2020
@author: tatyanamironova
"""
from random import randint
player_wins = 0
computer_wins = 0
winning_score = 3
while player_wins < winning_score and computer_wins < winning_score:
print (f'Player score: {player_wins} Computer score: {computer_wins}')
print('Rock...')
print('Paper...')
print('Scissors...')
player = input('(Player, make your move): ').lower()
if player == 'quit' or player == 'q':
break
rand_num = randint(0,2)
if rand_num == 0:
computer = 'rock'
elif rand_num == 1:
computer = 'paper'
else:
computer = 'scissors'
print(f'computer plays {computer}')
if player == computer:
print('Its a tie!')
elif player == 'rock':
if computer == 'scissors':
print('Player wins')
player_wins += 1
elif computer == 'paper':
print('computer wins')
computer_wins += 1
elif player == 'paper':
if computer == 'scissors':
print('computer wins')
computer_wins += 1
elif computer == 'rock':
print('Player wins')
player_wins += 1
elif player == 'scissors':
if computer == 'paper':
print('Player wins')
player_wins += 1
elif computer == 'rock':
print('computer wins')
computer_wins += 1
else:
print('something went wrong')
if player_wins > computer_wins:
print('Congrats,you won!')
elif player_wins == computer_wins:
print('Its a tie')
else:
print('Unfortunately, the computer won')
| true
|
556c8b35139d8948b0c218579785dd640b57acde
|
prateek-chawla/DailyCodingProblem
|
/Solutions/Problem_120.py
| 1,456
| 4.1875
| 4
|
'''
Question -->
This problem was asked by Microsoft.
Implement the singleton pattern with a twist. First, instead of storing one instance,
store two instances. And in every even call of getInstance(), return the
first instance and in every odd call of getInstance(), return the second instance.
Approach -->
Create two instances and a flag to keep track of calls to getInstance()
Raise Exception on invalid instantiation
'''
class Singleton:
first_instance = None
second_instance = None
evenFlag = False
def __init__(self):
if Singleton.first_instance is not None and Singleton.second_instance is not None:
raise Exception(" This is a Singleton Class ")
else:
if Singleton.first_instance is None:
Singleton.first_instance = self
else:
Singleton.second_instance = self
@staticmethod
def getInstance():
if Singleton.first_instance is None or Singleton.second_instance is None:
Singleton()
else:
if Singleton.evenFlag:
Singleton.evenFlag = not Singleton.evenFlag
return Singleton.first_instance
else:
Singleton.evenFlag = not Singleton.evenFlag
return Singleton.second_instance
obj1 = Singleton.getInstance()
obj2 = Singleton.getInstance()
obj3 = Singleton.getInstance()
print(obj3)
obj4 = Singleton.getInstance()
print(obj4)
| true
|
94f45d00da655948c4efacef3f1918ee06fadc36
|
evmaksimenko/python_algorithms
|
/lesson1/ex9.py
| 480
| 4.4375
| 4
|
# Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
c = int(input("Введите третье число: "))
r = a
if a < b < c or c < b < a:
r = b
if a < c < b or b < c < a:
r = c
print("Среднее число %d" % r)
| false
|
40c7b3a00d05e1618a7a9bc16543e28d8ca048d0
|
evmaksimenko/python_algorithms
|
/lesson1/ex7.py
| 1,096
| 4.40625
| 4
|
# По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить,
# является ли он разносторонним, равнобедренным или равносторонним.
a = int(input("Введите первую сторону: "))
b = int(input("Введите вторую сторону: "))
c = int(input("Введите третью сторону: "))
if a < b + c and b < a + c and c < a + b:
if a == b == c:
print("Треугольник равносторонний")
elif a == b or a == c or b == c:
print("Треугольник равнобедренный")
else:
print("Треугольник разносторонний")
else:
print("Треульгольник с такими сторонами не может существовать")
| false
|
8e5c8f5ee8b8540d1c9d91dee38b44d67da57580
|
franky-codes/Py4E
|
/Ex6.1.py
| 433
| 4.375
| 4
|
#Example - use while loop to itterate thru string & print each character
fruit = 'BANANA'
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
#Exercise - use while loop to itterate thru string backwards
fruit = 'BANANA'
index = -1 # because len(fruit) - 1 is the last index in the string_x
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index - 1
| true
|
8e447141bae311f753957bbb453083c485694a0d
|
JoaoPauloPereirax/Python-Study
|
/Mundo2/WHILE/while003.py
| 1,146
| 4.25
| 4
|
'''Crie um programa que leia dois valores e mostre um menu na tela
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos números
[5] Sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.'''
valor1=int(input('Digite o valor1: '))
valor2=int(input('Digite o valor2: '))
escolha=0
while escolha!=5:
escolha=int(input('ESCOLHA A OPÇÃO DESEJADA\n[1]Somar\n[2]Multiplicar\n[3]Maior\n[4]Novos números\n[5]Sair'))
if escolha==1:
print('\n{}+{}={}\n'.format(valor1,valor2,valor1+valor2))
elif escolha==2:
print('\n{}x{}={}\n'.format(valor1,valor2,valor1*valor2))
elif escolha==3:
if valor1==valor2:
print('São iguais!')
else:
if valor1>valor2:
print('Entre {} e {} o maior é {}'.format(valor1,valor2,valor1))
else:
print('Entre {} e {} o maior é {}'.format(valor1,valor2,valor2))
elif escolha==4:
valor1=int(input('Digite o valor1: '))
valor2=int(input('Digite o valor2: '))
elif escolha==5:
print('Fim do programa!')
else:
print('Opção inválida!')
| false
|
e8309ecf0e484b9ffcffc02dda25e9af28c8cca1
|
JoaoPauloPereirax/Python-Study
|
/Mundo2/WHILE/while001.py
| 296
| 4.125
| 4
|
'''Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' e 'F'. Caso esteja errado, peça a digitação novamente até ter um valor correto.'''
sexo='a'
while (sexo.upper()!='M' or sexo.upper()!='F'):
sexo=str(input('Digite seu sexo(m/f): '))
print('Fim do programa')
| false
|
a1d9320dd8b18e908293e154403bf4c631c49b21
|
Anushad4/Python-Deeplearning
|
/ICP1/reversing a string.py
| 374
| 4.15625
| 4
|
#def reverse(string):
# string = string[::-1]
# return string
#s = "Anusha"
#s = input()
#print(s)
#print(reverse(s[2::]))
lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = input()
lst.append(ele)
a = ""
for j in lst:
a += j
print(a)
def reverse(string):
string = string[::-1]
return string
print(reverse(a[2::]))
| false
|
43716fe322cd9e307b98cefa32a1e35a1d387b87
|
omvikram/python-ds-algo
|
/dynamic-programming/longest_increasing_subsequence.py
| 2,346
| 4.28125
| 4
|
# Dynamic programming Python implementation of LIS problem
# lis returns length of the longest increasing subsequence in arr of size n
def maxLIS(arr):
n = len(arr)
# Declare the list (array) for LIS and
# initialize LIS values for all indexes
lis = [1]*n
# Compute optimized LIS values in bottom up manner
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1 :
lis[i] = lis[j]+1
# Initialize maximum to 0 to get
# the maximum of all LIS
maximum = 0
# Pick maximum of all LIS values
for i in range(n):
maximum = max(maximum , lis[i])
return maximum
# end of lis function
# Driver program to test above function
arr = [10, 22, 9, 33, 21, 50, 41, 60]
arr1 = [16, 3, 5, 19, 10, 14, 12, 0, 15]
arr2 = [10, 8, 6, 4, 2, 0]
print ("LIS length of arr is ", maxLIS(arr))
print ("LIS length of arr1 is ", maxLIS(arr1))
print ("LIS length of arr2 is ", maxLIS(arr2))
##############################################################################################
# Given a list of N integers find the longest increasing subsequence in this list.
# Example
# If the list is [16, 3, 5, 19, 10, 14, 12, 0, 15]
# one possible answer is the subsequence [3, 5, 10, 12, 15], another is [3, 5, 10, 14, 15].
# If the list has only one integer, for example: [14], the correct answer is [14].
# One more example: [10, 8, 6, 4, 2, 0], a possible correct answer is [8].
# Function to print the longest increasing subsequence
def lisNumbers(arr):
n = len(arr)
# Declare the list (array) for LIS and
# initialize LIS values for all indexes by 1
lis = [1]*n
# Compute optimized LIS values in bottom up manner
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1 :
lis[i] = lis[j]+1
# print(arr)
# print(lis)
myLISlist = []
# Print the LIS sequence from all LIS values
for i in range(0, len(lis)):
if(i == 0):
myLISlist.append(arr[0])
elif(i > 0 and lis[i] == lis[i-1]):
if(arr[i] > arr[i-1]):
myLISlist.append(arr[i-1])
else:
myLISlist.remove(arr[i-1])
myLISlist.append(arr[i])
elif(i > 0 and lis[i] > lis[i-1]):
myLISlist.append(arr[i])
print myLISlist
lisNumbers([10, 22, 9, 33, 21, 50, 41, 60])
lisNumbers([16, 3, 5, 19, 10, 14, 12, 0, 15])
lisNumbers([10, 8, 6, 4, 2, 0])
| true
|
b4c01ca063d09ba24aff1bfe44c719043d24d1c3
|
omvikram/python-ds-algo
|
/dynamic-programming/pattern_search_typo.py
| 1,035
| 4.28125
| 4
|
# Input is read from the standard input. On the first line will be the word W.
# On the second line will be the text to search.
# The result is written to the standard output. It must consist of one integer -
# the number of occurrences of W in the text including the typos as defined above.
# SAMPLE INPUT
# banana
# there are three bananas on the tree and one banano on the ground
# SAMPLE OUTPUT
# 2
def findTyposCount():
txt = input("Please enter the searching text here:")
pat = input("Please enter the searchable pattern here:")
pat_len = len(pat)
txt_arr = txt.split(" ")
counter_list = []
for each in txt_arr:
counter = 0
txt_len = len(each)
if(txt_len >= pat_len):
## Call a function to check the max possible match between each text and pattern
## If matching count > 1 then we can consider it as typo (ideally matching count > pat_len/2)
counter_list.append(each)
print(counter_list)
findTyposCount()
| true
|
a3ca34db407b81382afc3e61e6abbc74eed86c3a
|
omvikram/python-ds-algo
|
/dynamic-programming/bit_count.py
| 568
| 4.3125
| 4
|
# Function to get no of bits in binary representation of positive integer
def countBits(n):
count = 0
# using right shift operator
while (n):
count += 1
n >>= 1
return count
# Driver program
i = 65
print(countBits(i))
##########################################################################
# Python3 program to find total bit in given number
import math
def countBitsByLog(number):
# log function in base 2 take only integer part
return int((math.log(number) / math.log(2)) + 1);
# Driver Code
num = 65;
print(countBitsByLog(num));
| true
|
5fff518a9ffe783632b8d28920772fbc7ab54467
|
omvikram/python-ds-algo
|
/data-strucutres/linked_list.py
| 1,483
| 4.4375
| 4
|
# Python program to create linked list and its main functionality
# push, pop and print the linked list
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
# LinkedList class
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Remove an item from the LinkedList
def pop(self, key):
temp = self.head
# If head node itself holds the key to be deleted
if(self.head.data == key):
self.head = temp.next
temp = None
return
# this loop is to just set the prev node
while (temp is not None):
if(temp.data == key):
break
else:
prev = temp
temp = temp.next
#after the loop just change the next node
if(temp == None):
return
prev.next = temp.next
temp = None
# Utility function to print it the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
# Driver program for testing
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(10)
llist.printList()
llist.pop(4)
llist.printList()
| true
|
8ac6c88830679c6fb29732e283ec1884d30fdaa8
|
omvikram/python-ds-algo
|
/data-strucutres/heap.py
| 742
| 4.125
| 4
|
import heapq
## heapify - This function converts a regular list to a heap. In the resulting heap the smallest element
## gets pushed to the index position 0. But rest of the data elements are not necessarily sorted.
## heappush – This function adds an element to the heap without altering the current heap.
## heappop - This function returns the smallest data element from the heap.
## heapreplace – This function replaces the smallest data element with a new value supplied in the function.
H = [21,1,45,78,3,5]
# Use heapify to rearrange the elements
heapq.heapify(H)
print(H)
# Add element
heapq.heappush(H,8)
print(H)
# Remove element from the heap
heapq.heappop(H)
print(H)
# Replace an element
heapq.heapreplace(H,6)
print(H)
| true
|
43486f405621613de5d973ecfa3dfed21356969f
|
Adil-Anzarul/VSC-codes-c-cpp-python
|
/python_language/W11p2.py
| 1,257
| 4.75
| 5
|
# Give a string, remove all the punctuations in it and print only the words
# in it.
# Input format :
# the input string with punctuations
# Output format :
# the output string without punctuations
# Example
# input
# “Wow!!! It’s a beautiful morning”
# output
# Wow Its a beautiful morning
# # Python Program for
# # Creation of String
# # Creating a String
# # with single Quotes
# String1 = 'Welcome to the Geeks World'
# print("String with the use of Single Quotes: ")
# print(String1)
# # Creating a String
# # with double Quotes
# String1 = "I'm a Geek"
# print("\nString with the use of Double Quotes: ")
# print(String1)
# # Creating a String
# # with triple Quotes
# String1 = '''I'm a Geek and I live in a world of "Geeks"'''
# print("\nString with the use of Triple Quotes: ")
# print(String1)
# # Creating String with triple
# # Quotes allows multiple lines
# String1 = '''Geeks
# For
# Life'''
# print("\nCreating a multiline String: ")
# print(String1)
string=input()
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
print(string,end="")
| true
|
ddce169af5d2b344a2d3ce1e4e90a8c381f767af
|
Adil-Anzarul/VSC-codes-c-cpp-python
|
/python_language/W9p2.py
| 949
| 4.1875
| 4
|
# Panagrams
# Given an English sentence, check whether it is a panagram or not.
# A panagram is a sentence containing all 26 letters in the English alphabet.
# Input Format
# A single line of the input contains a stirng s.
# Output Format
# Print Yes or No
# Example:
# Input:
# The quick brown fox jumps over a lazy dog
# Output:
# Yes
# Input:
# The world will be taken over by AI
# Output:
# No
l = input().lower()
s = 'abcdefghijklmnopqrstuvwxyz'
for i in s:
if i not in l:
print('No',end='')
break
else:
print('Yes',end='')
# import string as st
# s=list(input().upper())
# if list(st.ascii_uppercase) == sorted(list(set(sorted(s)[sorted(s).index('A'):]))):
# print("Yes",end="")
# else:
# print('No',end="")
# # import string library function
# import string
# # Storing the value in variable result
# result = string.ascii_uppercase
# # Printing the value
# print(result)
# print(type(result))
| true
|
7e21b51ec88b79191088614971bbc325fff0fabf
|
AhhhHmmm/Programming-HTML-and-CSS-Generator
|
/exampleInput.py
| 266
| 4.15625
| 4
|
import turtle
# This is a comment.
turtle = Turtle()
inputs = ["thing1", "thing2", "thing3"]
for thing in inputs:
print(thing) # comment!!!
print(3 + 5) # little comment
print('Hello world') # commmmmmmm 3 + 5
print("ahhhh") # ahhhh
if x > 3:
print(x ** 2)
| true
|
851a08f4d1580cde6c19fb9dbc3dd939d0a7b6f3
|
vdmitriv15/DZ_Lesson_1
|
/DZ_5.py
| 1,604
| 4.125
| 4
|
# Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника
revenue = int(input("введите значение выручки: "))
cost = int(input("введите значение издержек: "))
profit = revenue - cost
if revenue > cost:
print(f"ваша прибыль {profit}")
profitability = profit / revenue
number_of_employees = int(input("введите количество сотрудников: "))
profit_to_employee = profit / number_of_employees
print(f"рентабельность выручки {profitability}")
print(f"прибыль фирмы в расчете на одного сотрудника {profit_to_employee}")
elif revenue < cost:
print(f"ваш убыток {profit*-1}")
else:
print("выручка равна издержкам. вы отработали в ноль")
| false
|
df7282d45332baf2d25d9ca1794b55cd802aac6c
|
evab19/verklegt1
|
/Source/models/Airplane.py
| 1,156
| 4.25
| 4
|
class Airplane:
'''Module Airplane class
Module classes are used by the logic layer classes to create new instances of Airplane
gets an instance of a Airplane information list
Returns parameters if successful
---------------------------------
'''
def __init__(self, name = "", model = "", producer = "", number_of_seats = "", plane_status = "A"):
self.name = name
self.model = model
self.producer = producer
self.number_of_seats = number_of_seats
self.plane_status = plane_status
def __str__(self):
return "{}{:20}{}{:20}{}{:25}{}{:20}{}{:10}{}".format('| ', self.name, '| ', self.model, '| ', self.producer, '| ', str(self.number_of_seats), '| ', str(self.plane_status), '|')
def get_name(self):
return str(self.name)
def get_model(self):
return str(self.model)
def get_producer(self):
return str(self.producer)
def get_number_of_seats(self):
return str(self.number_of_seats)
def get_plane_status(self):
return str(self.plane_status)
| true
|
905df9bcdb837b6e0692e1b2033aff9f72619a45
|
DrakeDwornik/Data2-2Q1
|
/quiz1/palindrome.py
| 280
| 4.25
| 4
|
def palindrome(value: str) -> bool:
"""
This function determines if a word or phrase is a palindrome
:param value: A string
:return: A boolean
"""
result = True
value_rev = value[::-1]
if value != value_rev:
result = False
return result
| true
|
15250c4e99d8133175c5956444b1473f70f194bb
|
Steven98788/Ch.03_Input_Output
|
/3.1_Temperature.py
| 446
| 4.5
| 4
|
'''
TEMPERATURE PROGRAM
-------------------
Create a program that asks the user for a temperature in Fahrenheit, and then prints the temperature in Celsius.
Test with the following:
In: 32 Out: 0
In: 212 Out: 100
In: 52 Out: 11.1
In: 25 Out: -3.9
In: -40 Out: -40
'''
print("Welcome to my Fahrenheit to Celsius converter!")
Fahrenheit=int(input("What is your Fahrenheit?"))
Celsius=(Fahrenheit-32)*5/9
print("Your Celsius is",Celsius)
| true
|
30cb2152ba61fdc70e20fde9f9b71daa05ffafa1
|
divyachandramouli/Data_structures_and_algorithms
|
/4_Searching_and_sorting/Bubble_sort/bubble_sort_v1.py
| 555
| 4.21875
| 4
|
# Implementation of bubble sort
def bubble_sorter(arr):
n=len(arr)
i=0
for j in range(0,n):
for i in range(0,n-j-1):
#In the jth iteration, last j elements have bubbled up so leave them
if (arr[i]>arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
array1=[21,4,1,3,9,20,25,6,21,14]
print(bubble_sorter(array1))
" Average and worst case time complexity: O(n*n)"
" The above algorithm always runs O(n^2) time even if the array is sorted."
"It can be optimized by stopping the algorithm if inner loop didn't cause any swap"
| true
|
3f3205aea8dd64a69b9ed91f6aab600d63da9475
|
divyachandramouli/Data_structures_and_algorithms
|
/3_Queue/Queue_builtin.py
| 384
| 4.21875
| 4
|
# Queue using Python's built in functions
# Append adds an element to the tail (newest element) :Enqueue
# Popleft removes and returns the head (oldest element) : Dequeue
from collections import deque
queue=deque(["muffin","cake","pastry"])
print(queue.popleft())
# No operation called popright - you dequeue the head which is the oldest element
queue.append("cookie")
print(queue)
| true
|
1f265b5316c3cd5fd6f103c8cac60a75584e01b3
|
Lee8150951/Python-Learning
|
/day05/01-OperateDictionary.py
| 575
| 4.375
| 4
|
# P88练习
# 练习6-1
man = {
'first_name': 'Jacob',
'last_name': 'Lee',
'age': 22,
'city': 'Shanghai'
}
print(man)
# 练习6-2 略
# 练习6-3
python = {
'dictionary': 'it can store many Key/value pairs',
'list': 'it can store many data, but they can be changed',
'tuple': 'it can store many data, and they can\'t be changed'
}
dictionary = python.get('dictionary', 'can\' find')
list = python.get('list', 'can\' find')
tuple = python.get('tuple', 'can\' find')
print(f"dictionary=>{dictionary}")
print(f"list=>{list}")
print(f"tuple=>{tuple}")
| false
|
9ad344b78580699941bee4bf63239492d1b69d85
|
Lee8150951/Python-Learning
|
/day07/03-Return.py
| 835
| 4.15625
| 4
|
# P127练习
# 练习8-6
def city_country(city, country):
conclusion = f"{city.title()}, {country.title()}"
return conclusion
info = city_country("Santiago", "Chie")
print(info)
info = city_country("Shanghai", "China")
print(info)
info = city_country("Tokyo", "Japan")
print(info)
# 练习8-7
def make_album(singer_name, album_name, count):
album = {
"singer_name": singer_name,
"album_name": album_name,
"count": count
}
return album
album = make_album("Jay Chou", "Mdm Yeh Huimei", 20)
print(album)
# 练习8-8
while True:
singer_name = input("Singer\'s Name: ")
album_name = input("Album\'s Name: ")
count = input("Album\'s count: ")
album = make_album(singer_name, album_name, count)
quit = input("Do you want to quit(y/n): ")
print(album)
if quit == "y":
break
| false
|
3bed81d65c30f440ee3abd6106801608f9f7e72c
|
zhanghui0228/study
|
/python_Basics/memory/mem.py
| 1,145
| 4.21875
| 4
|
#内存管理机制 ----赋值语句内存分析
'''
使用id()方法访问内存地址
'''
def extend_list(val, l=[]):
print('----------------')
print(l, id(l))
l.append(val)
print(l, id(l))
return l
list1 = extend_list(10)
list2 = extend_list(12, [])
list3 = extend_list('a')
print(list1)
print(list2)
print(list3)
"""
垃圾回收机制:
以引用计数为主,分代收集为辅
如果一个对象的引用数为0,python虚拟机就会回收这个对象的内存
引用计数的缺陷是循环引用的问题
"""
class Test(object):
def __init__(self):
print("对象生成了:{}".format(id(self)))
def __del__(self):
print("对象删除了:{}".format(id(self)))
def f0():
'''自动回收内存'''
while True:
''' 不断产生对象,但不使用它 '''
c = Test()
def f1():
'''内存一直在被引用,不会被回收'''
l = []
while True:
c = Test()
l.append(c)
print(len(l))
if __name__ == '__main__':
#f0()
f1() #电脑内存不大的,不要一直运行此函数
| false
|
137defbc2fbc8cd308d1fb892bfcce9f2f99498a
|
ola-lola/Python-Projects
|
/Hangman.py
| 2,070
| 4.125
| 4
|
import random
import time
from termcolor import colored
print("Hello there!")
time.sleep(1)
print("If you know some cities from Europe... ")
time.sleep(1)
print(colored("Let's play HANGMAN!", "green"))
time.sleep(1)
namey = input("What's your name?: ")
time.sleep(1)
print( "Hello " + namey + "!\n")
time.sleep(1)
print("Let's start a game!")
time.sleep(1)
print(colored("Please guess a one name of capital cities in Europe!", "green"))
cities = ("TIRANE","ANDORRA" , "VIENNA", "BAKU", "MINSK", "BRUSSELS", "SARAJEVO", "SOFIA", "ZAGREB", "PRAGUE",
"COPENHAGEN", "TALLINN", "HELSINKI", "PARIS", "TIBILISI", "BELGIA", "ATHENS", "BUDAPEST", "ROME",
"RIGA", "REYKJAVIK", "LUXEMBURG", "OSLO", "AMSTERDAM", "BELFAST", "WARSAW", "LISBON", "MOSCOW",
"EDINBURG", "BRATISLAVA", "MADRID", "STOCKHOLM", "KIEV", "LONDON", "BELGRADE")
letters_guessed_by_user = ''
attemps_left = 10
city = random.choice(cities)
print(city)
for char in city:
print("_ ", end = '' )
has_user_won = False
while attemps_left > 0 and not has_user_won :
print("\nPlease enter a letter or word: ")
letter = input("").upper() # .upper() - print only big letters
if len(letter) == 1 :
if letter in city:
letters_guessed_by_user += letter
everything_is_ok = True
for char in city:
if char in letters_guessed_by_user:
print(char, end = '')
else:
everything_is_ok = False
print("_ ", end= '')
if everything_is_ok == False:
has_user_won = False
else:
has_user_won = True
else:
attemps_left -= 1
print("Only", attemps_left , "attemps left!")
else:
if letter == city:
has_user_won = True
else:
attemps_left -= 1
print("Only", attemps_left , "attemps left!")
if has_user_won:
print(colored( "You won!", "red"))
else:
print(colored("You lost!", "red"))
| false
|
f1922a5f7e6139b3909e0c804c6277d66e44f314
|
AliAldobyan/queues-data-structure
|
/queues.py
| 2,407
| 4.15625
| 4
|
class Node:
def __init__(self, num_of_people, next = None):
self.num_of_people = num_of_people
self.next = next
def get_num_of_people(self):
return self.num_of_people
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class Queue:
def __init__(self, limit=20, front=None, back=None):
self.front = front
self.back = back
self.limit = limit
self.length = 0
self.waiting_time = 0
def is_empty(self):
return self.length == 0
def is_full(self):
return self.length == self.limit
def peek(self):
return self.front
def insert_node(self, number_of_people):
new_node = Node(number_of_people)
if self.is_empty():
self.front = new_node
else:
self.back.set_next(new_node)
self.back = new_node
self.length += 1
self.waiting_time += (30 * number_of_people)
def enqueue(self, num_of_people):
max_num = 12
num_of_people = int(num_of_people)
if self.is_full():
print("Sorry, can you wait? the queue to see the amusement park is full!")
else:
if num_of_people > 12:
while num_of_people > max_num:
num_of_people = num_of_people - max_num
self.insert_node(max_num)
self.insert_node(num_of_people)
def dequeue(self):
if self.is_empty():
print("Queue is Empty!")
else:
node_to_remove = self.front
self.front = node_to_remove.get_next()
self.length -= 1
self.waiting_time -= 30 * node_to_remove.get_num_of_people()
return f"The size of the group that went into the ride: {node_to_remove.get_num_of_people()}"
def get_waiting_time(self):
if self.waiting_time > 59:
return f"The waiting time for the queue is: {int(self.waiting_time / 60)} minutes"
else:
return f"The waiting time for the queue is: {int(self.waiting_time)} seconds"
visitors = Queue()
print("-"*45)
print(visitors.get_waiting_time())
print("-"*45)
visitors.enqueue(4)
visitors.enqueue(12)
visitors.enqueue(18)
print("-"*45)
print(visitors.get_waiting_time())
print(visitors.dequeue())
print(visitors.get_waiting_time())
print("-"*45)
| false
|
cc349db0742aaebc7650af633e66bc10cb3f14b2
|
matheusjunqueiradasilva/Jogo-adivinhacao
|
/jogo da adivinhacao.py
| 561
| 4.15625
| 4
|
import random
rand = random.randint(1, 200)
tentiva = 10
print(" Bem vindo ao jogo da advinhacao!")
print(" Tente advinhar o numero sorteado, e ele deve ser menor que 200!")
while True:
numero1 = int(input("digite o numero: "))
if numero1 == rand:
print(" parabens voce acertou! ")
break
elif numero1 > rand:
print("o numero que chutou foi maior! ")
elif tentiva == 0:
break
else:
print("o numero chutado foi menor ")
tentiva -= 1
print(f" numero restante de tentativas", +tentiva)
| false
|
5f25a0a9ad7ae81345007761fb6641542edcdd3b
|
GaoFan98/algorithms_and_ds
|
/Coursera/1_fibonacci_number.py
| 697
| 4.15625
| 4
|
# Recursive way
# def calc_fib(n):
# if n <= 1:
# return n
# return calc_fib(n-1)+calc_fib(n-2)
# n = int(input())
# print(calc_fib(n))
# Faster way of fibonacci
# def calc_fib(n):
# arr_nums = [0, 1]
#
# if (n <= 1):
# return n
#
# for i in range(2, n + 1):
# arr_nums.append(arr_nums[-1] + arr_nums[-2])
#
# return arr_nums[-1]
#
#
# print(calc_fib(9))
#
# Another way of Fibonacci with O(n)
# def good_fibonacci(n):
# if (n <= 1):
# return (n, 0)
#
# else:
# # here good_fibonacci works as counter-=1 step
# (a, b) = good_fibonacci(n - 1)
# # print(a,b)
# return (a + b, a)
#
#
# print(good_fibonacci(4))
| false
|
91a3b5ba76ba9b77775c981e048aec2cae7e8d9d
|
Fabulinux/Project-Cognizant
|
/Challenges/Brian-08302017.py
| 1,007
| 4.25
| 4
|
import sys
def main():
# While loop to check if input is valid
while(1):
# Try/Except statement for raw_input return
try:
# Prompt to tell user to input value then break out of while
val = int(raw_input("Please input a positive integer: ").strip())
break
except:
# Except invalid input error and prompts again
print "Invalid input, try again."
continue
# Construction of the staircase
for step in xrange(val):
# Variable to reduce redundancy
breakpoint = val-step-1
# Creates the spaces for the step
for space in range(0, breakpoint):
sys.stdout.write(' ')
# Creates the actual steps using "#"
for pound in range(breakpoint, val):
sys.stdout.write('#')
#Print new line for next step
print ""
# Basic main method call in python if running as a stand alone program
if __name__ == "__main__": main()
| true
|
78f333af2427a13909aa28b67c4be1675d3e81f7
|
AlexOKeeffe123/mastermind
|
/game/board.py
| 2,682
| 4.15625
| 4
|
import random
from typing import Text
#Chase
class Board:
def __init__(self, length):
"""The class constructor
Args:
self (Display): an instance of Display
"""
self._items = {} # this is an empty dictionary
self._solutionLength = length
def to_string(self):
"""Converts the board data to its string representation.
Args:
self (Board): an instance of Board.
Returns:
string: A representation of the current board.
"""
lines = "\n--------------\n"
for name, values in self._items.items():
# "Player {name}: ----, ****"
lines += f"Player {name}: {values[1]}, {values[2]}\n"
lines += "--------------"
return lines
def apply(self, turn):
""" Applies the given turn to the playing surface. Gets player's turn, name, and values
Args:
self (Board): an instance of Board.
turn (Turn): The turn to apply.
"""
guesserName = turn.get_guesser_name()
values = self._items[guesserName]
values[1] = turn.get_guess()
values[2] = self._create_hint(values[0], values[1])
def prepare(self, player):
"""Sets up the board with an entry for each player.
Args:
self (Board): an instance of Board.
player (string): gets player's values
"""
name = player.get_name()
code = str(random.randint(10 ** (self._solutionLength - 1), 10 ** self._solutionLength))
guess = hint = ""
for char in range(self._solutionLength):
guess += "-"
hint += "*"
self._items[name] = [code, guess, hint]
def _create_hint(self, code, guess):
"""Generates a hint based on the given code and guess.
Args:
self (Board): An instance of Board.
code (string): The code to compare with.
guess (string): The guess that was made.
Returns:
string: A hint in the form [xxxx]"""
hint = ""
for index, letter in enumerate(guess):
if code[index] == letter:
hint += "x"
elif letter in code:
hint += "o"
else:
hint += "*"
return hint
def get_solution(self, name):
"""Gets solution
Args:
self (Board): An instance of Board.
Return:
name (String): gets player's name
integer (Int): gets code"""
return self._items[name][0]
| true
|
1f15da7c30ac1cc5651b23777bda357d6edb6b53
|
gaogao0504/gaogaoTest1
|
/homework/pytestagmnt/calculator1.py
| 818
| 4.28125
| 4
|
"""
1、补全计算器(加法,除法)的测试用例
2、使用数据驱动完成测试用例的自动生成
3、在调用测试方法之前打印【开始计算】,在调用测试方法之后打印【计算结束】
坑1:除数为0的情况
坑2: 自己发现
"""
# 被测试代码 实现计算器功能
class Calculator:
# 相加功能
def add(self, a, b):
return a + b
# 相减功能
def sub(self, a, b):
return a - b
# 相乘功能
def multi(self, a, b):
return a * b
# 相除功能
def div(self, a, b):
return a / b
# if b == 0:
# print("0")
# else:
# return a / b
#
# try:
# return a / b
# except Exception as e:
# return "这里有个异常"
| false
|
b614122fb0117d4dd5afb5f148f5f803013a3397
|
LeedsCodeDojo/Rosalind
|
/AndyB_Python/fibonacci.py
| 1,355
| 4.25
| 4
|
def fibonacci(n, multiplier=1):
"""
Generate Fibonacci Sequence
fib(n) = fib(n-1) + fib(n-2)*multiplier
NB Uses recursion rather than Dynamic programming
"""
if n <= 2:
return 1
return fibonacci(n-1, multiplier) + fibonacci(n-2, multiplier) * multiplier
def fibonacciDynamic(n, multiplier=1):
"""
Generate Fibonacci Sequence
NB Uses Dynamic programming
"""
def processGeneration(populationHistory,generationCount):
generationSize = populationHistory[-1] + populationHistory[-2] * multiplier
populationHistory.append(generationSize)
return populationHistory[1:]
initialPopulation = [0,1]
return reduce(processGeneration, xrange(n-1), initialPopulation)[-1]
def mortalFibonacci(n, lifespan):
"""
Generate Fibonacci Sequence with Lifespan
NB Uses Dynamic programming so that sufficent generations are held in list
Last element of returned list contains the final generation
"""
def processGeneration(populationHistory,generationCount):
generationSize = populationHistory[-1] + populationHistory[-2] - populationHistory[0]
populationHistory.append(generationSize)
return populationHistory[1:]
initialPopulation = ([0] * (lifespan-1)) + [1]
return reduce(processGeneration, xrange(n), initialPopulation)[-1]
| true
|
7258f76011bedbf7e28c7c9f9f0401e1a2b78f17
|
ly061/learn
|
/基础/JSON序列化和反序列化.py
| 543
| 4.21875
| 4
|
# 序列化:把python转化为json
# 反序列化: 把json转为python数据类型
import json
# data = {"name": "ly", "language": ("python", "java"), "age": 20}
# data_json = json.dumps(data, sort_keys=True)
# print(data)
# print(data_json)
class Man(object):
def __init__(self, name, age):
self.name = name
self.age = age
def obj2json(obj):
return {
"name": obj.name,
"age": obj.age
}
man = Man("tom", 21)
jsonDataStr = json.dumps(man, default=lambda obj: obj.__dict__)
print(jsonDataStr)
| false
|
65a0a9921a54d50b0e262cccf64d980c2762f2f7
|
edwinjosegeorge/pythonprogram
|
/longestPalindrome.py
| 838
| 4.125
| 4
|
def longestPalindrome(text):
'''Prints the longest Palendrome substring from text'''
palstring = set() #ensures that similar pattern is stored only once
longest = 0
for i in range(len(text)-1):
for j in range(i+2,len(text)+1):
pattern = text[i:j] #generates words of min lenght 2 (substring)
if pattern == pattern[::-1]: #checks for palendrome
palstring.add(pattern) #stores all palindrome
if len(pattern) > longest:
longest = len(pattern)
if len(palstring) == 0:
print("No palindrome substring found found")
else:
print("Longest palindrome string are ")
for pattern in palstring:
if len(pattern) == longest:
print(pattern)
longestPalindrome(input("Enter some text : "))
| true
|
77ffe561d8ff2e08ce5aa7550b81091387ed4981
|
WellingtonTorres/Pythonteste
|
/aula10a.py
| 206
| 4.125
| 4
|
nome = str(input('Qual é o seu nome? '))
if nome == 'Wellington':
print('Alem do nome ser bonito é nome da capital da NZ!')
else:
print('Seu nome é tão normal')
print('Bom dia {}!'.format(nome))
| false
|
c3e4d19ad6b650bd400a75799c512bb8eecad4c9
|
ldswaby/CMEECourseWork
|
/Week3/Code/get_TreeHeight.py
| 2,274
| 4.5
| 4
|
#!/usr/bin/env python3
"""Calculate tree heights using Python and writes to csv. Accepts Two optional
arguments: file name, and output directory path."""
## Variables ##
__author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \
'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \
'Acacia Tang (t.tang20@imperial.ac.uk), ' \
'Dengku Tang (dengkui.tang20@imperial.ac.uk)'
__version__ = '0.0.1'
## Imports ##
import sys
import pandas as pd
import numpy as np
## Functions ##
def TreesHeight(degrees, dist):
"""This function calculates heights of trees given distance of each tree
from its base and angle to its top, using the trigonometric formula
height = distance * tan(radians)
Arguments:
- degrees: The angle of elevation of tree
- dist: The distance from base of tree (e.g., meters)
Output:
- The heights of the tree, same units as "distance"
"""
radians = degrees * np.pi / 180
height = dist * np.tan(radians)
print(height)
return height
def main(argv):
"""Writes tree height results to CSV file including the input file name in
the output file name.
"""
if len(argv) < 2:
print("WARNING: no arguments parsed. Default filename used: "
"'trees.csv'.\n")
filename = "trees.csv"
outdir = "../Data/"
elif len(argv) == 2:
filename = argv[1]
outdir = "../Data/"
elif len(argv) == 3:
filename = argv[1]
outdir = argv[2] # Accept output directory path as second arg
else:
print("WARNING: too many arguments parsed.Default filename used: "
"'trees.csv'.\n")
filename = "trees.csv"
outdir = "../Data/"
filename_noExt = filename.split('/')[-1].split('.')[0] # Assumes no full
# stops in filename
save_name = "../Results/%s_treeheights_python.csv" % filename_noExt
filepath = outdir + filename
trees_data = pd.DataFrame(pd.read_csv(filepath))
trees_data["Height"] = TreesHeight(trees_data["Angle.degrees"],
trees_data["Distance.m"])
# Save to csv
trees_data.to_csv(save_name, sep=",", index=False)
return 0
## Main ##
if __name__ == "__main__":
status = main(sys.argv)
sys.exit(status)
| true
|
d9a442c886eb178e2fab6422e8a1ef44e7e9ab07
|
bizhan/pythontest3
|
/chapter_1/range_vs_enumerate.py
| 1,040
| 4.1875
| 4
|
#print("Hello world")
def fizz_buzz(numbers):
'''
Given a list of integers:
1. Replace all integers that are evenly divisible by 3
with "fizz"
2. Replace all integers divisble by 5 with "buzz"
3. Replace all integers divisible by both 3 and 5 with
"fizzbuzz"
>>> numbers = [45, 22,14,65, 97, 72]
>>> fizz_buzz(numbers)
>>> numbers
['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']
'''
''' for i in range(len(numbers)):
num = numbers[i]
if num % 3 ==0 and num % 5 == 0:
numbers[i] = 'fizzbuzz'
elif num % 3 == 0:
numbers[i] = 'fizz'
elif num % 5 == 0:
numbers[i] = 'buzz'
'''
for i, num in enumerate(numbers):
if num % 3 ==0 and num % 5 == 0:
numbers[i] = 'fizzbuzz'
elif num % 3 == 0:
numbers[i] = 'fizz'
elif num % 5 == 0:
numbers[i] = 'buzz'
#return output
#print(fizz_buzz([45, 22, 14, 65, 97, 72]))
#ipython --no-banner -i range_vs_enumerate.py
#python3 -m doctest range_vs_enumerate.py
#[tup for tup in enumerate([1,2,3], start = 10)]
| false
|
954c952dba2e72d6b70c9d345b96090b0a43b732
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/TestSet.py
| 549
| 4.3125
| 4
|
from Set import Set
set = Set() # Create an empty set
set.add(45)
set.add(13)
set.add(43)
set.add(43)
set.add(1)
set.add(2)
print("Elements in set: " + str(set))
print("Number of elements in set: " + str(set.getSize()))
print("Is 1 in set? " + str(set.contains(1)))
print("Is 11 in set? " + str(set.contains(11)))
set.remove(2)
print("After deleting 2, the set is " + str(set))
print("The internal table for set is " + set.getTable())
set.clear()
print("After deleting all elements")
print("The internal table for set is " + set.getTable())
| true
|
f20df9950890ea3b43729837524065283366aa60
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/ComputeFactorialTailRecursion.py
| 322
| 4.15625
| 4
|
# Return the factorial for a specified number
def factorial(n):
return factorialHelper(n, 1) # Call auxiliary function
# Auxiliary tail-recursive function for factorial
def factorialHelper(n, result):
if n == 0:
return result
else:
return factorialHelper(n - 1, n * result) # Recursive call
| true
|
0ad23dca684097914370ac9f35a385b80ed74cc4
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/ComputeLoan.py
| 687
| 4.21875
| 4
|
# Enter yearly interest rate
annualInterestRate = eval(input(
"Enter annual interest rate, e.g., 8.25: "))
monthlyInterestRate = annualInterestRate / 1200
# Enter number of years
numberOfYears = eval(input(
"Enter number of years as an integer, e.g., 5: "))
# Enter loan amount
loanAmount = eval(input("Enter loan amount, e.g., 120000.95: "))
# Calculate payment
monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
totalPayment = monthlyPayment * numberOfYears * 12
# Display results
print("The monthly payment is", int(monthlyPayment * 100) / 100)
print("The total payment is", int(totalPayment * 100) /100)
| true
|
97a050e009a2c1e53a1842a6c7de60a6d6148b90
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/QuickSort.py
| 1,267
| 4.21875
| 4
|
def quickSort(list):
quickSortHelper(list, 0, len(list) - 1)
def quickSortHelper(list, first, last):
if last > first:
pivotIndex = partition(list, first, last)
quickSortHelper(list, first, pivotIndex - 1)
quickSortHelper(list, pivotIndex + 1, last)
# Partition list[first..last]
def partition(list, first, last):
pivot = list[first] # Choose the first element as the pivot
low = first + 1 # Index for forward search
high = last # Index for backward search
while high > low:
# Search forward from left
while low <= high and list[low] <= pivot:
low += 1
# Search backward from right
while low <= high and list[high] > pivot:
high -= 1
# Swap two elements in the list
if high > low:
list[high], list[low] = list[low], list[low]
while high > first and list[high] >= pivot:
high -= 1
# Swap pivot with list[high]
if pivot > list[high]:
list[first] = list[high]
list[high] = pivot
return high
else:
return first
# A test function
def main():
list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12]
quickSort(list)
for v in list:
print(str(v) + " ", end = "")
main()
| true
|
2b6c63f938d13dc8103f3cb8d5f7261f04c4676c
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/Decimal2HexConversion.py
| 745
| 4.375
| 4
|
# Convert a decimal to a hex as a string
def decimalToHex(decimalValue):
hex = ""
while decimalValue != 0:
hexValue = decimalValue % 16
hex = toHexChar(hexValue) + hex
decimalValue = decimalValue // 16
return hex
# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else: # 10 <= hexValue <= 15
return chr(hexValue - 10 + ord('A'))
def main():
# Prompt the user to enter a decimal integer
decimalValue = eval(input("Enter a decimal number: "))
print("The hex number for decimal",
decimalValue, "is", decimalToHex(decimalValue))
main() # Call the main function
| false
|
324bb0fd6f126c77d953ba9dc1096f8bdb0d9a50
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/SierpinskiTriangle.py
| 2,218
| 4.25
| 4
|
from tkinter import * # Import tkinter
class SierpinskiTriangle:
def __init__(self):
window = Tk() # Create a window
window.title("Sierpinski Triangle") # Set a title
self.width = 200
self.height = 200
self.canvas = Canvas(window,
width = self.width, height = self.height)
self.canvas.pack()
# Add a label, an entry, and a button to frame1
frame1 = Frame(window) # Create and add a frame to window
frame1.pack()
Label(frame1,
text = "Enter an order: ").pack(side = LEFT)
self.order = StringVar()
entry = Entry(frame1, textvariable = self.order,
justify = RIGHT).pack(side = LEFT)
Button(frame1, text = "Display Sierpinski Triangle",
command = self.display).pack(side = LEFT)
window.mainloop() # Create an event loop
def display(self):
self.canvas.delete("line")
p1 = [self.width / 2, 10]
p2 = [10, self.height - 10]
p3 = [self.width - 10, self.height - 10]
self.displayTriangles(int(self.order.get()), p1, p2, p3)
def displayTriangles(self, order, p1, p2, p3):
if order == 0: # Base condition
# Draw a triangle to connect three points
self.drawLine(p1, p2)
self.drawLine(p2, p3)
self.drawLine(p3, p1)
else:
# Get the midpoint of each triangle's edge
p12 = self.midpoint(p1, p2)
p23 = self.midpoint(p2, p3)
p31 = self.midpoint(p3, p1)
# Recursively display three triangles
self.displayTriangles(order - 1, p1, p12, p31)
self.displayTriangles(order - 1, p12, p2, p23)
self.displayTriangles(order - 1, p31, p23, p3)
def drawLine(self, p1, p2):
self.canvas.create_line(
p1[0], p1[1], p2[0], p2[1], tags = "line")
# Return the midpoint between two points
def midpoint(self, p1, p2):
p = 2 * [0]
p[0] = (p1[0] + p2[0]) / 2
p[1] = (p1[1] + p2[1]) / 2
return p
SierpinskiTriangle() # Create GUI
| true
|
bf8d3d46a74e9da8fe560231ceb161cd57a3316d
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/MergeSort.py
| 1,246
| 4.21875
| 4
|
def mergeSort(list):
if len(list) > 1:
# Merge sort the first half
firstHalf = list[ : len(list) // 2]
mergeSort(firstHalf)
# Merge sort the second half
secondHalf = list[len(list) // 2 : ]
mergeSort(secondHalf)
# Merge firstHalf with secondHalf into list
merge(firstHalf, secondHalf, list)
# Merge two sorted lists */
def merge(list1, list2, temp):
current1 = 0 # Current index in list1
current2 = 0 # Current index in list2
current3 = 0 # Current index in temp
while current1 < len(list1) and current2 < len(list2):
if list1[current1] < list2[current2]:
temp[current3] = list1[current1]
current1 += 1
current3 += 1
else:
temp[current3] = list2[current2]
current2 += 1
current3 += 1
while current1 < len(list1):
temp[current3] = list1[current1]
current1 += 1
current3 += 1
while current2 < len(list2):
temp[current3] = list2[current2]
current2 += 1
current3 += 1
def main():
list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12]
mergeSort(list)
for v in list:
print(str(v) + " ", end = "")
main()
| true
|
674a0def98a2f37c3dae8cf1ce070c767431b66a
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/EfficientPrimeNumbers.py
| 1,451
| 4.15625
| 4
|
def main():
n = eval(input("Find all prime numbers <= n, enter n: "))
# A list to hold prime numbers
list = []
NUMBER_PER_LINE = 10 # Display 10 per line
count = 0 # Count the number of prime numbers
number = 2 # A number to be tested for primeness
squareRoot = 1 # Check whether number <= squareRoot
print("The prime numbers are \n")
# Repeatedly find prime numbers
while number <= n:
# Assume the number is prime
isPrime = True # Is the current number prime?
if squareRoot * squareRoot < number:
squareRoot += 1
# Test whether number is prime
k = 0
while k < len(list) and list[k] <= squareRoot:
if number % list[k] == 0: # If true, not prime
isPrime = False # Set isPrime to false
break # Exit the for loop
k += 1
# Print the prime number and increase the count
if isPrime:
count += 1 # Increase the count
list.append(number) # Add a new prime to the list
if count % NUMBER_PER_LINE == 0:
# Print the number and advance to the new line
print(number);
else:
print(str(number) + " ", end = "")
# Check whether the next number is prime
number += 1
print("\n" + str(count) +
" prime(s) less than or equal to " + str(n))
main()
| true
|
3eea73798a4ddc9043f2123d5ba6f919ca239929
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/DataAnalysis.py
| 496
| 4.15625
| 4
|
NUMBER_OF_ELEMENTS = 5 # For simplicity, use 5 instead of 100
numbers = [] # Create an empty list
sum = 0
for i in range(NUMBER_OF_ELEMENTS):
value = eval(input("Enter a new number: "))
numbers.append(value)
sum += value
average = sum / NUMBER_OF_ELEMENTS
count = 0 # The number of elements above average
for i in range(NUMBER_OF_ELEMENTS):
if numbers[i] > average:
count += 1
print("Average is", average)
print("Number of elements above the average is", count)
| true
|
255e39ff64323b2afa0102ac92302511229317d6
|
timmy61109/Introduction-to-Programming-Using-Python
|
/examples/TwoChessBoard.py
| 1,263
| 4.15625
| 4
|
import turtle
def main():
drawChessboard(-260, -20, -120, 120) # Draw first chess board
drawChessboard(20, 260, -120, 120) # Draw second chess board
turtle.hideturtle()
turtle.done()
# Draw one chess board
def drawChessboard(startx, endx, starty, endy):
# Draw chess board borders
turtle.pensize(3) # Set pen thickness to 3 pixels
turtle.penup() # Pull the pen up
turtle.goto(startx, starty)
turtle.pendown() # Pull the pen down
turtle.color("red")
for i in range(4):
turtle.forward(240) # Draw a line
turtle.left(90) # Turn left 90 degrees
# Draw chess board inside
drawMultipleRectangle(startx, endx, starty, endy)
drawMultipleRectangle(startx + 30, endx, starty + 30, endy)
# Draw multiple rectangles
def drawMultipleRectangle(startx, endx, starty, endy):
turtle.color("black")
for j in range(starty, endy, 60):
for i in range(startx, endx, 60):
fillRectangle(i, j)
# Draw a small rectangle
def fillRectangle(i, j):
turtle.penup()
turtle.goto(i, j)
turtle.pendown()
turtle.begin_fill()
for k in range(4):
turtle.forward(30) # Draw a line
turtle.left(90) # Turn left 90 degrees
turtle.end_fill()
main()
| true
|
ec569b9b7975319724f3cc613fe4c45587fda197
|
peteasy/estrutura-de-dados
|
/AC 10 - Estrutura de dados - Merge sort.py
| 1,798
| 4.34375
| 4
|
# Estrutura de dados
# Atividade Contínua 10
# Alunos:
# André Niimi RA 1600736
# Caique Tuan RA 1600707
# Gustavo Andreotti RA 1600044
#Linguagem de programação utilizada: Python
# inicio da função recursiva
def mergeSort(lista):
# Dividindo a lista em duas partes
if len(lista)>1:
meio = len(lista)//2
L = lista[:meio]
R = lista[meio:]
# Executando recursivamente a função da parte esquerda
mergeSort(L)
# Executando recursivamente a função da parte direita
mergeSort(R)
# Atribuindo o valor 0(zero) para as variáveis i, j e k
i=0
j=0
k=0
# Este while só será encerrado quando a variável i
# for maior que a quantidade de números na parte esquerda
# e a variável j for maior que a quantidade de números na
# parte direita
while i < len(L) and j < len(R):
# Comparando os valores e decidindo qual valor será trocado
if L[i] < R[j]:
lista[k]=L[i]
i=i+1
else:
lista[k]=R[j]
j=j+1
k=k+1
# Atribuindo o menor valor na variável lista[posição atual]
while i < len(L):
lista[k]=L[i]
i=i+1
k=k+1
# Atribuindo o menor valor na variável lista[posição atual]
while j < len(R):
lista[k]=R[j]
j=j+1
k=k+1
# Exibindo a lista sem ordenação
lista = [54,26,93,17,77,31,44,55,20]
print ("Lista sem MergeSort: ", lista)
# Exibindo a lista com ordenação
mergeSort(lista)
print ("Lista com MergeSort: ", lista)
| false
|
6bfb64ca94d7670bada63dfcd9229cba6baa3d25
|
wjr0102/Leetcode
|
/Easy/MinCostClimb.py
| 1,094
| 4.21875
| 4
|
#!/usr/local/bin
# -*- coding: utf-8 -*-
# @Author: Jingrou Wu
# @Date: 2019-05-07 01:46:49
# @Last Modified by: Jingrou Wu
# @Last Modified time: 2019-05-07 01:53:03
'''
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
'''
import sys
def minCostClimbingStairs(cost):
"""
:type cost: List[int]
:rtype: int
"""
result = [sys.maxsize for i in range(len(cost))]
result[0] = cost[0]
result[1] = min(cost[0], cost[1])
for i in range(2, len(cost)):
result[i] = min(result[i - 1], result[i - 2] + cost[i])
return result[len(cost) - 1]
| true
|
f7a5fe592f5c42ffa1b5d8f6d63d11d588403556
|
ujjwalbaid0408/Python-Tutorial-with-Examples
|
/Ex22_StructuringElementForMorphological Transformations.py
| 697
| 4.15625
| 4
|
# Structuring element
"""
We manually created a structuring elements in the previous examples with help
of Numpy. It is rectangular shape. But in some cases, you may need elliptical/
circular shaped kernels. So for this purpose, OpenCV has a function,
cv2.getStructuringElement(). You just pass the shape and size of the kernel,
you get the desired kernel.
"""
import cv2
import numpy as np
# Rectangular Kernel
rect = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
# Elliptical Kernel
ellipt = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
# Cross-shaped Kernel
cross = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))
print rect
print ellipt
print cross
| true
|
da60d5b35c0c7be1a238dd303ce6ce1f07d9ae80
|
Max-Fu/MNISTPractice
|
/Digits_With_Neural_Network.py
| 1,035
| 4.21875
| 4
|
#!/usr/bin/python
#Import data and functions from scikit-learn packets, import plotting function from matplotlib
from sklearn.neural_network import MLPClassifier
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
#load the digits and asign it to digits
digits = datasets.load_digits()
#Use MLPClassifier (provided by sci-kit learn) to create a Neural Network with five layers (supervised learning)
#lbfgs: stochastic gradient descent
#hidden_layer_sizes: five hidden units and two hidden layer
#alpha: regulation penalty
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5,2), random_state = 4)
#load trainning data sets to two vectors X and y
X,y = digits.data[:-10], digits.target[:-10]
#Apply the neural network to the data set
clf.fit(X,y)
#print the prediction
print('Prediction: ', clf.predict(digits.data[-2]))
#print the picture of the digit
plt.imshow(digits.images[-2], cmap=plt.cm.gray_r, interpolation = "nearest")
#show the digit with matplotlib
plt.show()
| true
|
e070f5c318c6b44e4d5661509b855ff82f2621d7
|
Gabrihalls/Estudos-de-python
|
/desafios/dsf003.py
| 244
| 4.125
| 4
|
print('-----------------------TERCEIRO DESAFIO-----------------------')
primeiro = int(input('Qual primeiro número de sua soma?'))
segundo = int(input('Qual segundo número de sua soma?'))
print('O resulta de sua soma é:',primeiro+segundo)
| false
|
521f7092961eafb8ec49952366a9457e6549341f
|
HackerajOfficial/PythonExamples
|
/exercise1.py
| 348
| 4.3125
| 4
|
'''Given the following list of strings:
names = ['alice', 'bertrand', 'charlene']
produce the following lists: (1) a list of all upper case names; (2) a list of
capitalized (first letter upper case);'''
names = ['alice', 'bertrand', 'charlene']
upNames =[x.upper() for x in names]
print(upNames)
cNames = [x.title() for x in names]
print(cNames)
| true
|
fd9c99441cba0d403b6b880db4444f95874eeb0c
|
micriver/leetcode-solutions
|
/1684.py
| 2,376
| 4.3125
| 4
|
"""
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the array words.
Example 1:
Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
Example 2:
Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
Output: 7
Explanation: All strings are consistent.
Example 3:
Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
Output: 4
Explanation: Strings "cc", "acd", "ac", and "d" are consistent.
Constraints:
1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
The characters in allowed are distinct.
words[i] and allowed contain only lowercase English letters.
Count the number of strings where the allowed characters are consistent
if words[i][j] DOES NOT EQUAL ab[i] * n then do not increase the count to return
"""
allowed = "ab"
words = ["ad", "bd", "aaab", "baa", "badab"]
# Output: 2
def countConsistentStrings(allowed, words):
# count = 0
# loop through words
# for i in range(len(words)):
# for j in range(len(words[i])):
# print(words[i][j])
# for i in range(len(words)):
# for j in range(len(words[i])):
# # for x in range(len(allowed)):
# x = 0
# while x in range(len(allowed)):
# if words[i][j] == allowed[x]:
# x += 1
# if j == len(words[i]) - 1:
# count += 1
# else:
# i += 1
# return count
count = 0
allowed = set(allowed)
for word in words:
for letter in word:
if letter not in allowed:
count += 1
break
# return the number of consistent strings
return len(words) - count
# couldn't figure out a solution so decided to go with: https://leetcode.com/problems/count-the-number-of-consistent-strings/discuss/971323/Python-3-solution-100-faster-than-any-other-codes
# what is set(): https://www.geeksforgeeks.org/python-set-method/
# countConsistentStrings(allowed, words)
print(countConsistentStrings(allowed, words))
| true
|
aab785831638f7e29f6ca68343eff9c5cdc29c0e
|
micriver/leetcode-solutions
|
/1470_Shuffle_Array.py
| 983
| 4.375
| 4
|
"""
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
"""
# What is happening? Using the given integer (n) as a separator creating two arrays, you must reshuffle the given array and return a new array with the paired indexes
from typing import List
# nums = [2, 5, 1, 3, 4, 7]
# n = 3
# Output: [2,3,5,4,1,7]
nums = [1, 2, 3, 4, 4, 3, 2, 1]
n = 4
# Output: [1, 4, 2, 3, 3, 2, 4, 1]
def shuffle(nums: List[int], n: int) -> List[int]:
result = []
for i in range(n):
result.append(nums[i])
result.append(nums[i + n])
return result
print(shuffle(nums, n))
| true
|
26b569a159c98d69b9bdadbb2c8e498bacc41edf
|
sumibhatta/iwbootcamp-2
|
/Data-Types/26.py
| 348
| 4.3125
| 4
|
#Write a Python program to insert a given string at the beginning
#of all items in a list.
#Sample list : [1,2,3,4], string : emp
#Expected output : ['emp1', 'emp2', 'emp3', 'emp4']
def addString(lis, str):
newList = []
for item in lis:
newList.append(str+"{}".format(item))
return newList
print(addString([1,2,3,4], 'emp'))
| true
|
3151f1dd3c21b3603d8c616b643cdfb3f25d79a3
|
sumibhatta/iwbootcamp-2
|
/Data-Types/12.py
| 218
| 4.21875
| 4
|
#Write a Python script that takes input from the user and
# displays that input back in upper and lower cases.
string = "Hello Friends"
upper = string.upper()
lower = string.lower()
print(string)
print(upper)
print(lower)
| true
|
aa5cdbd2c62421ab8a68d3112e4703ff70504bff
|
KenFin/sarcasm
|
/sarcasm.py
| 1,715
| 4.25
| 4
|
while True:
mainSentence = input("Enter your sentence here: ").lower() # making everything lowercase
letters = ""
isCapital = 0 # Re-initializing variables to reset the sarcastic creator
for letter in mainSentence:
if letter == " ": # If there's a space in the sentence, add it back into the final sentence
letters += " "
elif isCapital == 0: # If it's not a space run it through the magic sentence converter
compare = """1234567890-=[]\;',./`""" # List of all the special characters in a special order
compare2 = """!@#$%^&*()_+{}|:"<>?~""" # List of all the shifted special characters in the same order
count = 0 # Counting to retain which space the special character is in
if letter in compare:
for i in compare:
count += 1 # Keeping track of what space the special character is in
if letter == i:
letter = compare2[count-1] # Changes the letter
break
elif letter in compare2: # Checks to see if the special character is a shifted one
for i in compare2:
count += 1 # Keeps track of the space
if letter == i:
letter = compare[count-1] # Changes the letter
break
letters += letter.capitalize() # Adds the letter and if it isn't a special character it capitalizes it
isCapital += 1 # Allows it to alternate between capitalizing and not
elif isCapital == 1: # If the last letter was changed just add this letter normally
letters += letter # Adds letter to the sentence
isCapital -= 1 # Allows next letter to be changed
print(f"Here is your sarcastic sentence: {letters}")
input("Press enter to continue.")
| true
|
f44e6b5789ee7c3d75a1891cb4df186016ff8d1a
|
tgm1314-sschwarz/csv
|
/csv_uebung.py
| 2,240
| 4.34375
| 4
|
import csv
class CSVTest:
"""
Class that can be used to read, append and write csv files.
"""
@staticmethod
def open_file(name, like):
"""
Method for opening a csv file
"""
return open(name, like)
@staticmethod
def get_dialect(file):
"""
Method that sniffs out the dialect of a give csv file
:param file: file you want to know the dialect off
"""
d = csv.Sniffer().sniff(file.read(1024))
file.seek(0)
return d
@staticmethod
def reg_dialect(name, delimiter):
"""
Method that can be used to register a new dialect for yourself
:param name: the name of the dialect you want to register
:param delimiter: the delimiter you want to set for the dialect
"""
csv.register_dialect(name, delimiter=delimiter)
@staticmethod
def read_file(file, dialect):
"""
Method that can be used to read a csv file
:param file: the file you want to read
:param dialect: the dialect that is used in the file
"""
return csv.reader(file, dialect)
@staticmethod
def append_files(reader1, reader2):
"""
Method that can be used to append two csv files together so it can be put into a third one
:param reader1: input from the first file
:param reader2: input from the second file
"""
out = []
for row in reader1:
out.append(row)
for row in reader2:
out.append(row)
return out
@staticmethod
def write_file(file, dialect, output):
"""
Method that can be used for writing a new csv file
:param file: name of the file you want to write
:param dialect: the dialect the file you want to write has
:param output: what the file you want to write contains
"""
writer = csv.writer(file, dialect=dialect)
for i in output:
writer.writerow(i)
@staticmethod
def close_file(file):
"""
Method that is used for closing the csv files once you are finished
:param file: the file you want to close
"""
file.close()
| true
|
c1249eca315f652960a09c2b903c93121c8a19c4
|
saiso12/ds_algo
|
/study/OOP/Employee.py
| 452
| 4.21875
| 4
|
'''
There are two ways to assign values to properties of a class.
Assign values when defining the class.
Assign values in the main code.
'''
class Employee:
#defining initializer
def __init__(self, ID=None, salary=None, department=None):
self.ID = ID
self.salary = salary
self.department = department
def tax(self):
return self.salary * 0.2
def salaryPerDay(self):
return self.salary / 30
| true
|
60f24bde8f1acd6637010627b439584eb8d08f32
|
mosesobeng/Lab_Python_04
|
/Lab04_2_3.py
| 1,048
| 4.3125
| 4
|
print 'Question 2'
##2a. They will use the dictionary Data Structure cause they will need a key and value
## where stock is the key and price is the value
shopStock ={'Apples ' : '7.3' , 'Bananas ' : '5.5' , 'Bread ' : '1.0' , 'Carrots ':'10.0','Champagne ':'20.90','Strawberries':'32.6'}
print 'The Initial Items in the store'
for i in shopStock:
print i +' '+ shopStock[i]
print''
##Changing the value of straberries
shopStock['Strawberries']='63.43'
##Adding another item to dictionary
shopStock['Chicken ']='6.5'
print 'The Final Items in the store'
for i in shopStock:
print i +' '+ shopStock[i]
print''
print''
print''
print 'Question 3'
##3a. The list should be used
##
##3b.
print 'The List for advertisement'
in_stock = shopStock.keys()
##3c.
always_in_stock=()
##convertion from list to tuple
always_in_stock+=tuple(in_stock)
##3d.
print ''
print 'Come to shoprite! We always sell:'
for i in always_in_stock :
print i
| true
|
f63bd219bb89d94f41d8aecea52d6b87ab0ab3a7
|
rafaelfneves/ULS-WEB-III
|
/aula03/aula3.py
| 2,116
| 4.34375
| 4
|
# -*- coding: utf-8 -*-
print('==============================[INICIO]==============================')
#String
frase=('Aula Online')
#upper() - para colocar em letra maiuscula
print(frase.upper())
print(frase.upper().count('O'))
#lower() - para colocar em letra minúscula
print(frase.lower())
#capitalize()
print(frase.capitalize())
#title() - vai analisar quantas palavras tem essa string, e transformar todas as primeiras letras de cada palavra
print(frase.title())
#swapcase() - inverte a caixa da string, o que é maiusculo vira minusculo e vice versa
print(frase.swapcase())
#strip() - remove os espaços
print(frase.strip())
#rstrip() - Remove espaço do lado direito
print(frase.rstrip())
#rstrip() - Remove espaço do lado esquerda
print(frase.lstrip())
#split() - dividir em sub strings, uma função que retorna uma lista
print(frase.split())
#join() - para definir o separador da palavra
print('-'.join(frase))
#===formatação de string===
#center() - centralizar
print(frase.center(100))
print(frase.center(100,'*'))
#ljust() - para alinhar a esquerda
print(frase.ljust(100))
print(frase.ljust(100,'-'))
#rjust() - para alinhar a direita
print(frase.rjust(100))
print(frase.rjust(100,'&'))
#Estruturas Condicionais - simples(if); composta(else); aninhada(elif)
a=7
b=9
if a>b:
print('A variavel A é maior: {}'.format(a))
if a<b:
print('A variavel B é maior: {}'.format(b))
#tipo um scanf
nome=input("\nQual o seu nome?")
if nome=='Rafael':
print('Esse nome é maravilhoso')
print('Bom dia!!{}'.format(nome))
#Exemplo de condicional composta
ano=int(input('\nQuantos anos tem o seu carro?'))
if ano <= 5:
print('Carro Novo')
else :
print('Carro Velho')
n1= float(input('Digite a nota 1: '))
n2= float(input('Digite a nota 2: '))
media = n1+n2/2
if media >= 7:
print('Passou!')
else:
print('Reprovou!')
#Indicar se o numero digitado é par ou impar
print('================================[FIM]================================')
| false
|
863c76edceb3d1e98acd52d7b45b114153532a1f
|
PreetiChandrakar/Letsupgrade_Assignment
|
/Day1.py
| 634
| 4.125
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[4]:
num=int(input("Enter Number to check prime or not:"))
m=0
i=0
flag=0
m=int(num/2)
for i in range(2,m+1):
if(num%i==0) :
print("Number is not prime")
flag=1
break
if(flag==0) :
print("Number is prime")
# In[3]:
num=int(input("Enter Number to get Factotial:"))
i=0
fact = 1
for i in range(2,num+1) :
fact = fact * i
print("Factorial of",num, "is:",fact)
# In[8]:
num=int(input("Enter Number till you need to find sum from 1 to:"))
i=1
sum =0
while(i<=num):
sum = sum + i
i=i+1
print(sum)
# In[ ]:
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.