blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3cde074ae49a40fb3dae8cabbcb3c4d3a909191a | audiotech2017/Python_Code | /Pratise.py | 703 | 3.921875 | 4 |
dictx = {'red':'1','blue':'2'}
dict1 = {'Name' : 'John1', 'Age' : '22', 'Sex' : 'Male'}
#dict = {'Name' : 'John2', 'Age' : '23', 'Sex' : 'Feale'}
#dict = {'Name' : 'John3', 'Age' : '24', 'Sex' : 'Feale'}
#TinyDict = {'Name' : 'John5', 'Age' : '24', 'Sex' : 'Feale'}
while True:
try: print (dict1.popitem())
... |
7febad1ce0b43fb85d203cd23507a8ace2fe10b0 | jackschulz/Machine_Learning__Final_Project | /one_hot.py | 3,283 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 19 13:31:46 2019
@author: lefty
"""
def one_hot_meat(meat_list, exclusion_list):
file = open("ingredients_spaces_alt.csv", "r")
l = file.readlines()
file.close()
recipes = []
for item in l:
temp = item.strip('\n')
temp = ... |
878c2e35b401cb7eddd93d775508230058a37084 | Nitin-patil2209/Snake-Game | /snake.py | 1,258 | 3.703125 | 4 | from turtle import Turtle
LIST_POS = [(0,0), (-20,0), (-40,0)]
UP = 90
RIGHT = 0
LEFT = 180
DOWN = 270
class Snake:
def __init__(self):
self.turtles = []
self.Create()
self.head = self.turtles[0]
def Create(self):
for i in LIST_POS:
self.Createbody(i)
... |
78a7f72237ff8b26257391f793243a5bda6cc773 | jchristy40/projecteulersolutions | /recurse.py | 276 | 3.578125 | 4 | def fact(prod,x):
while x > 1:
prod = prod*x
return fact(prod,x-1)
else:
return prod
def splitsum(x):
x=str(x)
n=1
sum=0
splitter=[x[i:i+n] for i in range(0,len(x), n)]
for y in splitter:
y=int(y)
sum = sum + y
return sum
print(splitsum(fact(1,1000)))
|
02effe468f1ab388b75fc30556b69f996e57b0b4 | charlievweiss/mastermind | /mastermind.py | 2,056 | 3.59375 | 4 | import numpy as np
Colors = ['r', 'o', 'y', 'g', 'b', 'w'] # red, orange, yellow, green, blue, white
def generate_code(length = 4):
# Generates code to break
code = []
for i in range(0, length):
index = np.random.randint(0, len(Colors))
color = Colors[index]
code.append(color)
... |
454fe9f3fdd991b682badef4526cb79813598761 | HariPrasad-N/datastructure | /utils/Node.py | 2,914 | 3.75 | 4 | class Node:
def __init__(self,data=None):
"""
attributes:
-> data - data in the node
"""
self.data=data
self.next=None
self.prev=None
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self.data)
def __neg__(self):
"""
returns negation(a.data) for a Node
Raises TypeE... |
584081d5c3b0a621194e72d1ab7429e8df7bef23 | Matheus73/DB-Fixes | /tuple_generator.py | 2,935 | 3.828125 | 4 | import functions
menu = """
Opções de atributos:
+---------------+-------------------------------------------------------+
| opcoes | definicao |
+---------------+-------------------------------------------------------+
| cpf | Gera um cpf aleatorio ... |
2cc818f209631711cb243f06de2229de30c97f2d | lilblue2225/encryption-program | /fileEncrypt.py | 3,273 | 4.5625 | 5 | from cryptography.fernet import Fernet
#this function takes a file of your choice and encrypts it's contents then
#outputs it to a file, with the option of saving the key to a file as well.
def encryptFile():
print ('Enter file name: ')
fileName = input() #user enters name of file to be encrypted
... |
f257a1bec6d73043ec66085e41d6b1f811fcee58 | Sujay2611/Coding | /circuit20april2.py | 245 | 3.546875 | 4 | def josephus(n):
p = 1
while p <= n:
p *= 2
# Return 2n - 2^(1 + floor(Logn)) + 1
return (2 * n) - p + 1
t=int(input())
for _ in range(t):
n,k=[int(x) for x in input().split()]
print((josephus(n)+2*k)%n) |
78a15f0f29117be6423d7cb040f1a70a0524f019 | attia7/AttiaGit | /coretabs ATM py/withdraw.py | 1,400 | 3.546875 | 4 | balance = 700
papers=[100, 50, 10, 5,4,3,2,1]
def withdraw(balance, request):
if balance < request :
print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance))
else:
print ('your balance >>', balance)
orgnal_request = request
while request > ... |
2a5e9c7be1fd772b693b90ea4cb50c4df5ad8bd5 | naistangz/codewars_challenges | /8kyu/helloNameWorld.py | 189 | 3.9375 | 4 | def hello(name=None):
if name == "" or name is None:
return "Hello, World!"
else:
return f"Hello, {name.lower().capitalize()}!"
print(hello("ALIce"))
print(hello()) |
cb6c4b8004fdd8e69756c743e148878513d44678 | jinkerry/PyStudy | /pythonclub/equality.py | 456 | 3.734375 | 4 | #encoding=utf-8
__author__ = 'jinfeng'
import re
def equality():
f = file('equality.txt', 'r')
text = ''
for line in f:
text += line
#找出两边都是三个连续大写字母的小写字母
#One small letter, surrounded by EXACTLY three big bodyguards on each of its sides
pattern = '[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]'
... |
5d0a13c2d6c528273a23cbcf01b42d04d5f19c79 | rupindermonga/word2SubWords | /final_word2sub.py | 3,380 | 3.625 | 4 | import wordninja, os, re
from math import log
import math
import json
from heapq import nsmallest
import pandas as pd
with open("wordninja_words_final.txt") as f:
words = f.read().split()
def smallest(numbers):
min_list = []
for eachTuple in numbers:
min_list.append(eachTuple[0])
small_numbers... |
abf632954ff9e8dc4f475c11c313c191e6321b3f | bhumika0311/Bootcamp-1 | /Assessment05/pangram.py | 670 | 3.9375 | 4 | alphabets = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
frequency = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0, 0, 0, 0, 0, 0 ,0 , 0 , 0 , 0 ,0 , 0, 0, 0, 0 ,0, 0]
def isPangram(Sentence):
Sentence = Senten... |
81eb15e38d305ea16483abd3a67293d07b40561e | Sametcelikk/Edabit-Solutions-Python | /Easy/20-) Shuffle the Name.py | 412 | 4.125 | 4 | """
Create a function that takes a string (will be a person's first and last name) and returns a string with the first and last name swapped.
Examples
name_shuffle("Donald Trump") ➞ "Trump Donald"
name_shuffle("Rosie O'Donnell") ➞ "O'Donnell Rosie"
name_shuffle("Seymour Butts") ➞ "Butts Seymour"
"""
def name_shuffl... |
bd8b77b3f281c7078af941d856c011490f28b666 | suprit08/PythonAssignments | /Tuples/TupleExample4.py | 524 | 4.09375 | 4 | #TupleExample4.py --------
tuple1 = (1,2,3)
print("Tuple1 = ", tuple1)
# For Repetition
tuple2 = ()
tuple2 = tuple1*2
print("tuple1*2 = ",tuple2)
# For Concatenation use '+'
tuple3 = ()
tuple3 = tuple1+tuple2
print("tuple1+tuple2 = ",tuple3)
# For Membership use 'in'
print("is 2 in tuple1 =",(2 in t... |
2b7e18b89e29b29f0f68a6818cda4a320a77e5da | Deepak-AISD/first-project | /main.py | 2,251 | 3.984375 | 4 | # Python script to scrape an article given the url of the article and store the extracted text in a file
# Url: https://medium.com/@subashgandyer/papa-what-is-a-neural-network-c5e5cc427c7
import os
import requests
import re
import sys
# Code here - Import BeautifulSoup library
from bs4 import BeautifulSoup
# Code ... |
94ec7761a59d87b1421ab86e3b7e2dd9db1b8bdc | estineali/Python-Programming | /decipher_this.py | 1,676 | 4.21875 | 4 | '''
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
the second and the last letter is switched (e.g. Hello becomes Holle)
the first letter is replaced by its character code (e.g. H becomes 72)
Note: there are no special characters used,... |
b094a8a8b0c17fb5714adff16583c7adac8c2cd6 | lauradp21/OOP | /Complejo.py | 1,291 | 4.28125 | 4 | class Complejo():
def __init__(self,x,y,u,v):
self.x = x
self.y = y
self.u = u
self.v = v
print("El primer numero complejo tiene la forma:", x, "+", y,"i")
print("El segundo numero complejo tiene la forma:", u, "+", v,"i")
def sumar(self):
parte1 = x + u ... |
a9e1798e4219bc9f532f3c3306ab3f4c793ba6fa | lukereed/PythonTraining | /Homework/HW02/review_session_20160203.py | 1,884 | 3.609375 | 4 | # first import libraries
import math
import sys
import csv # imports the csv module
# define script inputs
#script, fname = sys.argv
# define shear calcualtion function
def shear_calc(MH1, WS1, MH2, WS2, DH):
# first make sure all variables are floats not integers/strings
MH1 = float(MH1)
WS1 = float(WS1)
MH2 = f... |
f416e14e5bc3afcc5d2da27e31473929fa858ba5 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/hwxada001/question1.py | 274 | 3.75 | 4 | a = False
print("Enter strings (end with DONE):\n")
list = []
while a == False:
temp = input()
if temp == 'DONE':
break
if list.count(temp) == 0:
list.append(temp)
print("Unique list:")
for i in range(len(list)):
print(list[i]) |
346eaff5603e6816efb8017eb9c5e16eb2609b2a | yossibaruch/learn_python | /learn_python_the_hard_way/ex25.py | 956 | 4.375 | 4 | def break_words(stuff):
"""This function will break up words for us."""
return stuff.split(' ')
def sort_words(words):
"""Sorts the words"""
return sorted(words)
def print_first_word(words):
"""prints the first word after popping it off."""
print(words.pop(0))
def print_last... |
2fde7b705c657e11dcd5048ad921ecdea9d7399c | leandrotominay/pythonaprendizado | /aula0/funcoes.py | 377 | 3.953125 | 4 | #Funções são blocos de códigos que só serão executados quando forem chamados
# OBS: def's devem ser declaradas no começo do código para o funcionamento dos outros que chamarem o mesmo!
def soma(x, y):
print(x ,"+" ,end=" ")
print(y, end=" = ")
return x + y
s = soma(2, 3)
print(s)
def multiplicacao(x, y):... |
2e01ec6df6e5eb1588a65f10fa4773c9fe5b4739 | Jbranson85/Python | /Caesar_cipher-Jonathan Branson.py | 2,219 | 4.21875 | 4 | '''
Jonthan Branson-Caesar_cipher
Adapted from a programs written by Dr. Melissa Stange(simplecipher.py, string2.py)
In this program allows the user to enter in a message, and will then be asked
how many shifts they would like. The message will then be encoded and returned
to the user.
At this point in time... |
016f8af9d6a42298c76e7249a111952e8673ab4d | romu42/aoc2019 | /day4/get_password.py | 1,393 | 3.703125 | 4 | from collections import deque
def get_password_count(input: str) -> int:
count = 0
start, stop = input.split('-')
print(start, stop)
for password in range(int(start), int(stop)):
if check_increase(str(password)) and check_adjacent(str(password)):
count += 1
return count
def g... |
8285d8e8d1af18b1225db7dbb79c1226eddf2ab6 | sbhackerspace/sbhx-projecteuler | /001/euler001.py | 185 | 3.796875 | 4 | #!/usr/bin/python
# 2009.04.02 (terrible version)
# 2010.??.?? (one-liner)
print sum([x for x in range(1000) if x%3 == 0 or x%5 == 0])
#print sum([x for x in range(1000) if x%5 == 0])
|
426676e1a04840023066776d5161c5f92e12fe11 | niksite/PyTagCloud | /src/pytagcloud/lang/counter.py | 592 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import re
from pytagcloud.lang.stopwords import get_stop_words
from operator import itemgetter
def get_tag_counts(text):
"""
Search tags in a given text.
"""
words = map(lambda x: x.lower(), re.findall(r'[\w-]+', text, re.UNICODE))
stop_words = get_stop_words()
counted ... |
fd5cdc0d0d88a2a2265e7495c6233a0fe42290d6 | Lanlanshi/hello_coding | /month_1/hour_minute_second.py | 190 | 3.828125 | 4 | seconds=int(input('请输入秒数'))
second=seconds%60
minutes=seconds//60
hour=minutes//60
minute=minutes%60
print('转化以后的结果是:',hour,'小时',minute,'分钟',second,'秒') |
7dae0e66dd6c1ada222534ccd9393b86e9f989e7 | dkurchigin/gb_algorythm | /lesson8/task1.py | 1,151 | 3.546875 | 4 | # 1) Определение количества различных подстрок с использованием хеш-функции. Пусть на вход функции дана строка.
# Требуется вернуть количество различных подстрок в этой строке.
# Примечание: в сумму не включаем пустую строку и строку целиком.
# Пример работы функции:
#
# func("papa")
# 6
# func("sova")
# 9
import h... |
433823d76e8fb8ecfcc99ca47d9c1c1b55145903 | liarazhang/aimooc_ori | /实例1读心术/guess.py | 1,715 | 3.734375 | 4 | import random
import getopt
import sys
def human_guess():
# 从 0 - 1000 中,产生一个随机数
num = random.randint(0,1000)
i = 0
while 1:
# 异常处理 - 输入非int型数据的时候
try:
# guess 接收 - 从键盘输入的数字的值
guess = int(input('请输入数字 0~1000:'))
except ValueError:
print('请输入... |
d758ddc25ae50d9d4dc69907d0595d296392f508 | mariereed/minesweeper-flask-app | /minesweeper.py | 4,908 | 4.03125 | 4 | import random
def create_true_false_matrix(height, width, mine_count):
""" creates a {width}x{height} matrix with {mine_count} true randomly placed, the rest false """
# use a list comprehension to initialize a 2d array of "false"
matrix = [[False for x in range(width)] for y in range(height)]
while... |
0a608b9d0e03c2c64daac7598fea4c44a9f2c323 | PeterL64/UCDDataAnalytics | /3_Intro_To_Importing_Data_Python/3_Working_With_Relational_Databases_In_Python/10_Advanced_Querying_INNER_JOIN_Relational_Tables.py | 1,028 | 4.03125 | 4 | # SQL Relational Tables and INNER JOINS
# - Assign to "rs" the results from the following query: select all the records, extracting the "Title" of
# the record and "Name" of the artist of each record from the "Album" table and the "Artist"
# table, respectively. To do so, "INNER JOIN" these two tables on the "Art... |
9719d893d01766d5d2795364334afcc86bf16b04 | udemy-course/python3-oop-new | /ch7-object-oriented/property.py | 542 | 3.9375 | 4 | class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def name(self):
# 格式的规范
return self.__name.upper()
@property
def age(self):
return self.__age
@name.setter
def name(self, name):
# 做一些合法性的检查
... |
d44827e05d82c3b4c5621a53819edf7ad1a080c2 | kar97k/programming-exercises | /single_char_appear.py | 471 | 4.21875 | 4 | #!/usr/bin/env python3
#Реализуйте алгоритм, определяющий, все ли символы в строке встречаются
#только один раз
a = '1231'
char_repeated = False
for i in a:
if char_repeated: break
char_count = 0
for j in a:
if i == j: char_count += 1
if char_count == 2: char_repeated = True
if char_repea... |
a9396eedae06e46544736eca114f715741ce618c | front440/PYTHON | /Primer_Trimestre/Programas_Alternativas/Ejercicio01_MayorQue.py | 756 | 4.03125 | 4 | # Programa: Ejercicio01_MayorQue.py
# Proposito: Algoritmo que pida dos números e indique si el primero es
# mayor que el segundo o no.
#
# Autor: Francisco Javier Campos Gutiérrez
#
# Fecha : 16/10/2019
#
#
# Variables a usar
# * a <-- Almacenaremos el primer numero
# * b <-- Almacenaremos el segundo numero
#
# Al... |
07cb0e177fc6851379dd319658deea9224df809e | roastbeeef/100daysofcode | /days_1-3/datetime_exploration.py | 767 | 4.4375 | 4 | from datetime import datetime
from datetime import date
# returns todays date
datetime.today()
today = datetime.today()
# datetime object- important because you cant mix these objects
type(today)
todaydate = date.today()
todaydate
# note that when using date, the object type is a date and note a datetime
type(today... |
0b7548688867b452d6f5b5ca602c3500efc3d552 | mpettersson/PythonReview | /questions/list_and_recursion/num_ways_to_decode.py | 1,931 | 4.03125 | 4 | """
NUM WAYS TO DECODE
Given a string of digits that represents an encoded message (data), write a method to count the number of ways to
decode the message. You can assume that the message (data) only contains the characters zero through nine [0-9].
The encoding function is:
'a' --> 1
... |
24493e3d9697b5084bfca680912392a79a15d215 | PdxCodeGuild/class_platypus | /Code/Colton/Python/Lab_19.py | 1,052 | 3.828125 | 4 | deck_worth = {'A': 1, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
f_card = input(f"What's your first card? ")
f_card = deck_worth[f_card]
s_card = input(f"What's your second card? ")
s_card = deck_worth[s_card]
while True:
if f_card + s_card < 17:
... |
ef45d4501123d4ee21a7a9012c128bedde602660 | lifeloverxg/principlescomputing-1 | /Tic-Tac-Toe .py | 3,463 | 3.65625 | 4 | """
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
#import user34_Uc9ea2tRiN_0 as test_ttt
#import user35_PIk21NjpAa_0 as tests
#import user35_UuNOhyrtdu_2 as tests
# Constants for Monte Carlo simulator
# Change as desired
NTRIALS = 10 # Number ... |
99297528050c5ce812cdd8a3fc49eca01fef5796 | freakraj/python_projects | /string_indexing.py | 361 | 3.75 | 4 | # string indexing
language="python"
# position (index number)
# starting position dekhne ke liye ,end se postion dekhne ke liye
# p= 0 ,-6
# y =1 ,-5
# t =2 ,-4
# h =3 ,-3
# o =4 ,-2
# n= 5 ,-1
# string postion indexing see
print(language[1])
print(language[5])
# ending posion se
print(language[-1])
print... |
9eb03fe79f966d16dea5d68014f51e74e9420510 | sheetal101/loop | /fac.py | 152 | 3.609375 | 4 | n=int(input("enter a number: "))
while n>0:
j=1
fac=1
rem=n%10
while j<=rem:
fac=fac*j
j=j+1
n=n//10
print(fac)
|
a71f5c84eef908abff4a9d8eedf21501a0cfaad7 | Dragon-God/PythonRepo | /collatzSequence.py | 413 | 4.34375 | 4 | #This is a function to simulate the collatz sequence.
def collatz(number):
return (number//2) if (number % 2 == 0) else ((3*number)+1)
while True:
try:
print("Input the number: ", end="")
num = int(input())
i = num
break
except ValueError:
print("Error: Invalid input.\n Please input a whole n... |
80cd7cc638351ee3b976a4f308d72e2314c165e8 | takushi-m/atcoder-work | /work/arc068_c.py | 218 | 3.71875 | 4 | # -*- coding: utf-8 -*-
x = int(input())
if x<=6:
print(1)
exit()
if x<=11:
print(2)
exit()
r = x%11
ret = x//11
if r==0:
print(2*ret)
elif r<=6:
print(2*ret+1)
elif r<=11:
print(2*ret+2)
|
fc3cbb645609e6b555f121e01f4c82bf17f2a627 | seung-lab/torchfields | /torchfields/utils.py | 5,868 | 3.84375 | 4 | from functools import wraps
#############################################
# Decorators for enforcing return value types
#############################################
def return_subclass_type(cls):
"""Class decorator for a subclass to encourage it to return its own
subclass type whenever its inherited functio... |
25f3b5c78c99e743484d1fb84e2c306cee92b2ad | Nutsanee28/workshop2_str | /string_format.py | 351 | 3.625 | 4 | age = 20
txt = "myname is nutsanee, and i am {}"
result = txt.format(age) # ส่งageไปแทนที่{}กี่อันก็ได้โดยเรียงลำดับ{}
print("result : ", result)
# formatเป็นการต่อสตริงประเภทหนึ่งโดยนำตัวฝน()มาต่อ
|
1dfad4f3963f05b4aca663757d96d36211cd5bef | RobertoFigueroa/Lab2-TP | /Lab2.py | 1,467 | 3.765625 | 4 | #Maria Jose Castro 181202
#Roberto Figueroa 18306
#Diana de Leon 18607
#Ejercicio 1
#paquetes necesarios
import math
import itertools
def genElements(n):
return list(range(n))
mensaje = "1.Orden-Sin reemplazo\n2.Orden-Con remplazo\n3.Sin orden-sin remplazo\n4.Sin orden-con remplazo\n5.Salir"
o... |
ac61975148af4d21cd552bcd31750fc74beaf17c | gustavors22/shortest-path | /dijkstra/dijkstra.py | 1,625 | 4.21875 | 4 | class Dijkstra:
def __init__(self, graph, origin, destiny) -> None:
self.graph = graph
self.origin = origin
self.destiny = destiny
def dijkstra_algorithm(self) -> dict and dict:
"""this function will apply the dijkstra algorithm to the graph to return the shortest path"""
... |
7ea3bc03da8c1eeeb8ca6fab9d3f53a5fb545f1c | kent-recuca/AtCoder | /AtCoder/ABC128/A-Apple-Pie.py | 157 | 3.671875 | 4 | # -*- coding: utf-8 -*-
def main():
A,P = map(int,input().split())
A = A*3
pi = int((A+P)/2)
print(pi)
if __name__ == '__main__':
main()
|
429ad8cad55b1f7ffc53f953811e03823baf1dba | Karsten1987/code_snippets | /python/list_comprehension.py | 430 | 3.9375 | 4 | # your code goes here
def list_comprehension():
vec = [0, 10, 1, 10, 2, 10, 3, 10, 4, 10, 5, 10]
vec_filter = [x for x in vec if x != 10]
print vec_filter
def reverse_vector():
vec = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
vec_reverse = [vec[len(vec)-i-1] for i in range(len(vec))]... |
c4132f53e1292b06d2653304f1c6850f6e08485e | HenryChen1/my-practice-code | /Craps Game.py | 749 | 3.75 | 4 | print('Craps Game')
import random
craps_1 = int(random.randint(1,6))
craps_2 = int(random.randint(1,6))
n = 1
sum = craps_1 + craps_2
# print('first round sum is %d' % (sum))
if sum == 7 or sum == 11:
print('you win!')
print('%d' % (sum))
n = 0
if sum == 2 | 3 | 11:
print('you lose!')
print('%d'... |
3ab11cdc3bdb94fed9a5bd5ab8090e3f02e76014 | danglh1910elmk/K-Means | /kmeans-3_library.py | 440 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
clusters = []
points = np.array([[1,1],[1,1.3],[1.3,1],[4,4.8],[4.2,4.8],[4.1,4.5],[8,4.8],[8,5.2],[8.1,5],[8,5.4]])
# draw points
x, y = zip(*points)
plt.plot(x, y, 'ro')
# use library
kmeans = KMeans(n_clusters=3).fit(points)
cl... |
098840b21382da879ac168b9ac549ecbefecb329 | blockchain99/pythonlecture | /test111list2.py | 2,258 | 3.984375 | 4 | nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list[0][1]) # 2
print(nested_list[1][-1]) # 6
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("++=====very important====++")
print("-----option1----")
for l in nested_list:
for val in l:
print(val)
print("-----option2----")
[[print(val) fo... |
6b5b944b9f31f14c7ada8141edfbb6a023792f8a | RunningShoes/python_lianxice | /RandomWalker.py | 1,574 | 3.546875 | 4 | #!/usr/local/bin/python3
#-*-coding:utf-8-*-
import matplotlib.pyplot as plot
import random
class ranWakler():
'''
随机漫步
'''
def __init__(self,num_points=5000):
'''
初始化函数
'''
self.num_points=num_points
self.x_step=[0]
self.y_step=[0]
def stepDire... |
23913bb4f73c234ab61aed87e58b0b1bc392f3d1 | ndwei97/python_project | /Week 7 lab/Krenn_Cho_Fei_LabWk7c_Skrenn.py | 7,619 | 4.28125 | 4 | # Steven Krenn
# Sangmin Cho
# Eric Mingfei
# Date created: 5/2/17
# Data modified: 5/2/17
# gets gallons of gasoline from the user, and converts it
# to liters, barrels, co2, energy, and USD.
# Has a main menu function that lets the user pick
# if they want to convert 1 at a time, or a list of gas values at once.
# Th... |
2f3db3b00605efb5a19ef37eb9d37da2e00b45a7 | lusan/Seismic-activity-monitor--SAM- | /PlottingEarthquakeFinalRelease.py | 1,954 | 3.609375 | 4 | #After all the mods, its time for the final release version
#This powerful code is capable parsing a giant text and converting it to an
#informative map representing seismic activity all over the globe!
import csv
#Open the earthquake data file
filename = 'C:\Python27\Py Pro\SAM\dataset.csv'
#Create empty lists for t... |
10095aa8bf05be7d94e373b8a0b897daeb50bb02 | hasnain40247/PythonPong | /Score.py | 634 | 3.59375 | 4 | from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.lscore=0
self.rscore=0
self.hideturtle()
self.color("white")
self.penup()
self.updateScore()
def updateScore(self):
self.clear()
self.goto(-200,33... |
a989104d7790bbd62b71e893637bfd8e6a1bf0ab | MonicaCat/Cat-Food | /22.py | 688 | 3.65625 | 4 | import math
a = 12+13
print(a)
b = 78-66
print(b)
c = 11*22
print(c)
d = 52/2
print(d)
e = 6**2
print(e)
a = 5
b = 2
c = a*b
print("面积为:", c)
a = 12*5
print(a)
b = "有没有人告诉你."
print(b)
a = input()
b = input()
if float(a) == 0.0:
print("0")
else:
print("结果为:", float(b) / float(a))
a = float(input(1))
b = float... |
4fcd361e3baf5265e5397953986c4f34e0521b99 | agoncecelia/datasciencebootcamp | /modules/app.py | 501 | 3.546875 | 4 | from utils.math_utils import max_average
from classes.student import Student
agoni = Student("Agon", "Cecelia", "agonn.c@gmail.com", "127488", 7.89)
bislimi = Student("Bislim", "Bislimi", "bislimi.b@gmail.com", "127388", 6.78)
ahmeti = Student("Ahmet", "Ahmeti", "a.ahmeti@gmail.com", "127332", 7.12)
lista = []
lista.... |
7b4e229d0202c05f3640ae467003a2b023a82eac | k-schmidt/Coding_Problems | /code_rust/merge_two_sorted_linked_lists.py | 989 | 4.21875 | 4 | """
Merge Two Sorted Linked Lists
"""
def merge_sorted(head1, head2):
# if both lists are empty then merged list is also empty
# if one of the lists is empty then other is the merged list
if head1 is None:
return head2
elif head2 is None:
return head1
merged_head = None
if hea... |
b3afe1777807a1e590cd250eebf572fb750b4c74 | Sitwon/Pentago | /pentago.py | 8,357 | 3.609375 | 4 | #!/usr/bin/python
import sys
DEBUG = 0
class Place:
EMPTY = 0
WHITE = 1
BLACK = 2
def __init__(self):
self.state = self.EMPTY
def CheckPlace(self):
return self.state
def SetPlace(self, value):
assert((value == self.EMPTY) or (value == self.WHITE) or (value == self.BLACK))
self.state = value
def Print(s... |
a2573aed665d4ec84c3a3a988bbfc2e97bbc1c92 | iamrishap/PythonBits | /InterviewBits/arrays/first-missing-positive.py | 827 | 3.78125 | 4 | """
Given an unsorted integer array, find the first missing positive integer.
Example:
Given [1,2,0] return 3,
[3,4,-1,1] return 2,
[-8, -7, -6] returns 1
Your algorithm should run in O(n) time and use constant space.
"""
class Solution:
# @param A : list of integers
# @return an integer
def firstMissingP... |
aa91e89e186998f1497a9bb6ade9a11511523732 | smohsensh/smart-xo | /xo/game.py | 1,920 | 3.734375 | 4 | import random
from xo.calc import get_next_turn, get_best_move_score
from xo.model import Board
class Game:
def __init__(self):
self.board = Board()
self.play_for = None
self.starter = None
def initialize(self):
print('Playing a Game of X/O')
print('-' * 50)
p... |
99b57520f8b907241971f3b801615527f795308e | mxxu/leetcodeOJ | /minstack.py | 739 | 3.703125 | 4 | class MinStack:
# @param x, an integer
# @return an integer
def push(self, x):
self.elements.append(x)
self.size = self.size + 1
if len(self.elements) == 1 or self.getMin() > x:
self.min_eles.append(self.size - 1)
# @return nothing
def pop(self):
if self... |
e7b3806d0f498eb98f9da503b4892fb7f132cfb7 | eliffyildirim1/Wtech-Homeworks | /Homework-5/04_04_PlottingBasicChartsWithMatplotlib.py | 3,995 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# <font color=blue>Assignments for \"Plotting Basic Charts With Matplotlib\"</font>
# In this assignment, you will continue work with the [Coronavirus Source Data](https://ourworldindata.org/coronavirus-source-data). You will plot different chart types. Don't forget to set title... |
a978a47284e96bde4d3aca3a0d4322c6535f630a | hanbingo/friendly-disco | /project4.py | 151 | 4.03125 | 4 | counter = 0
while counter < 42:
if counter % 2 == 0:
print("HO HO HO")
else:
print("Happy new year")
counter = counter + 1
|
dd48ceb1c423c560e5a6ba989bb3335df141979c | fifthlight/test | /date01/homework5.py | 977 | 3.9375 | 4 |
#九九乘法表
# for i in range(1,10):
# for j in range(1,10):
# print('%d*%d=%2d '%(j,i,i*j),end='')
# print()
#while里面的这个条件判断就在for形式的括号里面体现了
# i=1
# while i <10:
# j=1
# while j<=9:
# print('%d*%d=%2d '%(j,i,i*j),end='')
# j+=1
# print()
# i+=1
#左下三角
# for i in range(1,10):
... |
c7d4837df914029e8595e16fdab3589c2bbc2a5f | furkanbakkal/Machine-Learning-with-Tensorflow | /draw.py | 1,064 | 4.1875 | 4 | # draw square in Python Turtle
from os import name
import turtle
import time
def boxing(start_point_x, start_point_y,length,label):
t = turtle.Turtle()
turtle.title("Squid Game Challange")
wn = turtle.Screen()
wn.setup(1200, 800)
wn.bgpic("test.gif")
t.hideturtle()
t.penup() ... |
8ee4973a81b68fd6695f741b0b95f94bea2ce268 | HelenaOliveira1/Exerciciosprova2bim | /Questão 24.py | 350 | 3.96875 | 4 | print("Questão 24")
print("")
N = int(input("Qual a quantidade de notas? "))
print("")
nota = float(input("Digite a nota: "))
i = 0
aux = 0
for media in range (1,N+1):
soma = nota + i
i = nota
aux +=1
if (aux < N):
nota = float(input("Digite a nota: "))
media = soma/N
print("")
print("A ... |
9a9df3e1aed9c2f985d794eda194a766b5f8a474 | jjassonnlee/elements-of-programming-interviews | /arrays/compute_the_next_permutation.py | 192 | 3.78125 | 4 | """
Given a permutation A, return the next permutation under dicitonary ordering.
If input is [1,0,3,2], return [1,2,0,3]
If input is [3,2,1,0], return []
"""
def next_permutation(A):
...
|
864c13c137d4e62364c9e1192872956fcc8d8c4c | srikanthpragada/PYTHON_10_JULY_2020 | /demo/basics/table.py | 100 | 3.921875 | 4 |
num = int(input("Enter number :"))
for i in range(1,21):
print(f"{num} * {i:2} = {num * i:4}")
|
03c26e56cece6de276fcf0b38072323172a250f3 | matthijsvk/Battleship | /battleship.py | 12,298 | 4.25 | 4 | # -*- coding: cp1252 -*-
from random import randint
import re
import copy
"""
This is the game of Battleship, where the computer puts some ships somewhere in the ocean. You can then shoot and try to hit the ships.
If you hit all parts of a ship, it is sunk! Try to sink all the enemy ships before you run out of ammo :)... |
668d238dafe1d88006a537460769a7385cdab714 | Sanchita210507/Class-111-Single-Sample-z-tests- | /school.py | 4,198 | 3.515625 | 4 | import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("school2.csv")
data = df["Math_score"].tolist()
fig = ff.create_distplot([data],["Math Scores"], show_hist= False)
#fig.show()
mean = statistics.mean(data)
std_deviation... |
2f2928e1b7d3a02c0870c5105a62ab23cb970f1b | joe-antognini/exercises | /praxis/ex200/brute_countprimes.py | 708 | 3.90625 | 4 | #! /usr/bin/env python
if __name__ == '__main__':
from segmented_sieve import *
else:
from ..ex108.segmented_sieve import segmented_sieve
def brute_countprimes(n):
'''Count the number of primes up to n using a segmented sieve of
Eratosthenes.'''
blocksize = int(1e8)
nprimes = 1
if blocksize > n:
pr... |
5bdf0a15a7a433c8cea5ee0ba53b9000d5a8e296 | ranjana980/Python | /loop files/even.py | 107 | 3.609375 | 4 | counter=1
while counter<=100:
if counter%2==0:
print(counter)
counter=counter=counter+1 |
5749dd2702cb129c8e31fc837b7065cd86a0bc27 | rsamit26/AlgorithmsAndDatastructure | /EulerProject/Largest palindrome product.py | 1,116 | 4.15625 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
class Solution:
def largestPallindrome(self, k):
n = 10**k-1
l = []
for i... |
96c70910bfa5e01a432c424c913630d6a155133d | MatheusFilipe21/exercicios-python-3 | /exercicio14.py | 195 | 3.78125 | 4 | temp = float(input('Escreva a temperatura em °C: '))
novatemp = (temp * 1.8) + 32
print('A temperatura de \033[34m{:.2f}\033[m em °C equivale a \033[31m{:.1f}\033[m°F'.format(temp, novatemp))
|
856758bf9651910a1b5602f7358e69c6657c1406 | gohdong/algorithm | /leetcode/1379.py | 794 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
# print(original)
# print(cl... |
812776057a2ac72df135a5234cf4afce3c416cc1 | castle-bravo/diamond_square | /diamond_square.py | 2,944 | 3.578125 | 4 | '''
file: diamond_square.py
title: Diamond-square algorithm
author: Alexander Gosselin
e-mail: alexandergosselin@gmail.com
alexander.gosselin@alumni.ubc.ca
date: August 19, 2015
license: GPLv3 <http://www.gnu.org/licenses/gpl-3.0.en.html>
'''
import numpy as np
import numpy.random as rnd
def diamond... |
36399b0d59d727648d3be1887f85ad07e6f62bb1 | deepu14d/Decrypto | /decrypto/src/vigenere_cipher.py | 1,525 | 3.828125 | 4 | class VigenereCipher:
def __init__(self) -> None:
"""This is a python implementation of Vigenere Cipher"""
def modify_key(self, msg: str, key: str) -> str:
'''Generates the key in a cyclic manner until it's length equal to the
length of text'''
if len(msg) > len(key):
... |
d99872ecb47e18b5460a4ef5267fa0d10cfd3d45 | yaalyy/Fruit_Machine | /slot machine.py | 1,208 | 3.765625 | 4 | import random
credit = 1
fruit = ['Cherry','Bell','Lemon','Orange','Star','Skull']
def roll():
global credit
credit=credit-0.2
results = []
bell_num = 0
skull_num = 0
same_num = 0
for i in range(3):
m = random.randint(0,5)
k = fruit[m]
results.append(k)
if ... |
8c95d7d310e2b2fb1e026732a719559d18079cb2 | xiaotiankeyi/PythonBase | /python_oo/oo_advanced/class_decorator_two.py | 423 | 3.78125 | 4 | # 实现类装饰器,为函数增加新的功能
class Family(object):
def __init__(self, func):
self.__func = func
def __call__(self, *args, **kwargs):
self.new()
result = self.__func()
print(result)
def new(self):
print('所要执行的新的功能!!!')
@Family
def daughter():
return '需要被装饰得类.....'
if... |
09978538015c35f4750dac07cdb5eb860889d2ae | MrDrewShep/Python_fundamentals | /error_handling.py | 880 | 3.75 | 4 | # TRY EXCEPT
def proclaim_user_birthday(name, age):
try:
new_age = age + 1
message = f"{name} is now {new_age} years old!"
print(message)
except Exception as e:
print(e)
print("ONLY WHEN MY PROGRAM CONTINUES")
proclaim_user_birthday("Drew", "45")
print("I'm after proclaim.... |
8d645f82835576b1e219ab5aeccaf0347b29dc0a | anderalex803/nuwara-online-courses | /datacamp/statistical-simulation-python/02_poker_two_of_a_kind.py | 557 | 3.53125 | 4 | # Shuffle deck & count card occurrences in the hand
n_sims, two_kind = 10000, 0
for i in range(n_sims):
np.random.shuffle(deck_of_cards)
hand, cards_in_hand = deck_of_cards[0:5], {}
for card in hand:
# Use .get() method on cards_in_hand
cards_in_hand[card[1]] = cards_in_hand.get(card[1], 0) ... |
907db787f072f64abb134ff67f457a36d359bb29 | ThomasHartmannDev/CursoPython | /Programas/01 - Fundamentos/10 - Tuplas/exemplo.py | 910 | 4.125 | 4 | '''
Diferente da lista que pode ser mudada, a Tupla è imutavel.
'''
tupla_unica = ('um',) # Caso queremos apenas um item na tupla devemos deixar essa (,) no final.
tupla_cores = ('Verde','Amarelo','Azul','Branco')# não precisamos colocar a (,) no final pois o python ja entendeu que se trata de uma tupla.
print(tupla_... |
d90d7b2636edf74d2698bfd42acd852883f8297e | InahoKai/algorithms-1 | /easy/isPowerOfFour.py | 297 | 3.8125 | 4 | # Runtime: 28 ms, faster than 90.26% of Python3 online submissions for Power of Four.
def isPowerOfFour(num: int) -> bool:
if num == 0:
return False
while num != 1:
if num % 4 != 0:
return False
num = num // 4
return True
print(isPowerOfFour(16)) |
01f1c86b72c530f95b8dff7c5a22970f294c69a8 | kanikashridhar/Elevator | /utils/elevator_helper.py | 774 | 4.125 | 4 | import typing
from typing import List, Tuple
def calculate_service_in_directions(requested_floors: List[int],
current_floor: int) -> Tuple[List[int], List[int]]:
"""
Creates two list from a input requested_floors list.
floors_in_up_direction - contains all the floor number whi... |
f5c5a2910c1b2d9aec42a7424a8f6aa265c0bd79 | Pigiel/udemy-python-for-algorithms-data-structures-and-interviews | /Stacks, Queues and Deques/Stacks, Queues, and Deques Interview Problems/Stacks, Queues, Deques Interview Questions /Balanced-Parentheses-Check.py | 1,109 | 4 | 4 | #!/usr/bin/env python3
def balance_check(s):
# Check if even number of brackets
if len(s) % 2 != 0:
return False
# Set of opening brackets
opening = set('([{')
# Matching pairs
matches = set([('(',')'), ('[',']'), ('{','}')])
# Use a list as a "Stack"
stack = []
# Check every parenthesis in string
fo... |
b05b908d77aa8237e4cdd2e7263d20fef9055d2f | Rakeshyakkundi/DSA | /stack.py | 659 | 3.703125 | 4 | ls = []
rev = []
max = 5
while True:
num = int(input("1.insert 2.pop 3.display 4.exit 5 reverse\n"))
if num ==1 and len(ls)<max:
n = int(input("Data :"))
ls.append(n)
continue
if num == 2 and len(ls)>0:
ls.pop()
continue
if num == 3:
print("Stack Top-Down ... |
8140b0c7897420d4773610c6cae2088b7d9059dd | haron68/CSCI-1133 | /arama006_3A.py | 997 | 3.546875 | 4 | # CSci 1133-20 HW 3
# Haron Arama
# HW 3, Problem 3A
inputType = input("Are input components int or float (i/f)? ")
if inputType == "f":
red = float(input("Red component: ")) * 255
green = float(input("Green component: ")) * 255
blue = float(input("Blue component: ")) * 255
rint =... |
06ed801583d1ba7c3912cf838e63acc795ec3cb0 | mvxdipro/old-projects | /filters.py | 3,249 | 3.65625 | 4 | #tyutyunnykd_mohamedm2
#Import function to get red, green, blue values
from cImage import *
import sys
def grayscale(image): #Function converts to grayscale by averaging the three color values
grayscaleIM = image.copy()
numP = image.getNumPixels()
for i in range (numP):
apixel = image.getPixel... |
0fbad9f2170e2b70b5aa59f3d9fdbe546b4931bd | hrantm/ML-AndrewNg | /ex1/warmup.py | 147 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import numpy as np
num = int(input("Enter num:" ))
def warmup(x):
return np.identity(x)
print(warmup(num)) |
5f072aa28d29058c32a8ca2a2ae21f534f520a81 | abiryusuf/pyhton_3 | /lists/removeList.py | 193 | 3.65625 | 4 |
thisList = ["red", "black", "blue", "white"]
# remove
# thisList.remove("red")
# print(thisList)
x = thisList.pop(1)
print(x)
print(thisList)
print(2**10)
p = 26
total = p**6
print(total) |
26f0ae622d691d417146f8620717eebbd7de9cd2 | dafedo/long-range_word_dependency | /correlation_function.py | 5,209 | 3.53125 | 4 | import re
from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def tokenize(sentence):
'''
List all the word tokens (consecutive letters) in a text. Normalize to lowercase.
'''
return re.findall('[a-z]+', sentence.lower())
def frequency(corpus):
''... |
6fc03e029814d1e7f48e0c65921d19a276c15b06 | CHilke1/Tasks-11-3-2015 | /Fibonacci2.py | 586 | 4.125 | 4 | class Fibonacci(object):
def __init__(self, start, max):
self.start = start
self.max = max
def fibonacci(self, max):
if max == 0 or max == 1:
return max
else:
return self.fibonacci(max - 1) + self.fibonacci(max - 2)
def printfib(self, start, max):
for i in range(start, max):
print("Fibonac... |
dc0df8c65f2da598e1696c763cbcfa3254426612 | santoshmano/pybricks | /trees/flip_tree.py | 907 | 3.984375 | 4 | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
if root == None:
return
inorder_traversal(root.left)
print(root.val, end=' ')
inorder_traversal(root.right)
def flip_tree(roo... |
6836cb34074d73fa92713f8a1fbef73a993d95e2 | Corinyi/ML_Python | /svmexercise.py | 535 | 3.84375 | 4 | # 2만명 데이터 작성(csv)
import random
def bmi_func(height, weight):
bmi = weight/(height/100)**2
if bmi < 18.5: return "low"
if bmi < 25: return "ok"
return "high"
fp =open('bmi.csv',"w",encoding="utf-8")
fp.write("height,weight,label\r\n")
# 데이터 생성
cnt = {'low' : 0,'ok' : 0,'high' : 0}
for i in range(100... |
5c225df9a4df6c34712cafdeaebfdeed45e6e7f1 | sadatrafsanjani/MIT-6.0001 | /Lec04/in.py | 214 | 3.953125 | 4 |
def isIn(s1, s2):
if (s1 in s2) or (s2 in s1):
return True
else:
return False
if isIn("Dragunov", "Dragunov is a sniper rifle"):
print("Yes")
else:
print("No")
|
282da6a82acb1c87d385af3595cdb30616d65391 | nabo715/LearningPython | /File_processing.py | 215 | 4.1875 | 4 | # Use words.txt as the file name
fname = raw_input("Enter file name:")
try:
fh = open(fname)
except:
print("Incorrect file name")
exit()
for line in fh:
line = line.rstrip()
print line.upper() |
ee8e82e51d4cdcad46024a25266da13f92308800 | yentingw/lexical-normalization-twitter-text | /main.py | 1,105 | 3.515625 | 4 | from bestMatch import *
# Read in the txt files and make them into lists
def getToken():
with open('misspell.txt', 'r') as token:
tokenLs = [item.strip() for item in token]
return tokenLs
tokenLs = getToken()
def getDict():
with open('dict.txt', 'r') as dictTxt:
dictLs = [item.strip(... |
9c14aa03df9430a990dd88c23f0d2dac3c91c7c3 | DataEngDev/CS_basics | /leetcode_python/Tree/implement-trie-prefix-tree.py | 5,195 | 3.90625 | 4 | # V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79388432
class Node(object):
def __init__(self):
self.children = collections.defaultdict(Node)
self.isword = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.