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 |
|---|---|---|---|---|---|---|
6ae75b586d58afc3890d770d67ce8b8cbe670665 | wwlorey/book-decrypter | /betterSubCrack.py | 7,015 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Inspiration: https://www.nostarch.com/crackingcodes
import copy, simpleSubCipher, wordPatterns, makeWordPatterns, sys, re
from detectEnglish import getEnglishCount
# Constants
DEFAULT_INPUT_FILE_NAME = 'encrypted_book.txt'
DEFAULT_OUTPUT_FILE_NAME = 'decrypted_book.tx... |
90f47fab82b4de824d9452b122d5255ccf42ab9f | Highcourtdurai/Machine-learning-projects | /kMeans.py | 990 | 3.515625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
from sklearn import datasets
x,y=datasets.make_blobs(n_samples=1500,random_state=10)
#x,y=datasets.make_circles(n_samples=1500,noise=0.05,factor=0.5) -- In this datasets we cannot do cluste... |
2cb6646f24744d8004bbc35dbc7728296b2bbcbb | Jdothager/CryptoPython | /initials.py | 421 | 3.984375 | 4 | def get_initials(fullname):
"""Given a person's name, return the person's initials (uppercase)"""
initials = fullname[0]
for i in range(len(fullname)-1):
if fullname[i] == " ":
initials = initials + fullname[i+1]
initials = initials.upper()
return initials
def main():
name ... |
f3901e5c758a2fc0d785d9c20769d5f0169a797f | daniloaugusto0212/EstudoPython | /Python-Udemy/Básico/aula15Listas.py | 788 | 4.125 | 4 |
idade = [] #inicializando lista vazia
idade.append(18) #adiciona o valor 18 à lista
idade.append(50)
idade.append(35)
idade.append(48)
idade.append(40) #adiciona o valor 18 ao final da lista
idade.insert(1, 30) #adiciona o valor 30 na posição 1 da lista
idade.pop() #remove o valor da última posição da lista
idade.po... |
36ce544dbd0734277bf6e029cc63ca5853c9a1f1 | daniloaugusto0212/EstudoPython | /Python-Udemy/SistemaPizzaria/Interface.py | 624 | 3.796875 | 4 | from tkinter import *
def mostrar():
armazenarLabel['text'] = 'Botão foi clicado'
janela = Tk()
janela.title('Curso de Python')
janela.geometry('300x300')
janela.resizable(False, False)
# Label(janela, text='Hello World', bg='black', fg='white', padx=30, pady=30).grid(row=0, column=0) edição da janela
# Entry(ja... |
98801d830847fec3f9b8f07ecef58385cc972134 | daniloaugusto0212/EstudoPython | /Python-Udemy/RedesNeurais/Tabelaand.py | 894 | 3.703125 | 4 | from random import *
pesoInicial1 =random()
pesoInicial2 = random()
pesoBias = random()
entrada1 =int(input('Digite a entrada 1:'))
entrada2 = int(input('Digite a entrada 2:'))
bias =1
erro = 1
while erro != 0:
if entrada1 == 1 and entrada2 == 1:
resultadoEsperado = 1
else:
resultadoEsperado... |
b10fc1ca26f8b02be67130acb967727948169eb7 | daniloaugusto0212/EstudoPython | /exercicios/PythonGuanabara/ex028JogoDeAdivinhacao.py | 404 | 3.84375 | 4 | from random import randint
from time import sleep
print('Vou pensar em um número entre 0 e 5. Tente adivinhar... ')
numeroComputador = randint(0, 5)
numero = int(input('Em que número eu pensei? '))
print('Processando...')
sleep(3)
if numeroComputador == numero:
print('PARABÉNS! Você conseguiu vencer!')
else:
p... |
3c77e33555f74defc480aa058b33fae32f82b59c | daniloaugusto0212/EstudoPython | /python_dankicode/exercicios/numero_primo.py | 361 | 4.03125 | 4 | num = int(input("Digite um número inteiro para saber se ele é primo: \n"))
primo = False
if num > 1:
for i in range(2, num):
print(i, "\n")
if (num % i) == 0:
primo = False
break
else:
primo = True
if primo:
print(f"O número {num} é primo!")
else:
print(f"... |
0ca4e32ad15132ec52d36c92d171741393feecec | daniloaugusto0212/EstudoPython | /exercicios/PythonGuanabara/ex04.py | 411 | 3.78125 | 4 | import math
frase = input('Digite algo: ')
print('O tipo primitivo desse valor é: ',type(frase))
print('Só tem espaços? ',frase.isspace())
print('É um número? ',frase.isnumeric())
print('É alfabético? ',frase.isalpha())
print('É alfanumérico? ',frase.isalnum())
print('Está em maiúsculas? ',frase.isupper())
print('Está ... |
c9caf5c48206f82b5c9ba870d1791a1e29a1ca41 | daniloaugusto0212/EstudoPython | /algoritmos/04-busca_binaria/main.py | 1,116 | 3.96875 | 4 |
numeros = list()
tamanho = int(input("Digite o tamanho do vetor: "))
for i in range(0, tamanho):
valor = int(input(f"Digite um número do vetor na posição {i}: "))
numeros.append(valor)
print(f"Vetor: {numeros}")
#SELECTION SORT
# 0 | 1 | 2 | 3 | 4
# 5 | 2 | 4 | 6 | 1
for i in range(tamanho):
indice_menor... |
a412f2894b43299a6732bf3af38b5cfa56f079b0 | daniloaugusto0212/EstudoPython | /Python-Udemy/Básico/aula16Listas.py | 492 | 3.78125 | 4 | lista = []
#adiciona a lista os valores de 1 até 1000
for i in range(1, 1001):
lista.append(i)
lista = list(range(1, 1001)) #mesma função do código acima (mais simplificado)
print(lista)
#verifica se o valor digitado exista na lista para apagá-lo
apagar = int(input('Digite um número para apagar da lista: '))
if... |
f257b2c4bd54a0ee3b64d6223c9a0bb007240d57 | daniloaugusto0212/EstudoPython | /exercicios/PythonGuanabara/ex14ConversorTemperatura.py | 230 | 4.09375 | 4 | '''Converte a temperatura de Celsius para Fahrenheit'''
temperatura = float(input("Informe a temperatura em °C: "))
converte = (temperatura * 9 / 5) + 32
print(f'A temperatura de {temperatura}°C corresponde a {converte}°F')
|
95e04761f619193d2190a9d62d5ec9c0ffe0beea | SharmaManish/crimsononline-assignments | /assignment1/question2.py | 863 | 4.15625 | 4 | def parse_links_regex(filename):
"""question 2a
Using the re module, write a function that takes a path to an HTML file
(assuming the HTML is well-formed) as input and returns a dictionary
whose keys are the text of the links in the file and whose values are
the URLs to which those links correspond... |
d045ce0519a50d00ef3276629f76b39224110dcf | EduarDomingos/Exercisos-LB-2B | /Ex2.py | 512 | 4.03125 | 4 | n1 = float(input("Digite Primeiro numero: "))
n2 = float(input("Digite segundo numero"))
n3 = float(input("Digite terceiro numero"))
n4 = float(input("Digite quarto numero"))
n5 = float(input("Digite quinto numero"))
n6 = float(input("Digite sexto numero"))
n7 = float(input("Digite setimo numero"))
n8 = float(input("Di... |
130b0896fc57c51d0601eea2483449f51de4142d | xfLee/Python-DeepLearning_CS5590 | /Lab_2/Source/Task_1.py | 640 | 4.1875 | 4 | """
Python program that accepts a sentence as input and remove duplicate words.
Sort them alphanumerically and print it.
"""
# Taking the sentence as input
Input_Sentence = input('Enter any sentence: ')
# Splitting the words
words = Input_Sentence.split()
# converting all the strings to lowercase
words = [elemen... |
eec458d8c6806cacabeef7b0188edd7db65306bc | xfLee/Python-DeepLearning_CS5590 | /Lab_2/Source/Task_2.py | 433 | 4.28125 | 4 | """
Python program to generate a dictionary that contains (k, k*k).
And printing the dictionary that is generated including both 1 and k.
"""
# Taking the input
num = int(input("Input a number "))
# Initialising the dictionary
dictionary = dict()
# Computing the k*k using a for loop
for k in range(1,num+1):
... |
360c5c36055d332107828b032f45a0fba4beff26 | israelElad/ML | /ex3/submit/ex_3.py | 7,973 | 3.890625 | 4 | # Elad Israel 313448888
import sys
import numpy as np
# go through each column(axis=0) and zscore it, returns the updated martix
def ZScoreNormalization(matrix):
return (matrix - matrix.mean()) / matrix.std()
# reLU activation function
def reLU(z):
return np.maximum(0, z)
# Calculate the ... |
591d265f4773fab8be1362b349278cd8ed41574a | mercy17ch/dictionaries | /dictionaries.py | 2,262 | 4.375 | 4 | '''program to show dictionaries'''
#A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values
#
#creating dictionary#
thisdict={"name":"mercy",
"sex":"female",
"age":23}
print(thisdict)
#... |
0ca4e93491a5410660981dd53d6c14dc5415cd9a | wprudencio97/csc122 | /assignment1/database_exercise.py | 339 | 3.8125 | 4 | import sqlite3
def main():
conn = sqlite3.connect('contacts.db')
cur = conn.cursor()
cur.execute("SELECT * FROM CONTACT")
rows = cur.fetchall()
conn.close()
for r in rows:
print('Contact ID:', r[0])
print('Name:', r[1])
print('Email:', r[2])
print('------------... |
ffaa3cd563a06238f1b5322412ef3bda30523e38 | baiper06/tutorial-tkinter | /Widgets/2. Boton_Entry_Message/Boton_Entry_Message.py | 1,295 | 3.671875 | 4 | from tkinter import *
ventana = Tk()
ventana.title("Computadores CE")
ventana.minsize(500,500)
ventana.maxsize(500,500)
#funcion que muestra lo ingresado en pantalla por medio de un message box
def mostrarValor():
messagebox.showinfo("Titulo mensaje",str(entrada.get()))
#Funcion que inserta en el... |
887425a739ee290fca4f7d05ab7b93d96cdbce82 | nimeshnischal/Dice-Rolling-Simulator | /dice_rolling_simulator.py | 2,078 | 3.875 | 4 | #This is a basic python program to simulate the rolling of a dice
import nimesh_app_basics
def get_min_max_values(user_choice_default_dice_boolean):
if not user_choice_default_dice_boolean:
while True:
print("Please enter the minimum and maximum values on the dice to simulate.")
m... |
a5f368ea34dd6b85d222ab23cab1da116907cf7f | KmrAnil/Python | /LinkedList.py | 3,915 | 4 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
#insert Node at the end of linked List
def insertNodeAtTail(self,new_node_data):
new_node = Node(new_node_data)
if self.head ==None:
se... |
df09dcc11ab6114ff7433a5dd1306506356cef87 | sudhanshu2k/Audio-Sentiment-Classification | /sentiment.py | 2,712 | 3.53125 | 4 | from textblob import TextBlob
def Sentiment(listToStr):
analysis=TextBlob(listToStr)
#print("analysis",type(analysis))
#for words, tag in analysis.tags:
# print(words,tag)
sentimentscore=analysis.sentiment.polarity
subjectivity=analysis.sentiment.subjectivity
print("sentimentscore",s... |
c4cac8a951246e1a70402e4a58520d9e659908b7 | rafaeloliveira00/Steganography | /audio/bytes_manipulation.py | 4,932 | 3.640625 | 4 | import more_itertools
import utils
def check_size(n_bytes_file, n_bytes_message):
"""Check if the message can be hidden
Parameters:
n_bytes_file: Number of bytes in the file
n_bytes_message: Number of the bytes in the message to hide
Returns:
True if the message ca... |
02a08e2cfab6fc6c28b74d385eb4be0283fc92d3 | yxtay/how-to-think-like-a-computer-scientist | /Lists/lists_ex5_max.py | 218 | 3.6875 | 4 | import random
myList = []
for i in range(100):
myList.append(random.randrange(0, 1000))
def max(l):
m = None
for el in l:
if m < el:
m = el
return m
print(max([1, 3, 5, 7, 6, 4, 3]))
print(max(myList)) |
ddfa575f5e2bd35f03775815ab7b0a531a7c473a | yxtay/how-to-think-like-a-computer-scientist | /Lists/lists_ex8_sum_even.py | 133 | 3.921875 | 4 | def sum_even(l):
s = 0
for el in l:
if el % 2 == 0:
s += el
return s
print sum_even(range(3))
print sum_even(range(10)) |
4e5c439381954931d11e3bfed0468842002ef471 | yxtay/how-to-think-like-a-computer-scientist | /Labs/count_letters.py | 308 | 3.875 | 4 | import string
def countAll(text):
letters = {}
for ch in text.lower():
if ch in string.ascii_lowercase:
if ch in letters:
letters[ch] += 1
else:
letters[ch] = 1
return letters
print(countAll('this is a random text')) |
fbf9d2c7b5d036aecdd423695e81e30b5b0ea61d | yxtay/how-to-think-like-a-computer-scientist | /Recursion/palindrome.py | 585 | 3.71875 | 4 | import string
def removeWhite(s):
outs = ''
for ch in s.lower():
if ch in string.ascii_lowercase:
outs += ch
return outs
def isPal(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and isPal(s[1:-1])
print isPal(removeWhite("hello"))
# testEqual(i... |
d3e4b62e4e70f9925e65fb7ea684d4ded1692dd7 | yxtay/how-to-think-like-a-computer-scientist | /Dictionaries/dict_ex1_alphabets.py | 321 | 3.65625 | 4 | import string
str = input("Please enter a sentence: ")
alphabet_count = {}
for ch in str.lower():
if ch in string.ascii_lowercase:
if ch in alphabet_count:
alphabet_count[ch] += 1
else:
alphabet_count[ch] = 1
keylist = alphabet_count.keys()
keylist.sort()
for al in keylist:
print al, alphabet_count[al... |
51b4a4c5555925087687e87cddfca3ccc9af277e | yxtay/how-to-think-like-a-computer-scientist | /Strings/strings_ex20.py | 148 | 3.96875 | 4 | def removeDups(inStr):
outStr = ''
for ch in inStr:
if ch not in outStr:
outStr += ch
return outStr
print(removeDups('Hello, World!')) |
76a6176d8b459c0ca7ed4c8275de33af97ed484c | Makarios-sudo/Atm-machine-function | /main.py | 6,113 | 4.21875 | 4 |
"""writing code on the functioning of an Atm machine """
default_pin = 1234
pin_limit = 3
enter_pin = 1
name = input("enter your name \n>>> ".title())
print(f"\nhello {name},".title())
while enter_pin <= pin_limit:
pin = int(input(f"your default pin is 1234\n\nplease enter your default pin \n>>> ".title()))
... |
ab7b594b5aef6df04ea80fcd26ca3476276130b7 | bacarlino/card_games | /solitaire.py | 1,049 | 3.546875 | 4 | from card_scene import CardScene
from scene import *
class SolitaireScene(CardScene):
def setup(self):
super().setup()
class WorkingPile:
def __init__(self):
pass
class SortedPile:
def __init__(self):
self.cards = []
def add_card(self, card):
... |
d4e2cb6d1dac6e74e0097146360ac77b5e7132ea | sajjad065/assignment2 | /Function/function5.py | 270 | 4.1875 | 4 | def fac(num):
fact=1;
if(num<0):
print(int("Please enter non-negative number"))
else:
for i in range(1,(num+1)):
fact=fact*i
print("The factorial is: ")
print(fact)
number=int(input("Enter number "))
fac(number)
|
b1282fc3cf4bfe3895451cbbbd18fa6517f92dce | sajjad065/assignment2 | /Function/function17.py | 295 | 4.28125 | 4 | str1=input("Enter any string:")
char=input("enter character to check:")
check_char=lambda x: True if x.startswith(char) else False
if(check_char(str1)):
print(str1 +" :starts with character :" +char)
else:
print(str1 +": does not starts with character: " +char)
|
7e70300b0eadbd65bf2b2a3f9add53977a9a4820 | sajjad065/assignment2 | /Datatype/qsn12.py | 101 | 4.15625 | 4 | str=input("Enter string ")
print("In uppercase: " +str.upper())
print("In lowercase: " +str.lower())
|
d6c476378fac0c7a2ce31678cb34da2f1977ee57 | sajjad065/assignment2 | /Datatype/qsn28.py | 637 | 4.21875 | 4 | total=int(input("How many elements do you want to input in dictionary "))
dic={}
for i in range(total):
key1=input("Enter key:")
val1=input("Enter value:")
dic.update({key1:val1})
print("The dictionary list is :")
print(dic)
num=int(input("please input 1 if you want to add key to the given dictionary "))
if... |
fc5ac079f5d7ef8693f3fc54ed9d4dd897c64390 | sajjad065/assignment2 | /Datatype/qsn3.py | 95 | 3.90625 | 4 | str=input("Enter any String ")
char=str[0]
newstr=str[1:].replace(char,'$')
print(char+newstr)
|
049b1d16fb011106c172d6604cf1cc2a469fcf01 | sajjad065/assignment2 | /Datatype/qsn10.py | 205 | 4.0625 | 4 | str=input("enter string ")
print("you entered " +str)
result=""
length=len(str)
for i in range(length):
if(i%2==0):
result=result+str[i]
print("new string having only even index is :" +result)
|
145df75616d4f4508295d8a0874e02c0b01b387e | sajjad065/assignment2 | /Function/function4.py | 88 | 4.15625 | 4 | def reverse_str():
str=input("enter string ")
print(str[-1::-1])
reverse_str()
|
c42e9fce3c1081560bde5925860079fbd4eaa234 | Archerman123/Change-combiner-python | /dist/data/Game.py | 7,690 | 4.03125 | 4 | """
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import sys
sys.path.append('pygame')
import pygame
sys.path.append('data')
sys.path.... |
7c8bb25371418732f273467f3a3f22b84c3131dd | yeqingyan/CCI_code | /Chapter1/q1_3.py | 815 | 3.671875 | 4 | """ Question 1.3 """
def urlify(char_array, length):
""" Replace all spaces in a char array with %20 """
spaces = 0
index = 0
while index < length:
if char_array[index] == ord(' '):
spaces += 1
index += 1
new_length = length + 2 * spaces
new_index = new_length - 1... |
67187b7fa22d33fa1dad89d75858d21e77fdb462 | yeqingyan/CCI_code | /Chapter3/q3_6.py | 2,607 | 3.8125 | 4 | """ Question 3.6 """
class AnimalShelter(object):
class LinkedListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __init__(self):
self.cats_first = None
self.cats_last = None
self.dogs_first = None
self.dogs_last = None
... |
a0dfd1f2adfbe517b225ecbbda2890adcc5f1920 | yeqingyan/CCI_code | /Chapter2/q2_2.py | 538 | 3.765625 | 4 | """ Question 2.2 """
from LinkedList import *
def kth_to_last(head, k):
""" find the kth to last element of a single linked list """
if not head:
return -1
size = 1
node = head
while node.next:
node = node.next
size += 1
i = size - k - 1
node = head
while i != 0... |
1b799de8b389de2c066fbfd76deee2385b7136a2 | gongran/scrapytest | /scrapytest/fenxi/topBlockChain.py | 1,786 | 3.609375 | 4 | from selenium import webdriver
# 分析全球排名前20的交易所上的币种
class BlockChain:
def __init__(self):
self.driver = webdriver.PhantomJS()
self.urls=[
'https://coinmarketcap.com/zh/exchanges/okex/',
'https://coinmarketcap.com/zh/exchanges/binance/',
'https://coinmarketcap.com/z... |
83b2e94d20e19ee211ddd71907e868891e1c08fd | Code-Institute-Submissions/delivery-company | /run.py | 6,094 | 3.5 | 4 | import gspread
# Import the gspread library.
from google.oauth2.service_account import Credentials
# Import the Credentials class from google auth.
SCOPE = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"
]
# The sc... |
12917ab14fbe344ce38b647c933f02f9edfa5a1e | QuantumGorilla/Fractals-and-patterns | /Sierpinski_Sieve.py | 744 | 3.65625 | 4 | import turtle as potte
def serp_tri(size, iterations):
if iterations == 1:
for i in range(3):
potte.color('blue')
potte.ht()
potte.fd(size)
potte.left(120)
potte.tracer(3)
else:
potte.ht()
serp_tri(size/2, iterations-1)
... |
325bac62e933f13ea7753cbb1263394f19bef928 | yanchingyu/Object-Oriented-programming-Cplusplus | /python/Rectangle_Encapsulation/main.py | 1,028 | 4 | 4 | from Rectangle import Rectangle
height1 = int(input())
height2 = int(input())
width1 = int(input())
width2 = int(input())
rectangle1 = Rectangle(height1, width1)
rectangle2 = Rectangle(height2, width2)
print(rectangle1.getArea(), " " , rectangle1.getPerimeter())
print(rectangle2.getArea(), " " , rectangle2.getPerime... |
7232b25de347464f0b3bd7db433903c7ca2b79e5 | enrriquep3/Python | /guess.py | 539 | 4.09375 | 4 | name = input("Enter your name: ")
print("Hello", name + "!")
age = int(input("What year did you born: "))
print("You are", 2021 - age, "Years old")
fav_sport = input("What is your Favorite Sport?: ")
print("Your Favorite Sport is:", fav_sport + "!")
fav_food = input("What is your Favorite Food?: ")
print("Your F... |
c7c4ac0953045bb396660fbccbd40a32c72ac944 | agao25/BicycleParameters | /bicycleparameters/plot.py | 2,638 | 3.53125 | 4 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
def compare_bode_bicycles(bikes, speed, u, y, fig=None):
"""Returns a figure with the Bode plots of multiple bicycles.
Parameters
----------
bikes : list
A list of bicycleparameters.Bicycle instances.
speed : float
... |
384a04b5deba5249f3c1442821f1601e585b6ee4 | MurphyPone/sentdexPML | /Testing_the_LinReg_Model.py | 1,849 | 3.75 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import random
# creates a random dataset for us to use
# @numPoints = int; the size of the dataset
# @variance = int; the volatility
# @step = double; the step size between y values
# @correlation = int; +1, -1,... |
ebbce4b8a948f2f4b465bde77f800e50e4d6a3dd | 15271856796/python_study | /day08 初识函数/03全局变量与局部变量.py | 1,208 | 4.03125 | 4 | # -*- coding:utf-8 -*-
a=10 #全局变量
def func():
print("输出里面的%s" %a) #可以直接引用全局的变量,前提是不对全局变量进行修改,
func()
print("输出外面的%s" %a)
a=10 #全局变量 自定义函数里可以直接应用全局变量,但是不允许进行修改,除非加一句声明,global a
def func():
global a ... |
0e92bfe6970ce457e3b28886c82a772f2aa88d27 | 15271856796/python_study | /day07 文件操作/01_mode_r.py | 1,038 | 3.59375 | 4 | # -*- coding:utf-8 -*-
f=open("aa1.txt",mode="r") #f是一个光标,指向文件的最开头,当文件aa.txt不存在时,会报错
print f.read() #read()函数是全读,所以现在光标指向文件的最后
c2=f.read() #此时再读时,就是空了
print c2
#所以要养成一个好的习惯
f.close() #关闭f与文件的链接
f=open("aa1.txt",mode="r")
print f.read(5) ... |
ddf383029c7040717604fa0ee2d79cef71cd0140 | 15271856796/python_study | /day05 拷贝/02 copy库.py | 739 | 4.1875 | 4 | import copy
a=[1,2,3,4]
b=copy.copy(a)
b.append(7)
print(a,b) #[1, 2, 3, 4] [1, 2, 3, 4, 7]
a={'1':2,'2':3}
b=copy.copy(a)
b['3']=4
print(a,b) #{'1': 2, '2': 3} {'1': 2, '2': 3, '3': 4}
#copy.copy()只能实现最外层的copy值
a=[1,2,3,[7,8]]
b=copy.copy(a)
print("a=%s,b=%s"%(a,b)) #a=[... |
8e458e5df77430778e5b96f6129e0dc48c1bc8e5 | 15271856796/python_study | /day05 拷贝/01 list中的=与copy.py | 434 | 3.9375 | 4 | # -*- coding:utf-8 -*-
list1=[1,2,3,5]
list2=list1
list1.append("6")
print(list1,list2) #[1, 2, 3, 5, '6'] [1, 2, 3, 5, '6'],因为有=的时候是把地址给了list2,并没有创建新的对象,即id(list1)=id(list2)
#正确的用法是
print(type(list1))
list2=list1.copy()
list1.append("hh")
print(list1,list2) #[1, 2, 3, 5, '6', 'hh'] [1... |
2ff38c99c697f8887420b2620e2685a2405bae6b | 15271856796/python_study | /day03 初始字典与集合/03 初始集合.py | 1,478 | 4.03125 | 4 |
# -*- coding:utf-8 -*-
#注意集合是没有索引和切片的(因为集合是无序的)
#集合就是字典中的key,所以里面元素是不能重复
#set的常用是对列表中的元素进行去重
lis=[1,2,1,3,5,123,5]
lis=set(lis)
print(lis) #{1, 2, 3, 5, 123}
#set还有一个常用功能是元素分解(分解并去重)
sentence='Welcome Back to This Tutorial'
print(set(sentence)) #{'l', 'h', 'e', 'm', 'W', 's', 'o', 'u', 'a... |
55360ed1d50b874710134a6f4904b623b8c35b04 | kieudinhson/baikiemtra | /Bai2.py | 251 | 3.59375 | 4 | A = [1,1,2,3,5,8,13,21,34,55,88]
B = [1,3,5,4,7,88,66,59,40,54]
C=[]
for i in range(0,len(A)):
for j in range(0,len(B)):
if A[i]==B[j]:
C.append(A[i])
print(C)
A = list (set(A)^set(C))
B = list (set(B)^set(C))
print(A)
print(B) |
4fb4e5a1167664e503eb9bb38c413e3372a1d8c9 | olivia-ea/PythonPrep | /2WayIfElseStatment.py | 419 | 4.03125 | 4 | #Chapter 4: 2 Way If Else Statement
import random
num1 = random.randint(0, 9)
num2 = random.randint(0, 9)
if num1 < num2:
num1, num2 = num2, num1 #switches num1 to num2 and num2 to num1 if necessary
answer = eval(input("What is " + str(num1) + " - " + str(num2) + "?\n"))
if num1 - num2 == answer:
print("Yo... |
65ad587eb4827b641b2460a6f3c97a9edabc68d5 | olivia-ea/PythonPrep | /TrigFunctions.py | 182 | 3.546875 | 4 | #Chapter 5: Trig Functions
import math
print("Degree\t\tSin\t\tCos")
for i in range(0, 370, 10):
print(i, "\t\t", format(math.sin(i), ".4f"), "\t",format(math.cos(i), ".4f"))
|
281300c5f2793e367d2cb2d68a9f3dcd98963f2f | olivia-ea/PythonPrep | /InsertionSort | 624 | 4.03125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the insertionSort2 function below.
def insertionSort2(n, arr):
for i in range(1, n):
key = arr[i] #second item since the first item is already sorted
j = i - 1 #last item
while (j >= 0) and key < arr[j]:
... |
2ed46d78686ddf29b6ddbbd5d6fc2c02652138f8 | olivia-ea/PythonPrep | /SumOfDigits.py | 486 | 3.9375 | 4 | #Chapter 2: Sum the Digits
number = eval(input("Enter a 5 digit number: "))
digit1 = number // 10000 #gives you first digit
random1 = number % 10000
digit2 = random1 // 1000 #gives you second digit
random2 = random1 % 1000
digit3 = random2 // 100 #gives you third digit
random3 = random2 % 100
digit4 = random3 /... |
9e4e9e0976ba296cffded3315d6453d739bc65be | DirectDuck/sort_visualizer | /sort_visualizer/algs.py | 4,350 | 3.640625 | 4 | class Sort():
def execute(self):
raise NotImplementedError(f'define execute method in {self.__class__.__name__} class')
class BubbleSort(Sort):
def execute(self):
self._bubble()
def _bubble(self):
for i in range(len(self.array) - 1):
for j in range(len(self.array) - ... |
cf9f4bcef6ac299587466ca665ae577871e79042 | Luke-Poeppel/SearchingAndSorting | /Deque.py | 2,698 | 3.984375 | 4 | class ArrayDeque:
'''
Implementation of the Deque ADT.
>>> d = ArrayDeque()
>>> d.enqueue_first(1)
>>> d.enqueue_last(2)
>>> d.enqueue_first(3)
>>> print(d.data)
[1, 2, 3]
'''
INITIAL_CAPACITY = 3
def __init__(self):
self.data = [None] * ArrayDeque.INITIAL_CAPACITY
self.num_of_elems = 0
self.front_in... |
799a05ee2cf28f5d884ca2797a2483c65b4f1b00 | AyalaGottfried/Nand-To-Tetris | /project8/Parser.py | 1,744 | 3.765625 | 4 | from CommandType import CommandType
class Parser:
def __init__(self, file_name):
self.file = open(file_name, "r")
self.code = self.file.readlines()
self.current = 0
self._clean_line()
self.line = self.code[self.current].split()
self.file.close()
def... |
7196d00695bfb319e5de537edbf5121456e7234d | mickeykoko321/omega | /omega/logger/filter_logs.py | 614 | 3.625 | 4 | import re
"""Module Filter Logs
Filter logs on specific criteria
"""
def by_strings(file, strings):
"""Filter logs by a list of strings. We return all the lines which contains the specific strings in the list.
:param file: str - Log file path
:param strings: list - Strings to find in the logs
:retur... |
807e313f114403cf412fce5a3a4a02c5528844b5 | abinaya2006/proj-107 | /pro107.py | 334 | 3.578125 | 4 | import pandas as pd
import plotly_express as px
df=pd.read_csv("data.csv")
print(df.groupby(["student_id","level"],as_index=False)["attempt"].mean())
mean_value=df.groupby(["student_id","level"],as_index=False)["attempt"].mean()
fig=px.scatter(mean_value,x="student_id",y="level",size="attempt",color="attempt... |
ce629c4f388d6ef1ba3a36e15f43d48e919f204f | DawoudSheraz/Google-CodeJam-Solutions | /Google Code Jam 2020/Qualifier/Nesting Depth/index.py | 743 | 3.546875 | 4 |
def get_new_str(input_str):
output_str = ""
prev_value = int(input_str[0])
output_str+=('(' * prev_value ) + str(prev_value)
for count in range(1, len(input_str)):
current = int(input_str[count])
if current>prev_value:
output_str+= ('(' * (current-prev_value)) + str(current)... |
7582a00e20a9c30d1cd0b5ec1292592e46f11330 | pasqualespica/my-realpyhton-tutorial | /List-Comprehension/examples.py | 4,253 | 4.65625 | 5 |
"""
Every list comprehension in Python includes three elements:
expression is the member itself, a call to a method,
or any other valid expression that returns a value.
In the example above, the expression i * i is the square of the member value.
member is the object or value in the list or iterable.
In the examp... |
218bc4a2009026a338abad42c9ac11c4818bf0d7 | pasqualespica/my-realpyhton-tutorial | /InheritanceCompositionOOPGuide/Decorators/simple_decorator.py | 1,512 | 4.34375 | 4 | import functools
# def my_decorator(func):
# def wrapper():
# print("Something is happening before the function is called.")
# func()
# print("Something is happening after the function is called.")
# return wrapper
# def say_whee():
# print("Whee!")
# say_whee = my_decorator(say... |
645910d37ea52d70b2d0f72c9a57a0293113d30f | pasqualespica/my-realpyhton-tutorial | /Lambda/00_simple_lambda.py | 223 | 3.796875 | 4 |
add_one = lambda x: x + 1
print (add_one(3))
print((lambda x: x * 2)(5) )
# Multi-argument functions
full_name = lambda first, last: f'Full name: {first.title()} {last.title()}'
print(full_name('guido', 'van rossum'))
|
f48464a39c73a575e1aeed2bb1c82f08178044c5 | pasqualespica/my-realpyhton-tutorial | /Python-Requests-Library-Guide/_07_other_http_methods.py | 993 | 3.578125 | 4 | import requests
# requests.post('https://httpbin.org/post', data={'key': 'value'})
# requests.put('https://httpbin.org/put', data={'key': 'value'})
# requests.delete('https://httpbin.org/delete')
# requests.head('https://httpbin.org/get')
# requests.patch('https://httpbin.org/patch', data={'key': 'value'})
# requests.... |
f8ffcfbace03cadea03c0e9efc3398af4233452f | pasqualespica/my-realpyhton-tutorial | /Concurrency/Intro_to_Threading/09_barrier_ex.py | 442 | 3.640625 | 4 | import threading
barrier = threading.Barrier(3) # Three Thread : thread1, thread2 and Main-thread
class thread(threading.Thread):
def __init__(self, thread_ID):
threading.Thread.__init__(self)
self.thread_ID = thread_ID
def run(self):
print(str(self.thread_ID) + "\n")
barrie... |
91c9a53e04cfbab2d401bdbe05e4c41d5667b32b | pasqualespica/my-realpyhton-tutorial | /RW-Files-Python/cvs/employee_birthday.py | 2,178 | 4.09375 | 4 | import csv
import os
print(f"My CWD {os.getcwd()}")
# Reading CSV Files With csv
with open('employee_birthday.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f"There are {len(row)} columns ")
... |
5c576f87d861929a5e9ac64a95ea6ec4b34755e8 | pasqualespica/my-realpyhton-tutorial | /args_kwargs_demystified/sum_integers_args_3.py | 211 | 3.625 | 4 | # sum_integers_args_3.py
def my_sum(*args):
result = 0
for x in args:
result += x
return result
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = [6, 7, 8, 9]
print(my_sum(*list1, *list2, *list3))
|
e7f8e237f7c0cc8b3645a4d3efa4dd7d586fabf4 | awesomediff/cs207-FinalProject | /awesomediff/core.py | 12,946 | 4.09375 | 4 | import math
import numpy as np
class variable:
def __init__(self,val,der=1):
"""
Initialize a variable object
with a specified value and derivative.
Expect scalar for val. Expect scalar
or a numpy array for der.
If no derivative is specified,
... |
551cc89461c3377d8367d96a90c1939a51c9db10 | LarissaSilveiraBonifacio/Python_DIO | /src/aula_2.py | 356 | 4.03125 | 4 | a = int(input('Escreva um numero: '))
b = int(input('Escreva outro numero: '))
soma = a + b
subtracao = a - b
multiplicacao = a * b
divisao = a / b
resto = a % b
print("Soma: " + str(soma))
print("Subtração: " + str(subtracao))
print("Multiplicação: " + str(multiplicacao))
print("Divisão: " + str(divisao))
print("Res... |
33b0a29a9422e5c4f828d12848c3875f65e1526f | VRINDHAB/IRetail-Major-project- | /sub.py | 95 | 3.890625 | 4 | a= int(input('enter number1: '))
b=int( input('enter number2:'))
dif=a-b
print("dif=",dif)
|
b93a756de4b0582af069280066f44048e757f23a | VRINDHAB/IRetail-Major-project- | /patrn32123,212,1.py | 196 | 3.671875 | 4 | a=int(input('enter n: '))
for i in range(a):
for k in range(i):
print(" ",end=" ")
for j in range(a-i,0,-1):
print(j,end=" ")
for p in range(2,a-i+1):
print(p,end=" ")
print() |
54402018758ae36b71e77a015ea18ae70562c25e | VRINDHAB/IRetail-Major-project- | /grplist.py | 183 | 4 | 4 | def list():
list=[]
list1=['A','23','abc']
list2=['B','24','zxy']
list3=['C','12','wer']
list.append(list1)
list.append(list2)
list.append(list3)
print(list)
list()
|
0e4a72bcd433123de399a85edd4d42421b5c4c2a | VRINDHAB/IRetail-Major-project- | /smlr.py | 132 | 4.03125 | 4 | a=int(input("enter num1:" ))
b=int(input("enter num2: "))
if (a<b):
print(a,"is smallest")
else:
print(b,"is smaller")
|
d9a7672a25a0bd6ba47710e53adfbb012f6ab886 | VRINDHAB/IRetail-Major-project- | /1,21,321 reverstree.py | 149 | 3.75 | 4 | a=int(input('enter a: '))
for i in range(a):
for k in range(a-i,a):
print(" ",end=" ")
for j in range(a-i-1,a);
print(j,end=" ")
print() |
f906312cb1fef26122551a96b7e7701596b778f7 | VRINDHAB/IRetail-Major-project- | /class2.py | 254 | 3.890625 | 4 | class Demo:
def __init__(self):
self.a=10
def read(self):
self.a=int(input("enter the num"))
def print(self):
print(self.a)
o1=Demo()
o1.read()
o1.print()
o2=Demo()
o2.read()
o2.print()
o3=Demo()
o3.a=0
o3.a=o1.a+o2.a
print(o3.a) |
49b2a6f82ab668fefbff42c9feeeb9c992943c30 | VRINDHAB/IRetail-Major-project- | /123inptrn.py | 156 | 3.78125 | 4 | a=int(input("enter v1 : "))
for i in range(a):
for k in range(1,a-i):
print(" ",end=" ")
for j in range(i+1,0,-1):
print(j,end=" ")
print() |
95e014715064dd9d5a425787972009c26047dd22 | Safyire/Python-Emblem | /python_emblem_test.py | 7,638 | 3.625 | 4 | import random
import time
# Initialization
weapon_type = 0
weapon_type_list = ["sword", "lance", "axe", "bow", "tome"]
player_hp = random.randint(30, 50)
player_str = random.randint(10, 20)
player_def = random.randint(9, 13)
player_spd = random.randint(5, 30)
player_skl = random.randint(3, 15)
player_luk = ... |
4d644d80b78fadc8b1ee14bedf242f2a380479de | hong-il/python-anaconda-sqlite | /main.py | 577 | 3.90625 | 4 | import sqlite3
conn = sqlite3.connect("test.db")
cur = conn.cursor()
query = """
CREATE TABLE IF NOT EXISTS board (
'idx' INTEGER PRIMARY KEY AUTOINCREMENT,
'writer' VARCHAR(100),
'title' VARCHAR(250),
'content' TEXT
)
"""
cur.execute(query)
query = "INSERT INTO board ('writer'... |
bd6c2b6f89f4fe45fb7f8195496d082945105192 | ksvkabra/move-files-script-python | /delete.py | 319 | 3.75 | 4 |
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file1.txt'
# File location
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
|
e83455d41955247717f6143cd88b746b80041a2f | MohammedBasheerUddin/Datastructures-And-Other-Codes | /Leetcode/python3/Longest Substring Without Repeating Characters.py | 773 | 3.96875 | 4 | # Given a string s, find the length of the longest substring without repeating characters.
# Input: s = "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
res = []
count = 0
for i in s: # go thr... |
8e22e05cf4401dd89fa578671472c856cd9e824c | danielvillanoh/datatypes_operations | /primary.py | 2,323 | 4.5625 | 5 | #author: Daniel Villano-Herrera
# date: 7/1/2021
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numb... |
63078b1d527f9b748351d55865aceb98e4c2f6f4 | malikdiarra/bloom_filter | /bloom_filter/bloom_filter.py | 2,487 | 3.65625 | 4 | import argparse
import math
import random
import hashlib
class BloomFilter():
"""
A simple implemention of a bloom filter for string
"""
def __init__(self, length, hashes):
self.length = length
self.hashes = hashes
self.m = length
self.k = hashes
self.bits = [Fa... |
12d70ddace6d64ace1873bd5e1521efe579daf6f | pedronobrega/ine5609-estrutura-de-dados | /doubly-linked-list/__main__.py | 967 | 4.21875 | 4 | from List import List
from Item import Item
if __name__ == "__main__":
lista: List = List(3)
# This will throw an exception
# lista.go_ahead_positions(3)
# This will print None
print(lista.access_actual())
# This will print True
print(lista.is_empty())
# This will print False
print(lista.is_full(... |
274d29eeccd43ce09ddab48953df24b1042bc29a | pedronobrega/ine5609-estrutura-de-dados | /doubly-linked-list/List.py | 5,966 | 3.984375 | 4 | from Item import Item
class List:
def __init__(self, size: int = 0):
self.size = size
self.itemCnt = 0
self.pointer: Item = None
# Pointer Methods
def go_ahead_positions(self, number: int) -> None:
""" Avança o ponteiro 'k' posições """
i = 0
current: Item = self.access_actual()
if... |
54a38474bcfc39ee234c64a8b7808d3df7e31c7d | payal-98/Student_Chatbot-using-RASA | /db.py | 1,205 | 4.15625 | 4 | # importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("students.db")
# cursor
crsr = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE students (
Roll_No INTEGER PRIMARY KEY,
Sname VARCHAR(20),
Class VARCHAR(30... |
6f898986da7bd470f00b72138dbb1feb132ab055 | Hilgon2/prog | /PE7/PE7_5.py | 153 | 3.75 | 4 | list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for getal in list:
for nummer in list2:
print(getal * nummer) |
b83bc5cb01975242b99f5a30096cf7db74cd4972 | Hilgon2/prog | /PE10/PE10_1.py | 405 | 3.6875 | 4 | price = 4356
persons = input("Hoeveel personen gaan er mee?")
try:
print(price / int(persons))
except:
if not persons.isnumeric():
print("Gebruik cijfers voor het invoeren van het aantal!")
elif int(persons) == 0:
print("Delen door nul kan niet!")
elif int(persons) < 0:
print("N... |
6f02cc4d0ae1a1d3dbaac3d5d3e55df330dc12dc | ecaterinacatargiu/Graphs | /Lab4/Lab4.py | 3,995 | 3.671875 | 4 | class DoubleDictGraph:
"""A directed graph, represented as two disctionaries/maps,
one from each vertex to the set of outbound neighbours,
the other from each vertex to the set of inbound neighbours"""
def __init__(self, n):
"""Creates a graph with n vertices (numbered from 0 to n-1)
an... |
445ae1af79d2e52db0fcc563d247558b57eb0400 | MilenOrfeev/aoc | /intcode.py | 4,801 | 3.78125 | 4 | import copy
import json
class Memory(object):
def __init__(self, code):
self._memory = code
self._memory.extend([0] * len(code))
def write(self, index, element):
self.extend_if_needed(index)
self._memory[index] = element
def read(self, index):
self.extend_if_neede... |
265f92f9dc79de491b1a04ddb2ee022f6fd4f351 | romaniecnockaert/db-1819 | /src/specs.py | 4,078 | 3.640625 | 4 | """
This file contains methods to automatically
1. Generate query names
2. Generate query parameters
3. Extract specific queries from a submitted python file
"""
def gen_all_q_names(nb_queries=10):
"""
Generate list of query names
Parameters
----------
nb_queries: int
Number of ... |
6c3a57b23d5d859a223fde2738b7f76175c54a2e | saqzari/Cloud_Encrytion | /group.py | 1,565 | 3.6875 | 4 | import pickle
import account
a = account
# reads array of users from group.pickle
def read():
f = open('pickles/group.pickle', "a")
f.close()
with open('pickles/group.pickle', 'rb') as handle:
try:
group = pickle.load(handle)
except EOFError:
group = []
return g... |
12beb6ad89b6010060319595fe7b128910b34a63 | sangajapatel06/CS351-Cloud-Computing-Lab | /Lab1/CloudLab-1.py | 8,246 | 4.1875 | 4 | import functools
from typing import List
import random
from operator import mul
from functools import reduce
# Problem 1
print("------ Q1 ------")
def split(word: str) -> List[str]: # Problem 1
"""Return the list of characters formed by breaking the string Name.
doctests:
>>> split("Word")
['W', ... |
a706c470a0a53f6eb88e4e0eb0622a3a02281f4c | Refuse0126/My-Python-Code | /Test/Python-cookbook/P1/6-8.py | 1,128 | 3.9375 | 4 | """
Date:2019.6.9
"""
#1.6创建一键多值的字典
import collections
def fun1():
d1=dict()
d1.setdefault('a',[])
d1['a'].append(1)
d1['a'].append(2)
print(d1)
d2=collections.defaultdict(list)
d2['a'].append(1)
d2['a'].append(2)
print(d2)
d3=collections.defaultdict(set)... |
6fcc8398db45b274b04ce0d1244891f5a77efa41 | Refuse0126/My-Python-Code | /Practice/case3.py | 890 | 3.828125 | 4 | """
泳池过道和围墙造价练习
Date:2019.5.17
"""
class circle():
from math import pi
def __init__(self,r):
self.r=r
def getc(self):
return (2*self.pi*self.r)
def gets(self):
return (self.pi*self.r*self.r)
class guodao(circle):
def __init__(self,r,width):
circle.__init__(self,r+wid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.