blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
40928ea20594fb3daff7da32fc889a96f27e3f1c | annaVVV/2017_Python_Interview | /reverse_str.py | 700 | 3.984375 | 4 | def rev_str(s1):
l = len(s1)
if l < 2:
return s1
i = 0
j = l - 1
s = list(s1)
while i < j:
print( s[i], s[j])
s[i], s[j] = s[j], s[i]
i = i + 1
j = j - 1
return ''.join(s)
def reverse(s):
str = ""
for i in s:
str = i + str
return str
# Pyth... |
c089e5df6cf1baddeb54a0bb7ebf03f808d6843a | annaVVV/2017_Python_Interview | /Interview_codingQQ/count_nonoverlaping_combinations.py | 2,354 | 3.625 | 4 | ###
# An artist is creating a collage out of newspaper of cut - outs.
# There is a long string of text from nespaper, where
# interesting substrings have been marked to cut out. Only two
# interesting positions of the text are needed, and the rest of the
# collage will be made of images. The two chosen interesting
# po... |
f7a79dd51a74a6494e7801b91d634fc21b15cfbb | joelewis43/ME499-HW-N | /P3.py | 1,176 | 4.09375 | 4 | #!/usr/bin/env python
from random import uniform as rand
from math import pi
#-------------------------------------------------------------------------------------------#
# Function: estPi
# Description: estimates the value of pi with Monte Carlo Integration
# Parameters: the number of trials (defaults to 100000)
# R... |
d25a76943898d4b8c68bf52309ea2c598022de71 | kshma/DiceRollingSimulator | /Dice Rolling Simulator.py | 1,296 | 3.90625 | 4 | import tkinter
from PIL import Image, ImageTk
import random
root = tkinter.Tk()
root.geometry('400x400')
root.title('Roll the dice')
BlankLine = tkinter.Label(root, text="")
BlankLine.pack()
# adding label with different font and formatting
HeadingLabel = tkinter.Label(root, text="Let's play",
fg = "light ... |
ba1725e2598210bcf5aef0921391116e7cecf867 | Valinor13/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-write_file.py | 270 | 3.984375 | 4 | #!/usr/bin/python3
"""A module containing a function for writing to a file"""
def write_file(filename="", text=""):
"""A function that writes to a file"""
with open(filename, 'w') as f:
bytecount = f.write(text)
f.close()
return bytecount
|
78d4e8907c2f849e9623c2169ca24b60f4082965 | Valinor13/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/8-simple_delete.py | 296 | 3.515625 | 4 | #!/usr/bin/python3
def simple_delete(a_dictionary, key=""):
if bool(a_dictionary) is False:
return None
keylist = a_dictionary.keys()
sig = 0
for i in keylist:
if i == key:
sig = 1
if sig == 1:
del a_dictionary[key]
return a_dictionary
|
48a13bfcd352270ecad6a045e844a0d37bfb6f48 | Valinor13/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-to_json_string.py | 196 | 3.546875 | 4 | #!/usr/bin/python3
"""A module that stores a function to convert to JSON"""
import json
def to_json_string(my_obj):
"""Returns a string converted to json"""
return json.dumps(my_obj)
|
705b2d383e3d0e9cb9d3098cadccd3449d283682 | Valinor13/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 911 | 4.375 | 4 | #!/usr/bin/python3
"""
A module to store simple functions for testing
...
Functions
---------
print_square(size)
Prints a square based on the input size
Exceptions
----------
raise : TypeError
Raises an error if arguments do not meet expected types
raise : ValueError
Raises an error if the input value is... |
f9e312b5a44271793d2813f15a476a9cac1223f8 | Valinor13/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/5-number_keys.py | 180 | 3.78125 | 4 | #!/usr/bin/python3
def number_keys(a_dictionary):
if bool(a_dictionary) is False:
return 0
count = 0
for x in a_dictionary:
count += 1
return count
|
a47bddf5e13ac380c7297d870a70e339621876bb | Valinor13/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/5-print_comb2.py | 130 | 3.640625 | 4 | #!/usr/bin/python3
for x in range(99):
print("{:d}{:d},".format(x // 10, x % 10), end=" ")
x += 1
print("{:d}".format(x))
|
084a667c43bb44dd704611c4ccf6f08a72973699 | Abhiaish/Python | /code14.py | 162 | 3.671875 | 4 | # find second largest element in an array
l=list(map(int,input().split()))
l.sort()
for i in range(0,len(l)):
l.pop()
print(l[-1])
break
|
c5ab0e8daae381aaa509688c6af046779515bba6 | Abhiaish/Python | /code6.py | 111 | 3.890625 | 4 | # count number of digits in a number.
n=int(input())
count=0
while(n!=0):
n=n//10
count+=1
print(count) |
469e48b4197700f629858a0f64b1f7c36de2959f | shivendratrivedi99/python-login-signup | /Login and signup/both.py | 2,764 | 3.75 | 4 | from tkinter import *
scr=Tk(className="Login or Signup")
def login():
u=Label(scr,text='UserName',font=('times',15,'bold'))
u.grid(row=1,column=0)
ue=Entry(scr,font=('times',15,))
ue.grid(row=1,column=1)
p=Label(scr,text='Password',font=('times',15,'bold'))
p.grid(row=2,column=0)
pe=Entry... |
83d7cf1299055b7c66b5ca1fbf579394a7c2b70f | crocs-muni/booltest | /booltest/timer.py | 1,065 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
class Timer(object):
"""
Simple stopwatch timer
"""
def __init__(self, start=False):
self.time_start = time.time() if start else None
self.time_acc = 0
def stop(self):
if self.time_start is None:
raise ... |
caf3bd1902e0a9997846afb7de792918fbfd0948 | eliflores/python-for-everybody | /exercises/dictionaries_exercise.py | 516 | 3.734375 | 4 | fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox_short.txt"
try:
fh = open(fname)
except:
print "Cannot open file",fname
exit()
dictionary = dict()
for line in fh:
if line.startswith('From '):
words = line.split()
email_address = words[1]
dictionary[email_address] = dictionary.get(ema... |
fef90c1238d187a126bdc874a14f8c253648181c | runnz121/Python_boot | /3weeks/3.py | 514 | 4.03125 | 4 | def find_even_number(n,m):
if n < m:
numbers = [i for i in range(n, m+1)]
else:
numbers = [i for i in range(m, n+1)]
mid = int((n + m+1)/2)
print(f"첫 번째 수 입력 : {n}")
print(f"두 번재 수 입력 : {m}")
for i in numbers:
if i == mid and i%2 == 0:
print(f"{mid} 중앙값")
... |
85a0b7f1c3ae4ee8728a0eb24b182c8d6bf5d600 | viacheslavzaharov/AaDS_1_184_2021 | /1.py | 360 | 3.5 | 4 | text = "The tiger once ranged widely from the Eastern Anatolia Region in the west to the Amur River basin, and in the south from the foothills of the Himalayas to Bali in the Sunda islands."
a = 0
s = 0
for word in text:
if word == "a":
a = a + 1
elif word == "s":
s = s + 1
print("'a' co... |
83ed18f5fa9c8f9882d7f7e96b2abfebd6bec4ef | viacheslavzaharov/AaDS_1_184_2021 | /2.4.py | 807 | 3.78125 | 4 | def merge_sort(numbers):
if len(numbers) <= 1:
return numbers, 0
middle = int( len(numbers) / 2 )
left, a = merge_sort(numbers[:middle])
right, b = merge_sort(numbers[middle:])
result, c = internal_sort(left, right)
return result, (a + b + c)
def internal_sort(left, right):
... |
e0095955c8d029ed73079b726e0da56fb2618fe8 | prafulmhrjn/LabProjects | /Project1/5.py | 1,148 | 4.25 | 4 | '''5. A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of
students in each class, print the smallest possible number of desks that can be purchased.
The program should read three integers: the number of students in each of the three classes, a, b and c respectivel... |
238f970de5409d794d8c866a24ec53650eade839 | prafulmhrjn/LabProjects | /Lab4/5.py | 135 | 4.34375 | 4 | '''5.Write a Python program that accepts a word from the user and reverse it.'''
word = str(input('Enter a word:')) [::-1]
print(word) |
aa6d140293180ee2ddff2688c2119e6c81479bf9 | prafulmhrjn/LabProjects | /Project1/1.py | 375 | 4.28125 | 4 | ''' 1. Write a program that takes three numbers and prints their sum. Every number is given on a seperate line.'''
first_number = int(input("Enter the first number:"))
second_number = int(input("Enter the second number:"))
third_number = int(input("Enter the third number:" ))
Sum = (first_number + second_number + thi... |
f812629becd6c300bdab045b8756d4eed85aa81d | prafulmhrjn/LabProjects | /Project3/2.py | 712 | 4 | 4 | '''2. WAP which accepts marks of four subjects and display total marks, percentage and grade.
Hint: more than 70% –> distinction, more than 60% –> first, more than 40% –> pass,
less than 40% –> fail'''
maths = float(input('Enter the marks of maths:'))
science = float(input('Enter the marks of science:'))
english = fl... |
d56ebe37ac6ea2aa0b0d4dc2279d4951e0318b22 | hpolowczyk/life_is_a_py-way | /PyBank/main.py | 2,095 | 3.796875 | 4 | # PyBank Assignment
# Import modules
import os
import csv
# Set path for file
bdgt_path = os.path.join("..", "PyBank", "budget_data.csv")
# Set empty lists
months = []
p_l = []
# Open the CSV
with open(bdgt_path, newline="", encoding="utf8") as bdgt_file:
csv_reader = csv.reader(bdgt_file, delimiter=",")
cs... |
a73b7e8a5e471dba722d06ff88227017ecd68690 | fsmith503/CrackingTheCodingInterviewPractice | /1-6.py | 776 | 3.71875 | 4 | #page 91 1.6 basic string compression using counts of repeated characters
#aabcccccaaa would become a2b1c5a3
def comp(str1):
if len(str1) == 1:
result = ""
running_count = 1
temp_char = str1[0]
result += temp_char
result += str(1)
return result
result = ""
run... |
2e43cc8fb2d7dd9556f9666a2d15749d90b704fc | fsmith503/CrackingTheCodingInterviewPractice | /2-6.py | 2,368 | 4.15625 | 4 | # CTCI 2.6
# Palindrome
import unittest
#from LinkedList import LinkedList
# My Solution
# Simple solution abusing python's list functionality
def is_palindrome1(head):
curr = head
list = []
# This adds everything in the linked list to a list
while curr:
list.append(curr.data)
... |
6a5c306fe3c56a85c0f51b06edd15ecdacde0e95 | rocksnow1942/mymodule | /mymodule/seq.py | 2,260 | 3.515625 | 4 | REVERSETRANS = str.maketrans("ACTGNactgn-", "TGACNtgacn-")
def revcomp(s):
"""
return reverse complement of a sequence.
"""
# define the dic out side is much faster.
# comp = map(lambda x: REVSECOMPDICT[x], s[::-1]) # slightly slower
return s.translate(REVERSETRANS)[::-1]
# def lev_dista... |
365c1ec2aa6b66613689d97092b674f527b60ca6 | KodeWorker/3DModelAnalysis | /dev/20190807/spline.py | 1,979 | 3.5 | 4 | # -*- coding: utf-8 -*-
# http://web.mit.edu/hyperbook/Patrikalakis-Maekawa-Cho/node17.html
# https://hub.packtpub.com/how-to-compute-interpolation-in-scipy/
# https://github.com/kawache/Python-B-spline-examples
from scipy.interpolate import splev
def spline_to_polyline(control_points, knot_values, degree, n_mul... |
876ce5d955a884821cbc3233e60d38bf8888b27c | spacetelescope/jwst | /jwst/scripts/asn_edit.py | 2,516 | 3.671875 | 4 | #!/usr/bin/env python
import argparse
from jwst.associations import asn_edit
def main():
"""
Parse command line, read, edit, write association file
"""
# Parse command line arguments
description_text = """
Edit Association File
This script adds or removes filenames from an association file. Th... |
8b87c0c39eae2a3de395efc7c55bcd49d992ccde | holgerthies/algorithms | /graphs/prim.py | 799 | 3.515625 | 4 | from algorithms.datastructures.heap import BinaryHeap, heapElement
def prim(G):
""" returns minimum spanning tree of G. """
# start with arbitrary vertix, say the first
v = G.vertices.keys()[0]
# edges of the spanning tree
T = set()
# currently in tree vertices
V = set([v])
# init heap with all neighbors of v
... |
71a23ef176e8022d281f07efad2d0d63d55a8ecb | Aibek-ch/English-Premier-League | /Codes/EPL.py | 2,671 | 3.625 | 4 | import csv
import re
import sqlite3
conn = sqlite3.connect('season.sqlite')
cur = conn.cursor()
year1 = input('Enter beginning of the period:')
year2 = input('Enter ending of the period:')
seasons = list()
for year in range(int(year1), int(year2), 1):
season = str(year) + '-' + str(year+1)
seasons... |
b72ec050dcbd6cd4da28ebd5c1cf9fdd1ef221a5 | dcsm8/python-mastery | /section_3/dictionaries.py | 357 | 3.671875 | 4 | # Dictionary
dictionary = {
'a': [1, 2, 3],
'b': 'Hello',
'c': True
}
user = dict(name='David')
print(dictionary.get('d'))
print(user)
print('a' in dictionary)
print('hello' in dictionary.values())
user2 = user.copy()
print(user)
print(user2)
user2.clear()
print(user)
print(user2)
user.update({'na... |
0a0c7fdfd7c02ddca1653a428fc79f228282fcaa | HassanMujtaba12/Encryption | /Encryption/CaesarCipher.py | 1,893 | 3.609375 | 4 | import base64
def encrypt(string, shift):
shift = int(shift)
cipher = ''
for char in string:
if char == ' ':
cipher = cipher + char
elif char.isupper():
cipher = cipher + chr((ord(char) + shift - 65) % 26 + 65)
else:
cipher = cipher + chr(... |
bb00def36065c38f315fb0f902ff36ae78239f5c | nodesense/deloitte-azure-db-synapse-may-2021 | /notebooks/DataFrame-Basic.py | 2,388 | 3.546875 | 4 | # Databricks notebook source
products = [
# (product_id, product_name, brand_id)
(1, 'iPhone', 100),
(2, 'Galaxy', 200),
(3, 'Redme', 300), # orphan record, no matching brand
(4, 'Pixel', 400),
]
brands = [
#(brand_id, brand_name)
(100, "Apple"),
(200, "Sams... |
a8ac0cecec5dcb957d0394519faf6546b18c7c17 | ChristChurchMayfair/ccm-alexa-skill | /src/utils/general_utils.py | 1,032 | 3.75 | 4 | def humanise_passage(book: str, start_chapter: str, start_verse: str, end_chapter: str, end_verse: str) -> str:
if len(start_chapter) == 0: # e.g. James
return book
if len(start_verse) == 0 and len(end_chapter) == 0 and len(end_verse) == 0: # e.g. Genesis 1
return f"{book} chapter {start_chapt... |
6d803ce35d3c97f6e2f37982f03b80578c04c47a | zoharmilul/ex12 | /GameGUI.py | 5,644 | 3.5625 | 4 | import tkinter as tk
from tkinter import messagebox
LETTER_HOVER_COLOR = "lightblue"
LETTER_REGULAR_COLOR = "lightgray"
BUTTON_HOVER_COLOR = 'gray'
REGULAR_COLOR = 'lightgray'
BUTTON_ACTIVE_COLOR = 'skyblue'
BUTTON_STYLE = {"font": ("arial", 15),
"borderwidth": 1,
"relief": tk.RAISED,
... |
516dbb12b5837b353a8b4d9e6a21171a0306d4ff | curiousYi/cs61a | /scratch-pad.py | 334 | 3.6875 | 4 | def gen_all_items(list_of_iterators):
"""
>>> nums = [[1, 2], [3, 4], [[5, 6]]]
>>> num_iters = [iter(l) for l in nums]
>>> list(gen_all_items(num_iters))
[1, 2, 3, 4, [5, 6]]
"""
list = []
for iterator in list_of_iterators:
for thing in iterator:
list.append(thing)
... |
a6beba19cd7d586a9639e83df03ee001c7f8d58d | save6/DesignPattern_Composite | /example.py | 1,824 | 3.796875 | 4 | from abc import ABCMeta, abstractmethod
class Component(metaclass=ABCMeta):
@abstractmethod
def print(self,num:int)->None:
pass
@abstractmethod
def add(self,component)->None:
pass
class AbstractComponent(Component):
def getName(self):
return self.name
def... |
04ca577a97896626efcff84f723425543a0e7c7e | z0nky/kurs_python | /01_lekcja/stringi2.py | 3,573 | 3.75 | 4 | # zadanie 1
#Stwórz zmienną przechowującą wyraz o długości nieparzystej większej niż 7 i zwróć łańcuch złożony z trzech środkowych znaków danego ciągu.
txt = "Pionierzy"
#sprawdza dlugosc wyrazu
mid = len(txt)//2
print(txt[mid - 1 : mid + 2])
# zadanie 2
#Stwórz dwie zmienne s1 i s2 przechowujące dowolne wyrazy, utwó... |
0d588e7ac3be4fa085b049904ab38e52a61ab1e4 | z0nky/kurs_python | /07_lekcja/zad_1/fitmeter.py | 855 | 3.8125 | 4 | import bmi
def main():
height = float(input('Podaj swój wzrost (format m.cm): '))
weight = float(input('Podaj swoją wagę: '))
bmi.bmi_status(bmi.calc_bmi(weight, height))
print(get_advice())
def get_advice():
with open(bmi.filename + '.txt') as f:
content = f.read()
print(content)
d... |
b1f36b9015330b493364a51c951407cf5e0de2a7 | z0nky/kurs_python | /01_hackaton/adress book.py | 1,921 | 4.28125 | 4 | def main_menu():
return ('Show all records - 1'
'\nAdd new record - 2'
'\nDelete record - 3'
'\nExit - 4')
def go_to_selection():
print()
print(main_menu())
go_to = input('Insert menu number positon (1-4): ')
if go_to == '1':
show_all()
elif go_to ==... |
5082e0f7083b58d392d6b7f7ea8d7019f23b9c40 | z0nky/kurs_python | /09_lekcja/homework.py | 434 | 3.703125 | 4 | from math import *
def rozklad(x):
if x <= 0:
return 0
i = 2
e = floor(sqrt(x))
r = []
while i <= e:
if x % i == 0:
r.append(i)
x /= i
e = floor(sqrt(x))
else:
i += 1
if x > 1:
r.append(x)
return r
# l=1
# whi... |
68f5019eded566bfeb826df466ed588cf97437be | z0nky/kurs_python | /09_lekcja/email finder.py | 369 | 4.09375 | 4 | def emailfinder():
if email.find('@') == -1:
return ('Email should include "@".')
else:
try:
emaillist.index(email)
return (email, 'is on the list')
except ValueError:
return ('Email not found.')
email = input('Enter emain you want to find: ')
emailli... |
ed596a746ab1d326508a86afe44cb87364a9f712 | z0nky/kurs_python | /02_lekcja/Pętla WHILE.py | 1,529 | 4 | 4 | alls = 3
while alls > 0:
subject = input("Przedmiot szkolny: ")
grade = input("Ocena w skali 1-6: ")
print(subject + ": " + grade)
alls = alls - 1
print("Job's done")
# kod alternatywny
przedmioty = input("Podaj przemdioty podzielone myślnikiem: ")
oceny = input("Podaj oceny podzielone myślnikiem: ")... |
813131bba84797aa939ed74fd11195d248aff945 | sushmita12321/test | /lab ex 2.1.py | 234 | 4.21875 | 4 | # check whether 5 is in list of first 5 natural numbers or not.Hint:List=>[1,2,3,4,5]
x =["1","2","3","4","5"]
if "5" in x:
print("5 is in list of natural number:")
else:
print("5 is not in the list of natural numbre:") |
4c3e87be58ebf02ca0ed879e5dbaef2ace0de8c3 | sushmita12321/test | /lab.ex3 .1.py | 359 | 4.34375 | 4 | # Write a pythone functionto find the Max of three numbers.
def max(x,y,z):
if x>y and x>z:
return x
elif y>x and y>z:
return y
else:
return z
x = float(input("enter a first no."))
y = float(input("enter a second no."))
z = float(input("enter a third no."))
print("greatest... |
ac427dc0b31b4234be90158d2bea8a6e5eacbf01 | sushmita12321/test | /8.py | 105 | 4 | 4 | # Write a pythone program to create the colon of a tuple.
my_tuple = (1,2,3,4,5,9)
print(my_tuple[2:5]) |
d0ccd50187e81e7ab4b69d1ffdb391204c2089e9 | AzimAstnoor/List | /q3.py | 392 | 4.03125 | 4 | def plus(num1, num2):
num3 = num1 + num2
return num3
def minus(num1, num2):
num3 = num1 - num2
return num3
def product(num1, num2):
num3 = num1 * num2
return num3
def quoteint(num1, num2):
num3 = num1 / num2
return num3
def remainder(num1, num2):
num3 = num1 ** num2
return num3
d... |
8e06107021a4f788d7e0f9aab481031876279ae1 | apulijala/python-crash-course-3 | /ch6/person.py | 7,618 | 4.34375 | 4 | """
6-1. Person: Use a dictionary to store information about a person you know.
Store their first name, last name, age, and the city in which they live.
You should have keys such as first_name, last_name, age, and city.
Print each piece of information stored in your dictionary.
"""
def store_person(first, last, age,... |
c0c6720d3611d434682a2aa572fe7d97853d1b29 | apulijala/python-crash-course-3 | /ch7/pizza_toppings.py | 2,408 | 4.34375 | 4 | """
7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of
pizza toppings until they enter a 'quit' value. As they enter each topping,
print a message saying you’ll add that topping to their pizza.
"""
def pizza_toppings_quit():
topping = input("Enter Pizza topping or enter quit? ")
top... |
654d08002eb6ae0423001ce2eba462c7bd52a0f5 | apulijala/python-crash-course-3 | /ch9/restaurant.py | 997 | 4.34375 | 4 | """
9-1. Restaurant: Make a class called Restaurant.
The __init__() method for Restaurant should store two attributes: a restaurant_name and a
cuisine_type. Make a method called describe_restaurant() that prints
these two pieces of information, and a method called open_restaurant()
that prints a message indicating ... |
649e242645e2dda300ddc59e1b9b938fa0ea676f | EderOBarreto/exercicios-python | /ex081.py | 389 | 4.03125 | 4 | valores = []
opcao = ''
while opcao != 'N':
valores.append(int(input('Digite um número: ')))
opcao = str(input('Deseja continuar? [S/N]:')).strip().upper()
print(f'{len(valores)} números foram digitados.')
valores.sort(reverse=True)
print(f'Lista decrescente = {valores}')
if 5 in valores:
print('O valor 5 ... |
fbc538b91e79caf98bd262cd4c62962411adc2be | EderOBarreto/exercicios-python | /ex029.py | 187 | 3.625 | 4 | vel_carro = int(input('Digite a velocidade do carro: '))
if vel_carro > 80:
print('Você foi multado.\nO valor da multa é de R$:{:.2f}.'.
format((vel_carro - 80) * 7.00))
|
5979e3dd7824640e6a770d317d1a8f7549a30ea1 | EderOBarreto/exercicios-python | /ex034.py | 166 | 3.828125 | 4 | salario = float(input('Qual é o seu salário: '))
if salario > 1250.00:
salario *= 1.1
else:
salario *= 1.15
print('O novo salário é {}'.format(salario))
|
9788033d4b5726605d76326af3f6cd123f4b7170 | EderOBarreto/exercicios-python | /ex023.py | 572 | 3.859375 | 4 | num = input('Digite um número de 0 a 9999:')
num = num.zfill(4)
unidade = num[3]
dezena = num[2]
centena = num[1]
milhar = num[0]
print('Unidade: {}'.format(unidade))
print('Dezena: {}'.format(dezena))
print('Centena: {}'.format(centena))
print('Milhar: {}'.format(milhar))
num2 = int(input('Digite um número de 0 a ... |
efa1604a3678a73880d48e6168de4f03ef0312e1 | EderOBarreto/exercicios-python | /ex065.py | 508 | 3.96875 | 4 | soma = contador = maior = menor = 0
continuar = 'S'
while continuar == 'S':
num = int(input('Digite um número: '))
if contador == 0:
menor = maior = num
else:
if num > maior:
maior = num
elif num < menor:
menor = num
soma += num
contador += 1
con... |
6f231add9624dfad7cdef6ecc805e5ba6695d99b | EderOBarreto/exercicios-python | /ex053.py | 184 | 4.1875 | 4 | frase = input('Digite uma frase:').replace(" ", "").upper()
if frase[::-1] == frase:
print('Esta frase é um palíndromo!')
else:
print('Esta frase não é um palíndromo!')
|
da94976eb4e029c210e1a676698f86365883fee7 | EderOBarreto/exercicios-python | /ex031.py | 538 | 3.546875 | 4 | cores = {'limpa': '\033[m',
'azul': '\033[34m',
'amarelo': '\033[33m',
'verde_bold': '\033[1;32m',
'magenta': '\033[35m',
'preto_e_branco': '\033[7;30m',
'sublinhado': '\033[4m'}
distancia = int(input('Digite a distância da viagem: '))
if distancia > 200:
prin... |
53bf148a0afeeb6189df52e033175304a23eda1d | EderOBarreto/exercicios-python | /ex033.py | 700 | 3.9375 | 4 | cores = {'limpa': '\033[m',
'azul': '\033[34m',
'amarelo': '\033[33m',
'verde_bold': '\033[1;32m',
'magenta': '\033[35m',
'preto_e_branco': '\033[7;30m',
'sublinhado': '\033[4m'}
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número:... |
8e8985ef4cc807783cdbed48ec79f59773b6ef3a | navarro0/visual-novel-engine | /slider.py | 2,058 | 3.546875 | 4 | import pygame
from pygame.locals import *
##########################################################################
## Slider ##
## -------------------------------------------------------------------- ##
## Class that defines a sliding bar, for use in the ... |
b83a610a34aeee63a4e6516c839d4d749deb33f1 | TheGoddcoder/teluskodemo | /prac2.py | 1,517 | 4.25 | 4 | # Write a Python program to get the Python version you are using
# import sys
# print(sys.version_info)
# print(sys.version)
# Write a Python program to display the current date and time
# import datetime
# import time
#
# print(datetime.datetime.now())
# print(time.ctime())
# Write a Python program which accepts the... |
4691da5e0ca1e99eef4e4804ce6dfd79b6ef2d6a | amyible/tigerapps | /tigerapps/cal/cal_util.py | 264 | 3.5 | 4 | from datetime import datetime
def strftime_yearopt(dt, fmt, comma=True):
this_year = datetime.today().year
if dt.year == this_year:
return dt.strftime(fmt)
if comma:
return dt.strftime(fmt + ", %Y")
return dt.strftime(fmt + " %Y")
|
28a2927b2d13c93b84f95178c1c0ed593cc92b33 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/GriesCampbell_PracticalProgrammingInPython/Chapter14_ObjectOrientedProgramming/notes/FileReadingMolecules.py | 630 | 3.5 | 4 | import Molecule
import Atom
def readMolecule(readerObj):
'''Read a single molecule from readerObj and return it or
return None to signal EOF.'''
line = readerObj.readline()
if not line:
return None
# Name of molecule: "COMPND name"
key, name = line.split()
# Other lines are... |
6cb0a99b68b08964f0950091bcd2751c205924fa | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/AllenBDowney_ThinkPython2/notes/Chapter14_Files.py | 4,755 | 3.625 | 4 | PATH = "/datascience/projects/statisticallyfit/github/learningprogramming/Python/python/PythonTutorial/[Downey] ThinkPython 2e/notes/"
PATH_TUTORIAL = "/datascience/projects/statisticallyfit/github/learningprogramming/Python/python/PythonTutorial/"
# 14.2 - reading/writing files
# note: careful with the 'w' option - i... |
009b376c8f812f46129f29b2edbcd70aee81abee | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/AllenBDowney_ThinkPython2/exercises/Exercise5.1_time.py | 1,278 | 4.25 | 4 | import time
import math
def displayTime():
# time in seconds since January 1 1970
totalSeconds = time.time()
secondsTemp = totalSeconds
years = int(totalSeconds // (365 * 24 * 60 * 60))
secondsTemp %= (365 * 24 * 60 * 60) # remaining secs after years taken out
days = int(secondsTemp // (24 ... |
88cfd989f0b0900465446f113931324846809381 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/GriesCampbell_PracticalProgrammingInPython/Chapter16_GUI/notes/16.3_2_UsingLambda.py | 1,067 | 3.796875 | 4 | from tkinter import *
from tkinter import ttk
# The controller
'''
def clickUp():
click(counter, 1)
def clickDown():
click(counter, -1)
'''
def click(counterVariable, value):
counterVariable.set(counterVariable.get() + value)
if __name__ == "__main__":
root = Tk()
# the model
# note: co... |
05e920ec22b087f7506f231af033ecd7584c59c9 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/JohnZelle_PythonProgramming/Chapter7_DecisionStructures/ex1_Wages.py | 945 | 4.09375 | 4 |
def getJobInput():
numHours = input("Enter number of hours worked this week: ")
while True:
try:
numHours = int(numHours)
except ValueError:
print("Invalid. Enter number of hours worked: ")
else:
break
hourlyRate = input("Enter the hourly rate ... |
66a495b69a2afa8e69d9e19a916f67bd810be37e | statisticallyfit/Python | /pythonlanguagetutorials/PythonUNE/Practicals/Practical4_#1_DowneyChapter4.3/Exercise4.3_part1,2.py | 906 | 4.0625 | 4 | import turtle
import tkinter
# method summary
# http://interactivepython.org/runestone/static/IntroPythonTurtles/Summary/summary.html
t = turtle.Turtle()
# -----------------------------------------------------------------------------------------------------------
def move(tempTurtle, x, y):
tempTurtle.penup()
... |
6435639a0155b67426498e96e981ac39fc4f768d | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/JohnZelle_PythonProgramming/Chapter7_DecisionStructures/ex6_SpeedingTicket.py | 472 | 3.59375 | 4 |
def calculateFine(speedLimit, clockedSpeed):
fine = 0.0
if clockedSpeed > speedLimit:
fine += 50 + 5*(clockedSpeed - speedLimit)
if clockedSpeed > 90:
fine += 200
# Now evaluate:
if fine == 0.0:
print("The speed was legal.")
else:
print("The speed was illegal... |
65eae508d2c50382ce56e8a0fcf77da8b2f6bd10 | statisticallyfit/Python | /pythonlanguagetutorials/PythonUNE/Practicals/Practical4_#1_DowneyChapter4.3/mypolygon.py | 189 | 3.890625 | 4 |
import turtle
import tkinter
bob = turtle.Turtle()
print(bob)
# the program
for i in range(4):
bob.fd(100)
bob.lt(90) # turning left 90 degrees
# end program
turtle.mainloop() |
8fca62c9acd7450914c322321cc42774217c5064 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/GriesCampbell_PracticalProgrammingInPython/Chapter12_DesigningAlgorithms/exercises/6_DutchFlag.py | 1,731 | 3.90625 | 4 |
def dutchFlagIntuitive(colors):
numRed, numGreen, numBlue = 0, 0, 0
for col in colors:
if col == "red":
numRed += 1
elif col == "green":
numGreen += 1
else:
numBlue += 1
newColors = []
newColors.extend(("red\n" * numRed).split())
newColor... |
fd965d321d77b6769c7c42f2d33356b75e7c0002 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/JohnZelle_PythonProgramming/Chapter5_Strings,Lists,Files/ex9_CountNumWords.py | 586 | 4.3125 | 4 |
def countNumWords(sentence):
"""Counts number of words in the sentence string."""
wordCount = 0
words = sentence.split() # split at whitespace
for word in words:
wordHasSomeLetters = any(letter.isalpha() for letter in list(word))
if wordHasSomeLetters:
wordCount += 1
... |
4ae2c3fcf27a45520568f23b540d0e2324449678 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/GriesCampbell_PracticalProgrammingInPython/Chapter14_ObjectOrientedProgramming/notes/University.py | 1,745 | 3.78125 | 4 |
class Member:
"""Member of university."""
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
def __str__(self):
return "Name: {0}\nAddress: {1}\nEmail: {2}".format(self.name, self.address, self.email)
class Faculty(Membe... |
63deac97f51d8ffa24b32996b69812cd70de7280 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/AllenBDowney_ThinkPython2/notes/Chapter19_Goodies.py | 7,200 | 3.953125 | 4 | import math
# 19.1 -- Conditional expressions
# example 1
x = 10
y = math.log(x) if x > 0 else float('nan') # instead of straight-up if-else
# example 2
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
# example 3: handling optional arguments
def initialize_bad(self, name, contents=None):
self.... |
cb24b58bd9bcc95c7b99a1f8d17cb5c1a4dfb912 | statisticallyfit/Python | /pythonlanguagetutorials/PythonUNE/Lectures/Lecture3.0_FurtherPython/newton.py | 380 | 4.03125 | 4 | #!/usr/bin/env python3
epsilon = 0.0000000000000000000000000000000000000000000000000001
square = input("Enter a value to find the root of: ")
a = float(square)
estimate = input("Enter initial estimate of root: ")
x = float(estimate)
while True:
print(x)
y = (x + a/x)/2
if(abs(x - y) < epsilon):
break
# otherwi... |
245c14a7e25672a9998ca9da6c12b362bb44ddc4 | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/AllenBDowney_ThinkPython2/notes/Chapter17_ClassesAndMethods.py | 3,798 | 4.34375 | 4 |
# NOTE: compare and contrast with chapter 16 classs: there, we didn't declare attributes in class, just
# note on the way in main function so any garbage names could be created on the fly.
# There, there were no compiler complaints that attributes weren't there.
# Here, there are complaints if you put all functio... |
7fcb415e08e4219de16d725e57d56f3d45c45e2f | statisticallyfit/Python | /pythonlanguagetutorials/PythonTutorial/AllenBDowney_ThinkPython2/exercises/Exercise6.5_GCD.py | 306 | 3.984375 | 4 |
# keep dividing b by the remainder of a/b until remainder is zero. When
# that happens, the pair number is the gcd.
def gcd(a, b):
if b == 0:
return a
elif b > a:
return gcd(b, a)
else:
return gcd(b, a % b)
print(gcd(36, 15))
print(gcd(36, 12))
print(gcd(481, 78)) |
08cf235f0219a696cf0354cd24cb2f9e0eb08930 | SoumendraM/GeekForGeeksDSA5 | /Mathematics/CountDigits.py | 199 | 3.65625 | 4 | def CountDigits(num):
sum = 0
while num > 0:
num = int(num/10)
sum += 1
return sum
if __name__ == '__main__':
num = 129758758575865865865
print(CountDigits(num)) |
5f6205701c21ab1cb2f8e395f2438d3b3ebd6477 | chrismesina14/CSE_320_Winter2020 | /Python/partition_sum.py | 1,819 | 3.984375 | 4 | def printSets(set1, set2) :
# Print set 1.
for i in range(0, len(set1)) :
print ("{} ".format(set1[i]), end ="");
print ("")
# Print set 2.
for i in range(0, len(set2)) :
print ("{} ".format(set2[i]), end ="");
print ("")
# Utility function to find the sets of the array which have equal sum.
def ... |
dbb45990d4e6de215b89576c01b3185f54e599ee | swynnejr/fundamentals | /file.py | 2,723 | 3.9375 | 4 | num1 = 42 #variable declaration: int
num2 = 2.3 #variable declaration: float
boolean = True #data type: boolean
string = 'Hello World' #data type: string
pizza_toppings = ['Pepperoni', 'Sausage', 'Jalepenos', 'Cheese', 'Olives'] #variable declaration: array
person = {'name': 'John', 'location': 'Salt Lake', 'age': 37, ... |
47b604da2af586551bdc0ffc9c5f69a44dec0019 | garyb6/Scooby-Python-Testing-Lab | /run_tests.py | 993 | 3.953125 | 4 | import unittest
from tests.friends_test import *
if __name__ == '__main__':
unittest.main()
def get_name (person5):
return person5 ["name"]
def get_favourite_tv_show (person2):
return person2["favourites"]["tv_show"]
#def person_likes_food__True(person2):
# fav_food = None
# for food in person2... |
5dd5ab21c08777371ebc70dda145c9facd24adec | dsinghl/mphy0021-2019-travel-planner-dsinghl | /travelplanner/route.py | 4,865 | 3.953125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import csv
class Route:
"""
Base class for a bus route.
Parameters:
route_filename : str
The file location of the route file.
A csv file is expected, each line with x_pos,y_pos,stop.
Each line must be one step... |
e76f6dbac41fb89ed44db450adf88f48bfde2874 | mkarawacki/DataDrivenAstronomy-USydney | /week 1 - image stacking/averaging_benchmark.py | 816 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 10 22:02:04 2017
@author: Mikołaj
"""
import numpy as np
import statistics
import time
def time_stat(func, size, ntrials):
# the time to generate the random array should not be included
timing=[]
# modify this function to time func with ntrials times using a ne... |
8f8c638ebb9feebf0e212849d3c657ced61f5ead | joiEspinoza/Bases-Python | /number.py | 669 | 4.03125 | 4 |
num1 = 10 #int
num2 = 10.6 #float
#---------------------------------------------------------------------
#---------------------------------------------------------------------
print( type( num1 ) )
print( type( num2 ) )
# indica el tipo de la variable
numUsu1 = input( "ingrese primer numero a sumar: " )
numUsu2 ... |
776e195dd39b751967f3426b36087b9616e5a788 | joiEspinoza/Bases-Python | /set.py | 558 | 3.890625 | 4 | colorsSet = { "red", "green", "blue" }
#tipo set no tiene indice
#---------------------------------------------------------------
#---------------------------------------------------------------
print( type( colorsSet ) )
# muestra el tipo de elemento
print( "red" in colorsSet )
# verifica si existe en set
colorsSe... |
6c1278d0fcadc4b3c8cfde312b136c0b1f15716f | Ajayyadav0299/PythonApplications | /random_text_genrator.py | 3,947 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 12:54:31 2018
@author: ajay yadav
"""
import random # for gentrating random things may be random letter or number
import string # for genrating the string
vowels ='aeiou' # for vowels
consonants = 'bcdfghjklmnpqrstvwxy' # for consonants
lette... |
fa205f98bc3b173e00dc2f2f2b8e77a9ee2e5e0d | ric-clemente/SAD-University-Work | /tpc1.py | 1,080 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 14:10:20 2018
@author: 30000794 Ricardo Clemente Informática de Gestão
"""
def Solution(S):
parenteses = 0
parenteses_recto = 0
chavetas=0
for i in range (len(S)):
if parenteses==-1 or chavetas==-1 or parenteses_recto==-... |
1ef2d91bd679348ff5f6c25e4b85adc361bdeb96 | yarishb/Grokking-Algorithms | /3. Recursions/elements_counter.py | 155 | 3.640625 | 4 | def elements_counter(arr):
if not arr:
return 0
else:
return 1 + elements_counter(arr[1:])
print(elements_counter([1,2,3,4,5]))
|
14898ad79dedd585c4b6c12c6dbbc0eb8ae4e7c9 | riakna/RoboticaMovelRemoteAPI-python | /t2/subsumption.py | 4,026 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 11:08:18 2018
@author: Anderson
Adaptado de https://github.com/alexander-svendsen/ev3-python/blob/master/behaviors/subsumption.py
"""
class Behavior(object):
"""
This is an abstract class. Should embody an specific behavior belonging to a robot. Each Behavio... |
c82d3175797451909d3fedc63ecf7177ea339931 | dojo-wes/python-algos | /algorithms/chapter1/biggie_size.py | 329 | 3.921875 | 4 | def biggie_size(arr):
for i in range(len(arr)):
if arr[i] > 0:
arr[i] = "big"
return arr
def biggie_size(arr):
i = 0
for val in arr:
if val > 0:
arr[i] = "big"
i += 1
return arr
def biggie_size(arr):
i = 0
while i < len(arr):
if arr[i] > 0:
arr[i] = "big"
i += 1
r... |
a3eb155607b389cf731d4c776e3a0595d3e913f3 | dojo-wes/python-algos | /algorithms/chapter1/max_min_avg.py | 606 | 4.3125 | 4 | # Given an array of numbers, print the max, min and average values for that array.
# loop through all numbers
# sum all of them
# avg = sum / number_of_items
# if the number I'm looking at < current min store new min
# if the number I'm looking at > current max store new max
my_list = [10, 5, 6, 7, 11, 15]
def max_min... |
1bca6cb0482fba85d0983bdef61efa5e27d383cc | dojo-wes/python-algos | /algorithms/chapter2/generate_coin_change.py | 996 | 3.828125 | 4 | # Change is inevitable(especially when breaking a twenty). Make generateCoinChange(cents) . Accept a number of American cents, compute and print how to represent that amount with smallest number of coins. Common American coins are pennies(1 cent), nickels(5 cents), dimes(10 cents), and quarters(25 cents).
# Third: add... |
3acc861f71bd56b410b0c8355744d53a54dd846e | Chiragitr/Learn_Python_The_Hard_Way | /ex4.py | 574 | 3.8125 | 4 | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars-drivers
cars_driven = drivers
carpool_capacity= cars_driven*space_in_a_car
average_passengers_per_car = passengers/cars_driven
print "There are", cars, "cars available."
print"there are only", drivers,"drivers available."
print"there ... |
9909e44be61111850121217c3dab8ff28eca5828 | felixseriksson/notebook | /powerset.py | 722 | 4.15625 | 4 | # def powerset(seq):
# """
# Returns all the subsets of this set. This is a generator. Handles lists, not sets.
# """
# if len(seq) <= 1:
# yield seq
# yield []
# else:
# for item in powerset(seq[1:]):
# yield [seq[0]]+item
# yield item
# if __name__ ... |
5c99c4fb4f82905e7bfd405ebf9b7f4cc6b158f1 | felixseriksson/notebook | /operatorprecedenceparsing.py | 3,168 | 3.765625 | 4 | def operand_check(element, output_queu):
if (element not in operator_dict.keys()) and (element not in parenthesis_dict.keys()):
output_queu.append(element)
def parenthesis_check(element, stack, output_queu):
if element == "(":
stack.append(element)
elif element == ")":
while stack[-... |
325f5571b54561ace73273bdb8d039c7935a2af2 | leonwetzel/LECCE | /lecce/feature/lexical.py | 3,900 | 3.515625 | 4 | #!/usr/bin/env python3
import math
import pickle
import nltk
from nltk.corpus import wordnet as wn
class Meaning:
"""
Contains functionality related to NLTK.
"""
ADJ, ADJ_SAT, ADV, NOUN, VERB = "a", "s", "r", "n", "v"
@staticmethod
def count_wordnet_senses(word, pos_tag=None):
"""Cou... |
72848f7b7d7ff324a80c770764be38bb4e484daf | rferrucci/rosalind | /RevComplement.py | 537 | 3.59375 | 4 | #!/usr/bin/env python
from rosalind import *
#!/usr/bin/env python
from rosalind import *
"""Solution to the Complementing a Strand of DNA problem in the Bioinformatics Stronghold section of Rosalind
location: http://rosalind.info/problems/revc/
Problem: return the reverse complement of a dna sequence
"""
# return t... |
1216d9d07aa57eeeca4415e057ade1acf30ed1e5 | LiliGuimaraes/100-days-of-code | /logical-exercises/URI-JUDGE/STRINGS/ComparacaoSubstrings.py | 545 | 3.890625 | 4 | first_string = str(raw_input('Digite a primeira palavra: ')).lower()
print(first_string)
second_string = str(raw_input('Digite a segunda palavra: ')).lower()
print(second_string)
first_list = []
second_list = []
for f in first_list:
first_list.append(f)
print first_list
for s in second_list:
second_list.app... |
16e199e676b819d66caba4300fe6695bdc558815 | LiliGuimaraes/100-days-of-code | /logical-exercises/Logica-Geral/gastos_telefone.py | 420 | 3.796875 | 4 | minutos = float(input("Quantos minutos foi a sua ligação? \n"))
valor_final = float(input("Qual o valor cobrado por esta ligação? \n"))
tarifa_normal = minutos / valor_final
tarifa_reduzida = tarifa_normal / 2
print("Desta forma, a tarifa de base usada para calcular o valor final foi de R${:.2f}".format(tarifa_normal... |
058d7ae50c9215a13f93f62e0e2d14b6946f40f7 | LiliGuimaraes/100-days-of-code | /CURSO-EM-VIDEO-PYTHON3/REPETICOES/WHILE/guanabara_exerc_58.py | 637 | 3.890625 | 4 | from random import randint
print("*" * 10)
print("JOGO DO ADIVINHA")
print("*" * 10)
print("\n")
num_random = randint(0, 10)
acertou = False
count = 0
while not acertou:
jogador = int(input("Digite uma aposta: \n"))
count += 1
if num_random == jogador:
acertou = True
else:
if jogador ... |
9259484c4a123f84cba4e5d5763be9bff761b259 | LiliGuimaraes/100-days-of-code | /logical-exercises/URI-JUDGE/STRINGS/LED.py | 2,571 | 3.8125 | 4 | def LED(number_repeat, teste_one, teste_two, teste_three):
res_teste_one = list(map(int, str(teste_one)))
sum = 0
for item_one in res_teste_one:
if((item_one == 1)):
sum += 2
elif((item_one == 2)):
sum += 5
elif(item_one == 3):
sum += 5
eli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.