blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
8ae3139d0ed27e930f4f557dee20b5bdfeb1e17a | tdnzr/project-euler | /Euler062.py | 1,443 | 3.578125 | 4 | # Solution to Project Euler problem 62 by tdnzr.
# I originally tried a solution based on going through all permutations of a cube,
# and testing if these permutations were also cubes. But this was impossibly slow.
# In contrast, this solution is based on the insight that there was no need to compute all permutations.
# In contrast to the original attempt, this solution yields the correct result in just 0.2s.
from collections import Counter
def run():
# Make a list of cubes, then sort all cubes by their digits, in ascending order.
# This makes the later permutation tests trivial.
listOfCubes = [i**3 for i in range(1, 10000)]
sortedCubes = ["".join(sorted(str(cube))) for cube in listOfCubes]
# Count how often each cube appears, then find five-fold duplicates:
counter = Counter(sortedCubes)
sortedCandidates = [number for (number, amount) in counter.items()
if amount == 5]
# Find the corresponding sorted numbers in sortedCubes. Because their indices haven't changed,
# I can re-compute the corresponding un-sorted number by taking the cube of their positions in the list.
actualCandidates = [(sortedCubes.index(i) + 1) ** 3
for i in sortedCandidates if i in sortedCubes]
return min(actualCandidates)
if __name__ == "__main__":
print(f"{run()} is the smallest cube for which exactly five permutations of its digits are cube.")
|
78450343ff4ac303b8dbbcd5218fa1de9dc8946d | Joey-Rose/oxycsbot | /chatbot.py | 6,078 | 3.765625 | 4 | """A tag-based chatbot framework."""
import re
from collections import Counter
class ChatBot:
"""A tag-based chatbot framework.
This class is not meant to be instantiated. Instead, it provides helper
functions that subclasses could use to create a tag-based chatbot. There
are two main components to a chatbot:
* A set of STATES to determine the context of a message.
* A set of TAGS that match on words in the message.
Subclasses must implement two methods for every state (except the
default): the `on_enter_*` method and the `respond_from_*` method. For
example, if there is a state called "confirm_delete", there should be two
methods `on_enter_confirm_delete` and `respond_from_confirm_delete`.
* `on_enter_*()` is what the chatbot should say when it enters a state.
This method takes no arguments, and returns a string that is the
chatbot's response. For example, a bot might enter the "confirm_delete"
state after a message to delete a reservation, and the
`on_enter_confirm_delete` might return "Are you sure you want to
delete?".
* `respond_from_*()` determines which state the chatbot should enter next.
It takes two arguments: a string `message`, and a dictionary `tags`
which counts the number of times each tag appears in the message. This
function should always return with calls to either `go_to_state` or
`finish`.
The `go_to_state` method automatically calls the related `on_enter_*`
method before setting the state of the chatbot. The `finish` function calls
a `finish_*` function before setting the state of the chatbot to the
default state.
The TAGS class variable is a dictionary whose keys are words/phrases and
whose values are (list of) tags for that word/phrase. If the words/phrases
match a message, these tags are provided to the `respond_from_*` methods.
"""
STATES = []
TAGS = {}
def __init__(self, default_state):
"""Initialize a Chatbot.
Arguments:
default_state (str): The starting state of the agent.
"""
if default_state not in self.STATES:
print(' '.join([
f'WARNING:',
f'The default state {default_state} is listed as a state.',
f'Perhaps you mean {self.STATES[0]}?',
]))
self.default_state = default_state
self.state = self.default_state
self.tags = {}
self._check_states()
self._check_tags()
def _check_states(self):
"""Check the STATES to make sure that relevant functions are defined."""
for state in self.STATES:
prefixes = []
if state != self.default_state:
prefixes.append('on_enter')
prefixes.append('respond_from')
for prefix in prefixes:
if not hasattr(self, f'{prefix}_{state}'):
print(' '.join([
f'WARNING:',
f'State "{state}" is defined',
f'but has no response function self.{prefix}_{state}',
]))
def _check_tags(self):
"""Check the TAGS to make sure that it has the correct format."""
for phrase in self.TAGS:
tags = self.TAGS[phrase]
if isinstance(tags, str):
self.TAGS[phrase] = [tags]
tags = self.TAGS[phrase]
assert isinstance(tags, (tuple, list)), ' '.join([
'ERROR:',
'Expected tags for {phrase} to be str or List[str]',
f'but got {tags.__class__.__name__}',
])
def go_to_state(self, state):
"""Set the chatbot's state after responding appropriately.
Arguments:
state (str): The state to go to.
Returns:
str: The response of the chatbot.
"""
assert state in self.STATES, f'ERROR: state "{state}" is not defined'
assert state != self.default_state, ' '.join([
'WARNING:',
f"do not call `go_to_state` on the default state {self.default_state};",
f'use `finish` instead',
])
on_enter_method = getattr(self, f'on_enter_{state}')
response = on_enter_method()
self.state = state
return response
def chat(self):
"""Start a chat with the chatbot."""
try:
message = input('> ')
while message.lower() not in ('exit', 'quit'):
print()
print(f'{self.__class__.__name__}: {self.respond(message)}')
print()
message = input('> ')
except (EOFError, KeyboardInterrupt):
print()
exit()
def respond(self, message):
"""Respond to a message.
Arguments:
message (str): The message from the user.
Returns:
str: The response of the chatbot.
"""
respond_method = getattr(self, f'respond_from_{self.state}')
return respond_method(message, self._get_tags(message))
def finish(self, manner):
"""Set the chatbot back to the default state.
This function will call the appropriate `finish_*` method.
Arguments:
manner (str): The type of exit from the flow.
Returns:
str: The response of the chatbot.
"""
response = getattr(self, f'finish_{manner}')()
self.state = self.default_state
return response
def _get_tags(self, message):
"""Find all tagged words/phrases in a message.
Arguments:
message (str): The message from the user.
Returns:
Dict[str, int]: A count of each tag found in the message.
"""
counter = Counter()
msg = message.lower()
for phrase, tags in self.TAGS.items():
if re.search(r'\b' + phrase.lower() + r'\b', msg):
counter.update(tags)
return counter
|
71e384765b953861bc117a642d436323136038d3 | Kathain/PythonRep | /myLessonPython/Lesson4.py | 1,843 | 3.8125 | 4 | #тут будем изучать что такое list , это список где можно хранить инфу
l = []
lis = [1, 54, 'x', 32, 2.44, ['S', 'T', 'R', 'O', 'K', 'A']]
print(lis)
#list можно заполнять с помощью циклов и др условных операторов
a = [a + b for a in 'list' if a != 's' for b in 'soup' if b != 'u']
print (a)
# .append добавляет элемент в конец списка
# .extend это функция которая помогает расширить список добавляя в его конец все эелементы списка
# .insert добавляет элемент в по индексу (первый элемент в списке всегда под номером ноль). НАПРИМЕР - 1 элемент заменяем числом 34 тогда - l.insert(1, 56)
# .remove она удаляет первый элемент в списке
# .pop она удаляет элемент . (если ничего не указываем то удаляет последний элемент) - эелемнент указываем по индексу
# .index эта функция показывает номер индекса элемента и указывается всегда через print
# .count возвращает количество элементов в списке print(l.count(56)) - сколько в списке чисел 56
# .sort она сортирует список на основе функции
# .reverse - переворачивает весь наш массив
# .clear очищает весь список
l.append(23)
l.append(34)
b = [24, 67]
l.extend(b)
l.insert(1, 56)
l.remove(34)
l.pop()
print(l.index(56))
print(l.count(56))
l.sort()
l.reverse()
l.clear()
print(l) |
961837328193c44cbddd4526543387d6f9adc868 | ArkadiyShkolniy/python_lesson_2 | /2.py | 350 | 3.875 | 4 | # Задача 2
# Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5.
sum=0
for i in range(10):
answer = int(input('Введите любую цифру'))
if answer==5:
sum+=1
print('Количество цифр пять:', sum)
|
9577c5965b44eb26c28f31f14e76239d1123d82d | angryBird2014/leetcode | /climp stairs.py | 448 | 3.703125 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
data = [1] * (n+1)
for i in range(1,n+1):
if i == 1:
data[1] = 1
elif i ==2:
data[2] = 2
else:
data[i] = data[i-1] + data[i-2]
return data[n]
if __name__ == '__main__':
sol = Solution()
print(sol.climbStairs(3)) |
34b80a8dbe984fe3ba39768d8c24c09b834c56bf | pchecinski/losowe-projekty | /sz-int-wsb/lab10/main.py | 939 | 3.71875 | 4 | import nltk
nltk.download('punkt')
nltk.download('stopwords')
from nltk.tokenize import sent_tokenize
text="""Hello Mr. Smith, how are you doing today? The weather is great, and city is awesome.
The sky is pinkish-blue. You shouldn't eat cardboard"""
tokenized_text=sent_tokenize(text)
print(tokenized_text)
from nltk.tokenize import word_tokenize
tokenized_word=word_tokenize(text)
print(tokenized_word)
from nltk.probability import FreqDist
fdist = FreqDist(tokenized_word)
print(fdist)
fdist.most_common(2)
# # Frequency Distribution Plot
# import matplotlib.pyplot as plt
# fdist.plot(30,cumulative=False)
# plt.show()
from nltk.corpus import stopwords
stop_words=set(stopwords.words("english"))
print(stop_words)
filtered_word=[]
for w in tokenized_word:
if w not in stop_words:
filtered_word.append(w)
print("Tokenized Words:",tokenized_word)
print("Filterd Words:",filtered_word) |
c297f96e0b78082c5a0fa8eff26e39cfdd8894a1 | KLC2018/Sunghun-Study-2-day | /practice2.py | 95 | 3.65625 | 4 | a = int(input())
c = []
for b in range(1,a+1):
c.append(b)
c.reverse()
for b in c:
print(b)
|
6c65b9d63216e5ae0e5793031b0a9a3065e06070 | cankarabey/Project-Database-1.2 | /dateHelper.py | 287 | 3.71875 | 4 | from datetime import *
from datetime import date
import datetime
def futureDate(mydate):
entry6_format = '%Y-%m-%d'
datetime_obj = datetime.datetime.strptime(mydate, entry6_format)
if datetime_obj.date() <= date.today():
return False
else:
return True
|
df2bb0e950567d9aa544b70ad3bbc624cc165ae7 | dlefcoe/daily-questions | /stackImplement.py | 1,252 | 4.34375 | 4 | '''
This problem was asked by Amazon.
Implement a stack API using only a heap. A stack implements the following methods:
push(item), which adds an element to the stack
pop(), which removes and returns the most recently added element (or throws an error if there is nothing on the stack)
Recall that a heap has the following operations:
push(item), which adds a new key to the heap
pop(), which removes and returns the max value of the heap
'''
class stackItem:
''' stack class '''
def __init__(self, value):
self.value = value
self.n = False
def push(self, item):
''' add item to the stack '''
self.value = stackItem(item)
self.n = True
def pop(self):
''' remove last item from stack '''
if self.n == True:
print('this is the last node')
self.value = None
def runMain():
''' this is the main routine '''
# create stack
s = stackItem(10)
print(s.__dict__)
# push to stack
s.push(20)
print(s.__dict__)
print(s.value.__dict__)
# remove last element from stack
s.pop()
print(s.__dict__)
#print(s.value.__dict__)
if __name__ == "__main__":
runMain()
|
b0f9c6dc990738fb72db66a4561206e0cd814bce | llaum/PythonTraining2017 | /exo/wc.py | 721 | 3.953125 | 4 | #!/usr/bin/env python3
# Exercice: recode wc en python
# > python wc.py fichier.txt
from sys import argv
from os.path import exists
def counting(filename):
""" Counts lines, characters & words """
nLines = nWords = nChars = 0
with open(filename, 'r') as f:
for line in f:
nLines += 1
nChars += len(line)
nWords += len(line.split())
return nLines, nWords, nChars
if len(argv) < 2:
print("Not enough arguments!")
exit(1)
else:
for filename in argv[1:]:
if exists(filename):
print("%d lines, %d words, %d chars" % counting(filename), "in file", filename)
else:
print("File not found:", filename)
exit(0)
|
e0319901b7b752214b81982283301599ca4ca479 | skipdev/python-work | /tkinter/EXAM.py | 4,146 | 3.59375 | 4 | from tkinter import *
from tkinter import messagebox
#the class
class Newsletter(Tk):
def __init__(self):
Tk.__init__(self)
#load images
self.default = PhotoImage(file="default.gif")
self.filled = PhotoImage(file="filled.gif")
self.empty = PhotoImage(file="empty.gif")
#style the window
self.configure(padx=10, pady=10, bg='#eee')
#add components
self.add_heading_label()
self.add_instructional_label()
self.add_email_frame()
self.add_type_frame()
self.add_subscribe_button()
def add_heading_label(self):
#create component
self.heading_label = Label(text="RECEIVE OUR NEWSLETTER")
self.heading_label.pack(fill=X)
self.heading_label.configure(font="Arial 14", pady=10)
def add_instructional_label(self):
#create component
self.instructional_label = Label(text="Please enter your email below to receive our newsletter.")
self.instructional_label.pack(fill=X)
#style component
self.instructional_label.configure(padx=10, pady=10, justify=LEFT)
def add_email_frame(self):
#create frame
self.email_frame = Frame()
self.email_frame.pack()
#create label
self.email_label = Label(self.email_frame, text="Email: ")
self.email_label.pack(side=LEFT)
#create entry
self.email_entry = Entry(self.email_frame)
self.email_entry.pack(side=LEFT)
#create image label
self.image_label = Label(self.email_frame, image=self.default)
self.image_label.pack(side=LEFT)
#style
self.email_frame.configure()
self.email_label.configure(padx=10, pady=10)
self.email_entry.configure(bd=2, fg="#f00", width=30)
self.image_label.configure(padx=10)
#events
self.email_entry.bind("<KeyRelease>", self.validation)
def add_type_frame(self):
#create frame
self.type_frame = Frame()
self.type_frame.pack()
#create label
self.type_label = Label(self.type_frame, text="Type: ")
self.type_label.pack(side=LEFT)
#create dropdown
self.type_choices = ['Weekly', 'Monthly', 'Yearly']
self.type_selected = StringVar()
self.type_selected.set('Weekly')
self.type_optionmenu = OptionMenu(self.type_frame, self.type_selected, *self.type_choices)
self.type_optionmenu.pack()
#style
self.type_frame.configure()
self.type_label.configure(padx=10, pady=10)
self.type_optionmenu.configure(bd=2, width=30)
def add_subscribe_button(self):
#create
self.subscribe_button = Button(text="Subscribe")
self.subscribe_button.pack(fill=X)
#style
self.subscribe_button.configure()
#events
self.subscribe_button.bind("<ButtonRelease-1>", self.message_box)
def message_box(self, event):
if (self.email_entry.get() == ""):
messagebox.showinfo("Newsletter", "Please enter your email!")
elif (self.type_selected.get() == "Weekly"):
messagebox.showinfo("Newsletter", "You have subscribed to the weekly newsletter! You will receive this every Monday.")
elif (self.type_selected.get() == "Monthly"):
messagebox.showinfo("Newsletter", "You have subscribed to the monthly newsletter! You will receive this on the first day of each month.")
elif (self.type_selected.get() == "Yearly"):
messagebox.showinfo("Newsletter", "You have subscribed to the yearly newsletter! You will receive this at the start of each year.")
else:
messagebox.showinfo("Newsletter", "Subscribed")
def validation(self, event):
if (self.email_entry.get() == ""):
self.image_label.configure(image=self.empty)
else:
self.image_label.configure(image=self.filled)
#the object
gui = Newsletter()
gui.title("Newsletter")
gui.mainloop()
|
f1147e79df2b0824e25d8a858d0a033cb36f0940 | jorge-sa/porta-tcp | /vestibular.py | 1,653 | 3.9375 | 4 | #função que identifica letras incompativeis
def detectarLetras(array):
#Letras permitidas
alts = "ABCDE"
cont = True
for n in array:
if n not in alts:
cont = False
return(cont)
#função de calculo da nota
def calcularNota(g,r):
nota = 0
for x in range(len(g)):
if g[x] == r[x]:
nota += 1
return(nota)
while True:
#Número de Questões
while True:
try:
n = int(input("Insira o número de questões: "))
break
except:
print("Erro: Insira um número!")
if (1 <= n <= 80):
#Gabarito
gab = input("Insira o gabarito: ")
#Respostas do Candidato
resp = input("Insira as Resposta do Candidato: ")
#Número de acertos
certo = 0
if (len(gab) == len(resp) == n):
if (gab == gab.upper()) and (resp == resp.upper()):
if detectarLetras(gab) and detectarLetras(resp):
print("A nota do candidato foi " + str(calcularNota(gab,resp)))
break
else:
print("Erro: Letras devem ser A, B, C, D ou E!")
else:
print("Erro: Todas as Letras devem ser Maiúsculas!")
else:
print("Erro: Inconsistência Numérica! Gabarito ou Respostas não correspondem ao número de questões!")
elif (n < 1):
print("Erro: Nenhuma Questão!")
else:
print("Erro: Questões Demais!")
|
955a23bf949dc4e0e2c3d3d65d2effc9e5568402 | deepnagariya07/datatypes_hackerank | /loops.py | 925 | 4.15625 | 4 | # Objective
# In this challenge, we're going to use loops to help us do some simple math. Check out the Tutorial tab to learn more.
# Task
# Given an integer, , print its first multiples. Each multiple (where ) should be printed on a new line in the form: n x i = result.
# Input Format
# A single integer, .
# Constraints
# Output Format
# Print lines of output; each line (where ) contains the of in the form:
# n x i = result.
# Sample Input
# 2
# Sample Output
# 2 x 1 = 2
# 2 x 2 = 4
# 2 x 3 = 6
# 2 x 4 = 8
# 2 x 5 = 10
# 2 x 6 = 12
# 2 x 7 = 14
# 2 x 8 = 16
# 2 x 9 = 18
# 2 x 10 = 20
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
i = 1
while i < 11:
x = n * i
print(str(n) + " x " + str(i) + " = " + str(x))
i = i + 1
if i == 11:
break |
c9e6efbdd45205acf6aceaf2f33416a28aaeddef | fuckualreadytaken/leetcode | /Median_of_Two_Sorted_Arrays.py | 590 | 3.6875 | 4 | #! /usr/bin/env python
# coding=utf-8
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
li = nums1 + nums2
li.sort()
length = len(li)
if length % 2:
mid = li[length / 2]
else:
mid = (li[int(length / 2) - 1] + li[int(length / 2)]) * 0.5
return mid
if __name__ == "__main__":
nums1 = [1, 2]
nums2 = [3, 4]
solve = Solution()
print(solve.findMedianSortedArrays(nums1, nums2))
|
4a17048ada5b4ee528675741e2ccced10b138ba8 | Mekichimo/MekiPythonLearning | /Python/variables/strings.py | 150 | 3.71875 | 4 | x = "hello"
print (x)
print (x[0])
print (x[1])
print (x[2])
print (x[3])
print (x[4])
x = "hello world"
s = x [0:4]
print (s)
s = x [:4]
print (s)
|
a1540671e9ed3302c3e62a07f8db3754b2740a4f | moasslahi/python-100DaysOfCode | /Challenges/week3Challenge.py | 536 | 4.4375 | 4 | # week 3 challenge
#1, create a list and apply 4 methods
Mylist = ["Mo",18,"Developer","Football"]
Mylist.append("Python") #append method adds an element
Mylist.insert(1,"Asslahi") #insert method adds an elemnet at the specified element
Mylist.pop() #pop method removes an element
Mylist.reverse() #reverse method reverses the order of the list
print(Mylist)
#2, write a code that checks if the word
# 'python' is in a tuple
Mytuple = ("Java","Python","Swift")
if "Python" in Mytuple:
print("Yes, 'Python' is in the tuple")
|
03812b053ecf23b1f536431f4a6c0276d4b6f086 | nestorivanmo/DataStructuresAndAlgorithms | /Lab/Práctica3_Counting_Radix_sort/Node.py | 681 | 3.625 | 4 | import csv
from random import randrange
class Node:
id = 0
city = ""
def __init__(self, id, city):
self.id = id
self.city = city
#append Node objects to a list
def readFromFile():
lista = []
with open('country50.csv') as file:
reader = csv.reader(file, delimiter=',')
for row in reader:
x = Node(row[0], row[1])
if x.name != "city":
lista.append(x)
return lista
#algorithm for shuffling a list's items
def sattoloCycle(items):
i = len(items)
while i > 1:
i -= 1
j = randrange(i)
items[j], items[i] = items[i], items[j]
#algorithm for printing elements in a Node list
def printList(items):
for x in items:
print(str(x.id) + ", " + x.city)
|
d132c8729e8e892e2b8471cbabde5fdf2263e12a | piyushgoyal1620/HacktoberFest2021 | /Python/sort_words_like_dictonary.py | 1,020 | 4.375 | 4 | def sort_words(): #defining the function for sorting the words.
k=1
while k==1: #this condition is used so that the porgram doesnt stop untill all the data has been fed
word=input('Enter the word, leave blank if you want to stop')
#'word' variable stores the word entered by the user
if word=='':
break #if the user want to stop entering the data, they can just press enter and the data entering phase will be over
else:
l.append(word)
print('Enter the order in which you want the Words to be displayed')
#message for the user
order=input('Enter \'A\' for asscending order, \'B\' for decending order')
#'A' is entered for alphabetical order and 'B' for the opposite
if order=='A':
l.sort() #Alphabatical sort
print(l)
if order=='B':
l.sort(reverse=True) #Opposite sort
print(l)
l=[] #the list that will store all the data is the variable 'l'
sort_words() #the function is called
|
fb513325cc1609c1bd645df5d4719db75bb7f50e | anisul-Islam/python-tutorials-code | /Program10.py | 194 | 3.703125 | 4 | # Relational operators - >,<,>=,<=, ==, != and Boolean data types -> True / False
print(20>10)
print(20>=10)
print(20>=20)
print(20<10)
print(20<=10)
print(20<=20)
print(20==20)
print(20!=20) |
200a575ffbdb12d8c318c4769e4f93e3f568d997 | Beadsworth/ProjectEuler | /src/solutions/Prob28.py | 384 | 3.859375 | 4 | import src.EulerHelpers as Euler
import math
def find_dia_sum(side):
"""
for box of size side x side, find sum of diagonals
side must be odd
"""
assert side % 2 == 1, "side must be odd"
# closed form solution
r = (side - 1) / 2
return int((16 * (r ** 3) + 30 * (r ** 2) + 26 * r + 3) / 3)
if __name__ == '__main__':
print(find_dia_sum(1001))
|
02921ea012a8359c9637cede4ddc4950b8f5483e | MED-SALAH/Data_Preprocessing | /regression_lineaire_multiple.py | 1,079 | 3.546875 | 4 | # Regression lineaire Multiple
# importer les librairies
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importer le dataset
dataset = pd.read_csv('50_Startups.csv')
x = dataset.iloc[:, :-1].values # varialble indépondante
y = dataset.iloc[:, -1].values # variable déponddante
# Gérer les varialbes catégoriques
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
x[:, 3] = labelencoder_x.fit_transform(x[:, 3])
onehotencoder = OneHotEncoder(categorical_features= [3])
x = onehotencoder.fit_transform(x).toarray()
x = x [:, 1:]
# Diviser le dataset entre le Training set et le Test set
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)
# Construction du Modéle
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train, y_train)
# Faire de nouvelle Prédictions
y_pred = regressor.predict(x_test)
regressor.predict(np.array ([[1, 0, 130000, 140000, 300000]])) |
fcda4ba9a7a70e1077de49839b24cd8ab86136fb | ekbaya/flask-api-back-end | /tasks/task.py | 1,412 | 3.5 | 4 | # import the pymysql module
import MySQLdb
import datetime
import time
# Code for creating a connection object
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your password
db="mysql") # name of the data base
try:
# Code for creating cursor from database connection
cursorInstance = db.cursor()
# Code for calculating timestamp of 14 days ago
tod = datetime.datetime.now()
d = datetime.timedelta(days = 14)
a = tod - d
unixtime = time.mktime(a.timetuple())
# SQL statement for deleting rows from a table matching a criteria
sqlDeleteRows = "Delete from locations where time_stamp < 'unixtime'"
# using the cursor delete a set of rows from the table
cursorInstance.execute(sqlDeleteRows)
# Check if there are any existing items with expired status
sqlSelectRows = "select * from locations"
# Execute the SQL query
cursorInstance.execute(sqlSelectRows)
#Fetch all the rows using cursor object
itemRows = cursorInstance.fetchall()
# print all the remaining rows after deleting the rows with status as "expired"
for item in itemRows:
print(item)
except Exception as ex:
print("Exception occured: %s"%ex)
finally:
cursorInstance.close() |
1708aee7f57545f3ed18d56b83888950652f122a | keanubowker8/OPP-Dice-Game | /dice_game.py | 3,191 | 3.921875 | 4 | from multi_sided_die import *
class DicePoker:
amount = 100
double = False
triple = False
a = '0'
def __init__(self):
pass
def roll_dice(self):
value = []
ms = MultiSidedDie(6)
for num in range(5):
ms.roll()
a = str(ms.get_value())
value.append(a)
print('Position numbers for dices ["0", "1", "2", "3", "4"]')
print('Dice results {}'.format(value))
g = input("Do you want to roll again, y or n? " )
if g == 'y':
x = input("Which dice do you want to roll again? Type in position of dices each separated by a space " )
x = x.split()
#print(x)
for dice in x:
ms.roll()
value[int(dice)] = str(ms.get_value())
print('Dice results {}'.format(value))
g = input("Do you want to roll again, y or n? " )
if g == 'y':
x = input("Which dice do you want to roll again? Type in position of dices each separated by a space " )
x = x.split()
#print(x)
for dice in x:
ms.roll()
value[int(dice)] = str(ms.get_value())
print('Dice results {}'.format(value))
print(value)
return value
def count_numbers(self,mystr,z):
#global amount
# #global double
# self.double = False
# #global triple
# self.triple = False
counter = 0
z = set(z)
for i in z:
if mystr.count(i) == 2:
self.double = True
global a
self.a = i
counter +=1
if (mystr.count(self.a)!=2 and mystr.count(i)==3):
self.amount += 8
if mystr.count(i)== 3:
self.triple =True
if self.double and self.triple:
self.amount += 12
if mystr.count(i)== 4:
self.amount += 15
if mystr.count(i)== 5:
self.amount += 30
if (mystr=='12345' or mystr=='23456'):
self.amount += 20
if counter ==2:
self.amount += 5
else:
pass
def playgame(self):
g = input("Hello, welcome to the dice game! \n Would you like to play y or n? " )
if g == 'y':
while self.amount>10 and g =='y':
print("Your score is %s ." % (self.amount))
r = input("Press 1 to roll dice " )
if r == '1':
self.amount-=10
z = self.roll_dice()
mystr = ''.join(z)
for i in z:
if mystr.count(i)== 2:
a = i
self.count_numbers(mystr,z)
g = input("Would you like to continue playing y or n?" )
print("Game Over! \n Your final score is %s ." % (self.amount))
dp = DicePoker()
dp.playgame() |
6a6e5252a48624c5a61adfe21084f65d45b8a032 | iAtec-ua/python_course | /practice 5/Task_5_2_Numbers_to_words.py | 5,709 | 3.609375 | 4 | # Script prompts a number from user and prints the number in words
# Create libraries for all kind of numbers
ordinary_numbers = {
"0": "",
"1": " один",
"2": " два",
"3": " три",
"4": " чотири",
"5": " п'ять",
"6": " шість",
"7": " сім",
"8": " вісім",
"9": " дев'ять",
"10": " десять",
"11": " одинадцять",
"12": " дванадцать",
"13": " тринадцать",
"14": " чотирнадцать",
"15": " п'ятнадцять",
"16": " шістьнадцять",
"17": " сімнадцять",
"18": " вісімнадцять",
"19": " дев'ятнадцять",
}
decimal_numbers = {
"0": "",
"2": " двадцать",
"3": " тридцать",
"4": " сорок",
"5": " п'ядесят",
"6": " шісдесят",
"7": " сімдесят",
"8": " вісімдесят",
"9": " дев'яносто"
}
hundreds = {
"0": "",
"1": " сто",
"2": " двісті",
"3": " триста",
"4": " чотириста",
"5": " п'ятсот",
"6": " шістсот",
"7": " сімсот",
"8": " вісімсот",
"9": " дев'ятсот"
}
numbers_for_thousands = {
"0": "",
"1": " одна",
"2": " дві",
"3": " три",
"4": " чотири"
}
# використання функції гарна ідея
# Ліпше не використовувати стільки вкладень коду
# Це погіршує сприймання та збільшує ймовірність появи багів
# Я додав приклад рішення, який буде використовувати цикл і дозволить скоротити кількість вкладень
# див (Task_5_2_Example.py)
# також бажано враховувати обмеження в 120 символів на стрічку
# це негласне правило щодо форматування коду
def user_prompt(msg):
# логіку щодо отримання даних можна винести в окрему функцію
prompt_number = input(msg)
if not prompt_number.isdigit():
return user_prompt("Вы ввели не число. Введіть число: ")
# перевірку можна розвернути, і при виконанні умови видавати повідомлення про помилку
# це дозволить уникнути зайвого вкладення коду зі стрічок 74 - 116
if int(prompt_number) in range(1, 9999):
# ми не використовуємо цю змінну
number_length = len(prompt_number)
number_list = list(prompt_number)
int_prompt_number = int(prompt_number)
if int_prompt_number < 20:
print(f"Ваша цифра:{ordinary_numbers[prompt_number]}!")
elif int_prompt_number < 100:
print(f"Ваша цифра:{decimal_numbers[number_list[0]]}{ordinary_numbers[number_list[1]]}!")
elif int_prompt_number < 1000:
if int(number_list[-2]) == 1:
decimal_list = number_list[-2:]
decimals = str("".join(decimal_list))
print(f"Ваша цифра:{hundreds[number_list[0]]}{ordinary_numbers[decimals]}!")
else:
print(
f"Ваша цифра:{hundreds[number_list[0]]}{decimal_numbers[number_list[1]]}{ordinary_numbers[number_list[2]]}!")
elif int_prompt_number < 10000:
if int(number_list[0]) == 1:
if int(number_list[-2]) == 1:
decimal_list = number_list[-2:]
decimals = str("".join(decimal_list))
print(
f"Ваша цифра:{numbers_for_thousands[number_list[0]]} тисяча{hundreds[number_list[1]]}{ordinary_numbers[decimals]}!")
else:
print(
f"Ваша цифра:{numbers_for_thousands[number_list[0]]} тисяча{hundreds[number_list[1]]}{decimal_numbers[number_list[2]]}{ordinary_numbers[number_list[3]]}!")
elif int(number_list[0]) in range(2, 5):
if int(number_list[-2]) == 1:
decimal_list = number_list[-2:]
decimals = str("".join(decimal_list))
print(
f"Ваша цифра:{numbers_for_thousands[number_list[0]]} тисячі{hundreds[number_list[1]]}{ordinary_numbers[decimals]}!")
else:
print(
f"Ваша цифра:{numbers_for_thousands[number_list[0]]} тисячі{hundreds[number_list[1]]}{decimal_numbers[number_list[2]]}{ordinary_numbers[number_list[3]]}!")
else:
if int(number_list[-2]) == 1:
decimal_list = number_list[-2:]
decimals = str("".join(decimal_list))
print(
f"Ваша цифра:{ordinary_numbers[number_list[0]]} тисяч{hundreds[number_list[1]]}{ordinary_numbers[decimals]}!")
else:
print(
f"Ваша цифра:{ordinary_numbers[number_list[0]]} тисяч{hundreds[number_list[1]]}{decimal_numbers[number_list[2]]}{ordinary_numbers[number_list[3]]}!")
else:
return user_prompt("Ваше число менше 1 або більше 9999. Введіть число від 1 до 9999:")
print(user_prompt("Введіть число від 1 до 9999: ")) |
8ded61e9e792591fa905e3ab9a94f321f4441b34 | JacobBarnholdt/battleship | /Highscore.py | 1,910 | 3.6875 | 4 |
class Highscores:
def __init__(self):
self.file_name = "Highscore.txt"
self.scores = []
self.read_scores()
# self.add_score("nisåss2", 2)
self.print_scores()
self.write_scores()
return
def read_scores(self):
file = open(self.file_name,"r")
scoreslines = file.readlines()
for scorepairs in scoreslines:
pair = scorepairs.split()
name = pair[0]
score = int(pair[1])
scoreitem = (score, name)
self.scores.append(scoreitem)
print("Name = " + name + " had score = " + str(score))
file.close()
return
def add_score(self,name,score):
new_score_item = (score, name)
self.scores.append(new_score_item)
self.sort_scores()
if len(self.scores) > 10:
self.scores = self.scores[:10]
self.write_scores()
def sort_scores(self):
sortedscores = sorted(self.scores,key = lambda score: score[0])
self.scores = sortedscores
return
def get_scores(self):
self.sort_scores()
lines = ""
self.scores.reverse()
for score in self.scores:
name = score[1]
val = score[0]
lines = "Name = " + name + " had score = " + str(val) + "\n" + lines
return lines
def print_scores(self):
print("Sorted")
self.sort_scores()
for score in self.scores:
name = score[1]
val = score[0]
print("Name = " + name + " had score = " + str(val))
return
def write_scores(self):
file = open(self.file_name,"w")
lines = []
for score in self.scores:
name = score[1]
val = score[0]
line = name + " " + str(val) + "\n"
file.write(line)
file.close()
return
|
3a47ceda8a2304ae0f521481cb3d1ef8b06e5594 | heeryoncho/playnview_distinctwordfinder | /crawl_data/jpop.py | 13,831 | 3.53125 | 4 | import os
import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
'''
# Author: Heeryon Cho <[email protected]>
# License: BSD-3-clause
This code gathers yearly top 100 j-pop song information from the Oricon website.
Note that this code only retrieves song name and artist name;
the lyrics url is not retrieved. (This will be done later.)
'''
'''
|++++++++++++++++++++++|
| scrape_web_page(url) |
|++++++++++++++++++++++|
is a general function for executing the HTTP GET request.
'''
USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
def scrape_web_page(url):
html = requests.get(url, headers=USER_AGENT, verify=False)
soup = BeautifulSoup(html.content, 'html.parser')
return soup
'''
|+++++++++++++++++++++++++++++|
| fetch_song_ranking_oricon() |
|+++++++++++++++++++++++++++++|
gathers 1,000+ 10-years worth top-100 j-pop songs from the Oricon website.
'''
def fetch_song_ranking_oricon():
# Oricon website is crawled using the below url:
# e.g., 'https://www.oricon.co.jp/rank/js/y/2017/p/10/'
ranking_url = 'https://www.oricon.co.jp/rank/js/y/'
# Each Oricon webpage lists 10 songs, so we have to loop 10 times
# to crawl 100 songs per year.
frames = []
for year in range(2008, 2018):
for page in range(1, 11):
year_url = ranking_url + str(year) + '/p/' + str(page) + '/'
print(year_url)
# Find top 10 songs/artist pair per webpage.
soup = scrape_web_page(year_url)
songs = soup.find_all(attrs={'itemprop': 'name'})
artists = soup.find_all('p', attrs={'class': 'name'})
rank1 = soup.find_all('p', attrs={'class': 'num '})
rank2 = soup.find_all('p', attrs={'class': 'num num-s'})
rankings = rank1 + rank2
print(songs)
print(artists)
song_list = []
for s in enumerate(songs):
song_list.append(s[1].string)
artist_list = []
for a in enumerate(artists):
artist_list.append(a[1].string)
ranking_list = []
for r in enumerate(rankings):
ranking_list.append(r[1].string)
df = pd.DataFrame({
'Ranking': ranking_list,
'SongName': song_list,
'ArtistName': artist_list,
'Year': year
})
print(df)
frames.append(df)
len(frames) # 10 years worth
result = pd.concat(frames)
# Save the j-pop ranking result in csv format under 'ranking' directory.
result.to_csv('ranking/jp_ranking.csv', index=False)
'''
*** !!! IMPORTANT !!! ********************
Because j-pop song titles and artist names are expressed in a variety of ways,
e.g., names of the individual artists are listed for the given music group
instead of the group name, using string match of the artist name and song title
to search for the lyrics can sometimes fail.
Hence, MANUAL CORRECTIONS were made on some of the song titles and artist names to
better match the lyrics search on the following two websites:
1. http://uta-net.com/
2. http://j-lyric.net/
The manually corrected file is 'ranking/jp_ranking_manually_corrected.csv'.
We use this file instead of 'jp_ranking.csv' file
to crawl j-pop lyrics from the above two websites.
'''
'''
|++++++++++++++++++++++++++++++++|
| fetch_url_utanet(artist, song) |
|++++++++++++++++++++++++++++++++|
searches a single song's lyric text URL link on the Utanet website.
'''
def fetch_link_utanet(artist, song):
assert isinstance(artist, str), 'Search term must be a string'
# Utanet website seems to refuse connection over time, so
# enough time gap of 10 seconds is set to prevent ConnectionError.
time.sleep(10)
uta_url = 'https://www.uta-net.com/search/?Aselect=1&Bselect=1&Keyword={}&sort=4'.format(artist)
try:
soup = scrape_web_page(uta_url)
link = soup.find('a', string=song)
print(link)
if link != None:
lyric_url = link['href']
return lyric_url
except requests.exceptions.RequestException as e:
print(e)
'''
|++++++++++++++|
| first_pass() |
|++++++++++++++|
collects and saves URL links to lyrics texts on the Utanet site.
'''
def first_pass():
# Manually corrected file is used to increase the chance of finding the lyrics urls.
df = pd.read_csv('ranking/jp_ranking_manually_corrected.csv')
year_list = []
ranking_list = []
artist_list = []
song_list = []
url_list = []
for i, row in df.iterrows():
artist = row['ArtistName']
song = row['SongName']
# Oricon ranking sometimes lists multiple song titles
# in a single rank, i.e., tied songs or single titles,
# and these multiple songs are concatenated using '/'.
# We use '/' to split the song titles.
if '/' in song:
songs = song.split('/')
for j, s in enumerate(songs):
artist_list.append(artist)
song_list.append(s)
year_list.append(row['Year'])
ranking_list.append(row['Ranking'])
link = fetch_link_utanet(artist, s)
url_list.append(link)
# Only one song per rank is executed below. (i.e., no '/'.)
else:
artist_list.append(artist)
song_list.append(song)
year_list.append(row['Year'])
ranking_list.append(row['Ranking'])
link = fetch_link_utanet(artist, song)
url_list.append(link)
df = pd.DataFrame({
'Ranking': ranking_list,
'SongName': song_list,
'ArtistName': artist_list,
'Year': year_list,
'URL': url_list
})
# Save utanet url links to file.
df.to_csv('ranking/jp_ranking_url_utanet.csv', index=False)
df = df.dropna() # Remove missing values to see how many links were gathered from the Utanet site.
print("\nUtanet searched:", df.shape)
'''
|+++++++++++++++++++++|
| fetch_link_jlyric() |
|+++++++++++++++++++++|
searches a single song's lyric text URL link on the J-lyric.net website.
'''
def fetch_link_jlyric(artist, song):
assert isinstance(artist, str), 'Search term must be a string'
assert isinstance(song, str), 'Search term must be a string'
query = 'kt=' + song + '&ct=2&ka=' + artist + '&ca=2&kl=&cl=2'
escaped_search_term = query.replace(' ', '+')
# J-lyric.net website seems to refuse connection over time, so
# enough time gap of 10 seconds is set to prevent ConnectionError.
time.sleep(10)
jlyric_url = 'http://search2.j-lyric.net/index.php?{}'.format(escaped_search_term)
print(jlyric_url)
try:
soup = scrape_web_page(jlyric_url)
links = soup.find_all('p', attrs={'class': 'mid'})
print(links)
if links != []:
lyric_url = links[0].find('a', href=True)
return lyric_url['href']
except requests.exceptions.RequestException as e:
print(e)
'''
|+++++++++++++++|
| second_pass() |
|+++++++++++++++|
collects and saves URL links to lyrics texts on the J-lyric.net site.
*** Note that the second_pass() searches and collects URL links where
the Utanet website failed.
'''
def second_pass():
# The second pass starts where the 'jp_ranking_url_utanet.csv' left off,
# and fill in those lyrics URL links that Utanet website failed to collect.
df = pd.read_csv('ranking/jp_ranking_url_utanet.csv')
nans = lambda df: df[df.isnull().any(axis=1)] # Search for missing values.
missing = nans(df)
print("\nJ-pop lyrics' URL links that are still missing:", missing.shape)
year_list = []
ranking_list = []
artist_list = []
song_list = []
url_list = []
for i, row in missing.iterrows():
artist = row['ArtistName']
song = row['SongName']
if '/' in song:
songs = song.split('/')
for i, s in enumerate(songs):
artist_list.append(artist)
song_list.append(s)
year_list.append(row['Year'])
ranking_list.append(row['Ranking'])
link = fetch_link_jlyric(artist, s)
url_list.append(link)
else:
artist_list.append(artist)
song_list.append(song)
year_list.append(row['Year'])
ranking_list.append(row['Ranking'])
link = fetch_link_jlyric(artist, song)
url_list.append(link)
df = pd.DataFrame({
'Ranking': ranking_list,
'SongName': song_list,
'ArtistName': artist_list,
'Year': year_list,
'URL': url_list
})
df = df.dropna() # Remove missing values.
df.to_csv('ranking/jp_ranking_url_jlyrics.csv', index=False)
print("\nJlyrics searched:", df.shape)
'''
|+++++++++++++++++++++++++++|
| fetch_each_lyric_utanet() |
|+++++++++++++++++++++++++++|
crawls each j-pop lyric from 'https://www.uta-net.com/' using
the URL links saved at 'ranking/jp_ranking_url_utanet.csv'.
'''
def fetch_each_lyric_utanet(url):
assert isinstance(url, str), 'URL must be a string'
time.sleep(10)
uta_url = 'https://www.uta-net.com{}'.format(url)
try:
soup = scrape_web_page(uta_url)
lyrics_area = soup.find('div', attrs={'id': 'kashi_area'})
if lyrics_area != None:
lyrics = lyrics_area.get_text(separator='\n')
lyrics = lyrics.strip()
return lyrics
except requests.exceptions.RequestException as e:
print(e)
'''
|+++++++++++++++++++++++|
| crawl_lyrics_utanet() |
|+++++++++++++++++++++++|
crawls j-pop lyrics from the utanet website using the
the URL links saved at 'ranking/jp_ranking_url_utanet.csv'.
'''
def crawl_lyrics_utanet():
# Create 'lyrics_jp' directory if there is none.
lyrics_jp_dir = "lyrics_jp"
if not os.path.exists(lyrics_jp_dir):
os.makedirs(lyrics_jp_dir)
df = pd.read_csv('ranking/jp_ranking_url_utanet.csv')
df = df.dropna()
print("\n# of lyrics to be crawled from Utanet:", df.shape)
url_list = []
lyrics_list = []
for i, row in df.iterrows():
url = row['URL']
print(url)
url_list.append(url)
lyrics = fetch_each_lyric_utanet(url)
lyrics_list.append(lyrics)
df = pd.DataFrame({
'Lyrics': lyrics_list,
'URL': url_list
})
# Save crawled j-pop lyrics to file.
df.to_csv('lyrics_jp/jp_lyrics_utanet.csv', index=False)
'''
|++++++++++++++++++++++++++++|
| fetch_each_lyric_jlyrics() |
|++++++++++++++++++++++++++++|
crawls each j-pop lyric from 'http://j-lyric.net/' using
the URL links saved at 'ranking/jp_ranking_url_jlyrics.csv'.
'''
def fetch_each_lyric_jlyrics(url):
assert isinstance(url, str), 'URL must be a string'
time.sleep(10)
jlyric_url = url
try:
soup = scrape_web_page(jlyric_url)
lyrics_area = soup.find('p', attrs={'id': 'Lyric'})
if lyrics_area != None:
lyrics = lyrics_area.get_text(separator='\n')
lyrics = lyrics.strip()
return lyrics
except requests.exceptions.RequestException as e:
print(e)
'''
|++++++++++++++++++++++++|
| crawl_lyrics_jlyrics() |
|++++++++++++++++++++++++|
crawls j-pop lyrics from the jlyrics.net website using the
the URL links saved at 'ranking/jp_ranking_url_jlyrics.csv'.
'''
def crawl_lyrics_jlyrics():
# Create 'lyrics_jp' directory if there is none.
lyrics_jp_dir = "lyrics_jp"
if not os.path.exists(lyrics_jp_dir):
os.makedirs(lyrics_jp_dir)
df = pd.read_csv('ranking/jp_ranking_url_jlyrics.csv')
df = df.dropna()
print("\n# of lyrics to be crawled from J-lyric.net:", df.shape)
url_list = []
lyrics_list = []
for i, row in df.iterrows():
url = row['URL']
print(url)
url_list.append(url)
lyrics = fetch_each_lyric_jlyrics(url)
lyrics_list.append(lyrics)
df = pd.DataFrame({
'Lyrics': lyrics_list,
'URL': url_list
})
# Save crawled j-pop lyrics to file.
df.to_csv('lyrics_jp/jp_lyrics_jlyrics.csv', index=False)
'''
|++++++++++++++++|
| merge_lyrics() |
|++++++++++++++++|
merges the following two lyrics texts into one.
inputs:
--- lyrics_jp/jp_lyrics_utanet.csv
--- lyrics_jp/jp_lyrics_jlyrics.csv
output:
--- lyrics_jp/jp_lyrics.csv
'''
def merge_lyrics():
df_utanet = pd.read_csv("lyrics_jp/jp_lyrics_utanet.csv")
df_utanet = df_utanet.dropna()
df_jlyrics = pd.read_csv("lyrics_jp/jp_lyrics_jlyrics.csv")
df_jlyrics = df_jlyrics.dropna()
df_ja = pd.concat([df_utanet, df_jlyrics], axis=0)
# Save merged j-pop lyrics to file.
df_ja.to_csv("lyrics_jp/jp_lyrics.csv", index=None)
# Execute the below functions in a sequential manner.
#---------------------------------------
# Crawl and save top 100 j-pop song name and artist name
# for years 2008 - 2017. (10 years worth)
fetch_song_ranking_oricon()
#---------------------------------------
# Collect j-pop lyrics URL link info. from the Utanet website.
first_pass()
#---------------------------------------
# Collect j-pop lyrics URL link info. from the J-lyric.net website. (Try where Utanet failed.)
second_pass()
#---------------------------------------
# Crawl j-pop lyrics texts from the Utanet website.
crawl_lyrics_utanet()
#---------------------------------------
# Crawl j-pop lyrics texts from the J-lyric.net website. (Try where Utanet left off.)
crawl_lyrics_jlyrics()
#---------------------------------------
# Merge two lyrics csv to one.
merge_lyrics()
|
d869916c1f69c46aa491ffcf1554631d9a6fbf01 | marwafar/Python-practice | /length-last-word.py | 322 | 3.671875 | 4 | def length_of_last_word(s):
if len(s) == 0:
return 0
list_s=s.split()
if len(list_s) >1:
return len(list_s[-1])
elif len(list_s) == 1:
return len(list_s[0])
else:
return 0
s = "Hello World"
print(length_of_last_word(s))
|
fa7eba89b3c30fd2a5093aba03b19c989a284035 | dong-alex/kattis | /sjecista/solution.py | 1,797 | 3.5 | 4 | """
Alex Dong
1413809
List any resources you used below (eg. urls, name of the algorithm from our code archive).
Remember, you are permitted to get help with general concepts about algorithms
and problem solving, but you are not permitted to hunt down solutions to
these particular problems!
(binomial theorem) - https://github.com/UAPSPC/Code-Archive/blob/master/combinatorics/binomial.c
(combination w/ binomial) - https://en.wikipedia.org/wiki/Combination
List any classmate you discussed the problem with. Remember, you can only
have high-level verbal discussions. No code should be shared, developed,
or even looked at in these chats. No formulas or pseudocode should be
written or shared in these chats.
N/A
By submitting this code, you are agreeing that you have solved in accordance
with the collaboration policy in CMPUT 403.
"""
# consider n = 4, we get one intersection
# if n = 5 and we have 4 vertices from there, there will be an intersection from it
# vertices = {1,2,3,4,5}
# if set = {1,2,3,4} then we have 1 intersection
# if set = {1,2,3,5} then we have 1 intersection
# calculate how many combinations of 4 vertices in the set then that will be intersections for 5
# if n == 3 then we get 0 because we need 2 line segments from 4 points to create an intersection
# only going to 100th degree
binomial = [[0 for _ in range(100)] for _ in range(100)]
# converted from C++ programming repo
def getBinomial(vertices):
for k in range(0, 100):
binomial[k][0] = 1
binomial[k][k] = 1
for i in range(1, k):
binomial[k][i] = binomial[k-1][i-1]+binomial[k-1][i]
vertices = int(input())
if vertices <= 3:
print(0)
else:
# get number of combinations of 4
getBinomial(vertices)
print(binomial[vertices][4]) |
8332479462c260120fdec03f48fe5572d1e1e4a6 | jagrvargen/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 286 | 3.828125 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
myTup = ()
while len(tuple_a) < 2:
tuple_a = tuple_a + (0,)
while len(tuple_b) < 2:
tuple_b = tuple_b + (0,)
for i in range(2):
myTup = myTup + (tuple_a[i] + tuple_b[i],)
return myTup
|
0d937c6c68af8e11754ecce1d2af3645a75e5639 | amirsaleem1990/python-practice-and-assignments | /Exercises from www.practivepython org/Exercise #30&31&32.py | 1,617 | 3.9375 | 4 | # Exercise #30 & 31 & 32
# http://www.practicepython.org/exercise/2016/09/24/30-pick-word.html
# http://www.practicepython.org/exercise/2017/01/02/31-guess-letters.html
# http://www.practicepython.org/exercise/2017/01/10/32-hangman.html
def pick_word():
import random
return random.choice([i.lower() for i in open('/home/hp/Desktop/Exercises from www.practivepython org/exercise_30_related file.txt', 'r').read().split()])
def guess_letters():
print('\nWelcome to Hangman!\n')
aa = pick_word(); a = [i for i in aa]
m = aa[:]; l = 0; ss = list()
d = ['_' for i in range(len(aa))]
[print(i, end='') for i in d]; print('\n')
while '_' in d and l < len(aa):
if d != m:
print(str(len(aa)-l) + ' turn(s) left')
b = input('Enter a single latter: '); ss.append(b)
if len(b) == 1 and b not in d and ss.count(b)==1:
l +=1
if b in aa:
for i in range(aa.count(b)):
d[aa.index(b)] = b; a[a.index(b)]= ' '
[print(i, end='') for i in d]; print('\n')
else: print('you entered this latter before.. plz enter onother latter..\n')
if d == m:
print('Congratulation! you guess the word in ' + str(l)+' turns\n[for restart the game type guess_letters()]')
else: print('Game over!..... try again\(you wasnt seccesfully guessed the word (' + aa + ')')
nn = input('Are you want to play this game one more time? \n[y/n] ')
if nn== 'y': print(guess_letters())
elif nn == 'n': return 'Take care.. bye bye'
print(guess_letters())
|
fb9e93df43c42cbb33ff9d4ba1ee2279a7710e87 | Darkwing53/Dungeons_and_Dragons | /dungeon_and_dragons.py | 2,332 | 3.859375 | 4 | import random
import os
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
dungeon = [(x,y) for x in range(5) for y in range(5)]
def random_items():
return(random.sample(dungeon,3))
def make_dungeon(player_position):
print(" _ _ _ _ _")
for cell in dungeon:
y = cell[1]
if y < 4:
if cell == player_position:
print("|X", end = "")
else:
print("|_", end = "")
elif cell == player_position:
print("|X|")
else:
print("|_|")
def move_player(position,m_input):
x,y = position
if m_input.upper() == "UP":
x -= 1
elif m_input.upper() == "LEFT":
y -= 1
elif m_input.upper() == "RIGHT":
y += 1
elif m_input.upper() == "DOWN":
x += 1
elif m_input.upper() == "QUIT":
exit()
return(x,y)
random_select = random_items()
def moves(position):
x,y = position
moves = ["UP","RIGHT","DOWN","LEFT"]
if x == 0:
moves.remove("UP")
elif y == 4:
moves.remove("RIGHT")
elif x == 4:
moves.remove("DOWN")
elif y == 0:
moves.remove("LEFT")
return(moves)
def main():
location = random_select[0]
door = random_select[1]
dragon = random_select[2]
print("Welcome to the Dungeon!")
input("Press 'Enter' on your keyboard to start the game!")
make_dungeon(location)
print("You are currently in room {}".format(location))
while True:
move_list = moves(location)
print("You can move{}".format(move_list))
print("Enter 'QUIT' to quit")
main_input = input("\n").upper()
if main_input == "QUIT":
break
elif main_input in move_list:
location = move_player(location,main_input)
clear_screen()
make_dungeon(location)
if location == dragon:
print("You lost ! Dragon ate you")
break
elif location == door:
print("Congratulations . you won !")
break
else:
print("You are currently in room {}".format(location))
else:
clear_screen()
make_dungeon(location)
print("Walls are hard ! Don't run into them.")
main()
|
6e4c1223c5dcbeebfcfd6d67d26744161024e23f | mervesenn/Python-proje | /koşullu durumlar/fibonacciserisi.py | 266 | 4.21875 | 4 | """
fibonacci serisi yeni bir sayıyı önceki iki sayının toplamı şeklinde oluşturulur.
1,1,2,3,5,8,13,21,34.....
"""
a = 1
b = 1
fibonacci = [a, b]
for i in range(10):
a , b = b, a + b
print("a:", a,"b", b)
fibonacci.append(b)
print(fibonacci)
|
6630c0bfc4f1d029acd467d33c3e52e6d31b0a88 | zafarali/experiments | /python/calgpa.py | 1,870 | 3.796875 | 4 | from sys import argv
script_name, user = argv
print "Calculating GPA for ",user
f = open(user+".txt", "r")
summation = 0
total_credits = 0
def parsegrade(letter):
if letter=="A":
return 4.0
elif letter=="A-":
return 3.7
elif letter=="B+":
return 3.3
elif letter=="B":
return 3.0
elif letter=="B-":
return 2.7
elif letter=="C+":
return 2.4
elif letter=="C":
return 2.0
elif letter=="D":
return 1.0
else:
return 0.0
def parsegpa(grade):
if grade < 4.0 and grade >=3.7:
return "A"
elif grade <3.7 and grade >=3.3:
return "A-"
elif grade < 3.3 and grade >=3.0:
return "B"
elif grade < 3.0 and grade >= 2.7:
return "B-"
elif grade <2.7 and grade >= 2.3:
return "C+"
elif grade <2.3 and grade >=2.0:
return "C"
elif grade < 2.0 and grade >= 1.0:
return "D"
else:
return "F"
count = 0
print
#Class,credits,grade
print "COURSE Name (Credits): Grade (Points)"
for line in f:
if line[:2]=="--":
if line[2:3] == "F":
semester = "Fall"
else:
semester = "Winter"
year = "20"+line[3:5]
print "----"+semester+" "+year+"----"
else:
items = line.split(",")
credits = items[1]
count+=1
letter = items[2]
scale = parsegrade(letter)
earned = scale*float(credits)
summation = summation + earned
total_credits = total_credits + float(credits)
print items[0]+" ("+credits+"): "+letter+" ("+str(scale)+")"
print
grade = summation / total_credits
print "Total Grade Points Earned: "+str(summation)
print "Total Credits: "+str(total_credits)
print "Total Courses: "+str(count)
print
print "GPA: "+str(grade)+" "+parsegpa(grade)
print "Done."
f.close()
|
a884b8ba57610924bfc2338a621adb94f5b7acb3 | mathiasesn/obstacle_avoidance_with_dmps | /DMP/obstacle.py | 1,771 | 3.640625 | 4 | import numpy as np
class Obstacle:
def __init__(self, pos, radius = 0.015, discrete_steps = 15):
"""
Creates spherical obstacle centered at 'pos' with radius 'radius'.
Meshgrid created with amount of steps 'discrete_steps'.
"""
self.pos = np.array(pos)
self.r = radius
self.discrete_steps = discrete_steps
self.create_sphere()
self.__cur_indx_move_traj = 0 # current indx of moving trajectory
def create_sphere(self):
phi = np.linspace(0, np.pi, self.discrete_steps)
theta = np.linspace(0, 2*np.pi, self.discrete_steps)
phi, theta = np.meshgrid(phi, theta)
self.x = self.r * np.sin(phi) * np.cos(theta) + self.pos[0]
self.y = self.r * np.sin(phi) * np.sin(theta) + self.pos[1]
self.z = self.r * np.cos(phi) + self.pos[2]
def create_trajectory(self, to, steps):
"""
Create a linear trajectory from initial position
to input parameters with resolution steps.
"""
x_traj = np.linspace(self.pos[0], to[0], num=steps)
y_traj = np.linspace(self.pos[1], to[1], num=steps)
z_traj = np.linspace(self.pos[2], to[2], num=steps)
return np.dstack((x_traj,y_traj,z_traj))
def move_sphere(self, trajectory):
self.pos = trajectory[self.__cur_indx_move_traj]
self.create_sphere()
if len(trajectory) - 1 > self.__cur_indx_move_traj:
self.__cur_indx_move_traj += 1
return False
else:
return True
# Matlab visualization of obstacle:
# https://se.mathworks.com/help/robotics/examples/check-for-environmental-collisions-with-manipulators.html |
4da07735cba599c70ee00b04f69d63c33d94c537 | ToluwaniO/ITI1120 | /a3_8677256/a3_Q3_8677256.py | 665 | 4.0625 | 4 | #Family name: Ogunsanya Toluwani Damilola
# Student number: 8677256
# Course: IT1 1120
# Assignment Number 3 Question 3
def longest_run(l):
'''
(list of numbers) -> number
returns the length of the longest run in the list
preconditions: l must be a list
'''
mLen = 0
for i in range(len(l)-1):
count = 1
for j in range(i+1, len(l)):
if l[i] == l[j]:
count += 1
else:
break
if count > mLen:
mLen = count
return mLen
#main
a = input('Enter a list of numbers separated by comas: ')
a = a.strip()
l = list(eval(a))
print(longest_run(l))
|
8fe3cfb8487d7757206303b67eb80222ae756b10 | DebadityaShome/Coders-Paradise | /Python/Level 0/inRange.py | 445 | 4.03125 | 4 | """
Given an inRange(x,y) function,
write a method that determines whether a given pair (x, y) falls in the range (x < 1/3 < y).
Essentially, you’ll be implementing the body of a function that
takes in two numbers x and y and returns True if x < 1/3 < y; otherwise, it returns False.
"""
def inRange(x,y):
return (x < 1/3 < y)
x = float(input("First number ? ").strip())
y = float(input("Second number ? ").strip())
print(inRange(x,y)) |
8de8e20df1dd8e2860c469cb0f1c9af7bf288f32 | graviteja28/jetbrains | /Stage 3-4: I'm so lite.py | 5,340 | 4.0625 | 4 | '''
Stage 3-4: I'm so lite
Description
It's very upsetting when the data about registered users disappears after the program is completed. To avoid this problem, you need to create a database where you will store all the necessary information about the created credit cards. We will use SQLite to create the database.
SQLite is a database engine. It is a software that allows users to interact with a relational database. In SQLite, a database is stored in a single file — a trait that distinguishes it from other database engines. This allows for greater accessibility: copying a database is no more complicated than copying the file that stores the data, and sharing a database implies just sending an email attachment.
You can use the sqlite3 module to manage SQLite database from Python. You don't need to install this module. It is included in the standard library.
To use the module, you must first create a Connection object that represents the database. Here the data will be stored in the example.s3db file:
import sqlite3
conn = sqlite3.connect('example.s3db')
Once you have a Connection, you can create a Cursor object and call its execute() method to perform SQL queries:
cur = conn.cursor()
# Executes some SQL query
cur.execute('SOME SQL QUERY')
# After doing some changes in DB don't forget to commit them!
conn.commit()
To get data returned by SELECT query you can use fetchone(), fetchall() methods:
cur.execute('SOME SELECT QUERY')
# Returns the first row from the response
cur.fetchone()
# Returns all rows from the response
cur.fetchall()
Objectives
In this stage, create a database named card.s3db with a table titled card. It should have the following columns:
id INTEGER
number TEXT
pin TEXT
balance INTEGER DEFAULT 0
Pay attention: your database file should be created when the program starts if it hasn’t yet been created. And all created cards should be stored in the database from now.
Do not forget to commit your DB changes right after executing a query!
Example
The symbol > represents the user input. Notice that it's not a part of the input.
1. Create an account
2. Log into account
0. Exit
>1
Your card has been created
Your card number:
4000003429795087
Your card PIN:
6826
1. Create an account
2. Log into account
0. Exit
>2
Enter your card number:
>4000003429795087
Enter your PIN:
>4444
Wrong card number or PIN!
1. Create an account
2. Log into account
0. Exit
>2
Enter your card number:
>4000003429795087
Enter your PIN:
>6826
You have successfully logged in!
1. Balance
2. Log out
0. Exit
>1
Balance: 0
1. Balance
2. Log out
0. Exit
>2
You have successfully logged out!
1. Create an account
2. Log into account
0. Exit
>0
Bye!
'''
import random
import sqlite3
conn = sqlite3.connect('card.s3db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS card (id INTEGER PRIMARY KEY, number TEXT UNIQUE, pin TEXT, balance INTEGER DEFAULT 0);")
conn.commit()
account = {}
def main():
while 1:
n = int(input("1. create an account\n" + "2. Log into account\n" + "0. Exit\n"))
if n == 1:
createaccount()
elif n == 2:
r = logintoaccount()
if r == 2:
break
elif n == 0:
print("Bye!")
break
def luhh(cardnumber):
l = list(cardnumber)
s = int(l[-1])
for i in range(0, 15):
if i % 2 == 0:
if int(l[i]) * 2 > 9:
s = s + (int(l[i]) * 2) - 9
else:
s += int(l[i]) * 2
else:
s += int(l[i])
if s % 10 == 0:
return True
else:
return False
def createaccount():
while True:
inputpin = random.randint(1000, 10000)
y = random.randint(10 ** 9, 10 ** 10)
cardnumber = str(400000) + str(y)
if luhh(cardnumber):
break
print("Your card has been created")
print("Your card number")
print(cardnumber)
print("Your card pin")
print(inputpin)
cur.execute("INSERT INTO card(number, pin, balance) VALUES (?,?,?);",(cardnumber, inputpin, 0))
conn.commit()
account[cardnumber] = inputpin
def logintoaccount():
x1 = 1
while x1 != 0:
cardnumber = input("Enter your card number:")
pin = input("Enter your PIN")
if len(cardnumber) == 16:
old_pin = cur.execute(f"SELECT pin FROM card WHERE number = {cardnumber} And pin = {pin};").fetchone()
if type(old_pin) == type(None):
print("Wrong card number or PIN!")
return 0
if len(old_pin) == 1 and old_pin[0] == pin:
print("You successfully logged in!")
while 1:
print("1. Balance\n" + "2. Log out\n" + "0. Exit\n")
n1 = int(input())
if n1 == 1:
print("Balance: 0")
return 0
elif n1 == 2:
print("You have successfully logged out!")
return 0
elif n1 == 0:
print("Bye!")
return 2
else:
print("Wrong card number or PIN!")
return 0
else:
print("Wrong card number or PIN!")
return 0
main()
|
36440fbb16612d81dd8f83c201aa970cc7cfcfa4 | caszimirbehrens/patatje_met | /python3_III.py | 256 | 4.1875 | 4 | def reverse_string(woord):
stringA = ""
stringB = ""
for letter in woord:
stringA = letter
stringA += stringB
stringB = stringA
return stringB
woordje = input("geef woord ")
print(reverse_string(woordje))
|
81dd41a5eedecb63d2b6738c5de7ae1398a6992e | Shandmo/Struggle_Bus | /Other/Restaurant.py | 615 | 3.984375 | 4 | ## 9-1 Restaurant
## __init__ method should store two attributes. Make two methods, one that describes the restaurant, and one that "opens" the restaurant.
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
# attach attributes
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f"Restaurant Name: {self.restaurant_name.title()}\nCuisine: {self.cuisine_type.title()}")
def open_restaurant(self):
print(f"{self.restaurant_name.title()} is open for business!")
|
2dddce458a8f69b5419db323365b4c96d32ae859 | 4lasR0ban/Belajar-Python | /Tipe data dinamis/latihan01.py | 609 | 3.84375 | 4 | # latihan projek python
sayur = ['bayam', 'kangkung', 'wortel', 'selada']
print('Menu:')
print('1. Tambah data sayur')
print('2. Hapus data')
print('3. Tampilkan data sayur')
tambah = 1
hapus = 2
show = 3
choice = int(input('Pilihan anda: '))
while True:
if choice == 1:
x = str(input('Tambah data sayur: '))
sayur = sayur + [x]
print(sayur)
break
if choice == 2:
x = str(input('Sayur yang akan dihapus: '))
sayur.remove(x)
print(sayur)
break
if choice == 3:
print(sayur)
break
else:
print('Maaf input salah')
|
c9d8d9b2fa39a113217231b955c1a01e42eb9186 | red-sap/cloud1907 | /06.function/01.function_defind.py | 784 | 3.640625 | 4 | # 在Python中为了让程序能够得到精简,我们回去引入函数的概念
# number = [1, 4, 2, 3, 5, 1]
# for i in range(len(number)):
# for j in range(len(number) - 1):
# if number[j] > number[j+1]:
# number[j], number[j+1] = number[j+1], number[j]
#
#
# number02 = [23, 12, 34, 115, 123]
# for i in range(len(number)):
# for j in range(len(number) - 1):
# if number[j] > number[j+1]:
# number[j], number[j+1] = number[j+1], number[j]
# 函数的定义
def funcName(param):
pass
def mp(l):
for i in range(len(l)):
for j in range(len(l) - 1):
if l[j] > l[j+1]:
l[j], l[j+1] = l[j+1], l[j]
print(l)
mp([12, 10, 45, 23, 31, 21])
number = [12, 11, 23, 21, 45, 34, 25]
mp(number)
|
704b120794dbc7367dbd65f86c39aed1243c2722 | MarcioPorto/federated-phenotyping | /project/phenotyping/dataset.py | 992 | 3.5625 | 4 | import pandas as pd
class DatasetProvider:
def __init__(self,train_path,test_path):
self.train_path = train_path
self.test_path = test_path
self.data_train = pd.read_csv(train_path)
self.data_test = pd.read_csv(test_path)
def split_data(self,data_stream,num_parts):
"""Divides the data into given number of parts"""
list_data = []
start = 0
part = len(data_stream) // num_parts
for i in range(num_parts):
if(i == num_parts - 1):
list_data.append(data_stream[start:])
else:
list_data.append(data_stream[start:start + part])
start += part
return list_data
def provide_data(self,dataset = 'train',splits = 3):
if(dataset == 'train'):
return self.split_data(self.data_train,splits)
elif(dataset == 'test'):
return self.split_data(self.data_test,splits) |
992efbbb16605888dd85496235e5f7cbd73c862a | zois-tasoulas/algoExpert | /medium/linkedListConstruction.py | 4,720 | 3.828125 | 4 | class Node:
"""
value : int
prev : Node
next : Node
"""
def __init__(self, value, prev=None, nxt=None):
self.value = value
self.prev = prev
self.next = nxt
class DoublyLinkedList:
"""
head : Node
tail : Node
"""
def __init__(self):
self.head = None
self.tail = None
def searchNode(self, node):
current = self.head
while current and current != node:
current = current.next
return current
def insertBefore(self, node, nodeToInsert):
current = self.searchNode(nodeToInsert)
if current:
self.remove(current)
nodeToInsert.next = node
nodeToInsert.prev = node.prev
if node.prev:
node.prev.next = nodeToInsert
node.prev = nodeToInsert
if self.head == node:
self.head = node.prev
def insertAfter(self, node, nodeToInsert):
current = self.searchNode(nodeToInsert)
if current:
self.remove(current)
nodeToInsert.next = node.next
nodeToInsert.prev = node
if node.next:
node.next.prev = nodeToInsert
node.next = nodeToInsert
if self.tail == node:
self.tail = self.tail.next
def insertAtPosition(self, position, nodeToInsert):
if position < 1:
raise Exception("position should be a positive integer")
if position == 1:
self.setHead(nodeToInsert)
else:
node = self.head
for _ in range(1, position):
if not node:
break
node = node.next
if not node:
raise Exception("List shorter than the requested position")
self.insertBefore(node, nodeToInsert)
def setHead(self, node):
if not self.tail and not self.head:
self.head = node
self.tail = node
else:
if not self.head:
current = self.tail
while current.prev:
current = current.prev
self.head = current
self.insertBefore(self.head, node)
def setTail(self, node):
if not self.tail and not self.head:
self.tail = node
self.head = node
else:
if not self.tail:
current = self.head
while current.next:
current = current.next
self.tail = current
self.insertAfter(self.tail, node)
def remove(self, node):
if self.head == node and self.tail == node:
self.head = None
self.tail = None
elif self.head == node:
self.head = self.head.next
if self.head:
self.head.prev = None
elif self.tail == node:
self.tail = self.tail.prev
if self.tail:
self.tail.next = None
else:
node.prev.next = node.next
node.next.prev = node.prev
node.next = None
node.prev = None
def removeNodesWithValue(self, value):
current = self.head
while current:
temp = current.next
if current.value == value:
self.remove(current)
current = temp
def containsNodeWithValue(self, value):
current = self.head
while current:
if current.value == value:
return True
current = current.next
return False
def print(self):
if not self.head:
print("Empty list")
return
current = self.head
while current.next:
print(current.value, end="->")
current = current.next
print(current.value)
if self.head:
if self.tail:
print("head:", self.head.value, end=" ")
else:
print("head:", self.head.value)
if self.tail:
print("tail:", self.tail.value)
def main():
dl_list = DoublyLinkedList()
dl_list.print()
node_1 = Node(1)
dl_list.setHead(node_1)
dl_list.print()
node_7 = Node(7)
dl_list.setTail(node_7)
dl_list.print()
node_5 = Node(5)
dl_list.insertAtPosition(2, node_5)
dl_list.print()
node_3 = Node(3)
dl_list.insertBefore(node_5, node_3)
dl_list.print()
node_4 = Node(4)
dl_list.insertAfter(node_3, node_4)
dl_list.print()
dl_list.remove(node_5)
dl_list.print()
dl_list.removeNodesWithValue(3)
dl_list.print()
print(dl_list.containsNodeWithValue(2))
if __name__ == "__main__":
main()
|
d54a5e47079f0347cfe4680278911596ae923a21 | not-sponsored/Guide-to-Data-Structures-and-Algorithms-Exercises | /algorithms/middle_link.py | 2,463 | 3.84375 | 4 | import sys
class Node():
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_node(self):
print(self.value)
class SinglyLinkedList():
def __init__(self, head=None):
self.head = head
def add_node(self, val):
new_node = Node(val)
if self.head == None:
self.head = new_node
else:
pointer = self.head
while pointer.next != None:
pointer = pointer.next
pointer.next = new_node
def add_many_nodes(self, values):
for val in values:
self.add_node(val)
def print_nodes(self):
pointer = self.head
if pointer != None:
pointer.print_node()
while pointer.next != None:
pointer = pointer.next
pointer.print_node()
def get_last_node(self):
pointer = self.head
if pointer == None:
print('Error no nodes')
return
while pointer.next != None:
pointer = pointer.next
return pointer
def reverse_nodes(self):
pointer_one = self.head
# if no nodes do nothing
if pointer_one != None:
pointer_two = pointer_one.next
pointer_one.next = None
# if only one node then we are done
if pointer_two != None:
# have pointers at nOne, nTwo, nThree
pointer_three = pointer_two.next
while pointer_three != None:
# point second.next to first
pointer_two.next = pointer_one
# point first to second
pointer_one = pointer_two
# point second to third
pointer_two = pointer_three
# point third to fourth
pointer_three = pointer_two.next
# handle two nodes or more case
pointer_two.next = pointer_one
self.head = pointer_two
def count(self, pointer):
if pointer == None:
return 0
if pointer.next == None:
return 1
else:
return 1 + self.count(pointer.next)
def middle(self, node_cnt):
middle = int(node_cnt/2)
if middle == 0:
print('Cannot divide list')
return
pointer = self.head
count = 0
while count < middle:
pointer = pointer.next
count += 1
return pointer
def main(arr):
single_ll = SinglyLinkedList()
single_ll.add_many_nodes(arr)
node_count = single_ll.count(single_ll.head)
print(f"node count: {node_count}")
middle_node = single_ll.middle(node_count)
print(f'middle node: {middle_node.value}')
# copy value of next node then link to next next node
middle_node.value = middle_node.next.value
middle_node.next = middle_node.next.next
single_ll.print_nodes()
if __name__ == '__main__':
main([int(x) for x in sys.argv[1].split(',')])
|
307984652ba4607429f90d40b736121de7735583 | konfer/PythonTrain | /src/train/test/NestedLoopTest.py | 190 | 3.78125 | 4 | # coding:utf-8
row = 0
column = 0
theNum = int(raw_input("Please input a num:\n"))
i = 1
while i < theNum:
i += 1
j = 1
while j < i:
print j,
j += 1
print
|
7845c82ef3fb0b8f82fc1d7424e95af1a9cbb816 | PrestonTGarcia/Electric-Field | /Electric-Field-3D/visualization.py | 8,142 | 4.375 | 4 | ##################################################################
# visualization --- Program that creates a 3D matplotlib graph #
# that visualizes the electric field created from two particles #
# created from the user's inputs. #
# @author Preston Garcia #
##################################################################
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
# Constants
K = 8.99 * np.power(10, 9)
def createSphere(c, r):
"""Method that creates the information for the sphere
that represents the particles given the center and the
radius of the sphere.
Parameters
----------
c - The array containing the x, y, and z coordinates of
the center of the sphere.
r - The radius of the sphere.
Return
----------
[x, y, z] - The datapoints for the entire cirlce in the x,
y, and z directions.
"""
phi = np.linspace(0, 2*np.pi, 100)
theta = np.linspace(0, np.pi, 100)
x = r * np.outer(np.cos(phi), np.sin(theta)) + c[0]
y = r * np.outer(np.sin(phi), np.sin(theta)) + c[1]
z = r * np.outer(np.ones(np.size(phi)), np.cos(theta)) + c[2]
return [x, y, z]
def findSigns(x, y, z, x1, y1, z1, q1, x2, y2, z2, q2):
"""
Method that finds the signs and reduces the length
of each of the arrows in the vector field. This method
uses the equation Fx = KQ / r^2 * rx / r,
Fy = KQ / r^2 * ry / r and Fz = KQ / r^2 * rz / r.
All of these equations simplify to Fx = KQrx / r^3 and
Fy = KQry / r^3 and Fz = KQrz / r^3.
Parameters
----------
x - The x coordinate of the current particle on the vector field
y - The y coordinate of the current particle on the vector field
z - The z coordinate of the current particle on the vector field
x1 - The x coordinate of the first particle entered by user
y1 - The y coordinate of the first particle entered by user
z1 - The z coordinate of the first particle entered by user
q1 - The charge of the first particle entered by user
x2 - The x coordinate of the second particle entered by user
y2 - The y coordinate of the second particle entered by user
z2 - The z coordinate of the second particle entered by user
q2 - The charge of the second particle entered by user
Return
----------
signsArr - The xf, yf, zf, and net force of the arrows
signsArr[0] - The xf
signsArr[1] - The yf
signsArr[2] - The zf
signs
"""
r1x = x - x1
r1y = y - y1
r1z = z - z1
r1 = np.sqrt(np.square(r1x) + np.square(r1y) + np.square(r1z))
r2x = x - x2
r2y = y - y2
r2z = z - z2
r2 = np.sqrt(np.square(r2x) + np.square(r2y) + np.square(r2z))
denom1 = np.power(r1, 3)
denom2 = np.power(r2, 3)
if (denom1 == 0):
eForce1X = 0
eForce1Y = 0
eForce1Z = 0
else:
eForce1X = (K * q1 * r1x) / (denom1)
eForce1Y = (K * q1 * r1y) / (denom1)
eForce1Z = (K * q1 * r1z) / (denom1)
if (denom2 == 0):
eForce2X = 0
eForce2Y = 0
eForce2Z = 0
else:
eForce2X = (K * q2 * r2x) / (denom2)
eForce2Y = (K * q2 * r2y) / (denom2)
eForce2Z = (K * q2 * r2z) / (denom2)
eNetX = eForce1X + eForce2X
eNetY = eForce1Y + eForce2Y
eNetZ = eForce1Z + eForce2Z
eNetForce = np.sqrt(np.square(eNetX) + np.square(eNetY) + np.square(eNetZ))
signsArr = [eNetX / np.abs(eNetX), eNetY / np.abs(eNetY), eNetZ / np.abs(eNetZ), eNetForce]
return signsArr
def main(x1E, y1E, z1E, q1E, x2E, y2E, z2E, q2E):
"""
Method that creates the visualization for the electric field
around both of the particles created by user.
Parameters
----------
x1E - The value from the x1 entry on the main window
y1E - The value from the y1 entry on the main window
z1E - The value from the z1 entry on the main window
q1E - The value from the q1 entry on the main window
x2E - The value from the x2 entry on the main window
y2E - The value from the y2 entry on the main window
z2E - The value from the z2 entry on the main window
q2E - The value from the q2 entry on the main window
"""
# Converts each to floats since Entry.get() returns a string
try:
x1 = float(x1E)
y1 = float(y1E)
z1 = float(z1E)
q1 = float(q1E)
x2 = float(x2E)
y2 = float(y2E)
z2 = float(z2E)
q2 = float(q2E)
except ValueError:
mb.showerror("Value Error", "One or more of your values are not a number.")
midXFrom1 = (x2 - x1)/2
midYFrom1 = (y2 - y1)/2
midZFrom1 = (z2 - z1)/2
midXFrom2 = -midXFrom1
midYFrom2 = -midYFrom1
midZFrom2 = -midYFrom1
signsList = []
forceList = []
forceXAreas = np.arange(min(x1, x2) - 10, max(x1, x2) + 10, 5)
forceYAreas = np.arange(min(y1, y2) - 10, max(y1, y2) + 10, 5)
forceZAreas = np.arange(min(z1, z2) - 10, max(z1, z2) + 10, 5)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_xlim(min(x1, x2) - 10, max(x1, x2) + 10)
ax.set_ylim(min(y1, y2) - 10, max(y1, y2) + 10)
ax.set_zlim(min(z1, z2) - 10, max(z1, z2) + 10)
p1 = createSphere([x1, y1, z1], 1)
p2 = createSphere([x2, y2, z2], 1)
if (q1 <= 0): #Checks for protons or electrons
ax.plot_surface(p1[0], p1[1], p1[2], color='b') # b = electron
else:
ax.plot_surface(p1[0], p1[1], p1[2], color='r') # r = proton
if (q2 <= 0):
ax.plot_surface(p2[0], p2[1], p2[2], color='b')
else:
ax.plot_surface(p2[0], p2[1], p2[2], color='r')
# Coloumb force arrows
if (q2/q1 > 0):
ax.quiver(x1, y1, z1, -midXFrom1, -midYFrom1, -midZFrom1, color='black')
ax.quiver(x2, y2, z2, -midXFrom2, -midYFrom2, -midZFrom2, color='black')
else:
ax.quiver(x1, y1, z1, midXFrom1, midYFrom1, midZFrom1, color='black')
ax.quiver(x2, y2, z2, midXFrom2, midYFrom2, midZFrom2, color='black')
# Electric field arrows
for i in range(0, len(forceXAreas)):
for j in range(0, len(forceYAreas)):
for k in range(0, len(forceZAreas)):
forceSigns = findSigns(forceXAreas[i], forceYAreas[j], forceZAreas[k], x1, y1, z1,
q1, x2, y2, z2, q2)
signsList.append([forceSigns[0], forceSigns[1], forceSigns[2]])
forceList.append(forceSigns[3])
#ax.quiver(forceXAreas[i], forceYAreas[j], forceZAreas[k], signs[0], signs[1], signs[2])
threshholdOne = np.average(forceList) / 3
threshholdTwo = threshholdOne * 2
threshholdThree = threshholdOne * 3
forceIndex = 0
for i in range(0, len(forceXAreas)):
for j in range(0, len(forceYAreas)):
for k in range(0, len(forceZAreas)):
if forceList[forceIndex] > threshholdThree:
ax.quiver(forceXAreas[i], forceYAreas[j], forceZAreas[k], signsList[forceIndex][0],
signsList[forceIndex][1], signsList[forceIndex][2], color="red")
elif forceList[forceIndex] > threshholdTwo and forceList[forceIndex] < threshholdThree:
ax.quiver(forceXAreas[i], forceYAreas[j], forceZAreas[k], signsList[forceIndex][0],
signsList[forceIndex][1], signsList[forceIndex][2], color="orange")
elif forceList[forceIndex] > threshholdOne and forceList[forceIndex] < threshholdTwo:
ax.quiver(forceXAreas[i], forceYAreas[j], forceZAreas[k], signsList[forceIndex][0],
signsList[forceIndex][1], signsList[forceIndex][2], color="yellow")
elif forceList[forceIndex] < threshholdOne:
ax.quiver(forceXAreas[i], forceYAreas[j], forceZAreas[k], signsList[forceIndex][0],
signsList[forceIndex][1], signsList[forceIndex][2], color="green")
forceIndex += 1
plt.show()
|
68b91a2c95f8a2fd1c7245f16b78d1679c88251d | mintdouble/LeetCode | /Easy/598_范围求和||/main.py | 328 | 3.625 | 4 | # 思路:返回x坐标的最小值与y坐标最小值的乘积,因为坐标值越小加1的次数越多,所以最大值集中在矩阵的左上角
class Solution:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
return m*n if len(ops) < 1 else min([x[0] for x in ops]) * min(x[1] for x in ops)
|
e0507ab3347ed687581ce2d29bd706dd907aa626 | ferxohn/proyecto1 | /REPORTE-01-GOMEZ-FERNANDO.py | 17,897 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Por: Fernando Gómez Perera
import lifestore_file as lifestore
# Variables que contienen los distintos conjuntos de datos
products = lifestore.lifestore_products
sales = lifestore.lifestore_sales
searches = lifestore.lifestore_searches
# Listas con los usuarios y contrasenas registradas en el sistema
users = ['fernando', 'vanessa', 'javier']
passwords = ['fernando123', 'vanessa123', 'javier123']
# Variables auxiliares para la ejecucion del login de usuario
attempts = 3
can_run = False
user_input = None
# Implementacion del login de usuario
while attempts > 0:
# El usuario ingresa su nombre de usuario si previamente no lo ha hecho
if user_input == None:
user_input = input('Ingrese un nombre de usuario: ')
user_exists = False
# Se comprueba si el nombre de usuario existe en el sistema
for i in range(len(users)):
if user_input == users[i]:
user_ind = i
user_exists = True
# Si el nombre de usuario no existe en el sistema, el sistema se cierra
if not(user_exists):
print('El usuario ingresado no existe.')
break
# El usuario ingresa su contrasena
else:
password_input = input('Ingrese su contrasena: ')
# Si su contrasena es invalida, entonces pierde un intento
if password_input != passwords[user_ind]:
print('La contraseña ingresada es invalida.')
attempts -= 1
# Si su contrasena es valida, entonces el sistema le da acceso
else:
can_run = True
break
# Comprobar si el usuario tiene acceso al sistema
if can_run:
print('\n¡Bienvenido!')
else:
exit()
# Lista para guardar el acumulado de ventas por producto
sales_by_prod = list()
# Contador de ventas totales de todos los productos
total_sales = 0
# Obtener las ventas totales por producto
for product in products:
sales_product = 0
sales_product_refund = 0
sum_score = 0
mean_score = -1
refunds = 0
for sale in sales:
# Comprobar si la venta le pertenece al producto actual
if product[0] == sale[1]:
# Se aumenta el total de ventas de ese producto
sales_product += 1
# Se aumenta la puntuacion del producto
sum_score += sale[2]
# Si el producto fue reembolsado, se aumenta el total de reembolsos de ese producto
if sale[-1]:
sales_product_refund += 1
# Las ventas totales de todos los productos se aumentan
total_sales += sales_product
# Se calcula el promedio de puntuacion del producto
if sales_product:
mean_score = sum_score // sales_product
# Se indica si el producto tuvo reembolsos
if sales_product_refund:
refunds = 1
sales_by_prod.append(product + [mean_score, refunds, sales_product])
# Lista para guardar el acumulado de busquedas por producto
searches_by_prod = list()
# Acumulador del total de busquedas de todos los productos
total_searches = 0
# Obtener las busquedas totales por producto
for product in products:
searches_product = 0
for search in searches:
if product[0] == search[1]:
searches_product += 1
total_searches += searches_product
searches_by_prod.append(product + [searches_product])
# Filtrar y obtener las categorias de los productos
categories = list()
for product in products:
unique_category = True
for category in categories:
if product[3] == category:
unique_category = False
break
if unique_category:
categories.append(product[3])
# Menu para ejecutar alguna de las funciones disponibles en el sistema
while True:
print('*** Elija una de las siguientes opciones: ***')
print('1. Explorar los datos')
print('2. Ver los productos mas vendidos y productos rezagados')
print('3. Ver los productos por reseña en el servicio')
print('4. Total de ingresos y ventas promedio mensuales, total anual y meses con mas ventas al anio')
print('Ingrese cualquier otra tecla u oprima Ctrl+C para salir.')
functions = ['1', '2', '3', '4']
function_input = input('\nIngrese el numero de la funcion y oprima Enter: ')
function_selected = 0
# Comprobar la entrada del usuario
if len(function_input) == 1 and function_input != '':
for function in functions:
if function_input == function:
function_selected = int(function_input)
# Ejecutar alguna de las funciones disponibles en el sistema si la entrada del usuario es valida
if function_selected:
if function_selected == 1:
# Visualizar los primeros 5 registros de la lista de productos
print('\nTotal de productos: ', len(products))
print('* Primeros 5 registros:')
print('----------------------------------------------------------------')
print(' ID | Nombre | Precio | Categoria | Stock ')
print('----|---------------------------|--------|--------------|-------')
for product in products[0:5]:
print(' '+str(product[0])+' | '+product[1][0:20]+'. . .'+' | '+str(product[2])+' | '+product[3]+' | '+str(product[4]))
# Visualizar los primeros 5 registros de la lista de ventas
print('\nTotal de ventas: ', len(sales))
print('* Primeros 5 registros:')
print('-------------------------------------------------------')
print(' ID | ID prod | Puntuacion | Fecha | Reembolso ')
print(' | | (1 al 5) | | (1 sí, 0 no) ')
print('----|---------|------------|------------|--------------')
for sale in sales[0:5]:
print(' '+str(sale[0])+' | '+str(sale[1])+' | '+str(sale[2])+' | '+sale[3]+' | '+str(sale[4]))
# Visualizar los primeros 5 registros de la lista de busquedas
print('\nTotal de busquedas: ', len(searches))
print('* Primeros 5 registros:')
print('------------------')
print(' ID | ID producto ')
print('----|-------------')
for search in searches[0:5]:
print(' '+str(search[0])+' | '+str(search[1]))
print('\n')
if function_selected == 2:
# Ordenar los productos por sus ventas totales de forma descendente
for i in range(len(sales_by_prod)):
current_ind = i
last_ind = i - 1
while sales_by_prod[last_ind][-1] < sales_by_prod[current_ind][-1] and last_ind > -1:
sales_by_prod[current_ind], sales_by_prod[last_ind] = sales_by_prod[last_ind], sales_by_prod[current_ind]
current_ind -= 1
last_ind -= 1
# Lista para almacenar los productos mas vendidos
best_selling_products = list()
# Obtener los productos que representen el 60% de todas las ventas
sum_sales = sales_by_prod[0][-1]
i = 0
while sum_sales <= total_sales*0.6:
best_selling_products.append(sales_by_prod[i])
i += 1
sum_sales += sales_by_prod[i][-1]
# Mostrar el listado con los productos obtenidos
print('\n* Productos mas vendidos')
print('--------------------------------------')
print(' Nombre | Ventas ')
print('-----------------------------|--------')
for product in best_selling_products:
print(' '+product[1][0:20] + '. . . | ', product[-1])
# Ordenar los productos por sus busquedas totales de forma descendente
for i in range(len(searches_by_prod)):
current_ind = i
last_ind = i - 1
while searches_by_prod[last_ind][-1] < searches_by_prod[current_ind][-1] and last_ind > -1:
searches_by_prod[current_ind], searches_by_prod[last_ind] = searches_by_prod[last_ind], searches_by_prod[current_ind]
current_ind -= 1
last_ind -= 1
# Lista para almacenar los productos mas buscados
most_searched_products = list()
# Obtener los productos que representen el 60% de todas las busquedas
sum_searches = searches_by_prod[0][-1]
i = 0
while sum_searches <= total_searches*0.6:
most_searched_products.append(searches_by_prod[i])
i += 1
sum_searches += searches_by_prod[i][-1]
# Mostrar el listado con los productos obtenidos
print('\n* Productos mas buscados')
print('-----------------------------------------')
print(' Nombre | Busquedas ')
print('-----------------------------|-----------')
for product in most_searched_products:
print(' '+product[1][0:20] + '. . . | ', product[-1])
# Lista para almacenar los productos menos vendidos por categoria
worst_selling_products = list()
# Obtener los 6 productos menos vendidos por categoria
for category in categories:
i = 0
category_products = list()
for product in sales_by_prod[::-1]:
if product[3] == category:
i += 1
if i > 6:
break
category_products.append(product)
worst_selling_products.append(category_products)
# Mostrar el listado con los productos obtenidos
print('\n* Productos menos vendidos por categoria')
for category in worst_selling_products:
print('Categoria: ', category[0][3])
print('--------------------------------------')
print(' Nombre | Ventas ')
print('-----------------------------|--------')
for product in category:
print(' '+product[1][0:20] + '. . . | ', product[-1])
print('\n')
# Lista para almacenar los productos menos buscados por categoria
less_searched_products = list()
# Obtener los 7 productos menos vendidos por categoria
for category in categories:
i = 0
category_products = list()
for product in searches_by_prod[::-1]:
if product[3] == category:
i += 1
if i > 6:
break
category_products.append(product)
less_searched_products.append(category_products)
# Mostrar el listado con los productos obtenidos
print('\n* Productos menos buscados por categoria')
for category in less_searched_products:
print('Categoria: ', category[0][3])
print('-----------------------------------------')
print(' Nombre | Busquedas ')
print('-----------------------------|-----------')
for product in category:
print(' '+product[1][0:20] + '. . . | ', product[-1])
print('\n')
print('\n')
if function_selected == 3:
# Ordenar los productos por su puntuacion promedio de forma descendente
for i in range(len(sales_by_prod)):
current_ind = i
last_ind = i - 1
while sales_by_prod[last_ind][5] < sales_by_prod[current_ind][5] and last_ind > -1:
sales_by_prod[current_ind], sales_by_prod[last_ind] = sales_by_prod[last_ind], sales_by_prod[current_ind]
current_ind -= 1
last_ind -= 1
high_score_products = list()
# Obtener los 20 productos con las mejores puntuaciones
i = 0
while i < 20:
high_score_products.append(sales_by_prod[i])
i += 1
print('\n* Productos con mejores puntuaciones')
print('-----------------------------------------')
print(' Nombre | Puntuacion ')
print('-----------------------------|-----------')
for product in high_score_products:
print(' '+product[1][0:20] + '. . . | ', product[5])
# Ordenar los productos por su puntuacion promedio de forma ascendente
for i in range(len(sales_by_prod)):
current_ind = i
last_ind = i - 1
while sales_by_prod[last_ind][5] > sales_by_prod[current_ind][5] and last_ind > -1:
sales_by_prod[current_ind], sales_by_prod[last_ind] = sales_by_prod[last_ind], sales_by_prod[current_ind]
current_ind -= 1
last_ind -= 1
low_score_products = list()
# Obtener los 20 productos con las peores puntuaciones si tuvieron reembolsos
i = 0
for product in sales_by_prod:
if product[6]:
low_score_products.append(product)
i += 1
if i == 20:
break
print('\n* Productos con peores puntuaciones, si tuvieron reembolsos')
print('-----------------------------------------')
print(' Nombre | Puntuacion ')
print('-----------------------------|-----------')
for product in low_score_products:
print(' '+product[1][0:20] + '. . . | ', product[5])
print('\n')
if function_selected == 4:
# Filtrar y obtener los meses
months = list()
for sale in sales:
current_month = sale[3][3:5]
unique_month = True
for month in months:
if current_month == month:
unique_month = False
break
if unique_month:
months.append(current_month)
# Ordenar los meses de forma ascendentes
for i in range(len(months)):
current_ind = i
last_ind = i - 1
while months[last_ind] > months[current_ind] and last_ind > -1:
months[current_ind], months[last_ind] = months[last_ind], months[current_ind]
current_ind -= 1
last_ind -= 1
# Listas para almacenar las ventas y los ingresos por mes
months_sales = list()
months_incomes = list()
print('\n** Resumen mensual:')
# Se obtienen los valores mensuales
for month in months:
print('Mes: ', month)
month_sales = 0
month_incomes = 0
# La busqueda se hace por producto
for product in sales_by_prod:
month_sales_prod = 0
# Se calculan las ventas del mes de cada producto
for sale in sales:
current_product = sale[1]
current_month = sale[3][3:5]
if current_month == month and current_product == product[0]:
month_sales_prod += 1
# Se calculan las entradas que genero el producto en el mes
incomes_prod = product[2] * month_sales_prod
month_sales += month_sales_prod
month_incomes += incomes_prod
# Se despliegan los totales del producto si tuvo ventas en el mes
if month_sales_prod:
print('El producto '+product[1][0:20]+'. . . '+' de la categoria '+product[3]+ ' tuvo '+str(month_sales)+' ventas en el mes, ingresando $'+str(incomes_prod)+' en total.')
months_sales.append(month_sales)
months_incomes.append(month_incomes)
print('* El mes registro '+str(month_sales)+' ventas totales e ingresos por $'+str(month_incomes)+'.\n')
print('* En promedio, el mes registro ingresos por $' + str(month_incomes // month_sales)+'.\n')
# Se calculan los ingresos del anio
total_incomes = 0
for income in months_incomes:
total_incomes += income
print('\n** Resumen anual:')
print('El anio tuvo ' + str(total_sales) + ' ventas totales.')
print('El anio registro ingresos por $' + str(total_incomes) + ' en total.')
# Se obtiene el mes que registro mas ventas
max_sale = 0
for i in range(len(months_sales)):
if months_sales[max_sale] < months_sales[i]:
max_sale = i
print('* El mes ' + months[max_sale] + ' es el mes que registro mas ventas, con ' + str(months_sales[max_sale]) + ' ventas.')
# Se obtiene el mes que registro mas ingresos
max_income = 0
for i in range(len(months_incomes)):
if months_incomes[max_sale] < months_incomes[i]:
max_income = i
print('* El mes ' + months[max_income] + ' es el mes que registro mas ingresos, con ingresos por $' + str(months_incomes[max_income]) + ' totales.\n')
# Sino, el sistema se cierra
else:
print('\n¡Hasta luego!')
break
|
493d9421b90820f30501cca861197767bebf2934 | zhangxiaoyuan/pythonStudy | /src/loo_test.py | 1,294 | 3.796875 | 4 | #!usr/bin/python
#coding=utf-8
#while...else
count = 0
while count < 5:
print 'count=', count
count += 1
else:
print count, 'more than 5'
count =0
while count < 5:
print 'count=', count
count +=1
if count ==3:
break;
else:
print count ,'more than 5'
print 'if break can not execute else'
#for & for...else
i = 0
for word in 'python':
print 'word ',i,word
i +=1
list = ['123','abc', 12, 14, 15]
for ele in list:
print "ele : ", ele
tuple= ('apple', "pear", 'banana')
for index in range(len(tuple)):
print 'fruit is ', tuple[index]
for index in range(0,3):
print "fuint :", tuple[index]
#for...else
for i in range(10,20):
for j in range(2, i):
if (i % j == 0):
x = i /j
print "%d = %d * %d," % (i,j,x)
break;
else:
print i, 'is zhishu'
#pass unvaluable,just for fill ,empty sentense
for i in range(0, 3):
if i == 2:
pass
print 'just pass sentense,empty.unvaluable'
print 'value=', i
ivar1=10
var2 = 20;
print 'va = ', ivar1,var2
del ivar1
del var2
#print 'val = ', ivar1,var2 #wrong sentense, 2 para undefined
#random function
import random
fruit = ['apple','pear','banana','grape','mango',"xigua"]
print 'fruit : ', random.choice(fruit)
print 'a num in 100 adn 10000: ', random.randrange(5,10, 5)
str = 'hello world'
print str[0], str[1:5]
|
3435cf59814000c8047d7ccaf6777a9e1f1dd7fe | ArtemBaldin/STUDY | /PYTHON_INTRODUCTION/HOMEWORKS/home_work_4.py | 1,746 | 3.8125 | 4 | # That was intresting)))
import sys
def if_ru_in_text (text_):
ru_a="а, б, в, г, д, е, ё, ж, з, и, й, к, л, м, н, о, п, р, с, т, у, ф, х, ц, ч, ш, щ, ъ, ы, ь, э, ю, я"
ru_a=ru_a.replace("," " ", "")
ru_a=list(ru_a)
ch_text=0
for i in range(len(ru_a)):
ch_text +=text_.count(ru_a[i])
return ch_text
var_string = "hApPyHalLOweEn!"
print("Counting of vowels in string. Only in English.\n")
print("You can input your own string or use defaul option.")
print (f"\nDefault string is: {var_string}.\n")
print("Press: \n1- To input own string \n2- To use default string.")
try:
x= int(input("Input: "))
while x!=1 and x!=2:
x=int(input("Input right number: "))
if x==1:
var_string=input ("Your string is: ")
while if_ru_in_text (var_string)>0:
print("\nВы ввели Русские буквы. \nInput text in English.\n")
var_string=input ("Your string is: ")
except:
print ("\nWrong symbol.")
sys.exit("Program interrupted")
#print(f"\nnYour string is: {var_string}")
print("\nFirst way solution.\n-------------------")
#var_string = "hApPyHalLOweEn!"
#print(f"Your string: {var_string}")
var_string = var_string.lower()
vowels_list = "aeiou"
counting_vowels = 0
for i in vowels_list:
for k in var_string:
if i == k:
counting_vowels += 1
print(f"Total vowels in the string = {counting_vowels}")
###
#Second variant
print("\n\nSecond way solution.\n--------------------")
#var_string = "hApPyHalLOweEn!"
var_string= var_string.lower()
vowels_list='a', 'e', 'i', 'o', 'u'
vowels_list=list(vowels_list)
counting_vowels=0
for i in range(len(vowels_list)):
counting_vowels +=var_string. count(vowels_list[i])
print(f"Total vowels in the string = {counting_vowels}")
|
cc96c3b3eb94b24d228159c0eadf545174cb35df | naix5526/genese-final_python | /assignment-4b.py | 1,027 | 4.1875 | 4 | '''Implement question number 1, 2 and 4 from Session 2 Exercise as different functions in a single (.py) file.'''
'''1. Choose a list of your choice and find the sum of all elements of that list. For example, the
sum of [6,9,7,5,4] is 31.'''
example = [6,9,7,5,4]
def ele(choice):
sum = 0
for str1 in choice:
sum += str1
print("The sum of the list is:",sum)
ele(example)
'''2. Write a program that returns a list which contains common elements from two lists. Avoid
the duplicate elements from lists.'''
a = [1, 1, 3, 5, 7, 9, 9]
b = [2, 1, 6 ,9, 2, 1, 3, 5]
def dup(a,b):
inter = list(set(a) & set(b))
print('The common element from the list are',inter)
dup(a,b)
'''4. Write a code to ask an input from the user which is a string and display the string along
with its length.'''
inp = str(input("Enter a string to check the length "))
def length(e):
cou = 0
print("The string is:",e)
for each in e:
cou += 1
print("The length of the string is:",cou)
length(inp)
|
12f5d00abfa2d3dba5136c76570d5863a579fea2 | kidusasfaw/addiscoder_2016 | /labs/server_files_without_solutions/lab6/numKnightWays/numKnightWaysSolFast.py | 720 | 3.796875 | 4 | import sys
# This function takes as input two coordinates x and y, which the knight
# must eventually reach, and a list of pairs L. L[i] should be a list of
# length 2, representing a possible knight move--for example, if L[i] is
# [4, 5], the knight can move four units horizontally and five vertically
# in a single move.
def numKnightWays(x, y, L):
# student should implement this function
###########################################
# INPUT OUTPUT CODE. DO NOT EDIT CODE BELOW.
x, y, length = tuple(map(int, sys.stdin.readline().split()))
L = [map(int, sys.stdin.readline().split()) for i in range(length)]
ans = numKnightWays(x, y, L)
sys.stdout.write(str(ans))
sys.stdout.flush()
print ''
|
a707419fcc9f00aec6c5ff4883de62bf5f25ff92 | anastasiia-shevchenko/Python-3-course | /lab 01-02/main.py | 924 | 3.953125 | 4 | import math
a=True
while a:
print("Введите Х (Х>0)")
x = int(input())
if x<=0 :
print("Вы ввели не верное значение Х")
else:
a = (math.sqrt((3 * x + 2) ** 2 - 24 * x))
b = (3 * math.sqrt(x) - (2 / math.sqrt(x)))
Z = a / b
print("Результат:", Z)
a=False
print("---Определение избыточного числа---")
a=True
while a:
print("Введите N (N>0)")
n = int(input())
k=0
if n<=0 :
print("Вы ввели не верное значение N")
else:
for i in range(1,n/2):
if n%i==0:
k+=i
print(k)
a=False
if k>n:
print("Число", n, "избыточное так как сумма = ", k, ">", n)
else:
print("Число", n, "не избыточное так как сумма = ", k, "<=", n)
|
f7ffda930cc18f0c3a90535acf051fc8e851c486 | namhoang1594/PXU_Python | /Find_Min.py | 249 | 3.703125 | 4 | import random
n = int(input("Hay nhap so phan tu:"))
array = []
for item in range(n):
a = float(random.uniform(0,99))
array.append(a)
print(array)
min = array[0]
for item in array:
if item < min:
min = item
print("Min la: ", min) |
0c34f144d6e3087d14b5b32a2d90e22742d08e8e | 1798317135/note | /python/python函数/匿名函数.py | 674 | 3.59375 | 4 |
# 匿名函数 lambad 函数 与 javascript的匿名函数有很大差别
# 匿名函数 不宜处理复杂的程序
#
# ****** 方式一 *********
# --- (lambad 形参:返回值)(实参)
result = (lambda a,b:a + b)(1,2)
print(result)
# ******* 方式二 ********
#
# --- 用变量接收 匿名函数体 lambad 形参:返回值
result = lambda a,b : a -b
print(result(5, 1))
# ******* 运用场景 ********
#
# --- sorted() 里面的key接收的函数体可以用匿名函数 ,非常方便
arr = [{"name":"c","age":15},{"name":"a","age":16},{"name":"b","age":17}]
result = sorted(arr,key = lambda x : x["name"],reverse = True)
print(result) |
1dee15d1d03c2352072e2a0448d1d2ca612de320 | pranee786/python-scripts | /networking/tcpipserver.py | 629 | 3.71875 | 4 | import socket
host = 'localhost'
port = 4000
# Internet Protocol version 4, and TCP IP Protocol connection
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Socket to be binded with the set of host and port
s.bind((host,port))
# Server will start listening to the port
print('Server listening on port: ',port)
s.listen(1)
# Server will accept the client connection when client tries to connect to the server
c,addr = s.accept()
print('Connection from : ',str(addr))
# Server can send information using the connection
# The information should be encoded
c.send(b'Hello, How are you?')
c.send('Bye'.encode())
c.close()
|
e93688f364ebf3cbc94ecb4cfa9a706d0edbc1b5 | keiirizawa/BootCamp2019 | /ProblemSets/Computation/Wk1-DifInt/ProblemSet1b/shut_box.py | 1,878 | 3.859375 | 4 | import box
import numpy as np
import random
import time
import sys
if len(sys.argv) == 3:
player_name = sys.argv[1]
time_limit = float(sys.argv[2])
else:
print("Need three arguments!")
def simulate_roll(numbers_left):
if sum(numbers_left) <= 6:
return random.randint(1,6)
else:
return random.randint(1,6) + random.randint(1,6)
numbers_left = list(range(1,10))
start_time = time.time()
end_time = start_time + time_limit
no_choice = False
while (time.time() < end_time) & (len(numbers_left) != 0):
print("Numbers left: ", numbers_left)
rolls = simulate_roll(numbers_left)
print("Roll: ", rolls)
print("Seconds left: ", round(end_time - time.time()))
# Numbers cannot match roll.
if not box.isvalid(rolls, numbers_left):
print("Numbers left: ", numbers_left)
print("Roll: ", rolls)
print("Game Over!")
print("\n")
no_choice = True
break
else:
player_input = input("Numbers to eliminate: ")
print("\n")
list_integers = box.parse_input(player_input, numbers_left)
for integer in list_integers:
numbers_left.remove(integer)
final_time = round(time.time() - start_time, 2)
if no_choice:
print("Score for player {}: ".format(player_name), sum(numbers_left))
print("Time played: {} seconds".format(round(final_time)))
print("Better luck next time >:)")
# No numbers_left:
elif len(numbers_left) == 0:
print("Score for player {}: ".format(player_name), sum(numbers_left))
print("Time played: {} seconds".format(round(final_time)))
print("Congratulations!! You shut the box!")
# Time is Up!
else:
print("Score for player {}: ".format(player_name), sum(numbers_left))
print("Time played: {} seconds".format(round(final_time)))
print("Better luck next time >:)")
|
70868d3370b048e339a4af0e54b9cb015e9ad2c4 | daniel-reich/turbo-robot | /Fpymv2HieqEd7ptAq_11.py | 890 | 3.78125 | 4 | """
Write a function that groups a string into **parentheses cluster**. Each
cluster should be **balanced**.
### Examples
split("()()()") ➞ ["()", "()", "()"]
split("((()))") ➞ ["((()))"]
split("((()))(())()()(()())") ➞ ["((()))", "(())", "()", "()", "(()())"]
split("((())())(()(()()))") ➞ ["((())())", "(()(()()))"]
### Notes
* All input strings will **only** contain parentheses.
* **Balanced** : Every opening parens `(` must exist with its matching closing parens `)` in the same cluster.
"""
def split(txt):
result = []
open_count = 0
closed_count = 0
subset = ""
for char in txt:
if char == "(":
subset += "("
open_count += 1
if char == ")":
subset += ")"
closed_count += 1
if closed_count == open_count:
result.append(subset)
subset = ""
return result
|
7c5c11c5e0d107735843fbbdf9e7ff60195f192f | Klauanny/LinguagemPOO | /endereco.py | 721 | 3.8125 | 4 | class Endereco():
def __init__(self) -> None:
self._bairro = input("Digite o nome do seu bairro: ")
self._rua = input("Digite o nome da sua rua: ")
self._numero = "S/ Número"
try:
entrada = int(input("Digite o número da sua casa (caso não haja numero, digite '0'): "))
if (self._numero.isnumeric()):
self._numero = entrada
except:
while (not self._numero.isnumeric()):
print ('Preencha Corretamente!!!')
entrada = input("Digite o número da sua casa (caso não haja numero, digite '0'): ")
if (self._numero.isnumeric()):
self._numero = int(entrada) |
d555eab6f0b3653722818875a01d94ae1342ed1a | ErickMwazonga/sifu | /heaps/merge_k_sorted_arrays.py | 977 | 3.59375 | 4 | '''
Merge K Sorted Arrays
Input: [[1, 10, 11, 15],
[2, 4, 9, 14],
[5, 6, 8, 16],
[3, 7, 12, 13]]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Naive Approach
Put k lists in one big list - O(n*k),
Then sort the big list quicksort.
Overall time complexity would be O(nk) + O(nk log(nk)) = O(nklog(nk)).
Best Approach
https://medium.com/@amitrajit_bose/merge-k-sorted-arrays-6f9427661e67
https://medium.com/outco/how-to-merge-k-sorted-arrays-c35d87aa298e
'''
import heapq
def merge(lists):
final_list = []
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
while heap:
val, row_idx, col_idx = heapq.heappop(heap)
final_list.append(val)
if col_idx + 1 < len(lists[row_idx]):
next_val = lists[row_idx][col_idx + 1]
next_tuple = (next_val, row_idx, col_idx + 1)
heapq.heappush(heap, next_tuple)
return final_list
|
e6476823106ef379ef092d5e44cfe1fa319dc4f0 | rafaelperazzo/programacao-web | /moodledata/vpl_data/76/usersdata/184/36510/submittedfiles/jogoDaVelha.py | 1,958 | 3.75 | 4 | # -*- coding: utf-8 -*-
import math
x1 = int(input('Digite x1: '))
x2 = int(input('Digite x2: '))
x3 = int(input('Digite x3: '))
x4 = int(input('Digite x4: '))
x5 = int(input('Digite x5: '))
x6 = int(input('Digite x6: '))
x7 = int(input('Digite x7: '))
x8 = int(input('Digite x8: '))
x9 = int(input('Digite x9: '))
#CONTINUE...
if x1==x2==x3 and x1==0 and x2==0 and x3==0:
print('0')
elif x1==x2==x3 and x1==1 and x2==1 and x3==1:
print('1')
else:
if x4==x5==x6 and x4==0 and x5==0 and x6==0:
print('0')
elif x4==x5==x6 and x4==1 and x5==1 and x6==1:
print('1')
else:
if x7==x8==x9 and x7==0 and x8==0 and x9==0:
print('0')
elif x7==x8==x9 and x7==1 and x8==1 and x9==1:
print('1')
else:
if x1==x4==x7 and x1==0 and x4==0 and x7==0:
print('0')
elif x1==x4==x7 and x1==1 and x4==1 and x7==1:
print('1')
else:
if x2==x5==x8 and x2==0 and x5==0 and x8==0:
print('0')
elif x2==x5==x8 and x2==1 and x5==1 and x8==1:
print('1')
else:
if x3==x6==x9 and x3==0 and x6==0 and x9==0:
print('0')
elif x3==x6==x9 and x3==1 and x6==1 and x9==1:
print('1')
else:
if x1==x5==x9 and x1==0 and x5==0 and x9==0:
print('0')
elif x1==x5==x9 and x1==1 and x5==1 and x9==1:
print('1')
else:
if x3==x5==x7 and x3==0 and x5==0 and x7==0:
print('0')
elif x3==x5==x7 and x3==1 and x5==1 and x7==1:
print('1')
else:
print('E')
|
fd24c6f32d12bb3d75a15382950a5d0f21aae9ae | netor27/codefights-solutions | /arcade/python/arcade-theCore/06_LabyrinthOfNestedLoops/043_IsPower.py | 316 | 4.28125 | 4 | def isPower(n):
'''
Determine if the given number is a power of some non-negative integer.
'''
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt)+1):
for b in range(2, int(sqrt)+1):
if a ** b == n:
return True
return False |
378d28574750fe97740d97938cd69c51f0c823bc | lovekobe13001400/pystudy | /py-cookbook/1.数据结构和算法/1.14排序不支持原生比较的对象问题.py | 627 | 3.71875 | 4 | #排序对象
class User:
def __init__(self,user_id):
self.user_id = user_id
#重构__repr__方法后,不管直接输出对象还是通过print打印的信息都按我们__repr__方法中定义的格式进行显示了
#打印对象可视化
def __repr__(self):
return 'User({})'.format(self.user_id)
myUser = User(23)
print(myUser.user_id)
users = [User(23),User(3),User(99)]
print(users)
#方法1:
sorted_users = sorted(users,key=lambda u:u.user_id)
print(sorted_users)
#方法2:
from operator import attrgetter
a = sorted(users,key=attrgetter('user_id'))
print(a)
|
d4f2f8709e5ef7d3e7e633790b352b3225761048 | lmthanh2011/luongminhthanh-fundamental-c4e17 | /fundamental/session4/tamgiacpascal.py | 321 | 4.09375 | 4 | from turtle import *
speed (3)
shape ('turtle')
for i in range (3):
forward (50)
left (120)
right (60)
for i in range (3):
forward (50)
left (120)
right (60)
for i in range (3):
forward (50)
left (120)
right (60)
forward (50)
for i in range (3):
forward (50)
left (120)
mainloop ()
|
f0158d1898abbce5b9de153fe975059d5bef0e6e | lemming52/white_pawn | /leetcode/q019/solution.py | 1,115 | 3.90625 | 4 | """
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
d = 1
current = head.next
while current:
d += 1
current = current.next
removal_index = d - n
if removal_index <= 0:
return head.next
counter = 1
prior = head
current = head.next
while counter < removal_index:
prior = current
current = prior.next
counter += 1
if current.next is None:
prior.next = None
else:
following = current.next
prior.next = following
return head
|
cde071b3b3ea5ebd324c0816843da7bb943a6153 | beejjorgensen/bgpython | /source/examples/listops.py | 813 | 3.703125 | 4 | a = [5, 2, 8, 4, 7, 4, 0, 9]
print(len(a)) # 8, the number of elements in the list
a.append(100)
print(a) # [5, 2, 8, 4, 7, 4, 0, 9, 100]
print(a.count(4)) # 2, the number of 4s in the list
print(a.index(4)) # 3, the index of the first 4 in the list
v = a.pop() # Remove the 100 from the end of the list
print(v) # 100
print(a) # [5, 2, 8, 4, 7, 4, 0, 9]
a.reverse() # Reverse the list
print(a) # [9, 0, 4, 7, 4, 8, 2, 5]
a.insert(2, 999) # insert 999 before index 2
print(a) # [9, 0, 999, 4, 7, 4, 8, 2, 5]
b = [1, 2, 3]
a.extend(b) # Add contents of b to end of a
print(a) # [9, 0, 999, 4, 7, 4, 8, 2, 5, 1, 2, 3]
a.sort() # Sort all elements
print(a) # [0, 1, 2, 2, 3, 4, 4, 5, 7, 8, 9, 999]
a.clear() # Remove all elements
print(a) # [], an empty list of length 0
|
1e8d45588be301820d689b988c50174fee7ba0b4 | davidHards/Twitch_Project | /rowCount.py | 1,312 | 3.96875 | 4 | '''
Count number of rows in csv files
Date: 24/01/2019
Author: David Hards
This is a helper program that serves no purpose for project. This program
gets number of rows for each csv file, and displays count for how many have
99, 100 or other number of rows.
'''
import glob
import os
import csv
topGames=[]
os.chdir("E://UG Project Data")
for file in glob.glob("*top*"):
topGames.append(file)
index = len(topGames)
#print(index)
num = 0
theFile = topGames[0]
#print(theFile)
data = []
a = 0
b = 0
c = 0
#for x in range(index):
for x in range(index):
try:
theFile = topGames[x]
with open(theFile) as f:
reader = csv.reader(f)
#print(reader)
next(reader) # skip header
n = 0
for row in reader:
if (num % 2) == 0:
pass
else:
data.append(row)
#print("yes")
n += 1
num += 1
if (n == 100):
a += 1
elif (n == 99):
b += 1
else:
c += 1
except:
print("Problem file:")
print(theFile)
print(x)
print(len(data))
print(n)
print(a)
print(b)
print(c)
|
c2db1fb5b2099c63897fde6753abd69f4519f4a3 | nsudhanva/mca-code | /Sem3/Python/assignment4/4_frequency.py | 292 | 4.03125 | 4 | something = input('Enter a string: ')
some_char = input('Enter a character: ')
def count_occ(something, some_char):
count = 0
for i in something:
if i == some_char:
count += 1
return count
print('Count of', some_char, 'is', count_occ(something, some_char)) |
987036553f9c57871a524b7394f08efb8cdb87bc | JGuymont/ift2015 | /3_tree/LinkedBinaryTree.py | 5,655 | 3.921875 | 4 | #!/usr/local/bin/python3
from BinaryTree import BinaryTree
# implémentation de BinaryTree avec des noeuds chaînés
class LinkedBinaryTree(BinaryTree):
"""Binary tree implementation using linked nodes"""
class _Node:
def __init__(self, element, parent=None, left=None, right=None):
self._element = element
self._parent = parent
self._left = left
self._right = right
class Position(BinaryTree.Position):
def __init__(self, container, node):
self._container = container
self._node = node
def __str__(self):
return str(self._node._element)
def element(self):
return self._node._element
def __eq__(self, other):
return type( other ) is type( self ) and other._node is self._node
def _validate(self, p):
if not isinstance(p, self.Position):
raise TypeError('p must be proper Position type')
if p._container is not self:
raise ValueError('p does not belong to this container')
if p._node._parent is p._node:
raise ValueError('p is no longer valid')
return p._node
def _make_position(self, node):
return self.Position(self, node) if node is not None else None
def __init__(self):
self._root = None
self._size = 0
def __len__(self):
return self._size
def root(self):
return self._make_position(self._root)
def parent(self, p):
node = self._validate(p)
return self._make_position(node._parent)
def left(self, p):
node = self._validate(p)
return self._make_position(node._left)
def right(self, p):
node = self._validate( p )
return self._make_position( node._right )
def num_children(self, p):
node = self._validate( p )
count = 0
if node._left is not None:
count += 1
if node._right is not None:
count += 1
return count
def _add_root(self, e):
if self._root is not None:
raise ValueError('Root exists')
self._size = 1
self._root = self._Node(e)
return self._make_position(self._root)
def _add_left(self, p, e):
node = self._validate(p)
if node._left is not None:
raise ValueError('Left child exists')
self._size += 1
node._left = self._Node(e, node)
return self._make_position(node._left)
def _add_right(self, p, e):
node = self._validate(p)
if node._right is not None: raise ValueError( 'Right child exists' )
self._size += 1
node._right = self._Node(e, node)
return self._make_position(node._right)
def _replace(self, p, e):
node = self._validate(p)
old = node._element
node._element = e
return old
def _delete(self, p):
node = self._validate(p)
if self.num_children(p) == 2:
raise ValueError( 'p has two children' )
child = node._left if node._left else node._right
if child is not None:
child._parent = node._parent
if node is self._root:
self._root = child
else:
parent = node._parent
if node is parent._left:
parent._left = child
else:
parent._right = child
self._size -= 1
node._parent = node
return node._element
def _attach(self, p, t1, t2):
node = self._validate(p)
if not self.is_leaf( p ):
raise ValueError('position must be leaf')
if not type( self ) is type( t1 ) is type( t2 ):
raise TypeError('Tree types must match')
self._size += len(t1) + len(t2)
if not t1.is_empty():
t1._root._parent = node
node._left = t1._root
t1._root = None
t1._size = 0
if not t2.is_empty():
t2._root._parent = node
node._right = t2._root
t2._root = None
t2._size = 0
# unit testing
if __name__ == '__main__':
"""
A
B D
E F C J
G H
"""
mytree = LinkedBinaryTree()
A = mytree._add_root("A") #level 0
B = mytree._add_left(A, "B") #level 1
D = mytree._add_right(A, "D")
E = mytree._add_left(B, "E") #level 2 left
F = mytree._add_right(B, "F")
mytree._add_left( D, "C" ) #level 2 right
mytree._add_right( D, "J" )
mytree._add_left( F, "G" ) #level 3
mytree._add_right( F, "H" )
print( "breadth-first:" )
mytree.breadth_first_print( mytree.root() )
print( "---" )
exit()
print( "inorder:" )
mytree.inorder_print( mytree.root() )
print( "---" )
print( "preorder:" )
mytree.preorder_print( mytree.root() )
print( "---" )
exit()
print( "postorder:" )
mytree.postorder_print( mytree.root() )
print( "---" )
print( mytree.height( mytree.root() ) )
# printExpression
aSecondTree = LinkedBinaryTree()
plus = aSecondTree._add_root( '+' )
times1 = aSecondTree._add_left( plus, 'x' )
times2 = aSecondTree._add_right( plus, 'x' )
deux = aSecondTree._add_left( times1, '2' )
minus = aSecondTree._add_right( times1, '-' )
a = aSecondTree._add_left( minus, 'a' )
un = aSecondTree._add_right( minus, '1' )
trois = aSecondTree._add_left( times2, '3' )
b = aSecondTree._add_right( times2, 'b' )
aSecondTree.printExpression( aSecondTree.root() )
|
0434209a8ae7fd57e09f83906d35e99f9f7938ad | poncho901/python | /Useless Flights.py | 2,198 | 3.796875 | 4 | from typing import List
from collections import defaultdict
def useless_flight(schedule: List) -> List:
book = {}
new = {}
nodes = set()
result = []
for [d1,d2,cost] in schedule:
if d1 not in book.keys():
book[d1] = {}
book[d1][d2] = cost
if d2 not in book.keys():
book[d2] = {}
book[d2][d1] = cost
nodes = nodes | {d1,d2}
for j in nodes:
unvisited = {node:None for node in nodes}
visited = defaultdict(int)
current = j
currentdistance = 0
unvisited[current] = currentdistance
while True:
for neighbour, distance in book[current].items():
if neighbour not in unvisited: continue
newdistance = currentdistance + distance
if unvisited[neighbour] is None or unvisited[neighbour] > newdistance:
unvisited[neighbour] = newdistance
visited[current] = currentdistance
del unvisited[current]
if not unvisited or all(i is None for i in unvisited.values()): break
candidates = [node for node in unvisited.items() if node[1]]
current, currentdistance = sorted(candidates, key=lambda x:x[1])[0]
new[j] = visited
for k in range(len(schedule)):
[i,j,cost] = schedule[k]
if j in new[i].keys() and cost > new[i][j]:
result.append(k)
return result
if __name__ == '__main__':
print("Example:")
print(useless_flight([['A', 'B', 50],
['B', 'C', 40],
['A', 'C', 100]]))
# These "asserts" are used for self-checking and not for an auto-testing
assert useless_flight([['A', 'B', 50],
['B', 'C', 40],
['A', 'C', 100]]) == [2]
assert useless_flight([['A', 'B', 50],
['B', 'C', 40],
['A', 'C', 90]]) == []
assert useless_flight([['A', 'B', 50],
['B', 'C', 40],
['A', 'C', 40]]) == []
assert useless_flight([['A', 'C', 10],
['C', 'B', 10],
['C', 'E', 10],
['C', 'D', 10],
['B', 'E', 25],
['A', 'D', 20],
['D', 'F', 50],
['E', 'F', 90]]) == [4, 7]
print("Coding complete? Click 'Check' to earn cool rewards!") |
460597a99b01a5c48577ab7d5a1372a127001ebd | dinohunter2836/supreme-waffle | /lab1.py | 2,672 | 3.8125 | 4 | import re
import argparse
def word_count(path):
with open(path) as file:
text = file.read()
arr = re.split(r'\W', text)
word_dict = dict()
for index in range(0, len(arr)):
if arr[index] == '':
continue
if arr[index] in word_dict:
word_dict[arr[index]] += 1
else:
word_dict[arr[index]] = 1
sorted_dict = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
for i in range(0, min(10, len(sorted_dict))):
print(sorted_dict[i][0], end=' ')
print("\n")
def qsort(arr, left, right):
middle = arr[(left + right) // 2]
i = left
j = right
while i <= j:
while arr[i] < middle:
i += 1
while arr[j] > middle:
j -= 1
if i <= j:
p = arr[i]
arr[i] = arr[j]
arr[j] = p
i += 1
j -= 1
if i < right:
qsort(arr, i, right)
if j > left:
qsort(arr, left, j)
def merge_sort(arr):
if len(arr) > 1:
middle = (len(arr) - 1) // 2
arr1 = merge_sort(arr[slice(0, middle + 1)])
arr2 = merge_sort(arr[slice(middle + 1, len(arr))])
return merge(arr1, arr2)
else:
return arr
def merge(arr1, arr2):
i = 0
j = 0
arr = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
arr.append(arr1[i])
i += 1
else:
arr.append(arr2[j])
j += 1
while i < len(arr1):
arr.append(arr1[i])
i += 1
while j < len(arr2):
arr.append(arr2[j])
j += 1
return arr
def fibonacci(path):
with open(path) as file:
n = int(file.read().split()[0])
gen = fibonacci_generator()
for i in range(n):
print(next(gen))
def fibonacci_generator():
a = 1
b = 1
yield a
yield b
while True:
c = a + b
a = b
b = c
yield c
def quick_sort(path):
with open(path) as f:
arr = list(map(int, f.read().split()))
qsort(arr, 0, len(arr) - 1)
print(arr)
def merge_sorted(path):
with open(path) as f:
arr = list(map(int, f.read().split()))
print(merge_sort(arr))
functions = {
'text_stats': word_count,
'qsort': quick_sort,
'merge_sort': merge_sorted,
'fibonacci': fibonacci
}
parser = argparse.ArgumentParser(description="Choose a function to execute")
parser.add_argument('file_path', help="input file")
parser.add_argument('func', help='choose function to execute', choices=functions.keys())
args = parser.parse_args()
func = functions[args.func]
func(args.file_path)
|
bafdbb6d7d8836986b64d209f6df7c65e2f9c798 | shenlinli3/python_learn | /second_stage/day_01/demo_08_条件判断分支.py | 1,614 | 4.0625 | 4 | # input() 输入函数
# 该函数接收到的任何内容都是字符串类型
# in1 = input("请输入账号:")
# in2 = input("请输入密码:")
# print(in1, in2)
# 条件判断分支
# if 如果
# elif 又如果
# else 否则
# num1 = int(input("请输入第一个数:"))
# num2 = int(input("请输入第二个数:"))
# if num1 > num2: # True False
# print("第一个数大于第二个数")
# print("Test...1")
# elif num1 < num2:
# print("第一个数小于第二个数")
# print("Test...2")
# else:
# print("第一个数等于第二个数")
# print("Test...3")
# print("End...")
# weather = input("今天天气怎么样:")
# if weather == "晴天":
# sun = input("太阳大不大?")
# if sun == "大":
# print("穿短裤 戴墨镜")
# else:
# print("记得吃雪糕")
# elif weather == "雨天":
# print("带把伞")
# elif weather == "雪天":
# print("打雪仗记得带头盔")
# elif weather == "多云":
# print("在家打游戏")
# else:
# print("我听不懂你在说什么")
# 写一个小程序,用户输入0-100分,程序输出非常优秀(91-100)、
# 优秀(81-90)、良好(71-80)、及格(60-70)、不及格(0-59)等评级
score = float(input("请输入分数:"))
if 100 >= score >= 91:
print("非常优秀")
elif 91 > score >= 81:
print("优秀")
elif 81 > score >= 71:
print("良好")
elif 71 > score >= 60:
print("及格")
elif 60 > score >= 0:
print("不及格")
else:
print("分数异常")
|
9b973162d179e63e51093411c528481cdfac5c13 | ash/python-in-5days | /day3/05-file-not-there.py | 198 | 3.609375 | 4 | # Catch an exception if there is no file on disk.
try:
with open('non-existing.txt') as f:
data = f.read()
print(data)
except FileNotFoundError:
print('not found')
print('ok done')
|
2c4ba439611466fec7a4dc0efadf6273eaa3c712 | DerrickChanCS/Leetcode | /082.py | 1,370 | 3.734375 | 4 | """
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def killDupes(head):
if not head:
return
ptr = head
if ptr.next and ptr.val == ptr.next.val:
while ptr.next and ptr.val == ptr.next.val:
ptr = ptr.next
return killDupes(ptr.next)
else:
ptr.next = killDupes(ptr.next)
return ptr
return killDupes(head)
"""
dummy = ListNode(0)
dummy.next = head
prevUnique = dummy
prev = None
ptr = head
while ptr:
while ptr.next and ptr.val == ptr.next.val:
ptr = ptr.next
prevUnique.next = ptr.next
if ptr.next and ptr.val != ptr.next.val:
prevUnique = ptr
ptr = ptr.next
"""
|
531c631d1b2b447c97149f81eea69460d1cae602 | BingoJYB/Data-Structure-and-Algorithm | /swap vowels in string.py | 743 | 4.15625 | 4 | '''
Given a string, your task is to reverse only the vowels of string.
Examples:
Input: hello
Output: holle
Input: hello world
Output: hollo werld
'''
def swap(str_ls, x, y):
temp = str_ls[x]
str_ls[x] = str_ls[y]
str_ls[y] = temp
return str_ls
def solution(string):
s = list(string)
vowel = 'aeiouAEIOU'
head = 0
tail = len(s) - 1
while head <= tail:
if s[head] not in vowel:
head = head + 1
if s[tail] not in vowel:
tail = tail - 1
if s[head] in vowel and s[tail] in vowel:
swap(s, head, tail)
head = head + 1
tail = tail - 1
print(''.join(s))
|
4cec3b56e303e7ab040159ee67d4b0e8bf320fbf | aguscerdo/183D-capstone | /PHANTOMbots/test.py | 328 | 4.09375 | 4 |
desired_h= 5
actual_h = 350
difference = 180 - abs(abs(desired_h - actual_h) - 180)
print(difference)
if(actual_h < desired_h ):
if desired_h - actual_h > 180:
print("go left")
else:
print("go right")
else:
if actual_h - desired_h > 180:
print("go right")
else:
print("go left") |
f287cc57e656523333e56b029399324917051ad3 | Adasumizox/ProgrammingChallenges | /codewars/Python/8 kyu/StringRepeat/repeat_str_test.py | 795 | 3.671875 | 4 | from repeat_str import repeat_str
import unittest
import string
class TestRepeatStr(unittest.TestCase):
def test(self):
self.assertEqual(repeat_str(4, 'a'), 'aaaa')
self.assertEqual(repeat_str(3, 'hello '), 'hello hello hello ')
self.assertEqual(repeat_str(2, 'abc'), 'abcabc')
def test_rand(self):
from random import randint, choice
_repeat_str = lambda n, s: n * s
chars = string.ascii_letters + string.digits + string.punctuation + string.whitespace
for _ in range(50):
word = "".join(choice(chars) for i in range(randint(1, 50)))
repetition = randint(1, 50)
self.assertEqual(repeat_str(repetition, word), _repeat_str(repetition, word))
if __name__ == '__main__':
unittest.main() |
4a27024fe24707c3aeb78e38bf6d52d939b81a46 | shambhand/pythontraining | /material/code/advanced_oop_and_python_topics/9_DecoratorApplications/decorator_app4.py | 755 | 3.734375 | 4 | import sys
def tracer(func): # State via enclosing scope and func attr
def wrapper(*args, **kwargs):
wrapper.calls += 1
print('call %s to %s' % (wrapper.calls, func.__name__)) # calls is per-function, not global
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@tracer # Same as: spam = tracer(spam)
def spam(a, b, c):
print(a + b + c)
@tracer # Same as: eggs = tracer(eggs)
def eggs(x, y):
print(x ** y)
def main ():
spam(1, 2, 3) # Really calls wrapper, assigned to spam
spam(a=4, b=5, c=6) # wrapper calls spam
eggs(2, 16) # Really calls wrapper, assigned to eggs
eggs(4, y=4) # wrapper.calls _is_ per-decoration here
main ()
|
1bb4eab80f49a2667bd3fa4f730ac5997e551ac4 | chainchompa/Intro-Python | /src/days-2-4-adv/room.py | 1,498 | 3.6875 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, name, description, items):
self.name = name
self.description = description
self.items = items
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
def __str__(self):
return self.name
def next_room(self, direction):
if direction == "n":
return self.n_to
elif direction == "s":
return self.s_to
elif direction == "e":
return self.e_to
elif direction == "w":
return self.w_to
else:
return None
def print_items(self):
for item in self.items:
print(f"You find a {item.name.lower()} in this room!")
def find_item(self, input_item):
for item in self.items:
if item.name.lower() == input_item.lower():
return item
return None
def remove_item(self, item):
print(f"You have picked up the {item.name.lower()}")
self.items.remove(item)
def add_item(self, item):
self.items.append(item)
print(f"You have dropped the {item.name.lower()}")
class Dark_Room(Room):
def __init__(self, name, description, items, visibility):
super().__init__(name, description, items)
self.visibility = visibility
def light_on(self):
self.visibility = True
|
12da54a2c94f5f02f90dc32f7f1f0c2dca893c64 | sylvanoz14/hackerrank | /algorithms/strings/bear_and_steady_strain.py | 3,484 | 3.75 | 4 | from collections import defaultdict
"""
def smallest(s1, s2):
assert s2 != ''
d = defaultdict(int)
nneg = [0] # number of negative entries in d
def incr(c):
d[c] += 1
if d[c] == 0:
nneg[0] -= 1
def decr(c):
if d[c] == 0:
nneg[0] += 1
d[c] -= 1
for c in s2:
decr(c)
minlen = len(s1) + 1
j = 0
for i in xrange(len(s1)):
while nneg[0] > 0:
if j >= len(s1):
return minlen
incr(s1[j])
j += 1
minlen = min(minlen, j - i)
decr(s1[i])
return minlen
print smallest('AAGTGCCT', 'CAT')
#hints https://mydevelopedworld.wordpress.com/2012/12/12/solution-for-minimum-window-in-string-in-on/
#http://stackoverflow.com/questions/2459653/how-to-find-smallest-substring-which-contains-all-characters-from-a-given-string
"""
def walk(s, tosubstractchars,matchSub):
startIndex = matchSub['start']
endIndex = matchSub['end']
ccount = {k:v for k,v in matchSub['ccount'].items()}
if endIndex >= len(s) - 1:
return False
startc = s[startIndex]
i = startIndex
while True:
if tosubstractchars.get(s[i]):
startIndex = i
break
if i > endIndex:
return False
i += 1
i = endIndex + 1
while True:
if tosubstractchars.get(s[i]):
ccount[s[i]] += 1
if s[i] == startc:
endIndex = i
break
if i >= s_len - 1:
return False
i += 1
i = startIndex
while True:
if tosubstractchars.get(s[i]):
if tosubstractchars[s[i]] < ccount[s[i]]:
ccount[s[i]] -= 1
else:
startIndex = i
break
if i >= endIndex:
break
i += 1
matchSub['start'] = startIndex
matchSub['end'] = endIndex
matchSub['ccount'] = ccount
return matchSub
def first(s, tosubstractchars):
ccount={
"A":0,
"T":0,
"C":0,
"G":0
}
startIndex = 0
endIndex = 0
for i in range(len(s)):
if tosubstractchars.get(s[i]):
ccount[s[i]] += 1
if len(filter(lambda x : x < 0, [ccount[k] - v for k, v in tosubstractchars.items()])) == 0:
endIndex = i
break
for i in range(startIndex, endIndex):
if tosubstractchars.get(s[i]):
if tosubstractchars[s[i]] < ccount[s[i]]:
ccount[s[i]] -= 1
else:
startIndex = i
break
return {
"start": startIndex,
"end":endIndex,
"ccount": ccount
}
n = int(raw_input().strip())
s = raw_input().strip()
total = {
"A" : 0,
"T" : 0,
"C" : 0,
"G" : 0
}
for c in s:
total[c] += 1
s_len = len(s)
tosubstractchars = {}
for k, v in total.items():
if v > s_len / 4:
tosubstractchars.update({k: v - s_len / 4})
minresult = sum([v for k,v in tosubstractchars.items()])
if len(tosubstractchars) <= 0:
print 0
else:
ms = first(s, tosubstractchars)
result = ms['end'] - ms['start'] + 1
while True:
nextms = walk(s, tosubstractchars, ms)
if not nextms:
break
else:
ms = nextms
if ms['end'] - ms['start'] + 1 < result:
result = ms['end'] - ms['start'] + 1
if result <= minresult:
break
print result
|
d87731ebe3924041442b2816c0d3464830158f67 | jedzej/tietopythontraining-basic | /students/bec_lukasz/lesson_04_unit_testing/fibonacciTests.py | 1,329 | 4.125 | 4 | import unittest
def fib(number):
if number is not int(number):
raise ValueError
elif number is None:
raise TypeError
elif number <= 0:
raise RecursionError
else:
if number == 1 or number == 2:
return 1
else:
return fib(number - 1) + fib(number - 2)
class FibonacciTests(unittest.TestCase):
def test_if_number_1_is_equal_1(self):
number = 1
self.assertEqual(fib(number), 1)
def test_if__number_2_is_equal_1(self):
number = 2
self.assertEqual(fib(number), 1)
def test_if__number_6_is_equal_8(self):
number = 6
self.assertEqual(fib(number), 8)
def test_if_zero_returns_recursion_error(self):
number = 0
self.assertRaises(RecursionError, fib, number)
def test_if_negative_number_returns_recursion_error(self):
number = -1
self.assertRaises(RecursionError, fib, number)
def test_float_number_returns_value_error(self):
number = 1.0
self.assertRaises(ValueError, fib, number)
def test_if_string_returns_value_error(self):
number = 'string'
self.assertRaises(ValueError, fib, number)
def test_if_None_returns_type_error(self):
number = None
self.assertRaises(TypeError, fib, number)
|
3354a9a4ae759b3a00e66b9bca1cb227cd74c4b5 | soham-shah/Intro-to-AI | /Assignment3/asignment3.py | 4,920 | 4.28125 | 4 | #Name: Soham Shah
#Class: Intro to AI
#Instructor: Rhonda Hoenigman
#Assignment 3
#the goal of this is to create a graph from a text file and run a* search on it.
import sys
import heapq
import time
class Graph:
def __init__(self):
self.vertices = {}
self.heuristic = {}
def addVertex(self, value):
# check if value already exists
if value in self.vertices:
print
"Vertex already exists"
else:
self.vertices[value] = {}
def addHeuristic(self,node, value):
self.heuristic[node] = value
def addEdge(self, value1, value2, weight):
if (value1 in self.vertices and value2 in self.vertices):
self.vertices[value1][value2]= weight
self.vertices[value2][value1]= weight
else:
print("One or more vertices not found.")
def printGraph(self):
print(self.vertices)
def printHeuristic(self):
print(self.heuristic)
def dijsktra(self, initial, end):
start = time.time()
complexity = 0
distances = {} #keep track of distance to each node
previous = {} #keep track of shortest path to each node
priorityQueue = [] #priority queue of things to check next
for i in self.vertices:
if i == initial:
distances[i] = 0
heapq.heappush(priorityQueue, [0, i]) #add i to priority queue with initial dist of 0
else:
distances[i] = sys.maxsize
heapq.heappush(priorityQueue, [sys.maxsize, i])
previous[i] = None
complexity+=1
while (priorityQueue):
node = heapq.heappop(priorityQueue)[1]
# if we've reached the end it's the most efficient and so get the path and break out.
if node == end:
path = []
while previous[node]:
path.append(node)
node = previous[node]
path.append(initial)
path.reverse()
return ({"Algorithm":"Dijkstra's", "Path":path, "Distance": distances[end], "Nodes Evaluated":complexity, "time taken": time.time()-start})
#otherwise update the distances based on the time it takes to get to this node
for adj in self.vertices[node]:
complexity+=1
alternatePath = distances[node] + self.vertices[node][adj]
if alternatePath < distances[adj]:
distances[adj] = alternatePath
previous[adj] = node #update the path taken
#update the priority queue with the new distance info
for n in priorityQueue:
if n[1] == adj:
n[0] = alternatePath
break
heapq.heapify(priorityQueue)
def aStar(self, start, goal):
begining = time.time()
complexity = 0
priorityQueue = []
parentNode = {}
totalCost = {}
parentNode[start] = None
totalCost[start] = 0
heapq.heappush(priorityQueue, [0, start])
while priorityQueue:
current = heapq.heappop(priorityQueue)[1] #get the closest node from the pq
if current == goal: #if we've reached the end, then break out
break
for adj in self.vertices[current]: #add the new nodes in the list
complexity+=1
newCost = totalCost[current] + self.vertices[current][adj]
if adj not in totalCost or newCost < totalCost[adj]:
totalCost[adj] = newCost
estimate = newCost + self.heuristic[adj]
heapq.heappush(priorityQueue, [estimate, adj])
parentNode[adj] = current
#figure out the path based on the parent list
path = []
path.append(goal)
node = parentNode[goal]
while node!= start:
path.append(node)
node = parentNode[node]
path.append(start)
path.reverse()
return ({"Algorithm":"A* Search", "Path": path, "Distance": totalCost[goal], "Nodes Evaluated": complexity, "time taken": time.time()-begining})
#begining of the main code outside the class
test = Graph()
#code for reading the text file and creating the graph
#Filename: "Assignment3.txt"
for line in open(sys.argv[1],"r"):
#this means it's a weighted node in the graph so add it here
if line[0]== "[":
test.addVertex(line[1])
test.addVertex(line[3])
test.addEdge(line[1],line[3],int(line[5]))
#If the line isn't just blank then it's a heuristic
elif(line!="\n"):
test.addHeuristic(line[0],int(line[2:len(line)]))
#test.printGraph()
#test.printHeuristic()
print(test.dijsktra("S","F"))
print(test.aStar("S","F"))
|
0bac9788ef0adb51e19346d13a8b3bf3f20d0ce6 | salilkanitkar/lpthw_exercises | /e20.py | 966 | 3.90625 | 4 | #!/usr/bin/python
""" Exercise 20 """
"""
PreRequisite: A file e20_sample.txt must be already present before
running this exercise.
"""
from sys import argv
script, input_file = argv
def print_all(f):
f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print "LineNum: %d %s" % (line_count, f.readline())
current_file = open(input_file)
print "First, let's print the whole file"
print_all(current_file)
print "Now, lets rewind - back to the beginning of the file"
rewind(current_file)
print "Lets print first three lines"
line_count = 1
print_a_line(line_count, current_file)
line_count += 1
print_a_line(line_count, current_file)
line_count += 1
print_a_line(line_count, current_file)
"""
Test Run:
$ ./e20.py e20_sample.txt
First, let's print the whole file
Now, lets rewind - back to the beginning of the file
Lets print first three lines
LineNum: 1 This is Line1.
LineNum: 2 This is Line2.
LineNum: 3 This is Line3.
"""
|
a5743efd7661f225e316ca1638bd16b985127a88 | enrong/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Problem Set 2 Paying the Minimum.py | 617 | 3.71875 | 4 | balance = 5000
annualInterestRate = 0.18
monthlyinterestrate = annualInterestRate/12
upbalance = balance
monthlyPaymentRate = 0.02
i=-1
totalPaid = 0
while i < 12:
i += 1
minimummonthlypayment = upbalance*monthlyPaymentRate
upbalance = (upbalance - minimummonthlypayment)*(1+ monthlyinterestrate)
print ('Mouth: '+ str(i))
print ('Minimum monthly payment:' + str(round(minimummonthlypayment,2)))
print ('Remaining balance: ' + str(round(upbalance,2)))
totalPaid += minimummonthlypayment
print ('Total paid:' +str(round(totalPaid,2)))
print ('Remaining balance:' + str(round(upbalance,2))) |
77b42bcfe2f83c8928b0bfb6c1fffa403a14742a | PRSarte/ProgrammingAssignment1 | /getGuessedWord.py | 348 | 4 | 4 | def getGuessedWord (secretWord,lettersGuessed): #The function getGuessedWord was created
word = [] #This function shows the word with missing letters
for x in secretWord:
if x in lettersGuessed:
word.append(x)
else:
word.append('_')
return ''.join(word)
|
0df1540ed5a03ffb8cf7b6506b08abf9ed06c4cb | romanticair/python | /basis/turtle-draw-demo/递归Y分形.py | 320 | 3.90625 | 4 | import turtle
def tree(n, d):
# left -> right
if n == 0:
turtle.forward(d)
else:
turtle.forward(d)
for angle in (30, - 60):
turtle.lt(angle)
tree(n - 1, d / 2)
turtle.bk(d / 2)
turtle.lt(30)
turtle.lt(90)
tree(9, 150)
turtle.mainloop()
|
25a1ab288c6a8f62b7cb767686ca947bd5312a5e | shubhransujana19/Python | /split.py | 270 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 2 17:33:23 2021
@author: shubhransu
"""
import random
names = input("Give any names by using comma: ")
names_list = names.split(", ")
bill = random.choice(names_list)
print(f"{bill} will pay the bill")
|
918f0b361ebf5675f9a12c5002d7fdba1153c866 | budaLi/leetcode-python- | /交替位二进制之.py | 319 | 3.59375 | 4 | #-*-coding:utf8-*-
#author : Lenovo
#date: 2018/8/26
def hasAlternatingBits(n):
"""
:type n: int
:rtype: bool
"""
num=bin(n)[2:]
print(num)
num2=num[1:]
for i in range(len(num2)):
if num[i]==num2[i]:
return False
return True
res=hasAlternatingBits(5)
print(res) |
d7569a0c4c3d10a44132b72d7cca730f9a111906 | jingzli/python | /file_handling/unzipFiles.py | 301 | 3.546875 | 4 | def unzipFiles():
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
x = zip_file_path+'\\'+a
print x
abs_path.append(x)
for f in abs_path:
zip=zipfile.ZipFile(f)
zip.extractall(zip_file_path)
pass
|
79c646c7b807a301c5feb49ddbe477d70db4ec73 | Our-Python-Projects/Genetics-ans | /Codes/BCIproject1d.py | 1,528 | 3.703125 | 4 | #part d of project-1
import numpy as np
import timeit
n = 12
numOfExecutions = 10
# the following function initializes answer data structure and then gets the anser from another function
def analyticalAnswer():
ans = np.zeros((n,), dtype=np.int)
ans = analyticalConstructor(ans,n)
return ans
# the following function set the queens in the chess board according to the analytical algorithm(which is mentioned in the slide and ook)
def analyticalConstructor(ans, n):
if n<3:
return ans
if n%2 is 1:
ans[n-1] = n-1
analyticalConstructor(ans,n-1)
elif n%6 != 0:
for i in range(int(n/2)):
ans[i] = (int(n/2)+2*i-1)%n
for i in range(int(n/2),n):
ans[i] = (int(n/2)+2*i+2)%n
else:
for i in range(int(n/2)):
ans[i] = (2*i+1)
for i in range(int(n/2),n):
ans[i] = (2*i)%n
return ans
#this function runs the analytical algorithm with different sizes of input(from n=1 to n=numOfExecutions)
def analytic_timer():
analytic_times =(0,0,0)
for i in range(4,numOfExecutions+1):
global n
n = i
#we use timeit to measure time of algorithm(it operates algorithm 200 times and then we divide the overall time by 200 to find average time)
analytic_times = analytic_times + (np.sqrt(np.sqrt(np.sqrt(timeit.timeit(analyticalAnswer, number=200)/200))),)
return analytic_times
if __name__=="__main__":
print(analytic_timer()) |
964eab3832b76e8b6f74671435ca52ebfca322d0 | Ntims/Nt_Python | /실습20190419-20194082-김민규/P0614.py | 466 | 3.78125 | 4 | while True:
dualnum = int(input("양수 입력(3보다 작으면 종료)"))
if dualnum < 3:
print("프로그램을 종료합니다.")
break
else:
check = False
for i in range(2,dualnum):
if dualnum % i == 0:
print(dualnum, "는 소수가 아니다")
check = True
break
if check == False:
print(dualnum, "는 소수이다.")
|
59e29be6eafae5cd9cb23f59da6c41b3b26c63e4 | GeorgeKailas/python_fundamentals | /09_exceptions/09_05_check_for_ints.py | 487 | 4.59375 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
in1 = ""
while isinstance(in1, int) is False:
try:
in1 = int(input("give me a number please:"))
except ValueError:
print("You didn't enter a number try again")
print("You picked a number, good job")
|
d8a8944028bbcb932033eb8e58faed1e2bf045cd | IulianStave/wblck | /cmdline.py | 2,192 | 3.984375 | 4 | #Command Line arguments sys.argv
import sys
argumentsCount=len(sys.argv)
script=sys.argv[0]
if argumentsCount>1:
print("{} arguments passed on command line".format(argumentsCount))
print("The first argument is always the python script that you ran in command line: \'{}\'".format(script))
print("Here is the list of command line arguments:")
print(str(sys.argv))
#print(type(sys.argv))
for argument in sys.argv[1:]:
print(argument)
else:
print("No arguments passed through command line")
x=4
cond1 = x>0
cond2 = x<20
if cond1 and cond2:
print ("x")
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
print(type(x))
print("Key: Value elements of dict.items()")
"""
for key in a_dict.keys():
print(key, '->', a_dict[key])
"""
print("Using dictionary name")
for key in car:
print("{}:{}".format(key,car[key]))
for item in car.items():
print(item)
print("\nUsing .items()")
for key, val in car.items():
print(key,val)
tuples=(1,4,5)
for i in tuples:
print(i)
myL=[4,5,8,9,0]
newL=[item for item in myL if item>5]
print(newL)
#for item in myL if item > 7:
# print(item)
my_movies = [['How I Met Your Mother', 'Friends', 'Silicon Valley'],
['Family Guy', 'South Park', 'Rick and Morty'],
['Breaking Bad', 'Game of Thrones', 'The Wire']]
#"The title [movie_title] is [X] characters long."
for movieL in my_movies:
for movie in movieL:
print ("The title {} is {} characters long".format(movie, len(movie)))
for i in range(1,3):
print(i)
down = 0
up = 100
print('a')
for i in range(1,10):
guessed = int((up + down) / 2)
answer=''
'''
while True:
answer = input('Are you {} years old ? [less / more / correct] '.format(guessed))
if answer in ['less','correct','more']:
break
'''
while answer not in ['less','correct','more']:
answer = input('Are you {} years old ? [less / more / correct] '.format(guessed))
if answer == 'correct':
print ('Nice, so your age is {} '.format(guessed))
break
elif answer =='less':
up = guessed
else:
down = guessed
|
99fd18d04611949416190f23a0d3d4a26c4e3d5f | albertofcasuso/ejercicios_python | /adivina.py | 1,192 | 3.828125 | 4 | import random
a = random.randint(1, 1000)
salir = 0
intentos = 0
while salir != "exit":
salir = input("Adivina el número o escribe \"exit\" para salir: ")
try:
int_salir = int(salir)
if int_salir == a:
if intentos == 0:
print("¡¡¡Has acertado a la primera!!!")
a = random.randint(1, 1000)
else:
intentos += 1
a = random.randint(1, 1000)
print("Has acertado en "+str(intentos)+" intentos.")
intentos = 0
elif int_salir < a:
print("Más arriba")
intentos += 1
elif int_salir > a:
print("Más abajo")
intentos += 1
except ValueError:
if salir == "exit":
if intentos == 1:
print("Lo has intentado "+str(intentos)+" vez.")
salir == "exit"
elif intentos == 0:
print("Ni siquiera lo has intentado :( ")
salir == "exit"
else:
print("Lo has intentado "+str(intentos)+" veces.")
salir = "exit"
else:
print("no entiendo")
|
d8feb126be1f5d86786dcca13e815d56aeae1791 | stefano-gaggero/advent-of-code-2019 | /2019-20.py | 7,827 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
--- Day 20: Donut Maze ---
You notice a strange pattern on the surface of Pluto and land nearby to get a closer look. Upon closer inspection, you realize you've come across one of the famous space-warping mazes of the long-lost Pluto civilization!
Because there isn't much space on Pluto, the civilization that used to live here thrived by inventing a method for folding spacetime. Although the technology is no longer understood, mazes like this one provide a small glimpse into the daily life of an ancient Pluto citizen.
This maze is shaped like a donut. Portals along the inner and outer edge of the donut can instantly teleport you from one side to the other. For example:
A
A
#######.#########
#######.........#
#######.#######.#
#######.#######.#
#######.#######.#
##### B ###.#
BC...## C ###.#
##.## ###.#
##...DE F ###.#
##### G ###.#
#########.#####.#
DE..#######...###.#
#.#########.###.#
FG..#########.....#
###########.#####
Z
Z
This map of the maze shows solid walls (#) and open passages (.). Every maze on Pluto has a start (the open tile next to AA) and an end (the open tile next to ZZ). Mazes on Pluto also have portals; this maze has three pairs of portals: BC, DE, and FG. When on an open tile next to one of these labels, a single step can take you to the other tile with the same label. (You can only walk on . tiles; labels and empty space are not traversable.)
One path through the maze doesn't require any portals. Starting at AA, you could go down 1, right 8, down 12, left 4, and down 1 to reach ZZ, a total of 26 steps.
However, there is a shorter path: You could walk from AA to the inner BC portal (4 steps), warp to the outer BC portal (1 step), walk to the inner DE (6 steps), warp to the outer DE (1 step), walk to the outer FG (4 steps), warp to the inner FG (1 step), and finally walk to ZZ (6 steps). In total, this is only 23 steps.
Here is a larger example:
A
A
#################.#############
#.#...#...................#.#.#
#.#.#.###.###.###.#########.#.#
#.#.#.......#...#.....#.#.#...#
#.#########.###.#####.#.#.###.#
#.............#.#.....#.......#
###.###########.###.#####.#.#.#
#.....# A C #.#.#.#
####### S P #####.#
#.#...# #......VT
#.#.#.# #.#####
#...#.# YN....#.#
#.###.# #####.#
DI....#.# #.....#
#####.# #.###.#
ZZ......# QG....#..AS
###.### #######
JO..#.#.# #.....#
#.#.#.# ###.#.#
#...#..DI BU....#..LF
#####.# #.#####
YN......# VT..#....QG
#.###.# #.###.#
#.#...# #.....#
###.### J L J #.#.###
#.....# O F P #.#...#
#.###.#####.#.#####.#####.###.#
#...#.#.#...#.....#.....#.#...#
#.#####.###.###.#.#.#########.#
#...#.#.....#...#.#.#.#.....#.#
#.###.#####.###.###.#.#.#######
#.#.........#...#.............#
#########.###.###.#############
B J C
U P P
Here, AA has no direct path to ZZ, but it does connect to AS and CP. By passing through AS, QG, BU, and JO, you can reach ZZ in 58 steps.
In your maze, how many steps does it take to get from the open tile marked AA to the open tile marked ZZ?
Your puzzle answer was 690.
"""
import numpy as np
import re
#Classe che rappresenta la mappa del labirinto
class MyMap:
WALL = "#"
EMPTY = "."
EXPLORED = "+"
MOVES = [(0, 0), (-1, 0), (+1, 0), (0, -1), (0, +1)]
@staticmethod
def __printMap(m):
s = ''
for row in m:
s = ''.join([c for c in row])
print(s)
def __init__(self, fileName):
self.portals = dict()
self.portalsDir = dict()
self.min = -1
with open(fileName, "r") as f:
self.rows = f.readlines()
self.x = [ [str(c) for c in str(row) if c!='\n' ] for row in self.rows ]
self.grid = np.array(self.x)
self.columns = []
cols = self.grid.transpose() #Attenzione che il trasposto funziona solo per un 2D array e per essere tale le righe devono avere tutte la stessa lunghezza!
for col in cols:
self.columns.append(''.join(col))
self.__findPortals()
self.__createPortalsStruct()
def __insertToPortals(self, key, val):
if key not in self.portals:
self.portals[key] = [val]
else:
self.portals[key].append(val)
def __findPortals(self):
rec = re.compile("(?:([A-Z]{2})\.{1})|(?:\.{1}([A-Z]{2}))")
for i in range(0, len(self.rows)):
matches = rec.finditer(self.rows[i])
for match in matches:
if match.group(1) is not None:
self.__insertToPortals(match.group(1), (i,match.end(1)) )
if match.group(2) is not None:
self.__insertToPortals(match.group(2), (i, match.start(2)-1) )
for i in range(0, len(self.columns)):
matches = rec.finditer(self.columns[i])
for match in matches:
if match.group(1) is not None:
self.__insertToPortals(match.group(1), (match.end(1), i) )
if match.group(2) is not None:
self.__insertToPortals(match.group(2), (match.start(2)-1, i) )
def __createPortalsStruct(self):
for key in self.portals:
if key=="AA" or key=="ZZ":
continue
vals = self.portals[key]
self.portalsDir[vals[0]] = vals[1]
self.portalsDir[vals[1]] = vals[0]
def explore(self):
k = 0
startPos = self.portals["AA"][0]
queue = [(startPos, 0)]
while len(queue)>0:
pos, k = queue.pop()
#Se la distanza già >= della siatnza minima registrata finora è inutile esplorare oltre
if self.min!= -1 and k+1 >= self.min: #Se la distanza già >= inutile esplorare oltre
continue
for i in range(1, 5):
newPos = tuple(np.add(pos, MyMap.MOVES[i]))
x = self.grid[newPos]
if newPos in self.portalsDir:
self.grid[newPos] = MyMap.EXPLORED
queue.insert(0, (self.portalsDir[newPos], k+2) )
elif newPos==self.portals["ZZ"][0]:
if self.min==-1 or k+1<self.min:
self.min = k+1
elif x == MyMap.EMPTY:
queue.insert(0, (newPos, k+1) )
self.grid[newPos] = MyMap.EXPLORED
print("1---->" + str(self.min)) #690
def printMap(self):
MyMap.__printMap(self.grid)
#-----------------------------------------------------------------------------
mymap = MyMap("puzzle20.txt")
mymap.explore()
#mymap.printMap()
|
daa745dda0bb75bf6d4994d8ee32bd30da366451 | muremwa/Python-Pyramids | /inverted_triangle.py | 281 | 4.15625 | 4 | """
Triangle in the following manner
********
*******
******
*****
****
***
**
*
"""
def inverted_right(num_rows):
num_rows += 1
for i in range(1, num_rows):
line = "*"*(num_rows-i)
print(line)
rows = int(input("How many rows?: "))
inverted_right(rows)
|
fd01a6944084314342f59fa3cd277825bdfd447c | iLegendJo/GClegend | /chp5_awex7.py | 435 | 4.25 | 4 | #" exercise 7. The following statement calls a function named half, which
#returns a value that is half that of the argument. (Assume the number
#variable references a float value.) Write code for the function. "
def half(number):
total = 0.0
total = number / 2
return total
value = float(input(f"Please enter a number:"))
result = half(value)
print(f"This is the half of the argument: {value} {result}")
|
b6531888028638899460cd4e2ba0b53efcfe4c3d | Zhmur-Amir/Zadacha23 | /Zadacha6.py | 3,141 | 4 | 4 | import os
path_to_file = 'C:/Users//test/Zadacha6/text.txt'
file = open(path_to_file, "r")
try:
if (os.stat(path_to_file).st_size > 0):
print("file opened successfully")
if (os.stat(path_to_file).st_size == 0):
print("Error: empty file")
except OSError:
print("cannot open file")
def Sequence(file, c_1, c_2, c_3, b):
answer_flag = 1
string = file.read()
temp_int = ''
if (len(string) == 0):
print("Error: empty file")
exit(-3)
number_of_integers = len(string.split(" "))
if (number_of_integers < 3):
print("Error: there are less then 3 integers in file")
temp_1 = ''
t1flag = 0
index = 0
## :
while (t1flag == 0):
if (string[index] != " ") and (string[index] != '\n'):
temp_1 += string[index]
if (string[index] == " ") or (string[index] == "\n"):
t1flag += 1
temp_1 = int(temp_1)
index += 1
## :
temp_2 = ''
t2flag = 0
while (t2flag == 0):
if (string[index] != " ") and (string[index] != "\n"):
temp_2 += string[index]
if (string[index] == " ") or (string[index] == "\n"):
t2flag += 1
temp_2 = int(temp_2)
index += 1
## , , :
for index_ in range(index, len(string)):
if (string[index_] != " ") and (string[index_] != "\n"):
temp_int += string[index_]
if (string[index_] == " ") or (string[index_] == "\n") or (index_ == (len(string) - 1)):
try:
current_integer = int(temp_int)
if ((temp_1 * c_1 + temp_2 * c_2 + current_integer * c_3) != b):
answer_flag = 0
except ValueError:
pass ## Ignores non-integer character
temp_1 = temp_2
temp_2 = current_integer
temp_int = ''
return answer_flag
def Autotest():
test_file = open("C:/Users//test/Zadacha6/test.txt", "r")
answer = Sequence(test_file, 1,1,1,3)
if (answer == 1):
print("Autotest passed...Respect+")
else:
print("Autotest not passed")
exit(-1)
Autotest()
c_1 = int(input("Enter c_1: "))
c_2 = int(input("Enter c_2: "))
c_3 = int(input("Enter c_3: "))
b = int(input("Enter b: "))
answer = Sequence(file,c_1, c_2, c_3, b)
if (answer == 1):
print("Integers in sequence satisfy the recurrent ratio")
else:
print("Integers in sequence dont satisfy the recurrent ratio")
|
c22c41a7c3601f17d23bd2cfaadaf6b5510a1184 | pktrigg/DocumentDelivery | /_bootstrap/_scripts/scan.py | 3,732 | 3.578125 | 4 | # created [email protected]
# created: May 2015
# Based on twitter bootstrap
#
import os
import sys
import re
import csv
# specify a list of folder names which will be skipped in the scanning process. The list can be as long as you like.
def convert(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def loadCSVFile(fileName):
# 2do pkpk skip multiple commas in the text file. we can only have 1 comma per line or the dict does not work
data = {}
with open(fileName, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='`')
for row in reader:
data[row[0]] = " ".join(row[1:])
return data
def scanFolders(outputFileName, folder, ignoreFolders):
print("scanning folders and sub folders and build all links...")
dirs = os.listdir( folder )
for folder in dirs:
if os.path.isdir(folder):
if any(x in folder for x in ignoreFolders):
print("Skipping ignored folder: " + folder)
else:
# folder = folder.title()
print("compiling folder: " + folder)
FolderListing2Portal(outputFileName, folder)
return
def buildDropDownMenu(outputFileName, folder, ignoreFolders):
print("scanning folders and sub folders and build the menu...")
dirs = os.listdir( folder )
for folder in dirs:
if os.path.isdir(folder):
if any(x in folder for x in ignoreFolders):
print("Skipping ignored folder: " + folder)
else:
# folder = folder.title()
print("compiling menu from folder: " + folder)
FolderListing2DropDownMenu(outputFileName, folder)
#close out the menu
fout = open(outputFileName, "a")
fout.write(" </ul>\n")
fout.write(" </div>\n")
fout.write(" </div>\n")
fout.write(" </nav>\n")
fout.close()
return
def buildSideBarMenu(outputFileName, folder, ignoreFolders):
print("scanning folders and sub folders and build the menu...")
dirs = os.listdir( folder )
for folder in dirs:
if os.path.isdir(folder):
if any(x in folder for x in ignoreFolders):
print("Skipping ignored folder: " + folder)
else:
# folder = folder.title()
print("compiling menu from folder: " + folder)
FolderListing2SideBarMenu(outputFileName, folder)
#close out the menu
fout = open(outputFileName, "a")
fout.write(" </ul>\n")
fout.write(" </div>\n")
fout.write(" </div>\n")
fout.write(" </div>\n")
fout.close()
return
def FolderListing2Portal(outputFileName, folderName ):
import makeFileListingAsHTMLTable
document = makeFileListingAsHTMLTable.makeListing(folderName)
fout = open(outputFileName, "a")
fout.write(document)
fout.close()
return
def FolderListing2DropDownMenu(outputFileName, folderName ):
import makeFileListingAsHTMLTable
document = makeFileListingAsHTMLTable.makeListing2DropDownMenu(folderName)
fout = open(outputFileName, "a")
fout.write(document)
fout.close()
return
def FolderListing2SideBarMenu(outputFileName, folderName ):
import makeFileListingAsHTMLTable
document = makeFileListingAsHTMLTable.makeListing2SideBarMenu(folderName)
fout = open(outputFileName, "a")
fout.write(document)
fout.close()
return
def mergeFile(outputFileName, filename ):
fin = open(filename, "r")
document = fin.read()
fin.close()
fout = open(outputFileName, "a")
fout.write(document)
fout.close()
return
#replace a word with the target word based on case insensitivity, ie replace word,WORD,WoRd with Word
def wordSearchReplace (filename, searchWord, targetWord):
f = open(filename,'r')
filedata = f.read()
f.close()
print(("Search&Replacing:" + targetWord))
pattern = re.compile(searchWord, re.IGNORECASE)
newdata = pattern.sub(targetWord, filedata)
f = open(filename,'w')
f.write(newdata)
f.close()
return
|
3f59e7b490a76b86a06de55c9379120eb2169698 | EruDev/Python-Practice | /菜鸟教程100例/12.py | 180 | 3.5625 | 4 | # 题目:判断101-200之间有多少个素数,并输出所有素数。
for num in range(101, 200):
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.