blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6cc9650d0c79c94096cce338e593835596359972 | skyfall823/Python-Homework | /Assignment_5/lit_hw_5_5_2.py | 1,539 | 4.34375 | 4 | """
Tianyi Li
Class: CS 521 - Summer 2
Date: 10 August 2021
Homework Problem # 2
Description of Problem : Create 3 functions with docstring: letter_counts(),\
most_common_letter(), string_count_histogram()
"""
# Define Function
def letter_counts(str1):
""" Function to return dictionary with keys as character and values as their frequency"""
dict_1 = {}
for char in str1:
if char != ' ':
if char in dict_1:
dict_1[char] += 1
else:
dict_1[char] = 1
return dict_1
def most_common_letter(str2):
""" Function to return maximum occuring letters """
dict_2 = letter_counts(str2)
max_value = max(dict_2.values())
return [key for key,value in dict_2.items() if value == max_value], max_value
def string_count_histogram(str3):
""" Function to print historgram like letters """
dict_3 = letter_counts(str3)
for key in sorted(dict_3):
print(key * dict_3[key])
if __name__ == '__main__':
sentence = 'WHO WHAT WHERE WHEN WHY'
print ("The string being analyzed is:", '"{}"'.format(sentence))
print('Dictionary of letter counts:', letter_counts(sentence))
most_frequent = most_common_letter(sentence)
if len(most_frequent[0]) == 1:
print('Most frequent letter "' + str(most_frequent[0][0]) + '" appears ' + str(most_frequent[1]) + ' times.')
else:
print('Most frequent letters ' + str(most_frequent[0]) + ' appears ' + str(most_frequent[1]) + ' times.')
string_count_histogram(sentence)
| true |
299006fae86ae1eefbfd2eb4aac52f0549862947 | xuziyan001/lc_daily | /151-reverse-words.py | 728 | 4.28125 | 4 | """
给你一个字符串 s ,逐个翻转字符串中的所有 单词 。
单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
请你返回一个翻转 s 中单词顺序并用单个空格相连的字符串。
说明:
输入字符串 s 可以在前面、后面或者单词间包含多余的空格。
翻转后单词间应当仅用一个空格分隔。
翻转后的字符串中不应包含额外的空格
"""
class Solution:
def reverseWords(self, s: str) -> str:
l = [x for x in s.split(' ') if x != '']
l.reverse()
return ' '.join(l)
if __name__ == '__main__':
s = " hello world "
print(Solution().reverseWords(s)) | false |
6083259c8910c76053668d860c47536525b08b49 | luliudata/hackerrank_python | /solutions/easy/plus_minus.py | 559 | 4.15625 | 4 | def plusMinus(arr: list):
# Write your code here
num = len(arr)
num_p = 0
num_n = 0
for i in arr:
if i > 0:
num_p += 1
elif i < 0:
num_n += 1
i += 1
# https://stackoverflow.com/questions/9415939/how-can-i-print-many-significant-figures-in-python
ratio_p = num_p / num
ratio_n = num_n / num
ratio_zero = 1 - ratio_p - ratio_n
print('%.6f' % ratio_p + '\n' + '%.6f' % ratio_n + '\n' '%.6f' % ratio_zero)
# plusMinus([1, 1, 0, -1, -1])
# plusMinus([-4,3, -9, 0, 4, 1])
| false |
415cfa389e9a052ebfbb00fb7c196fdc3cb17086 | OSP123/Python_exercises | /test.py | 1,046 | 4.21875 | 4 | """ Sets the values of the instance variables height and width,
assuming they are both positive.
"""
"""
Defines class Rectangle and tests it by creating two Rectangle objects
"""
class Rectangle:
def __init__ (self):
self.height = 0
self.width = 0
def setData(self, height, width):
if type(height) != int or type(width)!=int:
raise TypeError()
if height > 0 and width < 0:
self.height = height
elif height < 0 and width > 0:
self.width = width
elif height < 0 and width < 0:
raise ValueError()
elif height < 0 or width < 0:
raise ValueError()
def __str__(self):
return "height = %i, and width = %i" % (self.height, self.width)
"""
Creates two Rectangle objects and calls methods on them for testing purposes
"""
if __name__ == "__main__":
r1 = Rectangle()
try:
r1.setData(-3, 4)
except:
print ("can't set the Rectangle to a negative value")
print (r1)
| true |
69703ef141514de058746bf42cbe5dffd0ac6aa7 | ktp-forked-repos/esperanto-analyzer | /esperanto_analyzer/speech/word.py | 2,328 | 4.21875 | 4 | """
This class represent the smallest unit with pratical meaning of one language. The function
of one word is to describe parts of humans thoughts, so its one unit of human language.
What's an Word?
===
A unit of language, consisting of one or more spoken sounds or their written representation,
that functions as a principal carrier of meaning.
Words are composed of one or more morphemes and are either the smallest units susceptible of
independent use or consist of two or three such units combined under certain linking conditions,
as with the loss of primary accent that distinguishes black·bird· from black· bird·.
Words are usually separated by spaces in writing, and are distinguished phonologically,
as by accent, in many languages.
Technically one word is one set of "Letters"
"""
import re
# pylint: disable=too-few-public-methods,missing-docstring
class Word:
# Only words with at least 4 characteres(This exclude words such as "ajn" and "kaj") that
# finish with "j", or "jn" are in plural.
PLURAL_DETECT_REGEXP = re.compile('.{2,}([^n]j|jn)$', re.IGNORECASE|re.UNICODE)
def __init__(self, content, context=None):
self._validate_content(content)
self.content = content
self.context = context
self.metadata = dict()
self.plural = (self._match_plural(context) not in [False, None])
def _match_plural(self, _context=None):
"""
This method determine if one word is in it's plural form.
Some context can be send to help to determine if some word is in plural or not.
"""
# Some words dont have plural (such as 'Adverb')
if not self.has_plural():
return None
return self.PLURAL_DETECT_REGEXP.match(self.content)
def has_plural(self): # pylint: disable=no-self-use
"""
This method determines if one words has the capibility of being in the plural.
This method should be override for subclasses(eg: Adverb)
"""
return True
def _validate_content(self, content): # pylint: disable=no-self-use
if not content:
raise NotContentError
class NotContentError(Exception):
"""
This Exception is raised when one Word is created with empty content.
Eg: Word('') # raise InvalidArticleError
"""
pass
| true |
4ed3978ef4ecf1efe3bb56d3116325a3db9e44c5 | FelixTheC/practicepython.org | /stringLists_excercise_6.py | 266 | 4.28125 | 4 | #! /usr/env/python3
string = input('Please type in a word: ')
stringBackwards = ''
for i in range(1,len(string)+1):
stringBackwards += string[-i]
if stringBackwards == string:
print('You typed in a palindrom')
else:
print('You typed in a normal word') | true |
cbee55767141345cc192c01f77fa47e4a306b3b7 | shiwanibiradar/10days_python | /day5/mullistfunc.py | 387 | 4.21875 | 4 | #Multiply the number in a list using function
def multiplication(number):
total=1
for x in number:
total = total * int(x)
return total
print("Enter how many no you want in list")
num=int(input(""))
i=0
b=[]
while i < num:
a=input("Enter the number in list")
b.append(a)
i +=1
print("numbers in list are ", b)
print("multiplication of numbers of lists are",multiplication((b)))
| true |
379c1479295403c2b9c01efcdab32c045e3f1c52 | shiwanibiradar/10days_python | /day1/if_else/square_rectangle.py | 356 | 4.3125 | 4 | #Take values of length and breadth of a rectangle from user and check if it is square or not.
length=int(input("Enter the length"))
breadth=int(input("Enter the breadth"))
if(length==breadth):
value1= length*breadth
print("It is Square with Area ", value1)
elif(length != breadth):
value2= length *breadth
print("It is rectangle with Area", value2)
| true |
f062c2342f5321a6052722007ec3270f6e4ddb41 | arund22/Python_Learning | /src/Calculator.py | 1,219 | 4.34375 | 4 |
def addition():
num1 = input("Enter the number :")
num2 = input("Enter the 2nd number : ")
num3 = num1 + num2
print("Addition of num1 and num2: ",num3)
def subtraction():
num1 = input("Enter the number :")
num2 = input("Enter the 2nd number : ")
num3 = num1 - num2
print("Subtraction of num1 and num2: ",num3)
def multiplication():
num1 = input("Enter the number :")
num2 = input("Enter the 2nd number : ")
num3 = num1 * num2
print("Multiplication of num1 and num2: ",num3)
def division():
num1 = input("Enter the number :")
num2 = input("Enter the 2nd number : ")
num3 = (num1/num2)
print("Division of num1 and num2: ",num3)
def calculator():
on = True
while on:
operation = raw_input("Enter the operation to perform + , - , * , / :")
if operation == '+':
addition()
elif operation == '-':
subtraction()
elif operation == '*':
multiplication()
elif operation == '/':
division()
elif operation == 'q':
on = False
print("Closing the Calculator")
else:
print("entered incorrect operation")
calculator() | true |
31fe615c17124ce84401a144db55cda9d2517f0e | Pazyl/ICT | /task 1/ex_27.py | 704 | 4.21875 | 4 | while True:
try:
choice = int(input('choice 1: the Height in [inches] and the Weight in [pounds]\n'
'choice 2: the Height in [meters] and the Weight in [kilograms]\n'
'Your choice: '))
if choice < 1 or choice > 2:
raise ValueError
except ValueError:
print("Invalid choice. The choice must be number [1] or [2]")
else:
break
height = float(input("Enter the height: "))
weight = float(input("Enter the weight: "))
if choice == 1:
bmi = weight / height ** 2 * 703
print("BMI is %.2f lb/in^2" % bmi)
elif choice == 2:
bmi = weight / height ** 2
print("BMI is %.2f kg/m^2" % bmi)
| false |
40926f85a42ec386bec3293bc7e67c365bd97602 | Pazyl/ICT | /task 1/ex_14.py | 206 | 4.15625 | 4 | # 1 feet = 12 inches (')
# 1 inch = 2.54 centimeters ('')
feet = int(input('Feet: '))
inches = int(input('Inches: '))
print('{0}\' {1}\'\' --> {2} cm'.format(feet, inches, ((feet * 12 + inches) * 2.54)))
| false |
fa770f8808ade69f90d23e09c105db0cf4b8709a | Pazyl/ICT | /task 1/ex_29.py | 265 | 4.25 | 4 | celsius = float(input("Enter the temperature (°C): "))
kelvin = celsius + 273.15
fahrenheit = (celsius * 9 / 5) + 32
print("the equivalent temperature in degrees Fahrenheit:", kelvin, 'K')
print("the equivalent temperature in degrees Kelvin", fahrenheit, '°F')
| false |
093fb3cc2d1f664fa9144aa3c632f149c11acab5 | GabrieleAsaro/Caesar-Cipher | /giulio_cesare.py | 651 | 4.21875 | 4 | text = input("Insert your text: ")
char_list = []
def printing(old_char, new_char):
print(' ┌────┐')
print(f'{old_char} -> │>>>3│ -> {new_char}')
print(' └────┘')
def encipher(string):
if string.isalpha():
for char in string:
calculation = (ord(char) - 97 + 3) % 26
char_list.append(chr(calculation + 97))
printing(char, chr(calculation + 97))
else:
print('This is not a valid char')
result = ''
for var in char_list:
result = result + var
print(f'Encrypted text: {result}')
encipher(text) | true |
77393308adf28ab73e3a74889a3241b2f4005c04 | IshaanBAgrawal/Day-10 | /exercise 10.1.py | 636 | 4.125 | 4 | def is_leap(yearss):
if yearss % 4 == 0:
if yearss % 100 == 0:
if yearss % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(years, months):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
months -= 1
is_leap_year = is_leap(years)
if is_leap_year == "Leap year." and months == 1:
return month_days[months] + 1
else:
return month_days[months]
#🚨 Do NOT change any of the code below
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
| true |
0d5579d6548ffecda38cf2255cc296f47a8667a8 | pamelahutchinson/September-21-2018 | /large-element.py | 568 | 4.34375 | 4 | #list of numbers
number_list = []
#loop to add input entry to the array, 5 in total
#range can be modified according to needs
for a in range(0,5):
number = int(input("Enter number: "))
number_list.append(number)
#function to calculate the largest number in the array
def largest(number_list):
max = number_list[0]
for a in range(1,len(number_list)):
if number_list[a] > max:
max = number_list[a]
return max
#giving the function a value
Ans = largest(number_list)
print("Largest number in given array is: ", Ans) | true |
f2d96b9a326d4dd94487a7dfd490b2aa32a02057 | alexakay/ICS3UClassNotes | /forloops_oct8.py | 563 | 4.15625 | 4 | # print("hello, world!")
#
# ex_var = 32
# ex_var2 = "hi"
#
# user_input = int(input("give me some input"))
#
# if user_input == 3:
# print ("your input was 3")
# elif user_input % 2 == 0:
# print("your input was even")
# else:
# print("it's not 3 or even")
#
# counter = 0
# while counter < 100:
# print(counter)
# counter = counter + 20
# counter += 20
# print (" ")
for x in range(0,6):
print ("Hello world!")
print(x)
print (" ")
for y in range(5,15,2):
print("hello")
print(y)
for i in range(10, 5, -1):
print(i)
| false |
06790d03d5ffd1a5a54ce837966a5422454a0b07 | Nagesh559/Python_Module3 | /Module3_CaseStudy1_Q12_Ans.py | 315 | 4.15625 | 4 | # Write a program that accepts a sequence of whitespace separated words as inputtext
# and prints the words after removing all duplicate words and sorting them alphanumerically.
s = raw_input('Enter a sentence:')
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words)))) | true |
8202808927b6ba4d0f574e99208e2473f590be35 | mlmldata/raspi_tempProbe | /led_control.py | 1,340 | 4.3125 | 4 | import RPi.GPIO as GPIO
import time
pin = 11 # This is the number of the GPIO pin the led should be connected to (GPIO17)
GPIO.setmode(GPIO.BOARD) #This tells the pi to use the pin numbers instead of the names
GPIO.setup(pin, GPIO.OUT)
led = GPIO.PWM(pin,200) # PWM stands for Pulse Width Modulation
led.start(0) # Initializes the LED at 0% duty cycle (off)
def toggle_on():
# Turns on the LED
led.ChangeDutyCycle(100)
print('ON')
def toggle_off():
# Turns off the LED
led.ChangeDutyCycle(0)
print('OFF')
def dot():
'''
Write a function that creates a dot in morse code with the LED
You can use the time.sleep() function to pause your code for a number of seconds
or a fraction of seconds
'''
def dash():
'''
Write a function that creates a dash in morse code with the LED
Hint, is three times as long as a dot
'''
def MLML():
'''
write a function that when called, will signal MLML in Morse Code using
the dot and dash functions you made before.
Reference the Morse Code handout to
'''
if __name__ == "__main__":
""" Use the space below to call the functions that you created above """
# example code - toggle LED on for four seconds)
toggle_on()
time.sleep(4)
toggle_off()
# exit cleanly
led.stop()
GPIO.cleanup()
| true |
8919f7b7a0371f3a52e6a57377c421a2889b33be | Pantherman/cti110 | /M3T1_PenderSr.py | 724 | 4.40625 | 4 | #This program will determine which rectangle has the bigger area.
#Anthony Pender Sr
#CTI 110
#William Buckwell
#September 13 2017
# Get the lenght and width of both rectangles.
length1 = int(input('Enter length of Rectangle 1 '))
width1 = int(input('Enter width of Rectangle 1 '))
length2 = int(input('Enter lenght of Rectangle 2 '))
width2 = int(input('Enter width of Rectangle 2 '))
#Calculate area of both rectangles.
area1 = int( length1 * width1 )
area2 = int( length2 * width2 )
#Determine which rectangle is larger or equal area.
if area1 > area2:
print ('Rectangle 1 is larger')
else:
if area2 > area1:
print ('Rectangle 2 is larger')
else:
print ('Both have same area')
| true |
c0e4dcea06a1c205ac8032bb74419c2e190ae0ad | Pantherman/cti110 | /M6T2_PenderSr.py | 333 | 4.28125 | 4 | # This program converts feet into inches
# 11/8/2017
# CTI-110 M6T2_FeetToInches
# Anthony Pender Sr
#
INCHES_PER_FOOT = 12
def main():
feet = int(input('Enter a number of feet: '))
print(feet, 'feet equals', feet_to_inches(feet), 'inches.')
def feet_to_inches(feet):
return feet * INCHES_PER_FOOT
main()
| false |
292e1909583484a0c698a618d2aa3aed92a7bc66 | mclancy96/python_learning | /firstLessons/rpsv1.py | 699 | 4.1875 | 4 | print("Let's play rock paper scissors!")
choice1 = input("Enter player 1's choice: ")
choice2 = input("Enter player 2's choice: ")
if choice1 == "rock" and choice2 == "scissors":
print("Player 1 wins!")
elif choice1 == "paper" and choice2 == "rock":
print("Player 1 wins!")
elif choice1 == "scissors" and choice2 == "paper":
print("Player 1 wins!")
elif choice1 == "rock" and choice2 == "paper":
print("Player 2 wins!")
elif choice1 == "paper" and choice2 == "scissors":
print("Player 2 wins!")
elif choice1 == "scissors" and choice2 == "rock":
print("Player 2 wins!")
elif not choice1 or not choice2:
print("Please enter a choice")
else:
print("There is no winner") | true |
efb5494ebc55e93db5d983f0818fe63330523f39 | AntonAroche/DataStructures-Algorithms | /arrays/height-checker.py | 779 | 4.25 | 4 | # A school is trying to take an annual photo of all the students. The students are asked to
# stand in a single file line in non-decreasing order by height. Let this ordering be
# represented by the integer array expected where expected[i] is the expected height of the ith student in line.
#
# You are given an integer array heights representing the current order that the students are
# standing in. Each heights[i] is the height of the ith student in line (0-indexed).
#
# Return the number of indices where heights[i] != expected[i].
def heightChecker(heights):
expected = sorted(heights)
wrong = 0
for i in range(0, len(heights)):
if expected[i] != heights[i]:
wrong += 1
return wrong
nums = [1,1,4,2,1,3]
print(heightChecker(nums))
| true |
f8cea6c5a11ef4df4a381691fd14bd842803a34c | juliekays/codingBat | /squirrelPlay.py | 564 | 4.1875 | 4 | """The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise."""
def squirrel_play(temp, is_summer):
if is_summer:
return (temp>=60 and temp<=100)
elif (temp>=60 and temp <=90):
return True
else:
return False
print squirrel_play(70,False)
print squirrel_play(95,False)
print squirrel_play(95,True)
| true |
4638942ce493663ecea52de84c7b1f4237ab1150 | elviravaladez/python-repository | /tuples.py | 856 | 4.53125 | 5 | # Tuples are like lists & dictionaries BUT they are IMMUTABLE!
# Once an element is inside a tuple, it CANNOT be reassigned
# Tuples use parenthesis
t = (1, 2, 3)
print(type(t))
# <class 'tuple'>
my_list = [1, 2, 3]
print(type(my_list))
# <class 'list'>
t = ('one', 2)
print(t)
# ('one', 2)
print(t[0])
# one
print(t[-1])
# 2
# INDEX METHOD
t = ('a', 'a', 'b')
print(t.index('a'))
# returns first index where the passed argument shows up in the tuple
# 0
print(t.index('b'))
# 2
# COUNT METHOD
print(t.count('a'))
# 2
# WHAT MAKES A TUPLE DIFFERENT (IMMUTABILITY)
print(my_list)
# [1, 2, 3]
my_list[0] = 'NEW'
print(my_list)
# ['NEW', 2, 3]
# t[0] = 'NEW'
# TypeError: 'tuple' object does not support item assignment
# WHY SHOULD I USE A TUPLE?
# Benefits: When passing around objects in your program and you don't want them to be changed.
| true |
70ed0f47a2dceb17b47c3006815a7a631e2b57a3 | arunkumar1722/CharlotteBank---Py | /bankaccount/checkingbankaccount.py | 935 | 4.125 | 4 | # Concrete implementation of Bank Account Abstraction representing Checking Bank Account
from .bankaccount import BankAccount
class CheckingBankAccount(BankAccount):
def __init__(self, account_no, account_holders, initial_deposit = 0):
self.account_no = account_no
self.account_holders = account_holders.split(',')
self.current_balance = initial_deposit
def deposit(self, deposit_amount):
if deposit_amount <= 0:
raise Exception('Deposit Amount should be > 0')
self.current_balance += deposit_amount
def withdraw(self, withdraw_amount):
if withdraw_amount > self.current_balance:
raise Exception('Insufficient Balance')
self.current_balance -= withdraw_amount
def accumulate_interest(self):
# Checking bank account flat interest
interest = self.current_balance * 0.01 / 100
self.current_balance += interest
| true |
442841d12c244204aadce7533164195193f4fd55 | kingl4166/CTI-110 | /P5T1_King.py | 426 | 4.25 | 4 |
# CTI-110
# P5T1_Kilometer Converter
# Lafayette King
# 4/10/2018
# get the distance in kilometers.
xfactor = 0.6214
def main():
kilometers = float(input("Enter distance in kilometers: "))
Miles = kilometers * xfactor
show_miles(kilometers)
def show_miles(km):
miles = km * xfactor
print(km,"kilometers equals",format(miles, ".2f"),"miles")
main()
| false |
4b40b4669fc3d8ca62120061cea4c77d1d8bd71e | macabdul9/python-learning | /basics/tuple.py | 770 | 4.40625 | 4 | """
@author : macab (macab@debian)
@file : tuples
@created : Thursday Mar 14, 2019 23:06:47 IST
"""
# tuples are in ()
mytuple = ("abdul", "waheed", "new")
#print(mytuple)
# difference between tuple and list list items are changable while tuple items unchangable
'''
mylist = ["abdul", "waheed", "new"]
mylist[0] = "eabdul"
mytuple[0] = "eabdul" # this will give an error saying tuples , tuple item does not supports object assignment
print (mylist)
print(mytuple)
'''
'''
# loop through tuple
for item in mytuple:
print(item)
'''
# adding items into the tuple
# adding items into the tuple is not possible becuase tuple is unchangable, hence there's no method to add an item
# short cut to see whether item is in tuple or not
print("ab" in mytuple)
| true |
0b9a68a860f8ec66b44a9e5557851b4e9b4efbd5 | macabdul9/python-learning | /basics/linkedlist.py | 1,500 | 4.15625 | 4 | class Node:
def __init__(self, data, nextNode = None):
self.data = data
self.next = nextNode
def printlist(current):
while current is not None:
print(current.data)
current = current.next
#
# def insertnode(head, data):
# newnode = Node(data)
# tmp = head
# #if linked list is empty
# if tmp is None:
# return newnode
# #reach to the end of the ll to insert the node
# while tmp.next is not None:
# tmp = tmp.next
# tmp.next = newnode
# return head
#insertion is also possible in constant time just maintain the both end of the ll
def insertnode(end, data):
newnode = Node(data)
if end is None:
return newnode
else:
end.next = newnode
end = newnode
return end
def pop_front(head):
if head is None:
return None
return head.next
def pop_back(head):
if head is None:
return None
if head.next is None:
return None
tmp = head
while tmp.next.next is not None:
tmp = tmp.next
tmp.next = None
return tmp
if __name__ == "__main__":
end = head = insertnode(None, 10)
end = insertnode(end, 20)
end = insertnode(end, 30)
end = insertnode(end, 40)
printlist(head)
print()
head = pop_front(head)
end = pop_back(head)
end = pop_back(head)
head = pop_back(head)
printlist(head)
head = end = insertnode(end, 30)
end = insertnode(end, 40)
printlist(head) | true |
5f6525bdf16608c88353aa50c86dfc65f962f925 | marcin96/pySort | /bubblesort.py | 623 | 4.125 | 4 | # author: Marcin Cherek
# python version: 2.7.11
# Date: 12th of April 2016
# language: English
# Title: Heapsort Algorithm python implementation
#public <bubbleSort>
#We iterate the Elements and compare them
#to each other. If the Element is bigger than
#it will be compared with the next one. Until it is
#smaller or it is the biggest Element
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
| true |
1851a58da4e1419729715dfc2301e2c7bc3e8126 | CodeInDna/Machine_Learning_with_Python | /01_Linear_Classifier_In_Python/04_Linear_Classifiers_Coefficients.py | 782 | 4.25 | 4 | # Changing the model coefficients
# When you call fit with scikit-learn, the logistic regression coefficients are automatically learned from your dataset. In this exercise you will explore how the decision boundary is represented by the coefficients. To do so, you will change the coefficients manually (instead of with fit), and visualize the resulting classifiers.
# A 2D dataset is already loaded into the environment as X and y, along with a linear classifier object model.
# Set the coefficients
model.coef_ = np.array([[0,1]])
model.intercept_ = np.array([0])
a=np.array([[1.78,0.43]])
b=np.array([0.43])
# Plot the data and decision boundary
plot_classifier(a,b,model)
# Print the number of errors
num_err = np.sum(y != model.predict(X))
print("Number of errors:", num_err) | true |
d0b2cbe7ffab6f302a60022d68a464da022a419e | terminalnode/codewars | /python/6k-primorial-of-a-number/primorial.py | 859 | 4.34375 | 4 | #!/usr/bin/env python3
# The primorial of n is the product of the n first prime numbers.
# For example, the primorial of 3 is 2*3*5 = 30.
def is_prime(n):
"""Check if a number is prime."""
# Negative numbers, 0 and 1 are not primes.
if n <= 1: return False
# No number is going to be divisible by more than half of itself,
# so there's no need to loop through more than n/2.
for i in range(2, int(n/2) + 1):
if n % i == 0: return False
return True
def get_primes(n):
primes = list()
current = 1
while n > 0:
current += 1
if is_prime(current):
n -= 1
primes.append(current)
return primes
def num_primorial(n):
product = 1
for prime in get_primes(n):
product *= prime
return product
if __name__ == '__main__':
print(sum(get_primes(1000)))
| true |
a96d95cae496a80736e0440725a41513a6f95b41 | RiyaMathew-11/hacktoberfest-1 | /String/changeToLowerCase.py | 379 | 4.34375 | 4 | def lowercase(str_data):
'''Python program to convert the string to lowercase without inbuilt functions'''
result = ''
for char in str_data:
if ord(char) >= 65 and ord(char)<=90:
result += chr(ord(char) + 32)
else:
result+=char
return result
print(lowercase("HeLLo WorLD"))
print(lowercase("HeLLo wOrLD"))
| true |
90ea253b87a0cb841c38dc1e32b1c4d2500d2af1 | Gabo1204/project_euler | /one.py | 346 | 4.25 | 4 |
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
i = 1
suma = []
while (i < 1000):
if i % 3 == 0 or i % 5 == 0:
suma.append(i)
i+=1
x = sum(suma)
print ("La suma de los multiplos es de: ")
print (x)
| true |
2ff9a8ec0ef5747983f68e22c1b5640a3013e67e | aldavis14/Davis-Math361B | /IntroToProgramming/Calculator_Davis.py | 411 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 20:07:10 2019
@author: allisondavis
"""
#input variables
x=
y=
z=
#%%
#creating the list
calculator=[x+y,(y*z)+(3*x),(x+y)**2,(2*((y*z)+(3*x))-(0.5*x))/(x+y),7%3]
print(calculator)
calculator[2]=calculator[2]+3
print(calculator)
calculator[-1]=calculator[-1]*(3/4)
print(calculator)
print('The sum of the list is',sum(calculator))
| true |
a658006b766ca8299523c343d6f7f0641bce8bba | akanz1/snippets | /replace_stubstrings.py | 845 | 4.53125 | 5 | # Replace parts of strings in a list
def replace_substring(strings_list, dictionary):
"""Replace parts of strings in a list according to the key-value mapping of a dictionary.
Example:
-------
lst = ['gloomy', 'carpet', 'house', 'mystery']
mapping = {'my': 'your', 'car': 'train'}
rename_substrings_from_dict(lst, mapping)
>>> ['glooyour', 'trainpet', 'house', 'yourstery']
Parameters
----------
strings_list : List
List of strings
dictionary : Dict
Mapping of the (sub-)strings
Returns
-------
New list with updated strings
"""
for i, string in enumerate(strings_list):
for key, value in dictionary.items():
string = string.replace("".join([key, "_"]), "".join([value, "_"]))
strings_list[i] = string
return strings_list
| true |
cf5b045aede744596bf272ef3517276fc0126037 | jinjiangliang/pythonLearner | /PythonResearch/Week1BasicsOfPython3/139CommonMistakes.py | 672 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 15:15:21 2018
@author: 1000877
1.3.9: Common Mistakes and Errors 6.44
list index out of range;
len(L)
dictionary are unordered
operation not supported by the object
'list' object has no attribute 'add'
L.append()
4)
access an object in the wrong way
dict_keys
D["1"]
5)
modify an immutable object
does not support modification;
6) operate two objects of different type
str(8)
7)
improper indentation
especialy in function.
"""
'''
#Read the error message.
Try help() or dir() .
Use Google or StackOverflow to find an answer.
Search the course discussion forum and post a question if yours hasn't been asked.
''' | true |
3504e0a72af1217e9891d998b3d3f58a4a2538db | CS-CooJ/Python_Crash_Course | /ch_3/motorcycles.py | 1,373 | 4.25 | 4 | motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati' #switches the first item in list with ducati
print(motorcycles)
motorcycles.append('honda') #append adds an item to the list
print(motorcycles)
motorcycles.insert(0, 'indian') #inserts at identified placing
print(motorcycles)
del motorcycles[-1] #deletes identified item
print(motorcycles)
popped_motorcycle = motorcycles.pop() #gets rid of the [-1] item and redefines new list
print(motorcycles)
print(popped_motorcycle)
last_owned = motorcycles.pop() #separates last and redefines into new variable
first_owned = motorcycles.pop(0) #separates first and redefines into new variable
print(last_owned)
print(first_owned)
message_first = "The first motorcycle I owned was an " + first_owned + " and I had it for 10 years."
message_last = "The last motorcycle I owned was a " + last_owned + " and I sold it last week."
print(message_first)
print(message_last)
print(motorcycles)
motorcycles = ['honda', 'suzuki', 'yamaha', 'indian', 'harley', 'ducati']
print(motorcycles)
motorcycles.remove('ducati') #to remove item by name
print(motorcycles)
motorcycles.insert(0, 'ducati')
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")
| true |
0e5faec46977b0d886011c386ff4ad6f313836bc | riteshbisht/dsprograms | /arrays/rearrangement/problem5.py | 542 | 4.21875 | 4 | """
Segregate even and odd numbers | Set 3
Given an array of integers, segregate even and odd numbers in the array.
All the even numbers should be present first, and then the odd numbers.
Examples:
Input : 1 9 5 3 2 6 7 11
Output : 2 6 5 3 1 9 7 11
Input : 1 3 2 4 7 6 9 10
Output : 2 4 6 10 7 1 9 3
"""
arr = [1, 3, 7, 4, 6, 8]
if __name__ == "__main__":
odd = -1
even = 0
for index, i in enumerate(arr):
if i % 2 == 0:
odd = odd + 1
arr[odd], arr[index] = arr[index], arr[odd]
print(arr)
| true |
439a96ff0046f69d0504e3718e15ea9d7e1d57e5 | csundara/CSE107 | /lab4/navigate2.py | 1,567 | 4.125 | 4 | import turtle
def main():
henery = turtle.Turtle()
userin = input('Please enter directions: ')
direction = userin.split(',')
# while userin != 'stop':
for inst in range(len(direction)):
if direction[inst] == 'forward': # moves turtle 100
henery.forward(100)
elif direction[inst] == 'left': # turns turtle left
# angle = input('How many degrees? ') # determines how far to
# turn turtle
inst = inst + 1
angle = direction[inst]
# turns turtle if user input is proper
if angle.isdigit():
henery.left(int(angle))
else:
# ignors input because input is invalid
print('Invalid number, not moving.')
elif direction[inst] == 'right': # turns turtle right
# angle = input('How many degrees? ')
# # determines how far to turn turtle
inst = inst + 1
angle = direction[inst]
# turns turtle if user input is proper
if angle.isdigit():
henery.right(int(angle))
else:
# ignors input because input is invalid
print('Invalid number, not moving.')
elif direction[inst] == 'stop' or direction[inst].isdigit():
continue
else:
# ignors input because input is invalid
print('Invalid input, not moving.')
# userin = input('Please enter a direction: ')
if __name__ == "__main__":
main()
| true |
1f408b01a5a7369ab11f080819fc7954d19b9c1d | asanka-code/python-stuff | /functions.py | 1,114 | 4.5625 | 5 | #!/usr/bin/python
############################################
# #
# Program: functions.py #
# Author: Asanka Sayakkara #
# Description: #
# This script demonstrates the usage #
# of functions in Python. #
# #
############################################
# A function which accepts parameters by value
def multi_para_function(a, b):
a = 100
b = 200
#print("a=%d b=%d" % (a, b))
first=10
second=20
multi_para_function(first, second)
print("After the multi para function, first=%d second=%d" % (first, second))
# A function which accepts parameters by reference
def para_list_function(params):
params[0] = params[0] + 100
params[1] = params[1] + 200
params=[10, 20]
para_list_function(params)
print("After the para list function %s" % params)
def str_para_function(string):
print("string=%s" % string)
myStr="Hello!"
str_para_function(myStr)
print("-------------------------------")
print("Default Values")
def funcWithDefaults(para1, para2=30):
ans = para1 + para2
return ans
print("answer= %d" % funcWithDefaults(1, 2))
print("answer= %d" % funcWithDefaults(1))
| true |
0199cb7d6e846ed6f5b8a547c3c6800c1bd619c4 | Raagini539/programs | /Beginner_3_2.py | 205 | 4.125 | 4 | //raagini
maxele.py
lst=[]
num = int(input("enter the number: "))
for n in range(num):
numbers = int(input("Enter number:"))
lst.append(numbers)
print("Maximum element in the list is :", max(lst)
| true |
938bd3555c307eace8df9447eec6b4ffdd6526ac | xuwenbingfor/pythonlearn1 | /pd/pd3.py | 552 | 4.125 | 4 | # 数据源读写
# DataFrame
## 常见属性values、index、columns、dtypes
## 查:loc[行索引名称(未指定index时是行索引位置)或条件,列索引名称]\iloc[行索引位置,列索引位置]
## at:https://blog.csdn.net/sinat_29675423/article/details/87975489
## 改:原理
## 增/删
## 统计:https://www.jianshu.com/p/360c69f0083e
#Series
## get
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.random.rand(4, 3), columns = list('abc'), index = ['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame.index)
print(frame) | false |
c42df8eb66bda5b2050a7f31497b836204461445 | vanokl/algs | /Algorithmic Warm Up/Fibonacci Number/fibonacci_number.py | 299 | 4.125 | 4 | # python3
def fibonacci_number(n):
assert 0 <= n <= 45
res = [0, 1]
if n < 2:
return res[n]
for i in range(2, n + 1):
res.append(res[i - 1] + res[i - 2])
return res[n]
if __name__ == '__main__':
input_n = int(input())
print(fibonacci_number(input_n))
| false |
4f30169491ac4edf16e49f775c5f7b09eb0edd9e | sungheeyun/PythonLectures | /src/basics/factorial_recursion.py | 543 | 4.59375 | 5 | """
Here we show that the factorial function can be implemented using recursion.
Note that the initial condition is critical.
"""
def factorial_recursion(n):
"""
Return the factorial of n using recursion.
Parameters
----------
n :
an integer of which the factorial is evaluated.
Returns
-------
result :
The factorial of n.
"""
if n == 1:
return 1
return factorial_recursion(n - 1) * n
if __name__ == "__main__":
m = 10
print(m, "! =", factorial_recursion(m))
| true |
172babf6ccc2b2244dd608747433ecd4cdb30fa9 | sungheeyun/PythonLectures | /src/basics/factorial.py | 541 | 4.625 | 5 | """
This examples shows that how we can implement a function which evaluates the factorial of the number given
as an argument and returns it.
"""
def factorial(n):
"""
Return the factorial of n.
Parameters
----------
n :
an integer of which the factorial is evaluated.
Returns
-------
result :
The factorial of n.
"""
result = 1
for x in range(2, n + 1):
result = result * x
return result
if __name__ == "__main__":
m = 10
print(m, "! =", factorial(m))
| true |
a61d7559a329de99b997fc248606f72bcadf5e71 | winson121/AlgorithmAndDataStructure | /Sort/DivideAndConquer/MergeSort.py | 1,491 | 4.3125 | 4 | def mergeSort(array):
start = 0
end = len(array)-1
temp = [None] * len(array)
mergeSortAux(array, temp, start, end)
def mergeSortAux(array, temp, start, end):
# merge the array into two half while the list is not single element
if start < end:
mid = (start + end) // 2
mergeSortAux(array, temp, start, mid)
mergeSortAux(array, temp, mid+1, end)
# merge the sorted subarray together to form a bigger sorted subarray
mergeArray(array, temp, start, mid, end)
# copy the sorted subarray to the original array
for i in range(start, end+1):
array[i] = temp[i]
def mergeArray(array, temp, start, mid, end):
left = start
right = mid+1
for i in range(start, end+1):
# if the left subarray is empty, append the element from right subarray to temp
if left > mid:
temp[i] = array[right]
right += 1
# if the right subarray is empty, append the element from left subarray to temp
elif right > end:
temp[i] = array[left]
left += 1
# if current element from the right subarray bigger than left subarray
# append left subarray to temp
elif array[left] <= array[right]:
temp[i] = array[left]
left += 1
else:
temp[i] = array[right]
right += 1
if __name__ == "__main__":
beta = [2,4,1,8,6,0,-1,9,6,5,8]
mergeSort(beta)
print(beta) | true |
521d1aedc8309d2d69ab602dd73230db173fb7bf | Malcolmlsh/Revenuereport | /Revenue Report.py | 1,167 | 4.15625 | 4 | # Revenue Report
#
#
#
# Write a function that gets user to input the monthly revenues for the past quarters.
# It then returns a variable of list data type to caller with the corresponding values.
# Then generate a revenue report denoting the month, revenue, and cumulative total for each month.
# It ends with a message that sums up the total revenue. Appropriate formatting has to be in place for numeric numbers (decimals and comma) and spacing.
# The output may look like the following.
def revenue_report():
months = [1,2,3]
cummulative_total = []
monthly_revenue = []
for i in range(1, len(months)+1):
user_input = float(input("Enter Revenue for month {}: ".format(i)))
monthly_revenue.append(user_input)
cummulative_total.append(sum(monthly_revenue))
print("""Revenue Report
---------------------------""")
for index,element in enumerate(monthly_revenue):
print("Revenue for {}: $ {:.2f} | Cummulative. Total: $ {:.2f}".format(int(index+1),element,cummulative_total[index]))
print("The company has made a total of $ {:.2f} in the last quarter.".format(cummulative_total[-1]))
revenue_report()
| true |
099a9769e4e449db2b851a588c56fcef70e53b06 | kazumihirata/codingbat | /python/Warmup-1/sum_double.py | 225 | 4.1875 | 4 | # Given two int values, return their sum. Unless the two values are the same, then return double their sum.
def sum_double(a, b):
if a == b :
return 2 * (int(a) + int(b))
else :
return int(a) + int(b)
| true |
489349957e8a7628af5dc0b14a125d9aa71ef38b | ydPro-G/Python_file | /python/9_class/9.3/try/9-8.py | 1,888 | 4.125 | 4 | # 用户
class User():
"""用户信息与问候用户"""
def __init__(self,first_name,last_name,age):
# 属性
self.first_name = first_name
self.last_name = last_name
self.age = age
# 方法
def describe_user(self):
print("用户名字是" + self.first_name + self.last_name)
print("用户年龄是" + str(self.age) + ".")
def greet_user(self):
print("欢迎光临," + self.first_name + self.last_name)
# 实例1
user_one = User('小','明',16)
# 方法
user_one.describe_user()
user_one.greet_user()
print("\n9-8")
class Privileges():#新建一个类,将这个类的实例用作另一个类的属性
"""新建一个类,将这个类的实例用作另一个类的属性"""
def __init__(self,privilege = '添加用户'): # 要将实例用作另一个类的属性必须要在形参或属性中指定值
self.privilege = privilege
def show_privileges(self):
print("管理员的权限有:" + self.privilege)
messages = Privileges()
messages.show_privileges() # 注意要调用方法
class Admin(User):
def __init__(self,first_name,last_name,age):
super().__init__(first_name,last_name,age)
self.one = Privileges() #将类中的实例用作这个类中的属性
admin = Admin('X','M',15)
print(admin.one.show_privileges()) #因为python中print函数需要返回值,如果你在print函数中所放的函数没有返回值,那么print将会return None
admin.one.show_privileges() # 这里先在实例中查找属性,并调用该属性中关联的类的另一类的方法
# python中print函数需要返回值,如果你在print函数中所放的函数没有返回值,那么print将会return None
# 简单来说就是在show_privileges方法中print()已经输出了返回值,那么在实例中自然 return None
| false |
161be077de4c80320b9ad91c9cd8eb53cab64b6c | ydPro-G/Python_file | /python/7_while_users/7.1/input.py | 2,165 | 4.4375 | 4 | # 7.1函数input()的工作原理:让程序暂停运行,等待用户输入,获取输入后,python将其储存在一个变量中
# 程序等待用户输入,在用户按回车键后继续运行,再将输入储存在变量中
# 针对集合中的每个元素都一个代码块
print("7.1")
message = input("Tell me someting, and I will repeat it back to you:")
print(message)
# input(),Python将用户输入解读为字符串
#7.1.1 编写清晰的程序
print("\n7.1.1")
name = input("Please enter your name: ")
print("Hello " + name + " !")
# 超过一行的提示怎么编写?
# 将提示储存在一个变量中,再使用函数input()将该变量传递给另一个变量
prompt = ("If you tell us who you are,we can presonalize the messages you see.")
prompt += "\nWhat is your first name? " # 创建多行字符串的方法(运算符+=在存储在prompt中的字符串末尾附加一个字符串)
name = input(prompt)
print("\nHello, " + name + " !")
# 7.1.2 使用int()来获取数值的输入
print("\n 7.1.2")
age = input("How old are you? ")
age = int(age) # 将字符串转换成数值进行比较
if age >= 18:
print("true")
print("\n") # 在实际程序中使用函数int()
height = input("How tall are you, in inches? ")
height = int(height) # 将字符串转换成数值比较
if height >=36:
print("\nYou`re tall enough to ride!")
else:
print("\nYou`ll be able to ride when you`re a little older.")
print("\n7.1.3")
# 7.1.3 求模运算符
# 处理数值信息,求模运算符(%)是一个很有用的工具,将两个数相除并返回余数。
print(4 % 3) # 1 只指出余数是多少
print(5 % 3) # 2
print(6 % 3) # 0
print(7 % 3) # 1
print("\n")
# 判断一个数是奇数还是偶数
number = int(input("Enter a number,and I`ll tell you if it`s even or odd: ")) # 输入的数字以字符串显示,使用int()将字符串转换成数值比较
if number % 2 == 0: # 如果求模2后是0,说明是整数
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
a = "tell me? "
message = int(input(a))
print(message) | false |
ca285e9a5dc64b49213d02eadd0936ea57dbe522 | arun-p12/sort-algorithms | /bubble_sort.py | 1,173 | 4.15625 | 4 | '''
Bubble sort -- time taken as a function of size ==> size**2 i.e. O(n**2)
Take two adjacent elements, and swap them if required. Repeat process, until end of list.
The last element of the list would now contain the required value.
Repeat for N - 1 iterations. But, in each iteration the list size reduces since the last
element is already sorted.
To further optimize, check if in a pass, there has been no swapping. If true, then it means the
list is already sorted, and we can stop right at the end of that pass.
'''
def bubble_sort(A, verbose=0, desc=0):
import common as c
for i in range(len(A)):
swapped = 0
for j in range(len(A) -1 - i): # -i :: keep ignoring items already sorted
if(A[j] > A[j+1]): # only worry about ascending order
(A[j], A[j+1]) = c.swap(A[j], A[j+1])
swapped = 1
if(verbose == 2): print(" sub:", j, " :: ", A)
if(verbose): print("iter #", i, " :: ", A)
if(not swapped): break # early exit if already sorted.
if(desc): A = A[::-1] # if descending read list from right to left
return(A)
| true |
7a7006db3f095a0f0ebe82c923ba91ae47a4d925 | rioshen/Problems | /leetcode/python/symmetric_tree.py | 1,326 | 4.34375 | 4 | #!/usr/bin/env python
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if not root:
return True
return self.symmetric(root.left, root.right)
def symmetric(self, left, right):
if not left and not right: # base case, hit the end
return True
if not left or not right: # subtrees have different depths
return False
if left.val != right.val: # subnodes' value aren't equal
return False
# recursively compare subtrees
return self.symmetric(left.left, right.right) and \
self.symmetric(left.right, right.left)
def isSymmetric(self, root):
'''Iteratly traverse the tree in preorder.'''
if not root:
return True
stack = [root.left, root.right]
while stack:
rgt, lft = stack.pop(), stack.pop()
if not lft and not rgt:
continue
if not lft or not rgt or lft.val != rgt.val:
return False
stack += [lft.left, rgt.right, lft.right, rgt.left]
return True
| true |
8fababdcd6b0eb70445bd5fae4564aa2644c181e | Navid-Rahman/Rock-Paper-Scissors | /Rock, Paper, Scissors.py | 1,274 | 4.125 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
variables = [rock, paper, scissors]
you = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors."))
import random
computer = random.randint(0,2)
if you==2 and computer==0:
print("You chose")
print(variables[you])
print("Computer chose")
print(variables[computer])
print("Computer wins.")
elif you==0 and computer==2:
print("You chose")
print(variables[you])
print("Computer chose")
print(variables[computer])
print("You wins.")
elif computer>you:
print("You chose")
print(variables[you])
print("Computer chose")
print(variables[computer])
print("Computer wins.")
elif you==computer:
print("You chose")
print(variables[you])
print("Computer chose")
print(variables[computer])
print("It's a draw.")
else:
print("You chose")
print(variables[you])
print("Computer chose")
print(variables[computer])
print("You win.") | false |
b43d9f0413c3fe9d58b1297cfd44daecbc1ffce0 | udaraweerasinghege/ADT-methods | /LinkedListRec/Mutating/linkedlistrec.py | 977 | 4.15625 | 4 | class EmptyValue:
pass
class LinkedListRec:
"""Linked List with a recursive implementation.
Note that there is no "Node" class with this implementation.
Attributes:
- first (object): the first item stored in this list,
or EmptyValue if this list is empty
- rest (LinkedListRec): a list containing the other items
in this list, or None if this list is empty
"""
def __init__(self, items):
""" (LinkedListRec, list) -> NoneType
Create a new linked list containing the elements in items.
If items is empty, self.first initialized to EmptyValue.
"""
if len(items) == 0:
self.first = EmptyValue
self.rest = None
else:
self.first = items[0]
self.rest = LinkedListRec(items[1:])
def convertlst(L):
if L.first is EmptyValue:
return []
else:
return [L.first] + convertlst(L.rest) | true |
6beaae226566f7de205f119374fb11eecad77ed8 | Titashr/python_basics | /cipher_wheel.py | 541 | 4.21875 | 4 | print("Ceaser's cipher\n")
inputString = input("Enter the required string : ")
inShift = int(input("Enter the required shift : "))
def my_cipher(string1, shift1):
stringList = list(string1)
length = len(stringList)
result = ""
for i in range(length):
test = stringList[i]
if test.islower():
result += chr((ord(test) + shift1 - 97) % 26 + 97)
else:
result += chr((ord(test) + shift1 - 65) % 26 + 65)
return result
result = my_cipher(inputString, inShift)
print(result)
| true |
a4b4371fe7084715895c10a048a6e215b5748562 | Journey-R/TIL | /Python/python_base/01_tuple.py | 1,522 | 4.125 | 4 | # tuple
# list와 비교할 수 있어야 함
# list와 공통점 : 순서 있음, 중복 허용,
# list와 차이점 : 추가/수정/삭제 불가 -> 읽기 전용
# ()로 변수 선언
# tuple 생성
my_tuple = ()
movie_rank = ("반도", "강철비2", "아이언맨")
test_tuple = (1) # 요소가 1개일 때는 해당 요소의 데이터타입이 요소의 데이터 타입
print(type(test_tuple)) # print : <class 'int'>
test_tuple2 = (1,) #(1,) : 요소가 1여도 ','가 있어야 튜플
print(type(test_tuple2)) # print : <class 'tuple'>
# () 생략 가능
test_tuple = 1,2,3,4,5
print(test_tuple, type(test_tuple)) # print : (1, 2, 3, 4, 5) <class 'tuple'>
multi_tuple = (100, 1000, "Ace", "Base", "Captine")
print(multi_tuple, type(multi_tuple))
print()
# indexing 가능
print(">>>>>>>>>>>> 튜플 인덱싱")
print(multi_tuple[0])
print(multi_tuple[-1])
print(multi_tuple[0]+multi_tuple[1]) # 인덱스의 값으로 산술연산
print(multi_tuple[2:], type(multi_tuple[2:])) # 'ACE'~'Captine'까지 출력
# tuple -> list 형변환 : list(tuple 데이터)
# (tuple은 readonly여서 list로 형변환해서 데이터 조작)
list = list(multi_tuple[2:])
print(type(list)) # print : <class 'list'>
# list -> tuple 형변환 : tuple(list 데이터)
casting_tuple = tuple(list)
print(type(casting_tuple)) # <class 'tuple'>
# 1~100 정수 중 짝수만 저장된 튜플 생성
tuple = tuple(range(2, 100, 2))
print(tuple)
| false |
4b359c1775d37ea4461b704d9ed589535e389a3f | manu-prakash-choudhary/Open-Source | /Good-First-Issues/ArrayFromDoubledArray.py | 793 | 4.21875 | 4 | '''
ALGORITHM EXPLANATION
The array is first sorted.
The 0th element of the array now holds the smallest value.
So half of this value cannot be in the array.
Therefore the 0th element is one of the original elements.
We remove it and add it to the originals.
We also remove its double.
We keep doing this until the array size reaches 0.
At this point, we have gone through all of the elements.
Therefore we can return the array of original elements.
'''
def arrayFromDoubledArray(arr):
arr.sort()
original = []
while (len(arr) > 0):
n = arr.pop(0)
arr.remove(n*2)
original.append(n)
return original
# Test cases
print("Test case 1:", arrayFromDoubledArray([4, 1, 18, 2, 9, 8]))
print("Test case 2:", arrayFromDoubledArray([4, 1, 2, 2, 8, 2, 4, 4])) | true |
66a323d749734ef1f23ae6a740443e33e6f63050 | JohnSurina/PythonPractice | /pythonpracticeDotOrg/exercise16.py | 1,088 | 4.25 | 4 | # Write a password generator in Python.
# Be creative with how you generate passwords - strong
# passwords have a mix of lowercase letters, uppercase letters,
# numbers, and symbols. The passwords should be random,
# generating a new password every time the user asks for a new password.
# Include your run-time code in a main method.
# Extra:
# • Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list.
# ----------------------------------------------------------- #
import random
lettersLower = "abcdefghijklmnopqrstuvwxyz"
lettersUpper = lettersLower.upper()
numbers = "1234567890"
symbols = "!@#$%&()[]\{\}?<>,.\\/"
randSet = lettersLower + lettersUpper + numbers + symbols
try:
numberCharacters = int(input("Please input the number of characters you would like in your password: "))
except ValueError:
print("please enter an actual number, cockSucker")
exit()
returnString = ""
for i in range(0,numberCharacters):
returnString = returnString + randSet[random.randint(0,len(randSet)-1)]
print(returnString) | true |
e66f031c895a27e18ec450041241f39e8675ac1c | JohnSurina/PythonPractice | /pythonpracticeDotOrg/dummy.py | 989 | 4.375 | 4 | # Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Extras:
# • Add on to the previous program by asking the user for another number
# and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
# • Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)
# ----------------------------------------------------------- #
import datetime
print("")
print("This program will tell you when you will turn 100 years old.")
usersName = input("What is your name?: ")
usersAge = input("what is your age?: ")
yearsUntil100 = 100 - int(usersAge)
today = datetime.date.today()
currentYear = today.year
yearUserTurns100 = currentYear + yearsUntil100
print("Hey {0}, you will turn 100 years in the year: {1}".format(usersName, yearUserTurns100)) | true |
db2c81b0eb7fff225d027ad552c0d56b43d7ab39 | UzairJ99/pythoncourseYMA | /lecture3/whileloops.py | 1,824 | 4.40625 | 4 | # syntax for while loops
'''
while(True):
# code block
print("hi")
'''
# we wouldn't want to run this because it will result in an infinite loop.
# instead we'll replace True with a dynamic condition (one that can change so the loop can stop eventually)
# Since the condition is currently set to True, it's static - never changes - and will cause the loop to repeat forever
# let's make a finite loop
counter = 0 # this counter will determine how many times we've looped
while (counter < 10):
print("hi")
counter += 1 # increase the value of counter by 1 each time the code loops
# this will print hi 10 times because it will loop until counter has reached the value 9 (notice counter < 10)
# let's use a boolean data type as our condition
keepGoing = True
while (keepGoing):
print("loop")
keepGoing = False # keepGoing is set to false, so the next iteration the condition is not met
# we only see 1 occurrence of "loop" because once the first iteration is complete, the condition is no longer met
# let's combine the two styles to make one complex loop
on = True # this variable will hold whether the game is still on or not
score = 0 # this variable keeps track of the player's score
while(on):
if (score == 10): # conditionals are a decision making model - more on this in lecture
on = False # turn off the game
else:
print("score: " + str(score))
score += 1 # increase the score
print("game over.")
# the game will increase the player's score until it reaches 10 and then it will end
# let's look at the break command. What if we wanted to terminate the loop based on another condition rather than
# the original condition.
score = 0
while(score < 10):
if (score == 5):
break
else:
print(score)
score += 1
| true |
faeeb69f2ae6a546fc45d94a93d3ddc1cf773df2 | Machkeck/Python-Course | /lesson3/3.4.py | 220 | 4.15625 | 4 | #python 3
while True:
n = eval(input("Type a number: "))
if n == "stop":
print("Stopped")
break
if type(n) == str:
print("Input is not a number")
else:
print(n,pow(n,3))
| false |
c703487042fd37de00bde9ef8f02e35df8bd6618 | qinglujinjin/CS161_Assignment10QL | /reverse_list_kh.py | 382 | 4.28125 | 4 | #Author: Khai Hoang
#Date: 11/13/2019
#Description: Takes a parameter list and reverses the order of the elements in that list.
# It should not return anything - it should mutate the original list.
def reverse_list(list_input):
list_input[::] = list_input[::-1]
print(list_input)
example_list = [7, -3, 12, 9]
print(example_list)
reverse_list(example_list)
print(example_list) | true |
54f36b8d86391ce5f28f43adb140467230030704 | Shahabmustafa/Python-Question | /Python-Question/qas3.py | 592 | 4.3125 | 4 | # (3) Matrix Transpose [2 pts.]
# The transpose of a square matrix M is an important tool that is used in solving systems of linear
# equations. It can be computed by swapping all of M’s rows and columns. For example:
# ANSWER
X = [[1,2,3,4],
[4,5,6,7],
[7,8,9,10],
[9,10,11,12]]
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through coloums
for j in range(len(result)):
result[j][i] = X[i][j]
for r in result:
print(r) | true |
25b05ec8d1b693f517f46f24ee948ae6ac4dd3fe | matbot/Py_merge_vs_insert_sorts | /mergeTime.py | 1,568 | 4.21875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
""" Author: Mathew McDade
Date: 1/9/2019
Class: CS325.400 Winter 2019
Assignment: HW1: merge sort --timed
Description: A simple Python implementation of merge sort.
Times the execution of the sort on arrays of random integers of increasing size and prints
the results to the terminal.
"""
from timeit import timeit
from random import randint
# Define mergesort --based on pseudocode provided on CLRS pg.31-34.
def merge(array, start, midpoint, end):
n1 = midpoint + 1
left_array = array[start:n1] # separate the subarrays to be merged.
right_array = array[n1:end + 1]
left_array.append(float("inf"))
right_array.append(float("inf"))
i = j = 0
for k in range(start, end + 1): # merge the partial arrays to a combined, ordered array.
if left_array[i] < right_array[j]:
array[k] = left_array[i]
i += 1
else:
array[k] = right_array[j]
j += 1
def mergesort(array, start, end):
if start < end:
midpoint = (start + end) // 2 # floor division --Python3
mergesort(array, start, midpoint)
mergesort(array, midpoint + 1, end)
merge(array, start, midpoint, end)
# MAIN
if __name__ == "__main__":
for x in range(3000, 30001, 3000):
rand_ints = []
for y in range(x):
rand_ints.append(randint(0, 10000))
time = timeit(lambda: mergesort(rand_ints.copy(), 0, len(rand_ints) - 1), number=10)
print("n: %i time: %f seconds" % (x, time))
| true |
91c06ad2533cadbdc577d33749766e91c68ec298 | lambdagirl/leetcode-practice | /sort-character-by-frenquency.py | 966 | 4.28125 | 4 | # # 451. Sort Characters By Frequency
# Given a string, sort it in decreasing order based on the frequency of characters.
# Example 1:
# Input:
# "tree"
# Output:
# "eert"
# Explanation:
# 'e' appears twice while 'r' and 't' both appear once.
# So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
import collections
def frequencySort(s):
res = ""
dic = collections.Counter(s)
for k, v in sorted(dic.items(), key=lambda kv: kv[1], reverse=True):
res += k*v
return res
def frequencySort_oN(s):
counts = collections.Counter(s)
max_freq = max(counts.values())
buckets = [[] for _ in range(max_freq + 1)]
for k, v in counts.items():
buckets[v].append(k)
res_list = []
for i in range(len(buckets) - 1, 0, -1):
for letter in buckets[i]:
res_list.append(i*letter)
return ''.join(res_list)
print(frequencySort("tree"))
print(frequencySort_oN("tree"))
| true |
2051cec1468045a77ed5b48a37962bc149974351 | lambdagirl/leetcode-practice | /delete-node.py | 755 | 4.3125 | 4 | class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
#modify the current node instead of deleting it
def delete_node(node):
if node.next:
node.value = node.next.value
node.next = node.next.next
else:
raise Exception("Can't delete the last node!")
a = LinkedListNode('A')
b = LinkedListNode('B')
c = LinkedListNode('C')
a.next = b
b.next = c
delete_node(b)
print(a.next.value)
#side effect
#1.First, it doesn't work for deleting the last node in the list.
#2.Any references to the input node have now effectively been reassigned to its next node.
#3.If there are pointers to the input node's original next node, those pointers now point to a "dangling" node
| true |
80af9a143b80b9c1b63280985bd99d4cefe6548e | LukeDykstra/2.7-Assessment | /String Slice Excellence.py | 1,367 | 4.21875 | 4 | import random
#this function checks the users name and ensures that it is a valid name
def force_name(message,lower,upper):
while True:
name=str(input(message)).title()
if len(name)>=lower and len(name)<=upper and name.isalpha():
break
else:
print("ERROR,{} No numbers please".format(message))
return name
def force_year(message, lower, upper):
while True:
try:
year= int(input(message))
if year>=lower and year<=upper:
break
else:
print("ERROR! {}, please enter a number between {} - {}".format(lower, upper))
except:
print("ERROR, please enter a number not text")
return year
def user_name_generator():
first_name=force_name("Please enter your first name",2,15)
last_name=force_name("{}, Plaese enter your last name".format(first_name),2,20)
last_name_slice=last_name[0]
date_enrol=force_year("What year did you enrol",2015,2050)
date_enrol=str(date_enrol)
date_enrol = date_enrol[2:4]
random_number=str(random.randint(100,900))
obhs_username=first_name+last_name_slice+"."+date_enrol+random_number
obhs_username = obhs_username.lower()
print("Your user name is: {}".format(obhs_username))
#main program
user_name_generator() | true |
affe66e7a43d81f131f785fd6605491e3ff72f56 | ccaguirre/functions | /releaseSixDrills.py | 2,882 | 4.375 | 4 | '''
Created on Apr 25, 2020
@author: ITAUser
'''
'''
For these drills you will be making functions that use all of the
skills we've covered in the units so far. This includes variables,
math operators, comparison operators, conditional statements, loops,
and functions.
'''
'''
1) Make a function that takes two parameters: a list(list),
and a string(name).
In the function you should make a loop that runs through the list,
and check if the name is in the list. If the name is in the list,
return the name. If the name isn't in the list, return "no".
Once done making the function, make a list of five names, and
a string variable storing another name.
Then call your function, putting in these two variables as the
parameters.
Finally, store what your function returns in another variable and
print out that variable.
'''
def List_Of_Names(name, nmlist):
if name in nmlist:
return name
else:
return "no"
nmlist = ["Garett", "Isaiah", "Jayden", "Nick", "Kobe"]
rightname = "Isaiah"
output = List_Of_Names(rightname, nmlist)
print(output)
'''
2) Make a function that calculates the Pythagorean theorem for
one side of a right triangle.
The Pythagorean Theorem is:
a**2 + b**2 = c**2
Here is a website with more info:
https://en.wikipedia.org/wiki/Pythagorean_theorem
You will also need the sqrt() function. Here is an example:
print(sqrt(4))
The computer would print(it looks weird but it's just 2):
(2+0j)
This can also be stored in variables like:
x = sqrt(4)
You must also copy paste the following line to the top of you code:
from cmath import sqrt
Your function should take two parameters(a and b). Then the function
should solve for c. Once solved, you should return c.
Once done making the function, make two variables for the two
sides of the triangle.
Then call your function, putting in these two variables as the
parameters.
Finally, store what your function returns in another variable and
print out that variable.
'''
from cmath import sqrt
def pytheorem(a, b):
c = sqrt(a**2 + b**2)
return c
Longside = 13
Shortside = 6
Longest = pytheorem(Longside, Shortside)
print(Longest)
'''
3) Make a list that stores 5 integers. Store the following numbers:
25, 55, 65, 70, 80, 90, and 100. Name this list grades.
This list will represent a 7 students grades.
Then, make a function that will check each students grade and print
whether they are passing: 80-100, on probation: 60-80, or failing:
0-60.
The function will have one parameter, which is the grade list. And
the function will return the number of students passing.
Call your function, using the grades list you made as the
parameter.
Finally, store what your function returns in another variable and
print out that variable.
'''
grades = [25, 55, 65, 70, 80, 90, 100]
def checkgrade(thegrades):
x = sum(p >= 80 for p in thegrades)
return x
k = checkgrade(grades)
print(k) | true |
6a9ed04843fc074b0a92670a4f8761e763c100f3 | zaidmsh/cmakefile | /python/codecdemy.py | 530 | 4.21875 | 4 | #!/usr/bin/env python
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
if type(food) == dict:
for item in food:
total += food[item]
elif type(food) == list:
for item in food:
return food[item]
else:
return item
return total
print compute_bill()
| true |
d8f36faa784e171151d8e1ed2666f4ffba8a9d84 | hunterprice04/tensorflow_examples | /hello_world/hello_world.py | 1,623 | 4.125 | 4 | #!/usr/bin/env python3
import tensorflow as tf
import numpy as np
from tensorflow import keras
print("djfhvk")
"""
Keras is an API in TensorFlow that makes it easy to define neural networks.
In keras you use the word Dense to define a layer of connected neurons.
Here, there is only one dense so there is one layer, and units is equal
to 1 so there is only one neuron.
Successive layers are defined in sequence hence the word Sequential.
"""
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
"""
There are two major function rules to be aware of: Loss functions and Optimizers.
The Loss function calculates how good or bad a guess is based off the previous
data its been given.
The Loss function measures the loss then gives the data to the optimizer which gives
the next guess
Here, the loss function is mean squared error and the optimizer is stochastic
gradient descent (sgd).
"""
model.compile(optimizer="sgd", loss='mean_squared_error')
"""
this is the training data that we are passing to the model
Y = 2X + 1
"""
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
"""
Training takes place in the fit command. It fits the model to the data.
epochs is the number of times the model will go through the training loop.
The training loop consists of making a guess, measuring how good or bad
the guesses are (loss function), then use the optimizer and the data to
make another guess.
Here, we are asking the model to fit the X values to the Y values.
"""
model.fit(xs, ys, epochs=500)
print(model.predict([10.0]))
| true |
6e57d15fdfab0a3c69bddb0b636057d174152471 | nidhicpatel/Scripting-Lab | /sl lab finals/8q/8a.py | 592 | 4.21875 | 4 | atoms={"H":"hydrogen",
"Li":"lithium",
"He":"helium",
"B":"boron"
}
print("enter existing element")
symbol=input()
print("enter element name")
element=input()
atoms[symbol]=element
print(atoms)
print("enter new element")
symbol=input()
print("enter element name")
element=input()
atoms[symbol]=element
print(atoms)
print("length of dictionary is",len(atoms))
print("enter the element you want to search")
element=input()
if element in atoms:
print("element found and it is",atoms[element])
else:
print("not found") | true |
18cc242b61205f14f9d644f09d0ef02b0a43bd3e | quyixiao/python_lesson | /object1/PointTest2.py | 983 | 4.4375 | 4 | # 这种动态的修改一个属性的方法和装饰器修饰一个类,差别是什么呢?
# 这些东西他们之前的差异是什么,如果
# 动态的属性修改,是定义是,类定义,继承是在定义的时候就写死了
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "{}:{}".format(self.x, self.y)
def show(self):
print(self.x, self.y)
p = Point(4, 5)
print(p)
setattr(p, 'z', 100)
setattr(p, 'y', 100)
print(p)
setattr(Point, 'x', 200)
print(p)
print(getattr(p, "__dict__"))
print(getattr(Point, "__dict__"))
p.show()
print('--------------------------------------------')
setattr(Point, 'show', lambda self: print(self.x + self.y))
p.show()
print('|||||||||||||||||||||||||||||||||||||')
setattr(p,'show',lambda self : print( self.x ,'-------------' ,self.y))
# 实例上是可以放方法定义
# 我们用自己正常的方法定义
p.show(p)
#
print( hasattr(p,'x')) | false |
58d001ab9ffa126d1cd29ef7b0f9ebc9d87dd0f6 | quyixiao/python_lesson | /map1/pythontest.py | 785 | 4.28125 | 4 | # Python 是动态语言,变量随时可以赋值,且能赋值为不同的类型
# Python 不是静态编译型语言,变量类型是在运行时决定的
# 动态语言很灵活,但是也在这种特性的
#
#
def add(x,y):
"""
:param x:int
:param y:int
:return:int
"""
return x + y
print(add(4,5 ))
print(add('hello ','world '))
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
add(4,'hello')
# 难发现,由于不做任何类型,
# 难使用,函数的使用者看到函数的时候,并不知道你的函数的设计,并不知道应该传入什么类型
# 函数改变了,但是文档没有更新,如果文档没有更新,但是代码改变了,所以最好是阅读源码,对于数学而言
#
| false |
f3355359b0d21efcb57c14582cf4dd42f03e756a | Dagotur/geek-study | /lesson04/homework05.py | 875 | 4.15625 | 4 | # Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from functools import reduce
my_list = [el for el in range(100, 1000) if el % 2 == 0]
all_multiply = reduce(lambda x, y: x * y, my_list)
all_sum = reduce(lambda x, y: x + y, my_list)
print(f"Результат перемножения всех элементов = {all_multiply}")
print(f"Результат сложения всех элементов = {all_sum}")
| false |
c9f4099d99440a981c30196ba6a3ee9c010af3ca | mnabu55/leetcode | /CodingChallenge/2021/02February/17_LetterCasePermutation.py | 1,742 | 4.28125 | 4 | '''
Given a string S, we can transform every letter individually
to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create.
You can return the output in any order.
Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: S = "3z4"
Output: ["3z4","3Z4"]
Example 3:
Input: S = "12345"
Output: ["12345"]
Example 4:
Input: S = "0"
Output: ["0"]
Constraints:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.
'''
from typing import List
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
result = []
def helper(S, i, result):
if i >= len(S) - 1:
if S[i].isalpha():
return [S[i].lower(), S[i].upper()]
else:
return [S[i]]
len_S = len(S)
start = i
while i < len_S and not S[i].isalpha():
i += 1
if i >= len_S:
return [S]
end = i
# tmp_result = helper(S, i + 1, result)
tmp_result = helper(S, i+1, result)
new_result = []
for sub in tmp_result:
new_result.append(S[start:end].lower() + sub)
new_result.append(S[start:end].upper() + sub)
return new_result
result = helper(S, 0, result)
print("result: ", result)
return result
solution = Solution()
assert solution.letterCasePermutation("a1b2") == ["a1b2","a1B2","A1b2","A1B2"], "case01,ng"
assert solution.letterCasePermutation("12345") == ["12345"], "case02,ng"
assert solution.letterCasePermutation("37c") == ["37c", "37C"], "case03,ng"
| true |
1f2003faeb5dc5799ab12f3a6b71e48fb3b56f63 | mnabu55/leetcode | /problemset/09PalindromeNumber.py | 1,076 | 4.375 | 4 | '''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
reverse = s[::-1]
for i in range(len(s)):
if s[i] != reverse[i]:
return False
return True
def isPalindrome2(self, x: int) -> bool:
return str(x) == str(x)[::-1]
def isPalindrome3(self, x: int) -> bool:
return False if x < 0 else x == int(str(x)[::-1])
solution = Solution()
assert solution.isPalindrome3(-121) == False, "case 1 ng"
assert solution.isPalindrome3(10) == False, "case 2 ng"
assert solution.isPalindrome3(121) == True, "case 3 ng"
| true |
ec6d12dc019ab58baf3d86a3130127826c0aad27 | GauravBhardwaj/pythonDS | /28questionsbyArdenDertat/3FindMissingElement.py | 2,495 | 4.28125 | 4 | #There is an array of non-negative integers.
#A second array is formed by shuffling the elements of the first array and
#deleting a random element.Given these two arrays, find which element is
#missing in the second array
import timeit
def find_missing_element1(arr1,arr2):
'''
brute force, check if element in first is in others
Time complexity: O(n2) but considering the complexity of search in list as O(n)
Space complexity: O(1)
'''
for num in arr1:
if not num in arr2:
return num
def find_missing_element2(arr1, arr2):
'''
create set of both list and find the substraction, its like using inbuilt methods
Time complexity: O(n) as set diffrence says, its depends on len(s)
Space complexity: O(1)
'''
set1 = set(arr1)
set2 = set(arr2)
set3 = set1-set2
return set3
def find_missing_element3(arr1, arr2):
'''
since all array numbers are positive , diffrence of sum of both array
Time complexity: O(n), depends on sum function actually
Space complexity: O(1)
'''
sum1 = sum(arr1)
sum2 = sum(arr2)
return sum1-sum2
def find_missing_element4(arr1, arr2):
'''
Time complexity: O(n), depends on sum function actually
Space complexity: O(1)
'''
result = 0
for num in arr1+arr2:
result ^= num
return result
arr1 = [4,1,0,2,9,6,8,7,5,3]
arr2 = [6,4,7,2,1,0,8,3,9]
#test 1
print find_missing_element1(arr1, arr2)
t1 = timeit.Timer("find_missing_element1([4,1,0,2,9,6,8,7,5,3], [6,4,7,2,1,0,8,3,9])","from __main__ import find_missing_element1")
print "algo1: ", t1.timeit()
#test 2
print find_missing_element2(arr1, arr2)
t2 = timeit.Timer("find_missing_element2([4,1,0,2,9,6,8,7,5,3], [6,4,7,2,1,0,8,3,9])","from __main__ import find_missing_element2")
print "algo2: ", t2.timeit()
#test3
print find_missing_element3(arr1, arr2)
t3 = timeit.Timer("find_missing_element3([4,1,0,2,9,6,8,7,5,3], [6,4,7,2,1,0,8,3,9])","from __main__ import find_missing_element3")
print "algo3: ", t3.timeit()
#test4
print find_missing_element4(arr1, arr2)
t4 = timeit.Timer("find_missing_element4([4,4,1,0,2,9,6,8,7,5,3], [6,4,4,7,2,1,0,8,3,9])","from __main__ import find_missing_element4")
print "algo4: ", t4.timeit()
#algo1: 1.05260896683
#algo2: 1.42342090607
#algo3: 0.73545217514
#algo4: 1.49461483955
#conclusion says algo3 is fastest but it doesnt handles duplicate, which is a drawback,
#so the bit manipulation works best in duplicate handling
| true |
85d48e9b22fa11ed7caa09b66149962913e41848 | Faizmuazzam/A_E31190648_Faiz_Muazzam_Data_Warehouse | /Project/Konsep_Data_Warehouse/Tugas/Latihan_1.py | 378 | 4.125 | 4 | # Buat Sebuah list untuk menyimpan kenalanmu
# Isi list sebanyak 5
kenalan = ["Naufal","Retsa","Salvation","Rijal","Imel"]
#Tampilkan isi list index no 3
print("Nilai Index ke-3 -->",kenalan[3])
# Tampilkan panjang list
print ("Semua Kenalan Ada :",len(kenalan),"Orang")
# Tampilkan semua teman dengan perulangan
print("Menampilkan semua data :")
for i in kenalan:
print(i)
| false |
8acf48b296a3b9362f47b6ce3f03ed48a85ce85c | mmweber2/adm | /factor/sieve.py | 817 | 4.21875 | 4 | def sieve(n):
"""Returns a list of all prime numbers between 2 and n (inclusive).
Args:
n: integer, the number up to which to find prime numbers.
Must be greater than 1.
Returns:
A list of integer primes between 2 and n.
Raises:
ValueError: n is < 2.
"""
if n < 2:
raise ValueError("cannot search for primes < 2")
possible_primes = range(n + 1)
# Allow 0-indexing by filtering non-prime initial numbers
possible_primes[0] = None
possible_primes[1] = None
for i in xrange(2, int(n**0.5) + 1):
# Don't check multiples of non-prime numbers
if possible_primes[i] is None:
continue
for j in xrange(i * 2, n + 1, i):
possible_primes[j] = None
return filter(None, possible_primes)
| true |
23125a85dce89c7cbfaccd50ecc5a211a31eb80a | mmweber2/adm | /priority/heap.py | 2,942 | 4.28125 | 4 | class Heap(object):
"""A data structure of ordered keys with quick access to the
smallest key in the set.
The default comparator is used.
"""
def __init__(self):
# Start with a never-used 0 as index 0 for easy integer division,
# multiplication, and indexing.
self.heap_list = [0]
def push(self, value):
"""Add an item to the heap."""
self.heap_list.append(value)
self._heap_up()
def size(self):
"""Returns the number of items in the Heap.
A newly created Heap is of size 0.
"""
return len(self.heap_list) - 1
def peek(self):
"""Returns the smallest item in the Heap without altering it.
Raises an IndexError if the Heap is empty.
"""
if self.size() == 0:
raise IndexError("No items on the heap.")
return self.heap_list[1]
def _heap_up(self):
"""For push; move a newly added value from the end of the
array up to its proper index.
"""
# Always start at the (newly added) last item of the array.
index = self.size()
# Checking for index / 2 > 0 means that we never alter the
# base 0 at index 0.
while index / 2 > 0:
if self.heap_list[index] < self.heap_list[index / 2]:
self.heap_list[index], self.heap_list[index / 2] = (
self.heap_list[index / 2], self.heap_list[index])
index /= 2
def _heap_down(self):
"""For pop; move a newly swapped value down from the root to
its proper index.
"""
# Always start at the (newly changed) root.
index = 1
# Move down until the node doesn't have any children.
while index * 2 <= self.size():
smaller_child = self._min_child(index)
if self.heap_list[index] > self.heap_list[smaller_child]:
self.heap_list[index], self.heap_list[smaller_child] = (
self.heap_list[smaller_child], self.heap_list[index])
index = smaller_child
def _min_child(self, index):
"""Return the index of the smallest of a node's children."""
index *= 2
# If index now equals size(), the node only has one child.
if index < self.size() and (
self.heap_list[index] > self.heap_list[index + 1]):
index += 1
return index
def pop(self):
"""Removes and returns the smallest item in the Heap.
Raises an IndexError through peek() if the Heap is empty.
"""
# Rely on peek() for heap size checking and getting the element.
minimum = self.peek()
# Position last item as new root
self.heap_list[1] = self.heap_list[self.size()]
# Remove last list item using list's pop, not this method.
self.heap_list.pop()
self._heap_down()
return minimum
| true |
df33db10cdadafac48c47cf0746fc9ebdd8e2677 | andrei406/Meus-PycharmProjects-de-Iniciante | /PythonExercicios/Aula18.py | 1,502 | 4.1875 | 4 | #Se colocar uma estrutura dentro de uma outra estrutura, se mudada-la, onde ela for colocada, também
"""test = list()
test.append('Gustavo')
test.append(40)
galera = list()
galera.append(test)
test[0] = 'Maria'
test[1] = 22
galera.append(teste)
print(galera)"""
#Para evitar isso, basta copiar a lista em vez de colocar dentro de outra
"""test = list()
test.append('Gustavo')
test.append(40)
galera = list()
galera.append(test[:])
test[0] = 'Maria'
test[1] = 22
galera.append(test[:])
print(galera)"""
#Outra forma de adicionar é assim
galera = [['João', 19], ['Ana', 33], ['Joaquin', 13], ['Maria', 45]]
#print(galera)
#print(galera[0])
#print(galera[0][0])
"""for p in galera:
print(p)
for p in galera:
print(p[0])
for p in galera:
print(f'{p[0} tem {p[1} anos de idade')
"""
#Aqui vai exibir os nomes.txt que der, vai copiar e vai exibir, se colocasse, assim que desse clear, ía ficar tudo vázio
"""galera = list()
dado = list()
totm = totme = 0 #Só da para declarar váriaveis simples assim, se fizer isso com as compostar, bem, se alterar uma, altera tudo
for c in range(0,5):
dado.append(str(input('Nome: ')))
dado.append(int(input('Idade: ')))
galera.append(dado[:])
dado.clear()
print(galera)
#Para exibir apenas os maiores
for p in galera:
if p[1] >= 18:
print(f'{p[0]} é maior de idade')
totm += 1
else:
print(f'{p[0]} é menor de idade')
totme += 1
print(f'O total de menor foi {totme} e o de maior {totm}')""" | false |
1d1bd74b7471d108e0a18a9f52495769a3e304a8 | andrei406/Meus-PycharmProjects-de-Iniciante | /PythonExercicios/ex057.py | 268 | 4.125 | 4 | s = str(input('Digite o seu sexo [M/F]: ')).upper()[0].strip()
while not 'M' and 'F' in s:
print('Só aceito M ou F para o sexo\nM para masculino e F para feminino!')
s = str(input('Digite novemente seu sexo [M/F]: ')).upper()
print('Seu sexo foi registrado!') | false |
96f2fc556ca1ce122106f7e273248df3dcc18c13 | andrei406/Meus-PycharmProjects-de-Iniciante | /CursoemVídeo/Aula 19.py | 1,266 | 4.1875 | 4 | #Básicão
"""pessoas = {'nomes' : 'Gustavo', 'sexo' : 'M', 'idade' : 22}
print(pessoas)
print(pessoas['nomes'])
#Qundo se quer utilizar aspas de aspas, use duplas se estiverem dentro de unicas e assim vice-versa
print(f'O {pessoas["nomes"]} tem {pessoas["idade"]} anos.')
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for k in pessoas.keys():
print(k)
print()
#print() quebra linha
#Nos dicionairos não utiliza o enumerate, mas sim os itens
for k, v in pessoas.items():
print(f'{k} = {v}')
del pessoas['sexo']
pessoas['nomes'] = 'Leanro'
pessoas['peso'] = 98.5"""
#diciónarios dentro de listas
"""brasill = list()
estado1 = {'uf': 'Rio de Janeiro', 'sigla' : 'RJ'}
estado2 = {'uf' : 'São Paulo', 'sigla' : 'SP'}
brasill.append(estado1)
brasill.append(estado2)
print(brasill[0]['sigla'])
"""
#Caracteristica legal
estado = dict()
brasil = list()
for c in range(0, 3):
estado['uf'] = str(input('Unidade Federativa: '))
estado['sigla'] = str(input('Sigla do estado: '))
#Como em uma lista para copiar tem que usar [:] em dicionarios é.copy()
brasil.append(estado.copy())
"""print(brasil)
for e in brasil:
print(e)"""
for e in brasil:
""""for k, v in e.items():
print(f'O campo {k} tem valor {v}')"""
| false |
40f797128b296bd3970c2677bd1387f159cf16fd | ekolik/-Python-Project_Euler | /3-largest_prime.py | 594 | 4.125 | 4 | n = rawn = raw_input()
n = int (n)
def prime_factors(n):
"""Returns all the prime factors of a positive integer"""
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n /= d
d = d + 1
if d*d > n:
if n > 1: factors.append(n)
break
return factors
numbers = [raw_input() for i in range(n)]
for i in range (n):
number = int (numbers[i])
pfs = prime_factors(number)
largest_prime_factor = max(pfs) # The largest element in the prime factor list
print largest_prime_factor
| true |
0ce0b9eebc7742675f8eb02a0962e848ec291e4f | DaDudek/Monopoly | /hidden_card_reader.py | 1,906 | 4.34375 | 4 | from hidden_card import HiddenCard
class HiddencardReader:
"""
This is a class for create hidden card from csv file
Attributes:
file -> csv file where are information about all hidden cards
"""
def __init__(self, file):
"""
The constructor for HiddencardReader class.
:param file: csv file where are information about all hidden cards
list_of_hidden_card: (list) : when reader create card its append her here
"""
self.file = file
self.list_of_hidden_card = []
def make_hidden_cards(self,):
"""
The function to create all hidden cards - main function of that class
This function read all lines from file, split it and create card
:return: void -> only change object
"""
tmp = 0
for line in self.file:
if tmp:
line.strip()
counter = 0
name = ""
card_type = ""
value = 0
info = ""
for word in line.split(","):
if counter == 0:
name = word
elif counter == 1:
card_type = word
elif counter == 2:
if word == "transport" or word == "power_station":
value = word
else:
if int(word) > 40:
value = int(word) * 1000
else:
value = int(word)
elif counter == 3:
info = word
counter += 1
card = HiddenCard(name, card_type, value, info)
self.list_of_hidden_card.append(card)
tmp += 1
return self.list_of_hidden_card
| true |
0cbd73e150e01ca62d0121392abcd1412f92ff5c | JAbrokwah/python-projects | /caesar-cipher/main.py | 634 | 4.15625 | 4 | from caesar_cipher import caesar_cipher
from exceptions import InvalidKeyException, InvalidModeException
if __name__ == "__main__":
print("Welcome to the Caesar Cipher!")
string = input("Please enter the string to encode/decode: ")
key = input("Please enter the key to encode/decode with: ")
mode = input("Please select 1 for encryption, or 2 for decryption: ")
try:
cipher = caesar_cipher(int(key), string, int(mode))
# output info to user
print("Your ciphered string is: {}".format(cipher))
except (InvalidKeyException, InvalidModeException) as error:
print(error.args[0])
| true |
add4e6b37c52662ba1970bb182168f756c7b4c3a | siddha091/practice | /question6.py | 525 | 4.21875 | 4 | '''
Write a program that maps a list of words into a list of integers representing the lengths of the correponding words
'''
def map_to_lengths_for(words):
lengths = []
for word in words:
lengths.append(len(word))
return lengths
def map_to_lengths_map(words):
return map(len, words)
def map_to_lengths_lists(words):
return [len(word) for word in words]
words = ['sid', 'i am here', 'test']
print map_to_lengths_for(words)
print map_to_lengths_map(words)
print map_to_lengths_lists(words) | true |
b6442cebf2dfdf89f6205853cd47c74985d27960 | OguzHaksever/UdemyPython3.9 | /conditions.py | 218 | 4.125 | 4 | age = int(input("How old are you? "))
if 16 <= age <= 65: # print if i in range (16, 66) aynı sonucu çıkarır
print("Have a good day at work.")
else:
print("You shouldn't be working.")
| false |
8d8ae1098f3388d1aa6c43b109702a48de55b2bd | OguzHaksever/UdemyPython3.9 | /formatting.py | 668 | 4.28125 | 4 | for i in range (1,13):
print("No. {0:2} squared is {1:<3} and cubed is {2:^4}".format(i, i** 2, i**3))
# İki noktadan sonraki sayı karakter boşluğu sayısı, okumayı kolaylaştırmak için
print()
print("Pi is approximately {0:12}".format(22/7)) # General format, 15 decimals
print("Pi is approximately {0:12f}".format(22/7)) # floating point value, 6 digit decimal
print("Pi is approximately {0:<52.50f}".format(22/7)) # floating point format with 50 decimal precision
print("Pi is approximately {0:<62.50f}".format(22/7)) #
print("Pi is approximately {0:<72.50f}".format(22/7)) # Maximum precision is between 51 - 53 decimals
| false |
f3aaa6ae7a9a57946bdb035a4d52e84541c1a292 | urbanfog/python | /100DaysofPython/Day19/turtle_race.py | 1,271 | 4.21875 | 4 | import turtle
from turtle import color
import random
screen = turtle.Screen()
screen.setup(width=500, height=400)
colours = ["red", "pink", "blue", "purple", "black", "green"]
y_pos = [100, 60, 20, -20, -60, -100]
user_bet = screen.textinput(title="Make your bet",
prompt="Which turtle will win? Choose a colour: ")
is_race_on = False
all_racers = []
class Racer(turtle.Turtle):
# def __init__(self, color, x, y):
def __init__(self, color, x, y):
super().__init__(shape="turtle")
self.color(color)
self.penup()
self.goto(x=x, y=y)
def race(self):
self.forward(random.randint(0, 10))
for i in range(0, 6):
racer = Racer(colours[i], -230, y_pos[i])
all_racers.append(racer)
if user_bet:
is_race_on = True
while is_race_on:
for racer in all_racers:
if racer.xcor() > 230:
is_race_on = False
winning_colour = racer.pencolor()
if winning_colour == user_bet:
print(
f"You won! The winning turtle colour was {winning_colour}.")
else:
print(
f"You lost! The winning turtle colour was {winning_colour}.")
racer.race()
screen.exitonclick()
| true |
104852d90595af1afb52297093edb0726ad1cc61 | C8230Ahmet/python | /artık-yıl.py | 225 | 4.15625 | 4 | year = int(input("Enter the year : "))
if year % 4 != 0 : print(year, "is not a leap year")
elif year % 100 != 0 or year % 100 == 0 and year % 400 == 0: print(year, "is a leap year")
else: print(year, "is not a leap year") | false |
eed11e47b9f2080bf58b2624ce818ce65d29edcb | coderZsq/coderZsq.practice.data | /study-notes/py-collection/11_列表/01_基本使用.py | 457 | 4.25 | 4 | # 创建一个列表(列表是一个可迭代对象)
scores = [
88, 75, 69, 93, 100,
43, 72, 51, 85, 77
]
# 计算平均分
print(f'平均是{sum(scores) / len(scores)}')
# # 计算总分
# total = 0
# # 遍历列表中的所有元素
# for i in scores:
# total += i
#
# # 计算平均分
# avg = total / len(scores)
# print(f'平均是{avg}')
# len('456') == 3
# 查看类型 <class 'list'>
# print(type(scores))
| false |
1ce42827560f455e4f1a33dbf6c644565c5dd546 | newmansw93/intro_to_python_solns | /week3/day5-intro_to_functions/hard_functions_assignment/check_ending_letters.py | 1,036 | 4.1875 | 4 | def filter_by_end_letter(string_lst, check_letter):
"""Filter the string list to those words that end with the check_letter.
Args:
string_lst: List of strings
check_letter: String (one letter)
"""
output_lst = []
for string in string_lst:
if string.endswith(check_letter):
output_lst.append(string)
'''List comp. way
output_lst = [string for string in string_lst
if string.endswith(check_letter)]
'''
return output_lst
print(filter_by_end_letter(['I', 'am', 'in', 'love', 'with', 'python'], 'n'))
# Should return ['in', 'python']
print(filter_by_end_letter(['Python', 'is', 'amazing'], 'g'))
# Should return ['amazing']
print(filter_by_end_letter(['This', 'is', 'a', 'silly', 'question'], 's'))
# Should return ['This', 'is']
print(filter_by_end_letter(['Hello', 'goodbye'], 'g'))
# Should return []
print(filter_by_end_letter(['Statistics', 'is' , 'kind', 'of', 'fun', 'sometimes'], 's'))
# Should return ['Statistics', 'is', 'sometimes']
| false |
fcecef9bd678dfac26a09e315675bd6c3c8af8ee | newmansw93/intro_to_python_solns | /week3/day5-intro_to_functions/hard_functions_assignment/check_for_substring.py | 1,310 | 4.3125 | 4 | def check_for_substring(lst_of_strings, substring):
"""Output a list of indices for those strings in lst_of_strings
that contain the inputted substring.
For each string in the lst_of_strings, see if the inputted substring
is contained within that string. If it is, output its index, and if it's
not, then don't.
Args:
lst_of_strings: List of Strings
substring: String
"""
output_lst = []
for idx, string in enumerate(lst_of_strings):
if substring in string:
output_lst.append(idx)
'''List comp. way
output_lst = [idx for idx, string in enumerate(lst_of_strings)
if substring in string]
'''
return output_lst
print(check_for_substring(['This', 'is', 'an', 'example'], 'is'))
# Should return [0, 1]
print(check_for_substring(["Let's", 'try', 'another', 'example'], 'Le'))
# Should return [0]
print(check_for_substring(["Well", "input", 'a', 'really', 'long', 'string', 'here', 'with', 'a', 'bunch', 'of', 'words', ',', 'which', 'will', 'give', 'us', 'a', 'long', 'test'], 'll'))
# Should return [0, 3, 14]
print(check_for_substring(['Now', 'back', 'to', 'a', 'shorter', 'list', 'tack'], 'ack'))
# Should return [1, 6]
print(check_for_substring(['Test', 'for', 'nothing'], 'zada'))
# Should return []
| true |
86b9ca6628080631419d033d03afe824514ca31d | newmansw93/intro_to_python_solns | /week3/day5-intro_to_functions/hard_functions_assignment/factorial.py | 373 | 4.375 | 4 | def calc_factorial(n):
"""Calculate the factorial of the inputted number.
Args:
n: Integer
"""
factorial = 1
for num in range(1, n + 1):
factorial *= num
return factorial
print(calc_factorial(5)) # 120
print(calc_factorial(3)) # 6
print(calc_factorial(2)) # 2
print(calc_factorial(6)) # 720
print(calc_factorial(1)) # 1
| true |
79b2ade0e566ed9318766d1eedcaecf03531364c | newmansw93/intro_to_python_solns | /week3/day5-intro_to_functions/hard_functions_assignment/word_count2.py | 767 | 4.4375 | 4 | def get_word_count(input_str, delimiter=' '):
"""Get the word count for the inputted string.
Get the word count for the inputted string, where we consider
words to be separated by the input delimiter (space by default).
Args:
input_str: String
delimiter: String
"""
words = input_str.split(delimiter)
word_count = len(words)
return word_count
print(get_word_count("separate,by,commas", ",")) # Should be 3.
print(get_word_count("Lets;try;using;semi;colons", ";")) # Should be 5.
print(get_word_count("What?about?using?question?marks", "?")) # Should be 5.
print(get_word_count("That was weird, let's go back to spaces.")) # Should be 8.
print(get_word_count("Check passing in a space now.", ' ')) # Should be 6.
| true |
cf360e32907be176759ad9cd04881afd2794027b | newmansw93/intro_to_python_solns | /week2/day3-beyond_numerics/remove_vowels.py | 338 | 4.5 | 4 | user_str = input('Please enter a string for us to remove the vowels from: ')
vowels = {'a', 'e', 'i', 'o', 'u'}
# One way to do this.
for vowel in vowels:
user_str = user_str.replace(vowel, '')
# Probably the most efficient way to do this.
user_str = ''.join(letter for letter in user_str if letter not in vowels)
print(user_str)
| true |
276f44a78ac5626283a408970d871966ca9cb75a | blip-lorist/interview-prep | /week-3/string_compression.py | 2,081 | 4.34375 | 4 | def string_compression_recursive(string, start):
'''
4. Implement a method to perform a basic string compression using the counts of repeated
characters. For example, the string aabccccaaa would become a2b1c4a3. If the compressed string would not become smaller than the original string, your method should return the original string.
'''
# Base case: When compression length (uniques X 2) will be > string length
# Base case: When start value is the end of the string
if start >= len(string):
return string
else:
string = list(string)
count = 0
# Look at the start value
current_letter = string[start]
# Iterate
for i in range(start, len(string)):
# If dups are found, increment counter the number of times this value occurs
if string[i] == current_letter and i == len(string) - 1:
count += 1
end = i + 1
break
elif string[i] == current_letter:
count += 1
else:
# If unique or string end is found, record this as the end and stop
end = i
break
# Remove dups, replace with current letter and count
if count > 0:
del string[start:end]
string.insert(start, str(count))
string.insert(start, current_letter)
string = ''.join(string)
# Recurse with new start location
return string_compression_recursive(string, start + 2)
def compression_wrapper(string):
'''
Checks the string once to see if there's any point for compression.
If the original string length < unique letters * 2, then there is
no reason to compress the string.
'''
unique_count = len(set(string))
if unique_count * 2 > len(string):
print string
else:
print string_compression_recursive(string, 0)
# Examples
compression_wrapper('asdf')
compression_wrapper('aasdfff')
compression_wrapper('aasddfff')
compression_wrapper('aaaddfffff')
| true |
7b217950aac32050f45c730889c2a05506c731cf | abouthugo/socket | /udp_helper/Server.py | 2,762 | 4.21875 | 4 | # App functionality for the UDP server.
"""
The compute function:
- Defines an array of valid operands that a client might use. Called [operands]
- Creates a copy of the string passed in into an array. Called [array]
- Flush out the previous value for the string passed in [y].
- Loop through the array for validation:
- if the character at index (s) is in [operands] or is a period or is a digit
then we add that character to the empty string
Notice that when we do not add a character we might encounter Syntax errors
For example if user enters "3*c+d" the array will return "3*+" and when the
eval() function is called it will result in a Syntax error.
Similarly in other instances it could result in an EOF error, thus we surround the
last steps with a try-catch clause
- We first try to evaluate the string and test if the result is a float
- If it is a float
then: format the string to only have 2 decimals and
report back to the program that called the function.
else: simply evaluate the string and report back to the program
that called the function
- When the program encounters an exception it reports to the user that
the expression entered was invalid.
"""
def compute(y):
operands = ['+', '-', '*', '/', '**', '%', '(', ")", "^"]
expr = [letter for letter in y]
y = ''
'''
TODO:
------
Make 10(10) work
'''
for s in expr:
if s in operands or s == '.' or type(s) == int or s.isdigit():
if s == '^': # User might be allowed to enter '^'
s = '**' # and it will be interpreted as '**'
y += str(s)
try:
if isinstance(eval(y), float):
y = f'{eval(y):.2f}'
if '.00' in y: # trimming purposes
y = y.split('.')[0]
return y
else:
return str(eval(y))
except (SyntaxError, EOFError, TypeError):
y = f'\tYour expression is invalid, you can only use operands: \n\t{operands} and digits 0-9'
return y
"""
The run_service function...
- Wait for data from client, the source ip becomes the destination ip
- Decode data and check if user wants to quit
- Manipulate the data and execute the compute function on the data received
- Encode the result and send to destination
- If user exists print a message to let the server know
"""
def run_service(socket, size):
expression, destination = socket.recvfrom(size)
expression = expression.decode('utf-8')
if expression.lower() != 'q':
expression = compute(expression)
socket.sendto(expression.encode(), destination) | true |
34a9f4e37693af9ae56d19c74eb225325d7caeda | abdieldeathayde/Entra21 | /exerciciosWhileComRepeticaoDia29042021.py | 1,821 | 4.15625 | 4 | import math
"""
def verificaNumeroPrimo(numero):
if (numero % 1 == 0 and numero % numero == 0 and numero % 2 != 0 and numero % 3 != 0 and numero % 5 != 0 and numero != 1):
print("Primo")
else:
print("Não primo")
#verificaNumeroPrimo(15)
"""
def primo(n):
if (n == 2 or (n!= 1 and n % 2 == 1)):
é_primo = True
else:
é_primo = False
divisão = 3
while (divisão < n // 2 and é_primo):
if (n % divisão == 0):
é_primo = False
divisão += 2
if (é_primo):
print("Primo");
else:
print("Não primo");
primo(int(input("digite um numero: ")))
"""
def verificaDigito():
#verificador de numeros adjacentes iguais
numero = int(input("Digite um valor inteiro: "))
if (numero >= 10 and numero < 100):
digito1 = numero // 10
digito2 = numero % 10
if (digito1 == digito2):
print("Sim")
else:
print("Não")
elif (numero >= 100 and numero < 1000):
while(numero > 0):
digito = numero % 10
digito2 = int(numero // 10)
digito3 = numero//100
print(str(digito) + " " + str(digito2) + str(digito3))
else:
print("não")
verificaDigito()
"""
def verificadorDeNumerosIdenticos():
numero_salvo = n = int(input("Digite um numero: "))
anterior = n % 10
n = n // 10
adjacente_iguais = False
posterior = 0
while (n > 0 and not adjacente_iguais):
atual = n % 10
if (atual == anterior):
adjacente_iguais = True
else:
posterior += 1
anterior = atual
n = n // 10
if adjacente_iguais:
print("Sim")
else:
print("Não")
verificadorDeNumerosIdenticos()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.