blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
92d59ab6a0189cc0af217ad8fd8f9aff366c49a4
kiwisquash/100daysofcode-with-python-course
/days/19-21-itertools/myCode/myTrafficLights.py
556
3.546875
4
import time import itertools import random lights = 'green yellow red'.split() def delayTime(lightIndex): if lightIndex == 1: return 1 else: return 1 + random.random()*3 def turnOnLights(lights): light_gen = itertools.cycle(lights) for color in light_gen: print(color,end="\r")...
d34a518ed0c89d5b26067bbb8559166f24beedb8
DaniiarR/Tic-Tac-Toe-game
/main.py
593
3.546875
4
from tkinter import * import os root = Tk() def oneVone(): #exec('xo2buttonbind') root.destroy() os.system('python xo2buttonbind.py') def computer(): #exec('tictactoe') root.destroy() os.system('python tictactoe.py') #tictactoe.GUI().mainloop() label = Label(root, text="Hello! Select ...
e2ef69091041781e4bacdb9418fc0fd796fed133
ivankonatar/SP-Midterm-Exam
/Task4.py
356
3.671875
4
def insert(): x = [1, 2, 4, 5, 6, 7, 8] y = [] n=input("Unesite n: ") br=0 for i in range (len(x)-1): if int(n)>=x[i] and int(n)<x[i+1]: y.append(x[i]) y.append(int(n)) br+=1 else: y.append(x[i]) br+=1 print("slozenost:...
6111440d20b02769cb20562ba9edf600c2356ab1
pyq111/Rikao
/Zhoukao1/demo3.py
109
3.5
4
import random list1=[] for i in range(20): a=int(random.randrange(0,9)) list1.append(a) print(list1)
0e456292074c7a62b54f2bdfb6d240c1d736af66
amykwon1209/python
/classpractice.py
743
3.640625
4
'''i = 0 while i < 11: print(i) i += 1''' '''place = "New York" place_list = ["I went to", "I want to", "I flew to", "My parents want to go to"] while len(place_list) > 0: print(place_list[0] + " " + place) place_list.remove(place_list[0])''' '''value = input("Place a number!") value =...
82f7b86090189aa406c0e2e9751c454b86cef7aa
Riebart/advent-of-code
/2020/08/a.py
695
3.53125
4
#!/usr/bin/env python3 import sys program = [line.strip() for line in sys.stdin.readlines()] runs = [0 for _ in range(len(program))] acc = 0 loop = True instruction = 0 while runs[instruction] <= 1: i = program[instruction] try: arg = int(i.split(" ")[1]) except: arg = None if i.sta...
f260b43ee322c8475e8388cf197472fd9e267203
sarureddi/unwantedspace
/play28.py
89
3.890625
4
def remove(string): return string.replace(" ","") word=input() print(remove(word))
d8855efc34c2296b6250a9cbe7e7f6e5c0e9843e
kevinelong/tdd-game
/board.py
1,755
3.671875
4
import random from position import Position class Board: def __init__(self, width=9, height=9): self._grid = [] self._width = width self._height = height self._content = [] for y in range(self._height): line = [] for x in range(self._width): ...
4879cc84005af321f00c305271d26325fec9a5ae
MetalSkink/Curso-Python
/Bucles/Ejercicios/Ejercicio9.py
420
4.15625
4
''' Bucles - Ejercicio 9: Hacer un programa donde el usuario ingrese una frase, se le devolverá la misma frase pero sin espacios en blanco y además un contador de cuántos caracteres tiene la frase (sin contar los espacios en blanco). ''' frase = input("Inserte una frase -> ") contador=0 for i in frase: if i != ...
e58f8b17ef04918e96682081b4b0a3e28446a43e
MetalSkink/Curso-Python
/Programa1.py
287
3.9375
4
#Opercdores aritmeticos ''' a = 10 b = 15 c = 20 resultado = ((a<b) and (b<c)) ''' #Salida de datos ''' nombre = "Xavier" edad = 23 print("Hola {} tienes {} años".format(nombre,edad)) print(f"Hola {nombre} tienes {edad} años") ''' #Entrada de datos ''' print(f"Hola {nombre}") '''
f35047451ec3a1f26b7134e0333f1af60da68f70
MetalSkink/Curso-Python
/Colecciones/Conjuntos.py
796
3.859375
4
# Conjuntos conjunto = set() conjunto = {1,2,3,4,5, "Hola", 4.56} conjunto.add(89) conjunto.discard(3) print(3 in conjunto) print(3 not in conjunto) print(conjunto) conjunto.clear() print(conjunto) a = {1,2,3} b = {3,4,5} z = frozenset({1,2,3,4,5}) #Hacer un conjunto inmutable para que no se pueda modificar prin...
729b9e54fe00daae5ccfa67be68a2d4913c97b2e
MetalSkink/Curso-Python
/Funciones/Ejercicios/Ejercicio3.py
2,170
3.96875
4
# Funciones - Ejercicio 3: # Crear un programa que tenga una lista de clientes, cada cliente tiene su Nombre, # Apellido y DNI. El programa tendrá el siguiente menú de opciones: # 1. Agregar nuevo cliente # 2. Mostrar todos los clientes # 3. Mostrar cliente por DNI # 4. Eliminar cliente # 5. Salir # PD: Cada opción ...
be177dea905f9ea23b835f3a3039473f822b0900
MetalSkink/Curso-Python
/Ejercicio1.py
199
3.921875
4
#Ejercicio 1 a = float(input("Ingrese el valor a: ")) b = float(input("Ingrese el valor b: ")) c = float(input("Ingrese el valor c: ")) resultado = (a**3 * (b**2 - 2*a*c)) / (2*b) print(resultado)
1e3d446c41600a291eccfed2f9b58364ec3019da
MetalSkink/Curso-Python
/Condicionales/Ejercicio2.py
693
4.25
4
''' Ejercicio2 : Hacer un programa que pida 3 numeros y determina cual es mayor ''' a = float(input("a -> ")) b = float(input("b -> ")) c = float(input("c -> ")) if a == b and b == c: print("Los 3 numeros son iguales") if a == b and b > c: print("Los primeros 2 numero son mayores e iguales") if b == c and b >...
0580654944069eae646fa4bdf4aad483dbba0437
MetalSkink/Curso-Python
/Bucles/BucleWhile.py
319
3.953125
4
# Bucle while import math numero = int(input("Digite un numero -> ")) while numero<0: print("ERROR: Ingrese un numero positivo") numero = int(input("Digite un numero -> ")) print(f"\nSu raiz cuadrada es {(math.sqrt(numero)):.2f}") i = 0 while i < 10: print(f"Hola mundo por vez numero {i}") i += 1
bbc7be2ae4b106540b74b00240b662cb9f08d1da
alirezaghey/algs-ds
/algs_ds/datastructures/queue/queue.py
2,824
3.8125
4
from __future__ import annotations from typing import Any # A Queue implementation using a custom doubly linked list # # # Author: Alireza Ghey # A private Node implementation for the doubly linked list class _Node: def __init__(self, data: Any, prevNode: _Node=None, nextNode: _Node=None): self._data: A...
0edf60bec44709de1b453b9861115573bd2f9c8c
fandw06/pibot-python
/arm.py
2,242
3.65625
4
from math import cos, sin, atan, sqrt, pi class Arm: L = 8.10 def __init__(self, bottom, right, left, claw): self.bottom = bottom self.right = right self.left = left self.claw = claw def set_angle(self, a1, a2, a3): self.bottom.set_angle(a1) ...
58b3749b681926f45dac0c76db47c85cc66cb9d7
Prim07/01pite
/matrix.py
685
3.828125
4
class Matrix: def __init__(self, x1, x2, y1, y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 def add(self, givenMatrix): return Matrix(self.x1 + givenMatrix.x1, self.x2 + givenMatrix.x2, self.y1 + givenMatrix.y1, self.y2 + givenMatrix.y2) def multiply(self, givenMatrix): ...
b7dc0f86fc22eacb5335b58d5599bd9751c3171f
swetadocker12/Game
/test.py
68
3.59375
4
var = input("Enter your name!") list1 = ["Hello", var] print(list1)
411dd8c5b001259b8e22270260be8049dc9255e2
Maryville-SWDV-630/ip-2-kylekanderson
/CheckingApp.py
2,169
4.0625
4
# SWDV-630: Object-Oriented Coding # Kyle Anderson # Week 2 Assignment ################################## # Driver Application ################################## from CheckingAccount import CheckingAccount # customer variables customerName = 'Kyle Anderson' customerAddress = '123 Main Street' accountNumber = 123456 i...
a561a577c695ade2931837567aaa198030454dbd
KarmicDemon/Neural-Network-on-Bike-Sharing-Data
/network.py
5,462
3.90625
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys # Neural Network with one hidden layer # 1st activation function as sigmoid # 2nd activation function as f(x) => x class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): self....
bb42362cafea615326221aaf185a1c7b7e4bad39
ChVimal/tic_tac_toe
/play.py
924
3.828125
4
#!/usr/bin/env python3 import tictactoe import sys def menu(): while True: print("\n1. start\n2. exit") what_user_want = input("Enter your choice: ") if what_user_want not in ("start", "exit", "1", "2"): print("Bad parameters!") continue if what_user_want in...
577e03524b3eeff330796c5081dd6167337d0146
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex048.py
748
3.9375
4
# Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500 #declara a variável que receberá o acumulador da soma dos ímpares múltiplos de 3 soma = 0 #declara a variável que receberá o contador dos ímpares múltiplos de 3 cont = 0 # o comando for...
1933a1ac368a8ebe93d82b89916d09746ad4785d
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex033.py
594
3.890625
4
# encontrando maior e menor valor dentre três números print('Vamos encontrar o maior e o menor valor entre três números.') n1 = int(input('Primeiro número: ')) n2 = int(input('Segundo número: ')) n3 = int(input('Terceiro número: ')) menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n2 and n3 < n1: menor = n3 p...
87a8bc9e32913b8fd8b75cd195247e4ea15c4758
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex046.py
313
3.84375
4
# faça um programa que mostre na tela uma contagem regressiva para fogos de artifício, # indo de 10 até 0, com um pausa de 1 segundo entre eles from time import sleep print("CONTAGEM REGRESSIVA!!") for segundo in range(10, 0, -1): print(segundo) sleep(1) print("{:=^30}".format("FELIZ ANO NOVO!!"))
50628d5f9fd53fd5e88f35bec1dbd3245555c9dd
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex035.py
382
4.09375
4
# condição de construção de um triângulo print('Analisando o triângulo') print('='*24) a = float(input('Primeiro segmento: ')) b = float(input('Segundo segmento: ')) c = float(input('Terceiro segmento: ')) if a < b + c and b < a + c and c < a + b: print('Os segmentos acima PODEM formar um triângulo.') else: print...
56d97d531aeb6b59eb81eb8b32c56d2b482cedec
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex019.py
255
3.703125
4
#sorteando um aluno from random import sample a1 = input('aluno 1: ') a2 = input('aluno 2: ') a3 = input('aluno 3: ') a4 = input('aluno 4: ') alunos = sample([a1,a2,a3,a4],k = 4) print('\nO aluno escolhido para apagar a lousa hoje é: {}'.format(alunos))
49effb7364bda9b3a4cbfaf2cfa2cfe39032d904
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex008.py
174
3.921875
4
#conversor de medidas m = float(input('Insira a medida em metros:')) cm = m*100 mm = m*1000 print('{} metros equivalem a {} centímetros, ou {} milímetros.'.format(m,cm,mm))
2acd41e05593c832a34229d42e8d79d12d12db07
fascarii/Projetos-Python
/Curso em vídeo - Python/Exercícios/cev_ex033(1).py
269
3.921875
4
# maior e menor valor entre três números print('Descubra o maior e o menor valor dentre os três números.') n1 = int(input('Primeiro número: ')) n2 = int(input('Segundo número: ')) n3 = int(input('Terceiro número: ')) if n1 > n2 > n3: print(n1 ,'é maior')
eec765c92bb7f04dcbf4556c44b6aee6df524240
peterckeim/tournamentDatabase
/tournament.py
10,423
3.765625
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 def execute_query(query, variables=(), fetch=False, commit=False): """Provides an easy way to connect to the PostgreSQL database, and execute a query based on a supplied args: query - the PostgreSQL query whic...
7b6cea53864552f9549a1e0346cb0166de8f582b
jiwon73/lecture_2
/root_func.py
346
3.796875
4
def get_root(a,b,c): r1 = (-b +(b**2-4*a*c)**(1/2))/(2*a) r2= (-b -(b**2-4*a*c)**(1/2))/(2*a) return r1, r2 #return [r1,r2] 이면 대가로로 리턴 root= get_root(1,5,6) print(root) #여러개 값을 리터할 때 (-2,-3)으로 리턴, 소가로가 디폴트 #root1, root2=get_root(1,5,6) #print('해는 ',root1,' 또는 ',root2)
4d004e2972fab96030cebf5963682e846f0c9585
davidhuangal/cifar10-cnn
/c10cnn.py
2,002
3.53125
4
import keras from keras.datasets import cifar10 from keras.models import Sequential from keras.layers import Conv2D, MaxPool2D, Activation from keras.layers import Dense, Dropout, Flatten ### DATA SETUP (X_train, y_train), (X_test, y_test) = cifar10.load_data() X_train = X_train.astype('float32') X_test = X_test.as...
88ff4eed8723d9968517dfb581b6feba04a6d1f9
Pruemebr/RobotTeamProject
/projects/zhangz14/final_project_pc.py
4,062
3.984375
4
# This project is meant to prevent the robot from knocking into obstacles in the front. When the distance from the robot # to the obstacle is less than 50 cm, the LEDs will be yellow. When the distance is less than 20 cm, the LEDs will be # red and the robot cannot move forward. The user can get the distance by clickin...
0cbb1fbbfac2c26c8bba84d4ae8ca5a74ec76b98
ioana01/Marketplace
/tema/consumer.py
2,311
4.28125
4
""" This module represents the Consumer. Computer Systems Architecture Course Assignment 1 March 2021 """ from threading import Thread import time class Consumer(Thread): """ Class that represents a consumer. """ def __init__(self, carts, marketplace, retry_wait_time, **kwargs): """ ...
1f0964cfd05cca15992159e92c8011d5ced30c8f
anshiquanshu66/conll2019-snopes-experiments
/src/rte_pac/utils/dataset.py
1,187
3.640625
4
from csv import DictReader class DataSet: """ Define class for Fake News Challenge data """ def __init__(self, file_stances, file_bodies): # Load data self.instances = self.read(file_stances) bodies = self.read(file_bodies) self.heads = {} self.bodies = {} ...
4ff3e99a408d896b4260680980b204794cae01f4
dnaport22/pyex
/Functions/averageheight.py
1,081
4.15625
4
#~PythonVersion 3.3 #Author: Navdeep Dhuti #StudentNumber: 3433216 #Code below generate answer for question:: #What is the average value of the numbers in the field [height] in the range(1.75)and(2.48)inclusive? #Function starts def Average_height(doc_in): doc = open(doc_in+'.csv','r') #Open the input file came ...
ad2fa3e7005722972e5cc8ea9331204a262aaa7a
dnaport22/pyex
/oop/averageheight.py
1,024
3.9375
4
#~PythonVersion 3.3 #Author: Navdeep Dhuti #StudentNumber: 3433216 #Code below generate answer for question:: #What is the average value of the numbers in the field [height] in the range(1.75)and(2.48)inclusive? #Defining class class averageHeight: #Defining constructor def __init__(self, doc): self.f...
75c116338c42a6df55b5f0cabd9c9965ab5ae1eb
dnaport22/pyex
/Functions/numofsells.py
718
3.5625
4
#~PythonVersion 3.3 #Author: Navdeep Dhuti #StudentNumber: 3433216 #Code below generate answer for question:: #Count the number of (sell's) in the field [action] #Function starts def NumofSells(doc_in): #Open the input file came from 'infile' doc = open(doc_in+'.csv','r') #initialising variables sel...
6e99dde5916f3d934deb3889997dfe48340e928b
bendmorris/adelaide_swc
/testing_lessons/error_handling/dnaContent.py
2,495
3.859375
4
#define an exception class for non-existing base pairs class UnknownBaseException(Exception): pass #implement our list of tests test = [ #input #expected_output ['gtcagtc', {'G':2, 'T':2, 'C':2, 'A':1}], #function should always return nucleotide content using uppercase letters for the dictionary keys....
d5c74b6ac2ea719d3c243eb36b72808651ad6d2e
fcdmoraes/Aulas-SanFrancis
/sf_aula8.py
881
3.8125
4
##lista = [1,3,7,4,3,7,8] ## ##print(lista[0]) ##print(len(lista)) ## ##lista.append(0) ##print(lista) ## ##lista.insert(1,2) ##print(lista) ## ####lista.remove(3) ####print(lista) ## ##while 3 in lista: ## lista.remove(3) ## ##print(lista) ## ##x=lista.pop(2) ##print(lista) ##print(x) baralho = [] carta = 1 while...
e5975080f724697fefaaec1a53c334a42567f161
erickchaosz/shpy
/examples/4/sequence1.py
230
3.9375
4
#!/usr/bin/python2.7 -u import sys # print a contiguous integer sequence start = sys.argv[1] finish = sys.argv[2] number = start while int(number) <= int(finish): print number number = int(number) + 1 # increment number
a9fb3bc90fe2ce347f1ca6ea02239760e35963e6
PhaniMandava7/Python
/Practice/Sets.py
591
4.40625
4
# Sets are collection of distinct elements with no ordering. # Sets are good at membership testing. # empty_set = {} -------> this creates a dict. empty_set = set() courses_set = {'History', 'Physics', 'Math'} print(courses_set) courses_set.add('Math') print(courses_set) print('Math' in courses_set) courses_set =...
a723af9a1faae81b098e9b79025f031a0f8b2038
PhaniMandava7/Python
/FirstPythonProj/GetInputFromKeyboard.py
337
4.21875
4
greeting = "Hello" # name = input("Please enter your name") # print(greeting + ' ' + name) # names = name.split(" ") # for i in names: # print(i) print("This is just a \"string 'to test' \"multiple quotes") print("""This is just a "string 'to test' "multiple quotes""") print('''This is just a "string 'to test' mu...
bb09754c9389ada3c148205145a45e0cbda0936b
PhaniMandava7/Python
/Practice/TextWrap.py
1,311
4.0625
4
# textwrap module has 2 functions wrap() and fill() to wrap the texts. # textwrap.wrap(text[,width]) -------> wraps the single paragraph in text so every line is at most widh characters long. # wrap function returns a list of output lines, without final newlines. # textwrap.fill(text[,width]) -------> wraps the...
dfd0dd8055a658fc8152e79bb2247671302a94a0
hsd01/Python-DataBase
/Writing_sensors_data_to_database.py
1,387
3.78125
4
"""######################################################### Make sure to import GPIO of RPi and set it as u want: and make sure u run create_table() function only once conn = sqlite3.connect('c:/Users/Taka/Desktop/Sensor_1.db')=> c:/Users/Taka/Desktop/Sensor_1.db is the path for RPi path can be any...
5fdf5f42e378769caf8e2a3178129efb696b195b
sundoz/Norm-
/uravnenie.py
1,807
3.6875
4
#%% # 3.1 там уравнение def f(x): if x<=-2: b=1-(x+2)**2 elif -2<x<=2: b=-x/2 else: b=(x-2)**2+1 print(b) #%% f(5) #%% #удаляет из него все нечётные значения, а чётные нацело делит на два def modify_list(l): while i<len(l): if ...
6a835dc338b0ad1b8543c860fb3e9771d0907c30
sundoz/Norm-
/proverkaorfografii.py
232
3.5625
4
d={} d1={} n=int(input()) for i in range(n): d[input().lower()]='' m=int(input()) for i in range(m): a=input().split() for j in a: if str(j).lower() not in d: d1[j]='' for i in d1.keys(): print(i)
390beafa7c88a24c513e7aacdcbf2de1928a273d
DamianS6/learntris
/learntris.py
1,151
3.796875
4
#!/usr/bin/env python import sys from commands import Tetris tetris = Tetris() def choose_option(option): if option == 'q': sys.exit() elif option in ('p', 'P'): tetris.prepare_matrix(option) elif option == 'g': tetris.set_matrix() elif option == 'c': tetris.clear_matrix() elif option == '?s': tetri...
6c7d41a18476a461fbceec79924b253d39f9f311
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-12_version1.py
2,415
4.28125
4
''' Exercise 10.12. Two words “interlock” if taking alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled”. Solution: http://thinkpython2.com/code/interlock.py 1. Write a program that finds all pairs of words that interlock. Hint: don’t enumerate all pairs! 2...
6d32a9a8f1ef0df40373ce745a4fa69113000d71
paalso/learning_with_python
/ADDENDUM. Think Python/13 Case study - data structure/13-8.py
4,870
4.4375
4
''' Exercise 13.8. Markov analysis: 1. Write a program to read a text from a file and perform Markov analysis. The result should be a dictionary that maps from prefixes to a collection of possible suffixes. The collection might be a list, tuple, or dictionary; it is up to you to make an appropriate choice. You can...
79ad171494220bdae3c97318e7fbb096fab65a1b
paalso/learning_with_python
/18 Recursion/print_files.py
658
3.796875
4
import os def get_dirlist(path): """ Return a sorted list of all entries in path. This returns just the names, not the full path to the names. """ return sorted(map(str, os.listdir(path))) def print_files(path, prefix = ""): """ Print recursive listing of contents of path """ ...
4a3b021521f82d44da0c95bc95f9aea1650092aa
paalso/learning_with_python
/23 Inheritance/CardGame.py
2,825
3.90625
4
import Deck, Hand, Card class CardGame: deck = Deck.Deck() deck.shuffle() class OldMaidHand(Hand.Hand): def remove_matches(self): counter = 0 hand_copy = self.cards[:] for card in hand_copy: matching_card = Card.Card(3 - card.suit, card.rank) ...
9976b38449ce9d889aef71e75abd1d436ef9d10e
paalso/learning_with_python
/10 Event-Driven Programming/10-1.py
3,366
4.125
4
## Chapter 10. Event-Driven Programming ## http://openbookproject.net/thinkcs/python/english3e/events.html ## Exercise 1 ## =========== # Add some new key bindings to the first sample program: # Pressing keys R, G or B should change tess’ color to Red, Green or Blue. # Pressing keys + or - should increase or de...
b5b4d56978de1eafaa0b103497be6dd17fadbdea
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-6.py
866
4.09375
4
''' Exercise 10.6. Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams ''' import random def is_anagram(text1, text2): ## return sorted(text1) == sorted(text2) L1 = list(...
1a63f54074f8a96a4a3585950a253a25d068a0d0
paalso/learning_with_python
/18 Recursion/18-7.py
976
4.15625
4
# Chapter 18. Recursion # http://openbookproject.net/thinkcs/python/english3e/recursion.html # Exercise 7 # =========== # Write a function flatten that returns a simple list containing all the values # in a nested list from testtools import test def flatten(nxs): """ Returns a simple list cont...
4a1cace9cf0a17eaafe1b0127d6170b6ca0dacd1
paalso/learning_with_python
/14 List Algorithms/functions_tests.py
587
3.671875
4
from testtools import test def remove_adjacent_dups(xs): """ Return a new list in which all adjacent duplicates from xs have been removed. """ if len(xs) == 0: return [] adjacented = [xs[0]] for el in xs: if adjacented[-1] != el: adjacented.append(el...
4e13a17fdcaa1022e51da4c4bb808571a02d6177
paalso/learning_with_python
/26 Queues/ImprovedQueue.py
2,311
4.1875
4
# Chapter 26. Queues # http://openbookproject.net/thinkcs/python/english3e/queues.html class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) class ImprovedQueue: def __init__(self): ...
342399d86a2922e5ce6ef218a76fc1ed2a6cdc22
paalso/learning_with_python
/06 Fruitful functions/6-17.py
927
4.09375
4
## Chapter 6. Fruitful functions ## http://openbookproject.net/thinkcs/python/english3e/fruitful_functions.html ## Exercise 17 ## =========== ## Write a function is_multiple(f, n) to satisfy these unit tests:.. import sys import math def test(did_pass): """ Print the result of a test. """ ...
ec0915fa2463fb1da2bb9ad4a5b55793d40fac93
paalso/learning_with_python
/09 Tuples/9-01_1.py
1,138
4.5
4
## Chapter 9. Tuples ## http://openbookproject.net/thinkcs/python/english3e/tuples.html ## Exercise 1 ## =========== # We’ve said nothing in this chapter about whether you can pass tuples as # arguments to a function. Construct a small Python example to test whether this # is possible, and write up your finding...
e66ceb92103c0c595bbaa0f6bc829e2208b34dba
paalso/learning_with_python
/18 Recursion/18-11/litter.py
1,729
4.21875
4
# Chapter 18. Recursion # http://openbookproject.net/thinkcs/python/english3e/recursion.html # Exercise 11 # ============ # Write a program named litter.py that creates an empty file named trash.txt in # each subdirectory of a directory tree given the root of the tree as an argument # (or the current directory...
6fa2efdc32d371e5f23a733a19b342dd8a2f76cc
paalso/learning_with_python
/05 Conditionals/5-12.py
629
3.71875
4
##5. Conditionals ##http://openbookproject.net/thinkcs/python/english3e/conditionals.html # 12. Extend the above program so that the sides can be given to the function in any order. def find_hypot (a, b): return (a * a + b * b) ** 0.5 def is_rightangled(a, b, c): eps = 0.000001 return abs(c -...
9ef73be5b8fdf09a171cff7e27c68773fda9963e
paalso/learning_with_python
/06 Fruitful functions/6-9.py
1,849
4.21875
4
##Chapter 6. Fruitful functions ##http://openbookproject.net/thinkcs/python/english3e/fruitful_functions.html ## Exercise 9 ## =========== ##Write three functions that are the “inverses” of to_secs: ##hours_in returns the whole integer number of hours represented ##by a total number of seconds. ##minutes_i...
f59eb2e8ecb041647137d4a66cb100353ad366f7
paalso/learning_with_python
/ADDENDUM. Think Python/13 Case study - data structure/13-2_3_net.py
3,503
4.15625
4
''' Exercise 13.2. Go to Project Gutenberg (http: // gutenberg. org ) and download your favorite out-of-copyright book in plain text format. Modify your program from the previous exercise to read the book you downloaded, skip over the header information at the beginning of the file, and process the rest of the wor...
1ada77a6b13c07c35793d86d7dd8671356910c09
paalso/learning_with_python
/ADDENDUM. Think Python/09 Case study - word play/9-6.py
1,370
4.15625
4
''' Exercise 9.6. Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there? ''' def is_abecedarian(word): """ Returns True if the letters in a word appear in alphabetical order (doub...
eca678dc8091cdc00b987c2733c163a32996e0dc
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-5.py
510
4.09375
4
''' Exercise 10.5. Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. ''' def is_sorted(L): for i in range(1, len(L)): if L[i] < L[i - 1]: return False return True t1 = [] t2 = [1]...
87948f279e5becb72db7deef006590720ddbeaba
paalso/learning_with_python
/08 Strings/8-6.py
1,569
4.4375
4
## Chapter 8. Strings ## http://openbookproject.net/thinkcs/python/english3e/strings.html ## Exercise 6 ## =========== # Print a neat looking multiplication table like this: # 1 2 3 4 5 6 7 8 9 10 11 12 # :-------------------------------------------------- # 1: 1 2 3 4 ...
32ec6ec6910b4cb9806e82cfdd8eb22e902c8827
paalso/learning_with_python
/04 Functions/4_4_ver0_0.py
1,339
4.28125
4
##4. http://openbookproject.net/thinkcs/python/english3e/functions.html ##4. Draw this pretty pattern: import turtle import math def make_window(colr, ttle): """ Set up the window with the given background color and title. Returns the new window. """ w = turtle.Screen() w.bgc...
c9b466df940ce854e8b362a48c71ab720025b83b
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-9.py
2,446
4.125
4
''' Exercise 10.9. Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why? ''' def load_words(dict_filename): """ Return...
3638b74fdff0456af03fd38137c7eceae3ddacb1
paalso/learning_with_python
/ADDENDUM. Think Python/13 Case study - data structure/13-6.py
1,209
4.21875
4
''' Exercise 13.5. Write a function named choose_from_hist that takes a histogram as defined in Section 11.2 and returns a random value from the histogram, chosen with probability in proportion to frequency. For example, for this histogram: >>> t = ['a', 'a', 'b'] >>> hist = histogram(t) # {'a': 2, 'b': 1} your ...
7783505fb7040ceefdd5794f88507f573b4d6bcf
paalso/learning_with_python
/07 Iterations/7-1.py
923
4.28125
4
## Chapter 7. Iteration ## http://openbookproject.net/thinkcs/python/english3e/iteration.html ## Exercise 1 ## =========== ## Write a function to count how many odd numbers are in a list. import sys def count_odds(lst): counter = 0 for n in lst: if n % 2 == 1: counter +...
e0dbd51a977024665d2211a0f4f82f3a7d5ce224
paalso/learning_with_python
/24 Linked lists/linked_list.py
1,471
4.21875
4
# Chapter 24. Linked lists # http://openbookproject.net/thinkcs/python/english3e/linked_lists.html class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) def print_backward(self): ...
19fa8778651981f1c2870f7435f4745fee1db1c1
rhodriguerrier/shadow_casting_2d
/rays.py
1,276
3.515625
4
import math from intersection import Intersection class Rays: def __init__(self, rads, current_x, current_y): self.rads = rads self.x2 = current_x + (1000 * math.cos(self.rads)) self.y2 = current_y + (1000 * math.sin(self.rads)) self.ray_end = { "x": se...
3c2673e9f0dc83a0209d0f877e27153f5abe548a
ys012313/p2_201611105
/w10Main_2.py
632
3.71875
4
def Grade(): score = [ ["English", 100], ["Math", 200], ["English", 200], ["Math", 200], ["English", 100], ["Math", 300] ] EnScore = 0 MaScore = 0 for i in range(0,len(score)): if score[i][0]=="English": EnScore=EnScore+score[i][1] for i...
05eab2bad5f3c3f63e21afcc0a2ea3fd80d1bc07
ys012313/p2_201611105
/w13Main_2.py
753
3.703125
4
import os import turtle wn=turtle.Screen() t1=turtle.Turtle() aFile=input("Filename") def getCoordsFromFile(aFile): fin=open(aFile,'r') coords=[] for line in fin: line1=line.split(',') aRect=[(line1[0],line1[1]),(line1[2],line1[3].strip())] coords.append(aRect) ...
805c87a5693ca777aaa5c67f47423527663238d8
Suraj-16/Python-Practice-Programs
/swapList.py
193
3.9375
4
list1 = [1,2,3,4,5,6] def swapList(list1): size = len(list1) temp = list1[0] list1[0] = list1[size - 1] list1[size - 1] = temp return list1 print(swapList(list1))
f8e64ca982a5154a5705944ac5e3bf4e074f9bda
NIRVANALAN/python_ex_01_sse_2018.4
/06.py
1,035
3.703125
4
"""已知一个椭圆的长轴长为10,短轴长为8,请设计算法求这个椭圆的面积,并编程实现。 要求1:利用特卡罗算法进行模拟。 要求2:分别打印在不同点数(至少设置4个不同的点数)情况下面积的近似值。 """ # 6 # phase 1 import random import time iter_num = 10000 def Monte_Calo_oval(iter_n): a = 5 b = 4 count = 0 for i in range(iter_n): x_rand = random.random()*a y_rand = random.random()*...
eda7099a42557b130debb533e86b9b30ec9f29ff
rakib05r/Python
/Clock.py
399
3.734375
4
from tkinter import * import time root = Tk() time1 = '' clock = Label(root, font=('times', 100, 'bold','italic'), bg='black', fg='green') clock.pack(fill='both', expand=1) root.title('Digital Clock') def tick(): global time1 time2 = time.strftime('%H:%M:%S') if time2 != time1: time1 = time2 ...
39652f5777aeeea092ad64a05e8e9a1ecd451a8b
rakib05r/Python
/Prime.py
165
4.03125
4
a=2 num=int(input("Enter a number")) while num > a : if num%a==0 & a!=num: print('not prime') a=a+1 else: print('prime') a=(num)+1 input("Exit")
31f1e8216aa472453c913963df6f2025c77b0698
HJTGit/git
/Python学习/对list进行切片.py
421
4
4
#range()函数可以创建一个数列: #>>> range(1, 101) #[1, 2, 3, ..., 100] #请利用切片,取出: #1. 前10个数; #2. 3的倍数; #3. 不大于50的5的倍数。 #要取出3, 6, 9可以用::3的操作,但是要确定起始索引。 L = [] for x in range(1, 101): L.append(x) print (L) print ('前10个数:', L[0:10]) print ('3的倍数:', L[2::3]) print ('不大于50的5的倍数。', L[4:50:5])
8c140d19783f218b49a0902f27fb01b828f4972e
HJTGit/git
/Python学习/dict的特点.py
223
3.734375
4
d = { '123': [1, 2, 3], # key 是 str,value是list 123: '123', # key 是 int,value 是 str ('a', 'b'): True # key 是 tuple,并且tuple的每个元素都是不可变对象,value是 boolean } print (d)
347eef69f5c2d28dba7b475960a8903ed693a0a6
HJTGit/git
/Python学习/迭代dict的key和value.py
301
3.890625
4
#请根据dict: #d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 } #打印出 name : score,最后再打印出平均分 average : score。 d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74} sum = 0 for k, v in d.items(): sum = sum + v print (k, ':', v) print ('average:', sum / len(d))
4526d7747be829fa9609129d9cd22dc6c25def38
HJTGit/git
/Python学习/对字符串切片.py
453
4.03125
4
#字符串有个方法 upper() 可以把字符变成大写字母: #>>> 'abc'.upper() #'ABC' #但它会把所有字母都变成大写。请设计一个函数,它接受一个字符串,然后返回一个仅首字母变成大写的字符串。 #提示:利用切片操作简化字符串操作。 def firstCharUpper(s): return s[0].upper()+s[1:] print (firstCharUpper('hello')) print (firstCharUpper('sunday')) print (firstCharUpper('september'))
ba71c757ede9b4a0f6c9876bf772a9a150ca9a80
Espherax/Random-Univesity-stuff-2
/Calculculadora simple.py
1,087
4.0625
4
def Menu(): """Menu function""" print ("""************ Calculator ************ Menu 1) Addition 2) Substraction 3) Multiplication 4) Division 5) Exit""") def Calculator(): """Mathematic operations""" Menu() opc = int(input("Select an option\n")) while (opc >0 and opc <5): ...
af380bf7377bec6c0406d8a5ab9ec2e48c02aa0d
alon211/LearnPython
/Full Course for Beginners/WorkingWithString.py
331
4.25
4
# 最原始的 print("I am John") # 换行符号 print("I am \n John") # 转义符号 print("I am \"John") # 字符串变量 MyStr = "I am John" print(MyStr) # 字符串函数 MyStr = "I am John" print(MyStr.lower()) print(MyStr.upper()) print(MyStr.isupper()) print(MyStr[0]) # 字符串index用法 print(MyStr.index('oh'))
06db73ffe61cb13f0aa1cc7ef2fe2ffbe1120f07
Chackoya/BolsaEML
/convnetCIFAR10.py
3,368
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ref: https://colab.research.google.com/drive/1ZZXnCjFEOkp_KdNcNabd14yok0BAIuwS#forceEdit=true&sandboxMode=true """ # CNN Tuto import tensorflow as tf from tensorflow import keras #from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as p...
b90826f43f0607fe8b395d2ddf0b6099c59219a9
GabrielDiasEstudos/Exercios-Python
/operadores/comparacao.py
232
3.796875
4
# Operadores de comparação matemática e de texto def mostrar_exemplo(): print(5 < 6) print(5 >= 6) print(5 == 5) print(5 != 5) print('Gabriel' == 'Gabriel') nome = 'Gabriel' print(nome == 'DIAS')
acb0c33303a211c707e5606f9312c51f2d8c28f8
GabrielDiasEstudos/Exercios-Python
/desvios/main_desvios.py
835
3.640625
4
## Seção de Estruturas de Desvio e Laços de Repetiçãos import desvios.se as ex_if import desvios.repeticao as ex_repeticao def mostrar_secao(): print('---------------------------------------------------------') print('-- Seção de Estruturas de Desvio e Laços de Repetiçãos --') print('---------------------...
2ba8377b240f51d4262468c8681927eb7b86a809
zyj0725/iterator_and_generator
/Generator_Fibonacci.py
304
3.609375
4
''' 使用yield实现斐波那契数列 ''' def fibonacci(num): f1,f2,count = 0,1,0 while count <= num: yield f1 f1,f2 = f1+f2,f1 count += 1 fib_gene = fibonacci(10) while True: try: print(next(fib_gene),end=' ') except StopIteration: break
6dfea9839760f8124ac74143ec886b836d85fa38
mattwfranchi/3600
/SampleCode/BasicTCPEchoClient.py
1,035
4.21875
4
from socket import * # Define variables that hold the desired server name, port, and buffer size SERVER_NAME = 'localhost' SERVER_PORT = 3602 BUFFER_SIZE = 32 # We are creating a *TCP* socket here. We know this is a TCP socket because of # the use of SOCK_STREAM # It is being created using a with statement, ...
54f2c2b794e6c0c5020c333d69bfc2e9ea7fd73d
hsinjungwu/self-learning
/100_Days_of_Code-The_Complete_Python_Pro_Bootcamp_for_2021/day-07.py
3,395
4
4
# Day 7 Step 1 word_list = ["aardvark", "baboon", "camel"] import random chosen_word = random.choice(word_list) guess = input("Guess a letter\n").lower() for l in chosen_word: if guess == l: print("right") else: print("wrong") # Day 7 Step 2 import random word_list = ["aardvark", "baboon", "camel"] chos...
086a3773b74c93e12755271fa0cf25d24399cb60
hsinjungwu/self-learning
/100_Days_of_Code-The_Complete_Python_Pro_Bootcamp_for_2021/day-12.py
756
4.15625
4
#Number Guessing Game Objectives: from art import logo import random print(logo) print("Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.") ans = random.randint(1, 100) attempts = 5 if input("Choose a difficulty. Type 'easy' or 'hard': ").lower() == "easy": attempts = 10 while at...
c8fcf1550d3585ed235aeaabbc5a77bf23cc246e
dendhi31/strava-friends-activities
/helpers.py
980
3.6875
4
#!/usr/bin/env python from math import cos, asin, sqrt from units import unit from constants import P, HOME_LOC km = unit('km') def distance(lat1, lon1, lat2, lon2): a = 0.5 - cos((lat2 - lat1) * P)/2 + cos(lat1 * P) * cos(lat2 * P) * (1 - cos((lon2 - lon1) * P)) / 2 return 12742 * asin(sqrt(a)) def start_d...
b6e201a9e0b4151431e055ed1ab71ec661a15efb
kamikazeren/Phys-177_Spring-Quarter_2016
/ex3b.py
1,172
3.90625
4
""" Renata Koontz SID: 861166139 Due: April 5, 2016 11:00 pm Exercise 3a - A Ball Drops from a Very Tall Tower part b Week 1 """ import numpy as np import math import matplotlib.pyplot as plt ##variables vMax = 0 ##maximun velocity vMin = 0 ##minimum velocity g = 9.81 ##gravity constant time = 0 ...
ce1f67a6d0ba0c0b976a93873d0d893016d85695
ap--/ordest
/ordest/__init__.py
3,537
3.734375
4
"""This module implements an insertion order preserving set container. * OrderedSet mutable set container that preserves insertion order """ __all__ = ["OrderedSet"] __author__ = "Andreas Poehlmann" __email__ = "andreas@poehlmann.io" from collections.abc import Iterable as _Iterable from collections.abc import Mu...
b599aa2e2d76a6117345a121038f2c7675ebae6c
iragomez68/Python-Lessons
/while_loop.py
399
3.9375
4
# Loop while a condition is being met run = "y" loop_size = 0 step_size = 1 loop_start = 2 while run == "y": print("Hi!") loop_size = int(input("Enter loop size: ")) step_size = int(input("Enter step size: ")) loop_size = loop_size + loop_start for x in range(loop_start,loop_size,step_size): ...
bbe5285a5f3844684a6e50de0732498452f306c9
iragomez68/Python-Lessons
/netflix_find.py
1,111
3.9375
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv csvpath = os.path.join('..', 'Resource', 'netflix_ratings.csv') video = input("What show or movie are you looking for? ") # # Method 1: Plain Reading of CSV files ...
5ce10f36afc8462d648e2d414253596dc39b5c90
dan0814/Python_Functions
/performUnpairedHeteroTTest.py
4,004
4.0625
4
"""This file contains a function that calculates the results of an unpaired heteroscedastic t test (t(calc) and degrees of freedom). The two values can be compared to critical t values to determine if p value is small (~0.05) """ # This function performs an unpaired heteroscedastic t test and returns the t(calc) ...
3be2e41c65875317ed4710e7f532638746a0310e
Shahil98/Optimization-Algorithms
/Genetic_Algorithms/ga.py
8,000
3.84375
4
""" Importing necessRY LIBRARIES. """ import numpy as np import random import matplotlib.pyplot as plt """ Following function is the function to be minimized. """ def func(x1,x2): return((x2-x1)**4 + 12*x1*x2 + x2 - x1 - 3) """ Following class is to define a chromosome/node. """ class Node(): def __init__(sel...
e74e251c59cb88439ffa12f5388bb74221e19178
parkero2/digital-science-task
/pin.py
190
3.515625
4
pin = "0456" guess = "0000" while pin != guess: guess = str(int(guess) + 1) if (len(guess) != 4): for i in range(4 - len(guess)): guess = "0" + guess print(guess)
c42be981525a6044c498c76f6bf3506148ebfd34
Rohiniwadi/1BM17CS078
/fib.py
171
3.515625
4
def pnz(n): if n==0 : print n,"is zero" elif n>0 : print n,"is positive" else: print n,"is negative" pnz(1) pnz(0) pnz(-2)